From 5301c83dd81c6f44965b03699fa62e8f59e587a6 Mon Sep 17 00:00:00 2001 From: markpet49 Date: Mon, 16 Sep 2019 16:37:50 -0500 Subject: [PATCH 01/11] Polyline deprecation fixes --- nbproject/configs/Paths.properties | 1 + src/gov/nasa/worldwind/Version.java | 25 +- src/gov/nasa/worldwind/render/Path.java | 1322 +++++++++-------- src/gov/nasa/worldwind/render/Polyline.java | 793 +++++----- .../worldwind/util/measure/AreaMeasurer.java | 180 +-- .../util/measure/LengthMeasurer.java | 326 ++-- src/gov/nasa/worldwindx/examples/Paths.java | 21 +- src/gov/nasa/worldwindx/examples/Shapes.java | 585 ++++---- src/org/codehaus/jackson/JsonGenerator.java | 4 + src/org/codehaus/jackson/JsonNode.java | 1 + src/org/codehaus/jackson/JsonParser.java | 6 +- 11 files changed, 1556 insertions(+), 1708 deletions(-) create mode 100644 nbproject/configs/Paths.properties diff --git a/nbproject/configs/Paths.properties b/nbproject/configs/Paths.properties new file mode 100644 index 0000000000..54efd97ca3 --- /dev/null +++ b/nbproject/configs/Paths.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.Paths diff --git a/src/gov/nasa/worldwind/Version.java b/src/gov/nasa/worldwind/Version.java index 351da32149..da9725d2e9 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 MINOR_VALUE = "2"; 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/render/Path.java b/src/gov/nasa/worldwind/render/Path.java index c30cea5e02..561cad406d 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; @@ -19,8 +18,11 @@ import gov.nasa.worldwind.pick.*; import gov.nasa.worldwind.terrain.Terrain; import gov.nasa.worldwind.util.*; +import gov.nasa.worldwind.util.measure.LengthMeasurer; +import static gov.nasa.worldwind.ogc.kml.impl.KMLExportUtil.kmlBoolean; import com.jogamp.opengl.*; + import javax.xml.stream.*; import java.awt.*; import java.io.IOException; @@ -28,10 +30,7 @@ import java.util.*; import java.util.List; -import static gov.nasa.worldwind.ogc.kml.impl.KMLExportUtil.kmlBoolean; - -// TODO: Measurement (getLength), Texture, lighting - +// TODO: 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 @@ -46,7 +45,7 @@ * AVKey#GREAT_CIRCLE}, {@link AVKey#RHUMB_LINE} or {@link AVKey#LINEAR}. (See {@link #setPathType(String)}.) *

* Paths have separate attributes for normal display and highlighted display. If no attributes are specified, default - * attributes are used. See {@link #DEFAULT_INTERIOR_MATERIAL}, {@link #DEFAULT_OUTLINE_MATERIAL}, and {@link + * attributes are used. See {@link #DEFAULT_PATH_INTERIOR_MATERIAL}, {@link #DEFAULT_PATH_OUTLINE_MATERIAL}, and {@link * #DEFAULT_HIGHLIGHT_MATERIAL}. *

* When the path type is LINEAR the path conforms to terrain only if the follow-terrain property is true. @@ -81,13 +80,19 @@ * @author tag * @version $Id: Path.java 3032 2015-04-17 17:53:35Z dcollins $ */ -public class Path extends AbstractShape -{ - /** The default interior color. */ - protected static final Material DEFAULT_INTERIOR_MATERIAL = Material.PINK; - /** The default outline color. */ - protected static final Material DEFAULT_OUTLINE_MATERIAL = Material.RED; - /** The default path type. */ +public class Path extends AbstractShape { + + /** + * The default interior color. + */ + protected static final Material DEFAULT_PATH_INTERIOR_MATERIAL = Material.PINK; + /** + * The default outline color. + */ + protected static final Material DEFAULT_PATH_OUTLINE_MATERIAL = Material.RED; + /** + * 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 +100,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 +135,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. @@ -128,14 +143,37 @@ public static interface PositionColors Color getColor(Position position, int ordinal); } + /** + * Provides a concrete implementation of PositionColors that specifies a single color per position. Provided + * primarily to ease migration from {@link Polyline}. + */ + public class OneColorPositionColors implements PositionColors { + + Color color; + + OneColorPositionColors(Color color) { + this.color = color; + } + + /** + * {@inheritDoc} + */ + @Override + public Color getColor(Position position, int ordinal) { + return color; + } + } + /** * 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 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 +205,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 +219,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 +234,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 +249,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 +259,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 +271,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 +299,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 +312,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 +326,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 +336,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 +346,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 +356,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 +365,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 +375,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 +402,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 +424,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 +443,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. @@ -428,13 +452,13 @@ protected static class PathPickSupport extends PickSupport * of color codes to a Path, where the color codes represent the range of pick colors that the Path's position * points are drawn in. */ - protected List pickablePositions = new ArrayList(); + protected List pickablePositions = new ArrayList<>(); /** * A map that associates each path with a picked object. Used to during box picking to consolidate the * information about what parts of each path are picked into a single picked object. Path's positions are drawn * in unique colors and are therefore separately pickable during box picking. */ - protected Map pathPickedObjects = new HashMap(); + protected Map pathPickedObjects = new HashMap<>(); /** * {@inheritDoc} @@ -442,8 +466,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 +479,7 @@ public void clearPickList() * * @return the list of Path pickable positions. */ - public List getPickablePositions() - { + public List getPickablePositions() { return this.pickablePositions; } @@ -467,14 +489,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 +517,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 +526,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 +567,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 +589,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 +630,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 +643,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 +658,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(); } @@ -668,19 +681,21 @@ protected PathData getCurrentPathData() protected double showPositionsThreshold = DEFAULT_DRAW_POSITIONS_THRESHOLD; protected double showPositionsScale = DEFAULT_DRAW_POSITIONS_SCALE; protected boolean positionsSpanDateline; + protected LengthMeasurer measurer = new LengthMeasurer(); - /** Creates a path with no positions. */ - public Path() - { + /** + * Creates a path with no positions. + */ + public Path() { + this.measurer.setFollowTerrain(this.followTerrain); + this.measurer.setPathType(this.pathType); } - public Path(Path source) - { + public Path(Path source) { super(source); - List copiedPositions = new ArrayList(); - for (Position position : source.positions) - { + List copiedPositions = new ArrayList<>(); + for (Position position : source.positions) { copiedPositions.add(position); } this.setPositions(copiedPositions); @@ -694,6 +709,8 @@ public Path(Path source) this.showPositions = source.showPositions; this.showPositionsThreshold = source.showPositionsThreshold; this.showPositionsScale = source.showPositionsScale; + this.measurer.setFollowTerrain(this.followTerrain); + this.measurer.setPathType(this.pathType); } /** @@ -702,14 +719,15 @@ 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); + this.measurer.setFollowTerrain(this.followTerrain); + this.measurer.setPathType(this.pathType); } /** @@ -718,21 +736,21 @@ 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); } this.setPositions(positions.list); + this.measurer.setFollowTerrain(this.followTerrain); + this.measurer.setPathType(this.pathType); } /** @@ -743,10 +761,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); @@ -756,6 +772,8 @@ public Path(Position posA, Position posB) endPoints.add(posA); endPoints.add(posB); this.setPositions(endPoints); + this.measurer.setFollowTerrain(this.followTerrain); + this.measurer.setPathType(this.pathType); } /** @@ -764,16 +782,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 +801,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 +814,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 +830,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 +858,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 +876,7 @@ public void setPositionColors(PositionColors positionColors) * * @see #setExtrude(boolean) */ - public boolean isExtrude() - { + public boolean isExtrude() { return extrude; } @@ -878,8 +886,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 +898,7 @@ public void setExtrude(boolean extrude) * * @see #setFollowTerrain(boolean) */ - public boolean isFollowTerrain() - { + public boolean isFollowTerrain() { return this.followTerrain; } @@ -901,12 +907,13 @@ 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.measurer.setFollowTerrain(followTerrain); this.reset(); } @@ -921,8 +928,7 @@ public void setFollowTerrain(boolean followTerrain) * * @see #setNumSubsegments(int) */ - public int getNumSubsegments() - { + public int getNumSubsegments() { return numSubsegments; } @@ -935,12 +941,35 @@ 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(); } + /** + * Returns the length of the line as drawn. If the path follows the terrain, the length returned is the distance one + * would travel if on the surface. If the path does not follow the terrain, the length returned is the distance + * along the full length of the path at the path's elevations and current path type. + * + * @return the path's length in meters. + */ + public double getLength() { + Object foo = this.getCurrentPathData().getEntries(); //.iterator(); + System.out.println(foo); +// this.getCurrentPathData().getEntries() +// Iterator infos = this.positions.values().iterator(); + return 0; // infos.hasNext() ? this.measurer.getLength(infos.next().globe) : 0; + } + + 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() { + return this.measurer; + } + /** * Indicates the terrain conformance target when this path follows the terrain. The value indicates the maximum * number of pixels between which intermediate positions of a path segment -- the path portion between two specified @@ -950,8 +979,7 @@ public void setNumSubsegments(int numSubsegments) * * @see #setTerrainConformance(double) */ - public double getTerrainConformance() - { + public double getTerrainConformance() { return terrainConformance; } @@ -962,8 +990,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 +1002,7 @@ public void setTerrainConformance(double terrainConformance) * * @see #setPathType(String) */ - public String getPathType() - { + public String getPathType() { return pathType; } @@ -988,9 +1014,9 @@ public String getPathType() * * @see Path Types */ - public void setPathType(String pathType) - { + public void setPathType(String pathType) { this.pathType = pathType; + this.measurer.setPathType(pathType); this.reset(); } @@ -1001,8 +1027,7 @@ public void setPathType(String pathType) * * @see #setDrawVerticals(boolean) */ - public boolean isDrawVerticals() - { + public boolean isDrawVerticals() { return drawVerticals; } @@ -1011,8 +1036,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 +1046,7 @@ public void setDrawVerticals(boolean drawVerticals) * * @return true if dots are drawn, otherwise false. */ - public boolean isShowPositions() - { + public boolean isShowPositions() { return showPositions; } @@ -1033,8 +1056,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 +1067,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 +1078,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 +1088,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 +1097,52 @@ 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) + @Override + 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) - { + @Override + protected boolean shouldUseVBOs(DrawContext dc) { return this.getCurrentPathData().tessellatedPositions.size() > VBO_THRESHOLD && super.shouldUseVBOs(dc); } @@ -1143,70 +1155,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 +1236,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 +1256,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 +1280,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 +1322,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 +1363,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 +1371,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 +1410,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 +1429,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 +1467,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 +1480,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 +1520,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 +1538,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 +1562,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 +1586,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 +1598,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 +1626,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 +1659,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 +1749,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 +1775,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 +1806,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 +1831,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 +1857,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 +1894,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 +1930,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 +1946,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 +1962,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 +1989,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 +2000,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 +2044,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 +2059,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 +2076,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 +2086,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 +2104,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 +2141,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 +2180,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 +2204,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 +2213,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 +2237,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 +2274,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 +2293,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 +2331,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 +2346,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 +2374,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 +2392,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 +2432,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 +2444,78 @@ 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} + */ + @Override + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { // Write geometry xmlWriter.writeStartElement("LineString"); @@ -2572,15 +2533,98 @@ 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(); xmlWriter.writeEndElement(); // LineString } + + /** + * Provided to ease the transition from Polyline + * + * @param color + */ + public void setColor(Color color) { + if (color == null) { + String msg = Logging.getMessage("nullValue.ColorIsNull"); + Logging.logger().severe(msg); + throw new IllegalArgumentException(msg); + } + + setPositionColors(new OneColorPositionColors(color)); + if (this.surfaceShape != null) { + ShapeAttributes attrs = this.surfaceShape.getAttributes(); + attrs.setOutlineMaterial(new Material(color)); + attrs.setOutlineOpacity(color.getAlpha() / 255.0); + attrs.setInteriorMaterial(attrs.getOutlineMaterial()); + attrs.setInteriorOpacity(attrs.getOutlineOpacity()); + } + + } + + /** + * Provided to ease the transition from Polyline + * + * @param lineWidth + */ + public void setLineWidth(double lineWidth) { + + this.activeAttributes.setOutlineWidth(lineWidth); + this.reset(); + if (this.surfaceShape != null) { + this.surfaceShape.getAttributes().setOutlineWidth(this.activeAttributes.getOutlineWidth()); + } + } + + /** + * Specifies an offset, in meters, to add to the path points when the path's follow-terrain attribute is true. See + * {@link #setFollowTerrain(boolean)}. Provided to ease the transition from Polyline + * + * @param offset the path offset in meters. + */ + public void setOffset(double offset) { + ArrayList newPositions = new ArrayList<>(); + for (Position p : this.positions) { + newPositions.add(new Position(p, offset)); + } + this.setPositions(newPositions); + } + + /** + * Sets the stipple pattern for specifying line types other than solid. See the OpenGL specification or programming + * guides for a description of this parameter. Stipple is also affected by the path's stipple factor, {@link + * #setStippleFactor(int)}. + * + * @param stipplePattern the stipple pattern. + */ + public void setStipplePattern(short stipplePattern) { + System.out.println("foo"); + +// this.stipplePattern = stipplePattern; +// if (this.surfaceShape != null) { +// this.surfaceShape.getAttributes().setOutlineStipplePattern(this.stipplePattern); +// } + } + + /** + * Sets the stipple factor for specifying line types other than solid. See the OpenGL specification or programming + * guides for a description of this parameter. Stipple is also affected by the path's stipple pattern, {@link + * #setStipplePattern(short)}. + * + * @param stippleFactor the stipple factor. + */ + public void setStippleFactor(int stippleFactor) { + System.out.println("foo"); +// this.stippleFactor = stippleFactor; +// +// if (this.surfaceShape != null) { +// this.surfaceShape.getAttributes().setOutlineStippleFactor(this.stippleFactor); +// } + } + } diff --git a/src/gov/nasa/worldwind/render/Polyline.java b/src/gov/nasa/worldwind/render/Polyline.java index 807b1c52f9..bfe9225287 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 + 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; } @@ -272,17 +251,15 @@ public double getOffset() * Specifies an offset, in meters, to add to the path points when the path's follow-terrain attribute is true. See * {@link #setFollowTerrain(boolean)}. * - * @param offset the path pffset in meters. + * @param offset the path offset 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 - { - ArrayList temp = new ArrayList(); + } 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) - { - ArrayList newPositions = new ArrayList(); + 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/util/measure/AreaMeasurer.java b/src/gov/nasa/worldwind/util/measure/AreaMeasurer.java index e7ec39398e..cd5001601a 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(), getAVKeyPathType()); + } // 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()); + true, getAVKeyPathType()); + } // 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..b8a6ae0a19 100644 --- a/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java +++ b/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java @@ -3,9 +3,9 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.measure; +import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.geom.*; import gov.nasa.worldwind.globes.*; import gov.nasa.worldwind.util.Logging; @@ -14,22 +14,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 @@ -37,70 +41,61 @@ public class LengthMeasurer implements MeasurableLength private ArrayList positions; private ArrayList subdividedPositions; private boolean followTerrain = false; - private int pathType = Polyline.GREAT_CIRCLE; + private String pathType = AVKey.GREAT_CIRCLE; private double maxSegmentLength = DEFAULT_MAX_SEGMENT_LENGTH; private Sector sector; 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 +104,30 @@ 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() - { + @Deprecated + public int getPathType() { + switch (pathType) { + case AVKey.LINEAR: + return Polyline.LINEAR; + case AVKey.RHUMB_LINE: + return Polyline.RHUMB_LINE; + case AVKey.GREAT_CIRCLE: + return Polyline.GREAT_CIRCLE; + default: + String message = Logging.getMessage("generic.ArgumentOutOfRange"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); + } + } + + public String getAVKeyPathType() { return this.pathType; } @@ -130,10 +138,39 @@ public int getPathType() * * @param pathType the type of path to measure. */ - public void setPathType(int pathType) - { - if (this.pathType != pathType) - { + @Deprecated + public void setPathType(int pathType) { + String mappedPathType = this.pathType; + switch (pathType) { + case Polyline.LINEAR: + mappedPathType = AVKey.LINEAR; + break; + case Polyline.RHUMB_LINE: + mappedPathType = AVKey.RHUMB_LINE; + break; + case Polyline.GREAT_CIRCLE: + mappedPathType = AVKey.GREAT_CIRCLE; + break; + default: + String message = Logging.getMessage("generic.ArgumentOutOfRange"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); + } + if (!this.pathType.equals(mappedPathType)) { + this.pathType = mappedPathType; + clearCachedValues(); + } + } + + /** + * Sets the type of path used when subdividing long segments, one of Polyline.GREAT_CIRCLE, which draws segments as + * a great circle, Polyline.LINEAR, which determines the intermediate positions between segments by interpolating + * the segment endpoints, or Polyline.RHUMB_LINE, which draws segments as a line of constant heading. + * + * @param pathType the type of path to measure. + */ + public void setPathType(String pathType) { + if (this.pathType != pathType) { this.pathType = pathType; clearCachedValues(); } @@ -144,8 +181,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 +190,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 +227,7 @@ public boolean isClosedShape() * * @return the number of terrain elevation samples used. */ - public double getLengthTerrainSamplingSteps() - { + public double getLengthTerrainSamplingSteps() { return this.lengthTerrainSamplingSteps; } @@ -207,17 +237,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 +252,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 +275,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 +293,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 +322,115 @@ 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 polylinePathType - 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) - { - return subdividePositions(globe, positions, maxLength, followTerrain, pathType, 0, positions.size()); + ArrayList positions, + double maxLength, boolean followTerrain, String avkeyPathType) { + return subdividePositions(globe, positions, maxLength, followTerrain, avkeyPathType, 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 index 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, String 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) - { - destLatLon = LatLon.interpolate(s, pos1, pos2); - } - 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 - { - if (segmentAzimuth == null) - { - segmentAzimuth = LatLon.greatCircleAzimuth(pos1, pos2); - segmentDistance = LatLon.greatCircleDistance(pos1, pos2); - } - destLatLon = LatLon.greatCircleEndPosition(pos1, segmentAzimuth.radians, - s * segmentDistance.radians); + switch (pathType) { + case AVKey.LINEAR: + destLatLon = LatLon.interpolate(s, pos1, pos2); + break; + case AVKey.RHUMB_LINE: + if (segmentAzimuth == null) { + segmentAzimuth = LatLon.rhumbAzimuth(pos1, pos2); + segmentDistance = LatLon.rhumbDistance(pos1, pos2); + } + destLatLon = LatLon.rhumbEndPosition(pos1, segmentAzimuth.radians, + s * segmentDistance.radians); + break; + case AVKey.GREAT_CIRCLE: + if (segmentAzimuth == null) { + segmentAzimuth = LatLon.greatCircleAzimuth(pos1, pos2); + segmentDistance = LatLon.greatCircleDistance(pos1, pos2); + } + destLatLon = LatLon.greatCircleEndPosition(pos1, segmentAzimuth.radians, + s * segmentDistance.radians); + break; + default: + String message = Logging.getMessage("generic.ArgumentOutOfRange"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); } // 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/worldwindx/examples/Paths.java b/src/gov/nasa/worldwindx/examples/Paths.java index 5ee8deaa59..29554f701a 100644 --- a/src/gov/nasa/worldwindx/examples/Paths.java +++ b/src/gov/nasa/worldwindx/examples/Paths.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.examples; import gov.nasa.worldwind.WorldWind; @@ -23,12 +22,11 @@ * @author tag * @version $Id: Paths.java 2292 2014-09-02 21:13:05Z tgaskins $ */ -public class Paths extends ApplicationTemplate -{ - public static class AppFrame extends ApplicationTemplate.AppFrame - { - public AppFrame() - { +public class Paths extends ApplicationTemplate { + + public static class AppFrame extends ApplicationTemplate.AppFrame { + + public AppFrame() { super(true, true, false); // Add a dragger to enable shape dragging @@ -42,7 +40,7 @@ public AppFrame() attrs.setOutlineWidth(2d); // Create a path, set some of its properties and set its attributes. - ArrayList pathPositions = new ArrayList(); + ArrayList pathPositions = new ArrayList<>(); pathPositions.add(Position.fromDegrees(28, -102, 1e4)); pathPositions.add(Position.fromDegrees(35, -100, 1e4)); Path path = new Path(pathPositions); @@ -53,14 +51,14 @@ public AppFrame() layer.addRenderable(path); // Create a path that uses all default values. - pathPositions = new ArrayList(); + pathPositions = new ArrayList<>(); pathPositions.add(Position.fromDegrees(28, -104, 1e4)); pathPositions.add(Position.fromDegrees(35, -102, 1e4)); path = new Path(pathPositions); layer.addRenderable(path); // Create a path with more than two positions and closed. - pathPositions = new ArrayList(); + pathPositions = new ArrayList<>(); pathPositions.add(Position.fromDegrees(28, -106, 4e4)); pathPositions.add(Position.fromDegrees(35, -104, 4e4)); pathPositions.add(Position.fromDegrees(35, -107, 4e4)); @@ -89,8 +87,7 @@ public AppFrame() } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind Paths", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/Shapes.java b/src/gov/nasa/worldwindx/examples/Shapes.java index 0253111b27..7f8f8d8a4c 100644 --- a/src/gov/nasa/worldwindx/examples/Shapes.java +++ b/src/gov/nasa/worldwindx/examples/Shapes.java @@ -5,7 +5,7 @@ */ package gov.nasa.worldwindx.examples; -import com.jogamp.opengl.util.awt.TextRenderer; +import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.Configuration; import gov.nasa.worldwind.event.*; import gov.nasa.worldwind.geom.*; @@ -14,6 +14,9 @@ import gov.nasa.worldwind.render.*; import gov.nasa.worldwind.util.BasicDragger; +import com.jogamp.opengl.util.awt.TextRenderer; +import gov.nasa.worldwind.WorldWind; + import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; @@ -28,39 +31,37 @@ * @author tag * @version $Id: Shapes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Shapes -{ - private static class Info - { +public class Shapes { + + private static class Info { + private final Object object; private final String name; - - public Info(String name, Object object) - { + + public Info(String name, Object object) { this.object = object; this.name = name; } } - + @SuppressWarnings("unchecked") - protected static class AppFrame extends JFrame - { + protected static class AppFrame extends JFrame { + private Dimension canvasSize = new Dimension(800, 600); private ApplicationTemplate.AppPanel wwjPanel; private RenderableLayer layer = new RenderableLayer(); private TextRenderer textRenderer = new TextRenderer(java.awt.Font.decode("Arial-Plain-13"), true, false); - - public AppFrame() - { + + public AppFrame() { // Create the WorldWindow. this.wwjPanel = new ApplicationTemplate.AppPanel(this.canvasSize, true); this.wwjPanel.setPreferredSize(canvasSize); - + ApplicationTemplate.insertBeforePlacenames(this.wwjPanel.getWwd(), layer); - + JPanel shapesPanel = makeShapeSelectionPanel(); shapesPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - + JPanel attrsPanel = makeAttributesPanel(); attrsPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); @@ -70,7 +71,7 @@ public AppFrame() JPanel p = new JPanel(new BorderLayout(6, 6)); p.add(attrsPanel, BorderLayout.CENTER); controlPanel.add(p, BorderLayout.SOUTH); - + this.getContentPane().add(wwjPanel, BorderLayout.CENTER); this.getContentPane().add(controlPanel, BorderLayout.WEST); this.pack(); @@ -84,17 +85,15 @@ public AppFrame() int y = parentLocation.y + (parentSize.height - prefSize.height) / 2; this.setLocation(x, y); this.setResizable(true); - - wwjPanel.getWwd().addRenderingListener(new RenderingListener() - { - public void stageChanged(RenderingEvent event) - { - if (!event.getStage().equals(RenderingEvent.BEFORE_BUFFER_SWAP)) + + wwjPanel.getWwd().addRenderingListener(new RenderingListener() { + public void stageChanged(RenderingEvent event) { + if (!event.getStage().equals(RenderingEvent.BEFORE_BUFFER_SWAP)) { return; - - if (currentShape instanceof Polyline) - { - Polyline p = (Polyline) currentShape; + } + + if (currentShape instanceof Path) { + Path p = (Path) currentShape; String length = Double.toString(p.getLength()); textRenderer.beginRendering(wwjPanel.getWidth(), wwjPanel.getHeight()); textRenderer.draw(length, 100, 100); @@ -106,9 +105,9 @@ public void stageChanged(RenderingEvent event) // Enable dragging and other selection responses this.setupSelection(); } - + private Renderable currentShape; - + private String currentPathColor = "Yellow"; private int currentPathOpacity = 10; private double currentPathWidth = 1; @@ -118,317 +117,292 @@ public void stageChanged(RenderingEvent event) private float currentOffset = 0; private int currentTerrainConformance = 10; private int currentNumSubsegments = 10; - + private String currentBorderColor = "Yellow"; private double currentBorderWidth = 1; private int currentBorderOpacity = 10; private String currentBorderStyle = "Solid"; - + private String currentInteriorColor = "Yellow"; private int currentInteriorOpacity = 10; private String currentInteriorStyle = "Solid"; - - private ArrayList onTerrainOnlyItems = new ArrayList(); - private ArrayList offTerrainOnlyItems = new ArrayList(); - - private void update() - { - for (JComponent c : onTerrainOnlyItems) - { + + private ArrayList onTerrainOnlyItems = new ArrayList<>(); + private ArrayList offTerrainOnlyItems = new ArrayList<>(); + + private void update() { + for (JComponent c : onTerrainOnlyItems) { c.setEnabled(currentFollowTerrain); } - - for (JComponent c : offTerrainOnlyItems) - { + + for (JComponent c : offTerrainOnlyItems) { c.setEnabled(!currentFollowTerrain); } - - if (this.currentShape instanceof SurfaceShape) - { + + if (this.currentShape instanceof SurfaceShape) { SurfaceShape shape = (SurfaceShape) currentShape; ShapeAttributes attr = shape.getAttributes(); - - if (attr == null) + + if (attr == null) { attr = new BasicShapeAttributes(); - - if (!currentBorderStyle.equals("None")) - { + } + + if (!currentBorderStyle.equals("None")) { float alpha = currentBorderOpacity >= 10 ? 1f : currentBorderOpacity <= 0 ? 0f - : currentBorderOpacity / 10f; + : currentBorderOpacity / 10f; Color color = null; - if (currentBorderColor.equals("Yellow")) + if (currentBorderColor.equals("Yellow")) { color = new Color(1f, 1f, 0f); - else if (currentBorderColor.equals("Red")) + } else if (currentBorderColor.equals("Red")) { color = new Color(1f, 0f, 0f); - else if (currentBorderColor.equals("Green")) + } else if (currentBorderColor.equals("Green")) { color = new Color(0f, 1f, 0f); - else if (currentBorderColor.equals("Blue")) + } else if (currentBorderColor.equals("Blue")) { color = new Color(0f, 0f, 1f); - + } + attr.setDrawOutline(true); attr.setOutlineMaterial(new Material(color)); attr.setOutlineOpacity(alpha); attr.setOutlineWidth(currentBorderWidth); - } - else - { + } else { attr.setDrawOutline(false); } - - if (!currentInteriorStyle.equals("None")) - { + + if (!currentInteriorStyle.equals("None")) { float alpha = currentInteriorOpacity >= 10 ? 1f : currentInteriorOpacity <= 0 ? 0f - : currentInteriorOpacity / 10f; + : currentInteriorOpacity / 10f; Color color = null; - if (currentInteriorColor.equals("Yellow")) + if (currentInteriorColor.equals("Yellow")) { color = new Color(1f, 1f, 0f); - else if (currentInteriorColor.equals("Red")) + } else if (currentInteriorColor.equals("Red")) { color = new Color(1f, 0f, 0f); - else if (currentInteriorColor.equals("Green")) + } else if (currentInteriorColor.equals("Green")) { color = new Color(0f, 1f, 0f); - else if (currentInteriorColor.equals("Blue")) + } else if (currentInteriorColor.equals("Blue")) { color = new Color(0f, 0f, 1f); - + } + attr.setInteriorMaterial(new Material(color)); attr.setInteriorOpacity(alpha); attr.setDrawInterior(true); - } - else - { + } else { attr.setDrawInterior(false); } - + shape.setAttributes(attr); - } - else - { + } else { float alpha = currentPathOpacity >= 10 ? 1f : currentPathOpacity <= 0 ? 0f - : currentPathOpacity / 10f; + : currentPathOpacity / 10f; Color color = null; - if (currentPathColor.equals("Yellow")) + if (currentPathColor.equals("Yellow")) { color = new Color(1f, 1f, 0f, alpha); - else if (currentPathColor.equals("Red")) + } else if (currentPathColor.equals("Red")) { color = new Color(1f, 0f, 0f, alpha); - else if (currentPathColor.equals("Green")) + } else if (currentPathColor.equals("Green")) { color = new Color(0f, 1f, 0f, alpha); - else if (currentPathColor.equals("Blue")) + } else if (currentPathColor.equals("Blue")) { color = new Color(0f, 0f, 1f, alpha); - - if (currentShape instanceof Polyline) - { - Polyline pl = (Polyline) currentShape; - pl.setColor(color); - pl.setLineWidth(currentPathWidth); - pl.setFollowTerrain(currentFollowTerrain); - pl.setTerrainConformance(currentTerrainConformance); - pl.setNumSubsegments(currentNumSubsegments); - - if (currentPathType.equalsIgnoreCase("linear")) - pl.setPathType(Polyline.LINEAR); - else if (currentPathType.equalsIgnoreCase("rhumb line")) - pl.setPathType(Polyline.RHUMB_LINE); - else - pl.setPathType(Polyline.GREAT_CIRCLE); - - pl.setOffset(currentOffset); - - if (currentPathStyle.equals("Dash")) - { - pl.setStippleFactor(5); - pl.setStipplePattern((short) 0xAAAA); + } + + if (currentShape instanceof Path) { + Path path = (Path) currentShape; + path.setColor(color); + path.setLineWidth(currentPathWidth); + path.setFollowTerrain(currentFollowTerrain); + if (path.isFollowTerrain()) { + path.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); + } else { + path.setAltitudeMode(WorldWind.ABSOLUTE); + } + path.setTerrainConformance(currentTerrainConformance); + path.setNumSubsegments(currentNumSubsegments); + + if (currentPathType.equalsIgnoreCase("linear")) { + path.setPathType(AVKey.LINEAR); + } else if (currentPathType.equalsIgnoreCase("rhumb line")) { + path.setPathType(AVKey.RHUMB_LINE); + } else { + path.setPathType(AVKey.GREAT_CIRCLE); } - else - { - pl.setStippleFactor(0); // solid + + path.setOffset(currentOffset); + + if (currentPathStyle.equals("Dash")) { + path.setStippleFactor(5); + path.setStipplePattern((short) 0xAAAA); + } else { + path.setStippleFactor(0); // solid } } } this.layer.removeAllRenderables(); - if (this.currentShape != null) + if (this.currentShape != null) { this.layer.addRenderable(this.currentShape); + } this.wwjPanel.getWwd().redraw(); } - - private Info[] buildSurfaceShapes() - { + + private Info[] buildSurfaceShapes() { LatLon position = new LatLon(Angle.fromDegrees(38), Angle.fromDegrees(-105)); - - ArrayList surfaceLinePositions = new ArrayList(); + + ArrayList surfaceLinePositions = new ArrayList<>(); // surfaceLinePositions.add(LatLon.fromDegrees(37.8484, -119.9754)); // surfaceLinePositions.add(LatLon.fromDegrees(38.3540, -119.1526)); // surfaceLinePositions.add(new LatLon(Angle.fromDegrees(0), Angle.fromDegrees(-150))); // surfaceLinePositions.add(new LatLon(Angle.fromDegrees(60), Angle.fromDegrees(0))); - surfaceLinePositions.add(position); surfaceLinePositions.add(LatLon.fromDegrees(39, -104)); surfaceLinePositions.add(LatLon.fromDegrees(39, -105)); surfaceLinePositions.add(position); - - return new Info[] - { - new Info("Circle", new SurfaceCircle(position, 100e3)), - new Info("Ellipse", new SurfaceEllipse(position, 100e3, 90e3, Angle.ZERO)), - new Info("Square", new SurfaceSquare(position, 100e3)), - new Info("Quad", new SurfaceQuad(position, 100e3, 60e3, Angle.ZERO)), - new Info("Sector", new SurfaceSector(Sector.fromDegrees(38, 40, -105, -103))), - new Info("Polygon", new SurfacePolygon(surfaceLinePositions)), - }; + + return new Info[]{ + new Info("Circle", new SurfaceCircle(position, 100e3)), + new Info("Ellipse", new SurfaceEllipse(position, 100e3, 90e3, Angle.ZERO)), + new Info("Square", new SurfaceSquare(position, 100e3)), + new Info("Quad", new SurfaceQuad(position, 100e3, 60e3, Angle.ZERO)), + new Info("Sector", new SurfaceSector(Sector.fromDegrees(38, 40, -105, -103))), + new Info("Polygon", new SurfacePolygon(surfaceLinePositions)),}; } - - private Info[] buildFreeShapes() - { + + private Info[] buildFreeShapes() { double elevation = 10e3; - ArrayList positions = new ArrayList(); + ArrayList positions = new ArrayList<>(); positions.add(new Position(Angle.fromDegrees(37.8484), Angle.fromDegrees(-119.9754), elevation)); positions.add(new Position(Angle.fromDegrees(39.3540), Angle.fromDegrees(-110.1526), elevation)); positions.add(new Position(Angle.fromDegrees(38.3540), Angle.fromDegrees(-100.1526), elevation)); - - ArrayList positions2 = new ArrayList(); + + ArrayList positions2 = new ArrayList<>(); positions2.add(new Position(Angle.fromDegrees(0), Angle.fromDegrees(-150), elevation)); positions2.add(new Position(Angle.fromDegrees(25), Angle.fromDegrees(-75), elevation)); positions2.add(new Position(Angle.fromDegrees(50), Angle.fromDegrees(0), elevation)); - - ArrayList positions3 = new ArrayList(); - for (double lat = 42, lon = -100; lat <= 45; lat += .1, lon += .1) - { + + ArrayList positions3 = new ArrayList<>(); + for (double lat = 42, lon = -100; lat <= 45; lat += .1, lon += .1) { positions3.add(new Position(Angle.fromDegrees(lat), Angle.fromDegrees(lon), elevation)); } - - ArrayList positions4 = new ArrayList(); + + ArrayList positions4 = new ArrayList<>(); positions4.add(new Position(Angle.fromDegrees(90), Angle.fromDegrees(-110), elevation)); positions4.add(new Position(Angle.fromDegrees(-90), Angle.fromDegrees(-110), elevation)); - - ArrayList positions5 = new ArrayList(); - for (int i = 0; i < 100; i++) - { + + ArrayList positions5 = new ArrayList<>(); + for (int i = 0; i < 100; i++) { positions5.add(Position.fromDegrees(38.0 + i * 0.0001, 30.0 + i * 0.0001, 1000.0 + i * 5.0)); } - + @SuppressWarnings({"UnnecessaryLocalVariable"}) - Info[] infos = new Info[] - { - new Info("Short Path", new Polyline(positions)), - new Info("Long Path", new Polyline(positions2)), - new Info("Incremental Path", new Polyline(positions3)), - new Info("Vertical Path", new Polyline(positions4)), - new Info("Small-segment Path", new Polyline(positions5)), - new Info("Quad", new Quadrilateral(Sector.fromDegrees(38, 40, -104, -105), elevation)), - new Info("None", null) - }; - + Info[] infos = new Info[]{ + new Info("Short Path", new Path(positions)), + new Info("Long Path", new Path(positions2)), + new Info("Incremental Path", new Path(positions3)), + new Info("Vertical Path", new Path(positions4)), + new Info("Small-segment Path", new Path(positions5)), + new Info("Quad", new Quadrilateral(Sector.fromDegrees(38, 40, -104, -105), elevation)), + new Info("None", null) + }; + return infos; } - - private JPanel makeShapeSelectionPanel() - { + + private JPanel makeShapeSelectionPanel() { final Info[] surfaceShapeInfos = this.buildSurfaceShapes(); GridLayout layout = new GridLayout(surfaceShapeInfos.length, 1); JPanel ssPanel = new JPanel(layout); ButtonGroup group = new ButtonGroup(); - for (final Info info : surfaceShapeInfos) - { + for (final Info info : surfaceShapeInfos) { JRadioButton b = new JRadioButton(info.name); - b.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + b.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent actionEvent) { currentShape = (Renderable) info.object; update(); } }); group.add(b); ssPanel.add(b); - if (info.name.equalsIgnoreCase("none")) + if (info.name.equalsIgnoreCase("none")) { b.setSelected(true); + } } ssPanel.setBorder(this.createTitleBorder("Surface Shapes")); - + final Info[] freeShapeInfos = this.buildFreeShapes(); layout = new GridLayout(freeShapeInfos.length, 1); JPanel fsPanel = new JPanel(layout); - for (final Info info : freeShapeInfos) - { + for (final Info info : freeShapeInfos) { JRadioButton b = new JRadioButton(info.name); - b.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { currentShape = (Renderable) info.object; update(); } }); group.add(b); fsPanel.add(b); - if (info.name.equalsIgnoreCase("none")) + if (info.name.equalsIgnoreCase("none")) { b.setSelected(true); + } } fsPanel.setBorder(this.createTitleBorder("Path Shapes")); - + JPanel shapesPanel = new JPanel(new GridLayout(1, 2, 8, 1)); shapesPanel.add(fsPanel); shapesPanel.add(ssPanel); - + return shapesPanel; } - - private Border createTitleBorder(String title) - { + + private Border createTitleBorder(String title) { TitledBorder b = BorderFactory.createTitledBorder(title); // b.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); return new CompoundBorder(b, BorderFactory.createEmptyBorder(10, 10, 10, 10)); } - - private JPanel makeAttributesPanel() - { + + private JPanel makeAttributesPanel() { JPanel panel = new JPanel(new GridLayout(1, 2, 8, 8)); panel.add(this.makePathAttributesPanel()); panel.add(this.makeInteriorAttributesPanel()); - + return panel; } - - private JPanel makePathAttributesPanel() - { + + private JPanel makePathAttributesPanel() { JPanel outerPanel = new JPanel(new BorderLayout(6, 6)); outerPanel.setBorder(this.createTitleBorder("Path Attributes")); - + GridLayout nameLayout = new GridLayout(0, 1, 6, 6); JPanel namePanel = new JPanel(nameLayout); - + GridLayout valueLayout = new GridLayout(0, 1, 6, 6); JPanel valuePanel = new JPanel(valueLayout); - + namePanel.add(new JLabel("Follow Terrain")); JCheckBox ckb = new JCheckBox(); ckb.setSelected(currentFollowTerrain); - ckb.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + ckb.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { currentFollowTerrain = ((JCheckBox) actionEvent.getSource()).isSelected(); update(); } }); valuePanel.add(ckb); - + JLabel label; - + namePanel.add(label = new JLabel("Conformance")); - int[] values = new int[] {1, 2, 4, 8, 10, 15, 20, 30, 40, 50}; + int[] values = new int[]{1, 2, 4, 8, 10, 15, 20, 30, 40, 50}; String[] strings = new String[values.length]; - for (int i = 0; i < values.length; i++) - { + for (int i = 0; i < values.length; i++) { strings[i] = Integer.toString(values[i]) + " pixels"; } JSpinner sp = new JSpinner( - new SpinnerListModel(strings)); + new SpinnerListModel(strings)); onTerrainOnlyItems.add(label); onTerrainOnlyItems.add(sp); - sp.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { + sp.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent changeEvent) { String v = (String) ((JSpinner) changeEvent.getSource()).getValue(); currentTerrainConformance = Integer.parseInt(v.substring(0, v.indexOf(" "))); update(); @@ -436,15 +410,13 @@ public void stateChanged(ChangeEvent changeEvent) }); sp.setValue(Integer.toString(currentTerrainConformance) + " pixels"); valuePanel.add(sp); - + namePanel.add(label = new JLabel("Subsegments")); - sp = new JSpinner(new SpinnerListModel(new String[] {"1", "2", "5", "10", "20", "40", "50"})); + sp = new JSpinner(new SpinnerListModel(new String[]{"1", "2", "5", "10", "20", "40", "50"})); offTerrainOnlyItems.add(label); offTerrainOnlyItems.add(sp); - sp.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { + sp.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent changeEvent) { String v = (String) ((JSpinner) changeEvent.getSource()).getValue(); currentNumSubsegments = Integer.parseInt(v); update(); @@ -452,248 +424,207 @@ public void stateChanged(ChangeEvent changeEvent) }); sp.setValue(Integer.toString(currentNumSubsegments)); valuePanel.add(sp); - + namePanel.add(new JLabel("Type")); - final JComboBox cb = new JComboBox(new String[] {"Great Circle", "Linear", "Rhumb Line"}); - cb.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + final JComboBox cb = new JComboBox(new String[]{"Great Circle", "Linear", "Rhumb Line"}); + cb.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { currentPathType = (String) cb.getSelectedItem(); update(); } }); cb.setSelectedItem("Great Circle"); valuePanel.add(cb); - + namePanel.add(new JLabel("Style")); - final JComboBox cb1 = new JComboBox(new String[] {"None", "Solid", "Dash"}); - cb1.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + final JComboBox cb1 = new JComboBox(new String[]{"None", "Solid", "Dash"}); + cb1.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { currentPathStyle = (String) cb1.getSelectedItem(); update(); } }); cb1.setSelectedItem("Solid"); valuePanel.add(cb1); - + namePanel.add(new JLabel("Width")); sp = new JSpinner(new SpinnerNumberModel(this.currentPathWidth, 1d, 10d, 1d)); - sp.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { + sp.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent changeEvent) { currentPathWidth = (Double) ((JSpinner) changeEvent.getSource()).getValue(); update(); } }); sp.setValue(currentPathWidth); valuePanel.add(sp); - + namePanel.add(new JLabel("Color")); - JComboBox cb2 = new JComboBox(new String[] {"Red", "Green", "Blue", "Yellow"}); + JComboBox cb2 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb2.setSelectedItem(currentPathColor); - cb2.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + cb2.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { currentPathColor = (String) ((JComboBox) actionEvent.getSource()).getSelectedItem(); update(); } }); valuePanel.add(cb2); - + namePanel.add(new JLabel("Opacity")); sp = new JSpinner(new SpinnerNumberModel(this.currentPathOpacity, 0, 10, 1)); - sp.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { + sp.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent changeEvent) { currentPathOpacity = (Integer) ((JSpinner) changeEvent.getSource()).getValue(); update(); } }); valuePanel.add(sp); - + namePanel.add(new JLabel("Offset")); sp = new JSpinner( - new SpinnerListModel(new String[] {"0", "10", "100", "1000", "10000", "100000", "1000000"})); - sp.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { + new SpinnerListModel(new String[]{"0", "10", "100", "1000", "10000", "100000", "1000000"})); + sp.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent changeEvent) { currentOffset = Float.parseFloat((String) ((JSpinner) changeEvent.getSource()).getValue()); update(); } }); sp.setValue("0"); valuePanel.add(sp); - + outerPanel.add(namePanel, BorderLayout.WEST); outerPanel.add(valuePanel, BorderLayout.CENTER); - + return outerPanel; } - - private JPanel makeInteriorAttributesPanel() - { + + private JPanel makeInteriorAttributesPanel() { JPanel outerPanel = new JPanel(new BorderLayout(6, 6)); outerPanel.setBorder(this.createTitleBorder("Surface Attributes")); - + GridLayout nameLayout = new GridLayout(0, 1, 6, 6); JPanel namePanel = new JPanel(nameLayout); - + GridLayout valueLayout = new GridLayout(0, 1, 6, 6); JPanel valuePanel = new JPanel(valueLayout); - + namePanel.add(new JLabel("Style")); - final JComboBox cb1 = new JComboBox(new String[] {"None", "Solid"}); - cb1.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + final JComboBox cb1 = new JComboBox(new String[]{"None", "Solid"}); + cb1.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { currentInteriorStyle = (String) cb1.getSelectedItem(); update(); } }); cb1.setSelectedItem("Solid"); valuePanel.add(cb1); - + namePanel.add(new JLabel("Opacity")); JSpinner sp = new JSpinner(new SpinnerNumberModel(this.currentBorderOpacity, 0, 10, 1)); - sp.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { + sp.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent changeEvent) { currentInteriorOpacity = (Integer) ((JSpinner) changeEvent.getSource()).getValue(); update(); } }); valuePanel.add(sp); - + namePanel.add(new JLabel("Color")); - final JComboBox cb2 = new JComboBox(new String[] {"Red", "Green", "Blue", "Yellow"}); + final JComboBox cb2 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb2.setSelectedItem(currentInteriorColor); - cb2.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + cb2.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { currentInteriorColor = (String) ((JComboBox) actionEvent.getSource()).getSelectedItem(); update(); } }); valuePanel.add(cb2); - + namePanel.add(new JLabel("Border")); - final JComboBox cb5 = new JComboBox(new String[] {"None", "Solid"}); - cb5.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + final JComboBox cb5 = new JComboBox(new String[]{"None", "Solid"}); + cb5.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { currentBorderStyle = (String) cb5.getSelectedItem(); update(); } }); cb5.setSelectedItem("Solid"); valuePanel.add(cb5); - + namePanel.add(new JLabel("Border Width")); sp = new JSpinner(new SpinnerNumberModel(this.currentBorderWidth, 1d, 10d, 1d)); - sp.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { + sp.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent changeEvent) { currentBorderWidth = (Double) ((JSpinner) changeEvent.getSource()).getValue(); update(); } }); sp.setValue(currentBorderWidth); valuePanel.add(sp); - + namePanel.add(new JLabel("Border Color")); - JComboBox cb4 = new JComboBox(new String[] {"Red", "Green", "Blue", "Yellow"}); + JComboBox cb4 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb4.setSelectedItem(currentBorderColor); - cb4.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + cb4.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { currentBorderColor = (String) ((JComboBox) actionEvent.getSource()).getSelectedItem(); update(); } }); valuePanel.add(cb4); - + namePanel.add(new JLabel("Border Opacity")); sp = new JSpinner(new SpinnerNumberModel(this.currentBorderOpacity, 0, 10, 1)); - sp.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { + sp.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent changeEvent) { currentBorderOpacity = (Integer) ((JSpinner) changeEvent.getSource()).getValue(); update(); } }); valuePanel.add(sp); - + outerPanel.add(namePanel, BorderLayout.WEST); outerPanel.add(valuePanel, BorderLayout.CENTER); - + return outerPanel; } - - private void setupSelection() - { - this.wwjPanel.getWwd().addSelectListener(new SelectListener() - { + + private void setupSelection() { + this.wwjPanel.getWwd().addSelectListener(new SelectListener() { private WWIcon lastToolTipIcon = null; private BasicDragger dragger = new BasicDragger(AppFrame.this.wwjPanel.getWwd()); - - public void selected(SelectEvent event) - { + + public void selected(SelectEvent event) { // Have hover selections show a picked icon's tool tip. - if (event.getEventAction().equals(SelectEvent.HOVER)) - { + if (event.getEventAction().equals(SelectEvent.HOVER)) { // If a tool tip is already showing, undisplay it. - if (lastToolTipIcon != null) - { + if (lastToolTipIcon != null) { lastToolTipIcon.setShowToolTip(false); this.lastToolTipIcon = null; AppFrame.this.wwjPanel.getWwd().redraw(); } // If there's a selection, we're not dragging, and the selection is an icon, show tool tip. - if (event.hasObjects() && !this.dragger.isDragging()) - { - if (event.getTopObject() instanceof WWIcon) - { + if (event.hasObjects() && !this.dragger.isDragging()) { + if (event.getTopObject() instanceof WWIcon) { this.lastToolTipIcon = (WWIcon) event.getTopObject(); lastToolTipIcon.setShowToolTip(true); AppFrame.this.wwjPanel.getWwd().redraw(); } } - } - // Have rollover events highlight the rolled-over object. - else if (event.getEventAction().equals(SelectEvent.ROLLOVER) && !this.dragger.isDragging()) - { + } // Have rollover events highlight the rolled-over object. + else if (event.getEventAction().equals(SelectEvent.ROLLOVER) && !this.dragger.isDragging()) { // AppFrame.this.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)) - { + || event.getEventAction().equals(SelectEvent.DRAG)) { // Delegate dragging computations to a dragger. this.dragger.selected(event); // 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 = wwjPanel.getWwd().getObjectsAtCurrentPosition(); - if (pol != null) - { + if (pol != null) { // AppFrame.this.highlight(pol.getTopObject()); AppFrame.this.wwjPanel.getWwd().redraw(); } @@ -703,30 +634,24 @@ else if (event.getEventAction().equals(SelectEvent.DRAG_END) }); } } - + private static final String APP_NAME = "WorldWind Shapes"; - - static - { - if (Configuration.isMacOS()) - { + + static { + 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"); } } - - public static void main(String[] args) - { - try - { + + public static void main(String[] args) { + try { AppFrame frame = new AppFrame(); frame.setTitle(APP_NAME); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } diff --git a/src/org/codehaus/jackson/JsonGenerator.java b/src/org/codehaus/jackson/JsonGenerator.java index 8a15019d4f..6821aa250b 100644 --- a/src/org/codehaus/jackson/JsonGenerator.java +++ b/src/org/codehaus/jackson/JsonGenerator.java @@ -224,12 +224,14 @@ public JsonGenerator configure(Feature f, boolean state) * @deprecated Use {@link #enable} instead * @param f Undocumented. */ + @Deprecated public void enableFeature(Feature f) { enable(f); } /** * @deprecated Use {@link #disable} instead * @param f Undocumented. */ + @Deprecated public void disableFeature(Feature f) { disable(f); } /** @@ -237,6 +239,7 @@ public JsonGenerator configure(Feature f, boolean state) * @param f Undocumented. * @param state Undocumented. */ + @Deprecated public void setFeature(Feature f, boolean state) { configure(f, state); } /** @@ -244,6 +247,7 @@ public JsonGenerator configure(Feature f, boolean state) * @return Undocumented. * @deprecated Use {@link #isEnabled} instead */ + @Deprecated public boolean isFeatureEnabled(Feature f) { return isEnabled(f); } diff --git a/src/org/codehaus/jackson/JsonNode.java b/src/org/codehaus/jackson/JsonNode.java index 231c0b786c..b48bac39f1 100644 --- a/src/org/codehaus/jackson/JsonNode.java +++ b/src/org/codehaus/jackson/JsonNode.java @@ -384,6 +384,7 @@ public byte[] getBinaryValue() throws IOException * or org.codehaus.jackson.map.ObjectMapper * instead. */ + @Deprecated public abstract void writeTo(JsonGenerator jg) throws IOException, JsonGenerationException; diff --git a/src/org/codehaus/jackson/JsonParser.java b/src/org/codehaus/jackson/JsonParser.java index 0c070c7d16..dedc624767 100644 --- a/src/org/codehaus/jackson/JsonParser.java +++ b/src/org/codehaus/jackson/JsonParser.java @@ -362,25 +362,29 @@ public boolean isEnabled(Feature f) { * @param f Undocumented. * @param state Undocumented. */ + @Deprecated public void setFeature(Feature f, boolean state) { configure(f, state); } /** * @deprecated Use {@link #enable(Feature)} instead * @param f Undocumented. */ + @Deprecated public void enableFeature(Feature f) { enable(f); } /** * @param f Undocumented. * @deprecated Use {@link #disable(Feature)} instead */ - public void disableFeature(Feature f) { disable(f); } + @Deprecated + public void disableFeature(Feature f) { disable(f); } /** * @param f Undocumented. * @return Undocumented. * @deprecated Use {@link #isEnabled(Feature)} instead */ + @Deprecated public final boolean isFeatureEnabled(Feature f) { return isEnabled(f); } From 0f308c1a7fcfd02ae5db68b694ccd9c1c31cc47c Mon Sep 17 00:00:00 2001 From: markpet49 Date: Mon, 16 Sep 2019 16:55:25 -0500 Subject: [PATCH 02/11] Polyline deprecation fixes --- src/gov/nasa/worldwind/render/Path.java | 10 ++++------ src/gov/nasa/worldwindx/examples/Shapes.java | 2 +- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/gov/nasa/worldwind/render/Path.java b/src/gov/nasa/worldwind/render/Path.java index 561cad406d..13b0ebfa64 100644 --- a/src/gov/nasa/worldwind/render/Path.java +++ b/src/gov/nasa/worldwind/render/Path.java @@ -673,6 +673,7 @@ protected PathData getCurrentPathData() { protected String pathType = DEFAULT_PATH_TYPE; protected boolean followTerrain; // true if altitude mode indicates terrain following + protected double offset = 0; // offset to use in clamp to ground mode protected boolean extrude; protected double terrainConformance = DEFAULT_TERRAIN_CONFORMANCE; protected int numSubsegments = DEFAULT_NUM_SUBSEGMENTS; @@ -1608,7 +1609,7 @@ protected void computePath(DrawContext dc, List positions, PathData pa FloatBuffer path = pathData.renderedPath; if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) { - path = this.computePointsRelativeToTerrain(dc, positions, 0d, path, pathData); + path = this.computePointsRelativeToTerrain(dc, positions, offset, path, pathData); } else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) { path = this.computePointsRelativeToTerrain(dc, positions, null, path, pathData); } else { @@ -2588,11 +2589,8 @@ public void setLineWidth(double lineWidth) { * @param offset the path offset in meters. */ public void setOffset(double offset) { - ArrayList newPositions = new ArrayList<>(); - for (Position p : this.positions) { - newPositions.add(new Position(p, offset)); - } - this.setPositions(newPositions); + this.offset=offset; + this.reset(); } /** diff --git a/src/gov/nasa/worldwindx/examples/Shapes.java b/src/gov/nasa/worldwindx/examples/Shapes.java index 7f8f8d8a4c..952e1e6b09 100644 --- a/src/gov/nasa/worldwindx/examples/Shapes.java +++ b/src/gov/nasa/worldwindx/examples/Shapes.java @@ -211,7 +211,7 @@ private void update() { path.setLineWidth(currentPathWidth); path.setFollowTerrain(currentFollowTerrain); if (path.isFollowTerrain()) { - path.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); + path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); } else { path.setAltitudeMode(WorldWind.ABSOLUTE); } From a4ec23f991b2c64a969c22f3b73a8f784c7796c0 Mon Sep 17 00:00:00 2001 From: markpet49 Date: Mon, 16 Sep 2019 18:06:46 -0500 Subject: [PATCH 03/11] Polyline deprecation fixes --- src/gov/nasa/worldwind/render/Path.java | 123 ++----------- .../util/measure/LengthMeasurer.java | 37 ++-- src/gov/nasa/worldwindx/examples/Shapes.java | 171 +++++++++--------- 3 files changed, 126 insertions(+), 205 deletions(-) diff --git a/src/gov/nasa/worldwind/render/Path.java b/src/gov/nasa/worldwind/render/Path.java index 13b0ebfa64..0ef067fa48 100644 --- a/src/gov/nasa/worldwind/render/Path.java +++ b/src/gov/nasa/worldwind/render/Path.java @@ -143,27 +143,6 @@ public static interface PositionColors { Color getColor(Position position, int ordinal); } - /** - * Provides a concrete implementation of PositionColors that specifies a single color per position. Provided - * primarily to ease migration from {@link Polyline}. - */ - public class OneColorPositionColors implements PositionColors { - - Color color; - - OneColorPositionColors(Color color) { - this.color = color; - } - - /** - * {@inheritDoc} - */ - @Override - public Color getColor(Position position, int ordinal) { - return color; - } - } - /** * 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 @@ -769,7 +748,7 @@ public Path(Position posA, Position posB) { throw new IllegalArgumentException(message); } - List endPoints = new ArrayList(2); + List endPoints = new ArrayList<>(2); endPoints.add(posA); endPoints.add(posB); this.setPositions(endPoints); @@ -825,6 +804,7 @@ public void setPositions(Iterable positions) { this.positions = positions; this.computePositionCount(); this.positionsSpanDateline = LatLon.locationsCrossDateLine(this.positions); + this.measurer.setPositions(this.positions); this.reset(); } @@ -955,11 +935,11 @@ public void setNumSubsegments(int numSubsegments) { * @return the path's length in meters. */ public double getLength() { - Object foo = this.getCurrentPathData().getEntries(); //.iterator(); - System.out.println(foo); -// this.getCurrentPathData().getEntries() -// Iterator infos = this.positions.values().iterator(); - return 0; // infos.hasNext() ? this.measurer.getLength(infos.next().globe) : 0; + PathData data = this.getCurrentPathData(); + if (data != null && data.getGlobeStateKey() != null) { + return this.measurer.getLength(data.getGlobeStateKey().getGlobe()); + } + return 0; } public double getLength(Globe globe) { @@ -1102,6 +1082,7 @@ public void setShowPositionsThreshold(double showPositionsThreshold) { this.showPositionsThreshold = showPositionsThreshold; } + @Override public Sector getSector() { if (this.sector == null && this.positions != null) { this.sector = Sector.boundingSector(this.positions); @@ -1563,6 +1544,7 @@ protected void prepareToDrawPoints(DrawContext dc) { * * @param dc the current draw context. */ + @Override protected void doDrawInterior(DrawContext dc) { if (this.shouldUseVBOs(dc)) { int[] vboIds = this.getVboIds(dc); @@ -1867,8 +1849,8 @@ protected void makeTessellatedPositions(DrawContext dc, PathData pathData) { 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; + pathData.tessellatedPositions = new ArrayList<>(size); + pathData.tessellatedColors = (this.positionColors != null) ? new ArrayList<>(size) : null; } else { pathData.tessellatedPositions.clear(); @@ -1964,7 +1946,7 @@ protected void makePositions(DrawContext dc, PathData pathData) { // Mark where the split position is so a new line is started there during rendering. if (pathData.splitPositions == null) { - pathData.splitPositions = new ArrayList(1); + pathData.splitPositions = new ArrayList<>(1); } pathData.splitPositions.add(pathData.tessellatedPositions.size()); @@ -2347,6 +2329,7 @@ protected Extent computeExtent(PathData current) { return box; } + @Override public Extent getExtent(Globe globe, double verticalExaggeration) { // See if we've cached an extent associated with the globe. Extent extent = super.getExtent(globe, verticalExaggeration); @@ -2375,10 +2358,12 @@ public Extent getExtent(Globe globe, double verticalExaggeration) { * * @return the computed reference position. */ + @Override public Position getReferencePosition() { return this.numPositions < 1 ? null : this.positions.iterator().next(); // use the first position } + @Override protected void fillVBO(DrawContext dc) { PathData pathData = this.getCurrentPathData(); int numIds = this.isShowPositions() ? 3 : pathData.hasExtrusionPoints && this.isDrawVerticals() ? 2 : 1; @@ -2433,6 +2418,7 @@ public List intersect(Line line, Terrain terrain) throws Interrupt return null; } + @Override public void move(Position delta) { if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); @@ -2452,6 +2438,7 @@ public void move(Position delta) { this.moveTo(refPos.add(delta)); } + @Override public void moveTo(Position position) { if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); @@ -2546,83 +2533,13 @@ protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLS } /** - * Provided to ease the transition from Polyline - * - * @param color - */ - public void setColor(Color color) { - if (color == null) { - String msg = Logging.getMessage("nullValue.ColorIsNull"); - Logging.logger().severe(msg); - throw new IllegalArgumentException(msg); - } - - setPositionColors(new OneColorPositionColors(color)); - if (this.surfaceShape != null) { - ShapeAttributes attrs = this.surfaceShape.getAttributes(); - attrs.setOutlineMaterial(new Material(color)); - attrs.setOutlineOpacity(color.getAlpha() / 255.0); - attrs.setInteriorMaterial(attrs.getOutlineMaterial()); - attrs.setInteriorOpacity(attrs.getOutlineOpacity()); - } - - } - - /** - * Provided to ease the transition from Polyline - * - * @param lineWidth - */ - public void setLineWidth(double lineWidth) { - - this.activeAttributes.setOutlineWidth(lineWidth); - this.reset(); - if (this.surfaceShape != null) { - this.surfaceShape.getAttributes().setOutlineWidth(this.activeAttributes.getOutlineWidth()); - } - } - - /** - * Specifies an offset, in meters, to add to the path points when the path's follow-terrain attribute is true. See - * {@link #setFollowTerrain(boolean)}. Provided to ease the transition from Polyline + * Specifies an offset, in meters, to add to the path points when the path's altitude mode is + * {@link WorldWind.CLAMP_TO_GROUND}. See {@link #setAltitudeMode(int) }. * * @param offset the path offset in meters. */ public void setOffset(double offset) { - this.offset=offset; + this.offset = offset; this.reset(); } - - /** - * Sets the stipple pattern for specifying line types other than solid. See the OpenGL specification or programming - * guides for a description of this parameter. Stipple is also affected by the path's stipple factor, {@link - * #setStippleFactor(int)}. - * - * @param stipplePattern the stipple pattern. - */ - public void setStipplePattern(short stipplePattern) { - System.out.println("foo"); - -// this.stipplePattern = stipplePattern; -// if (this.surfaceShape != null) { -// this.surfaceShape.getAttributes().setOutlineStipplePattern(this.stipplePattern); -// } - } - - /** - * Sets the stipple factor for specifying line types other than solid. See the OpenGL specification or programming - * guides for a description of this parameter. Stipple is also affected by the path's stipple pattern, {@link - * #setStipplePattern(short)}. - * - * @param stippleFactor the stipple factor. - */ - public void setStippleFactor(int stippleFactor) { - System.out.println("foo"); -// this.stippleFactor = stippleFactor; -// -// if (this.surfaceShape != null) { -// this.surfaceShape.getAttributes().setOutlineStippleFactor(this.stippleFactor); -// } - } - } diff --git a/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java b/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java index b8a6ae0a19..2c5bdf1ce4 100644 --- a/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java +++ b/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java @@ -70,7 +70,7 @@ public void setPositions(ArrayList positions, double elevation throw new IllegalArgumentException(message); } - ArrayList newPositions = new ArrayList(); + ArrayList newPositions = new ArrayList<>(); for (LatLon pos : positions) { newPositions.add(new Position(pos, elevation)); } @@ -78,6 +78,20 @@ public void setPositions(ArrayList positions, double elevation setPositions(newPositions); } + public void setPositions(Iterable positions) { + if (positions == null) { + String message = Logging.getMessage("nullValue.PositionsListIsNull"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); + } + + ArrayList newPositions = new ArrayList<>(); + for (Position p:positions) { + newPositions.add(p); + } + setPositions(newPositions); + } + public void setPositions(ArrayList positions) { if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); @@ -170,7 +184,7 @@ public void setPathType(int pathType) { * @param pathType the type of path to measure. */ public void setPathType(String pathType) { - if (this.pathType != pathType) { + if (!this.pathType.equals(pathType)) { this.pathType = pathType; clearCachedValues(); } @@ -262,6 +276,7 @@ public void setLengthTerrainSamplingSteps(double steps) { * * @return the current path length or -1 if the position list is too short. */ + @Override public double getLength(Globe globe) { if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); @@ -308,20 +323,6 @@ protected double computeLength(Globe globe, boolean followTerrain) { return length; } -// // This tries not to use the globe.computePointFromPosition so as to report accurate length on flat globes -// // However, it shows significant deviations for east-west measurements. -// private double computeSegmentLengthLinearApprox(Globe globe, Position pos1, Position pos2) -// { -// // Cartesian distance approximation for short segments - only needs globe radius -// LatLon midPoint = LatLon.interpolate(.5, pos1, pos2); -// double radius = globe.getRadiusAt(midPoint); -// double cosLat = Math.cos(midPoint.getLatitude().radians); -// return new Vec4( -// (pos2.getLongitude().radians - pos1.getLongitude().radians) * radius * cosLat, -// (pos2.getLatitude().radians - pos1.getLatitude().radians) * radius, -// pos2.getElevation() - pos1.getElevation() -// ).getLength3(); // Meters -// } /** * Subdivide a list of positions so that no segment is longer then the provided maxLength. *

@@ -333,7 +334,7 @@ protected double computeLength(Globe globe, boolean followTerrain) { * @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 avkeyPathType 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. */ @@ -369,7 +370,7 @@ protected static ArrayList subdividePositions(Globe globe, return positions; } - ArrayList newPositions = new ArrayList(); + ArrayList newPositions = new ArrayList<>(); // Add first position Position pos1 = positions.get(start); if (followTerrain) { diff --git a/src/gov/nasa/worldwindx/examples/Shapes.java b/src/gov/nasa/worldwindx/examples/Shapes.java index 952e1e6b09..84dadfd96f 100644 --- a/src/gov/nasa/worldwindx/examples/Shapes.java +++ b/src/gov/nasa/worldwindx/examples/Shapes.java @@ -32,36 +32,36 @@ * @version $Id: Shapes.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class Shapes { - + private static class Info { - + private final Object object; private final String name; - + public Info(String name, Object object) { this.object = object; this.name = name; } } - + @SuppressWarnings("unchecked") protected static class AppFrame extends JFrame { - + private Dimension canvasSize = new Dimension(800, 600); private ApplicationTemplate.AppPanel wwjPanel; private RenderableLayer layer = new RenderableLayer(); private TextRenderer textRenderer = new TextRenderer(java.awt.Font.decode("Arial-Plain-13"), true, false); - + public AppFrame() { // Create the WorldWindow. this.wwjPanel = new ApplicationTemplate.AppPanel(this.canvasSize, true); this.wwjPanel.setPreferredSize(canvasSize); - + ApplicationTemplate.insertBeforePlacenames(this.wwjPanel.getWwd(), layer); - + JPanel shapesPanel = makeShapeSelectionPanel(); shapesPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - + JPanel attrsPanel = makeAttributesPanel(); attrsPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); @@ -71,7 +71,7 @@ public AppFrame() { JPanel p = new JPanel(new BorderLayout(6, 6)); p.add(attrsPanel, BorderLayout.CENTER); controlPanel.add(p, BorderLayout.SOUTH); - + this.getContentPane().add(wwjPanel, BorderLayout.CENTER); this.getContentPane().add(controlPanel, BorderLayout.WEST); this.pack(); @@ -85,13 +85,13 @@ public AppFrame() { int y = parentLocation.y + (parentSize.height - prefSize.height) / 2; this.setLocation(x, y); this.setResizable(true); - + wwjPanel.getWwd().addRenderingListener(new RenderingListener() { public void stageChanged(RenderingEvent event) { if (!event.getStage().equals(RenderingEvent.BEFORE_BUFFER_SWAP)) { return; } - + if (currentShape instanceof Path) { Path p = (Path) currentShape; String length = Double.toString(p.getLength()); @@ -105,9 +105,9 @@ public void stageChanged(RenderingEvent event) { // Enable dragging and other selection responses this.setupSelection(); } - + private Renderable currentShape; - + private String currentPathColor = "Yellow"; private int currentPathOpacity = 10; private double currentPathWidth = 1; @@ -117,36 +117,36 @@ public void stageChanged(RenderingEvent event) { private float currentOffset = 0; private int currentTerrainConformance = 10; private int currentNumSubsegments = 10; - + private String currentBorderColor = "Yellow"; private double currentBorderWidth = 1; private int currentBorderOpacity = 10; private String currentBorderStyle = "Solid"; - + private String currentInteriorColor = "Yellow"; private int currentInteriorOpacity = 10; private String currentInteriorStyle = "Solid"; - + private ArrayList onTerrainOnlyItems = new ArrayList<>(); private ArrayList offTerrainOnlyItems = new ArrayList<>(); - + private void update() { for (JComponent c : onTerrainOnlyItems) { c.setEnabled(currentFollowTerrain); } - + for (JComponent c : offTerrainOnlyItems) { c.setEnabled(!currentFollowTerrain); } - + if (this.currentShape instanceof SurfaceShape) { SurfaceShape shape = (SurfaceShape) currentShape; ShapeAttributes attr = shape.getAttributes(); - + if (attr == null) { attr = new BasicShapeAttributes(); } - + if (!currentBorderStyle.equals("None")) { float alpha = currentBorderOpacity >= 10 ? 1f : currentBorderOpacity <= 0 ? 0f : currentBorderOpacity / 10f; @@ -160,7 +160,7 @@ private void update() { } else if (currentBorderColor.equals("Blue")) { color = new Color(0f, 0f, 1f); } - + attr.setDrawOutline(true); attr.setOutlineMaterial(new Material(color)); attr.setOutlineOpacity(alpha); @@ -168,7 +168,7 @@ private void update() { } else { attr.setDrawOutline(false); } - + if (!currentInteriorStyle.equals("None")) { float alpha = currentInteriorOpacity >= 10 ? 1f : currentInteriorOpacity <= 0 ? 0f : currentInteriorOpacity / 10f; @@ -182,14 +182,14 @@ private void update() { } else if (currentInteriorColor.equals("Blue")) { color = new Color(0f, 0f, 1f); } - + attr.setInteriorMaterial(new Material(color)); attr.setInteriorOpacity(alpha); attr.setDrawInterior(true); } else { attr.setDrawInterior(false); } - + shape.setAttributes(attr); } else { float alpha = currentPathOpacity >= 10 ? 1f : currentPathOpacity <= 0 ? 0f @@ -204,11 +204,9 @@ private void update() { } else if (currentPathColor.equals("Blue")) { color = new Color(0f, 0f, 1f, alpha); } - + if (currentShape instanceof Path) { Path path = (Path) currentShape; - path.setColor(color); - path.setLineWidth(currentPathWidth); path.setFollowTerrain(currentFollowTerrain); if (path.isFollowTerrain()) { path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); @@ -217,7 +215,7 @@ private void update() { } path.setTerrainConformance(currentTerrainConformance); path.setNumSubsegments(currentNumSubsegments); - + if (currentPathType.equalsIgnoreCase("linear")) { path.setPathType(AVKey.LINEAR); } else if (currentPathType.equalsIgnoreCase("rhumb line")) { @@ -225,15 +223,20 @@ private void update() { } else { path.setPathType(AVKey.GREAT_CIRCLE); } - + path.setOffset(currentOffset); - + + BasicShapeAttributes attrs = new BasicShapeAttributes(); + attrs.setOutlineMaterial(new Material(color)); + attrs.setInteriorMaterial(new Material(color)); + attrs.setOutlineWidth(currentPathWidth); if (currentPathStyle.equals("Dash")) { - path.setStippleFactor(5); - path.setStipplePattern((short) 0xAAAA); + attrs.setOutlineStippleFactor(5); + attrs.setOutlineStipplePattern((short) 0xAAAA); } else { - path.setStippleFactor(0); // solid + attrs.setOutlineStippleFactor(0); } + path.setAttributes(attrs); } } this.layer.removeAllRenderables(); @@ -242,10 +245,10 @@ private void update() { } this.wwjPanel.getWwd().redraw(); } - + private Info[] buildSurfaceShapes() { LatLon position = new LatLon(Angle.fromDegrees(38), Angle.fromDegrees(-105)); - + ArrayList surfaceLinePositions = new ArrayList<>(); // surfaceLinePositions.add(LatLon.fromDegrees(37.8484, -119.9754)); // surfaceLinePositions.add(LatLon.fromDegrees(38.3540, -119.1526)); @@ -256,7 +259,7 @@ private Info[] buildSurfaceShapes() { surfaceLinePositions.add(LatLon.fromDegrees(39, -104)); surfaceLinePositions.add(LatLon.fromDegrees(39, -105)); surfaceLinePositions.add(position); - + return new Info[]{ new Info("Circle", new SurfaceCircle(position, 100e3)), new Info("Ellipse", new SurfaceEllipse(position, 100e3, 90e3, Angle.ZERO)), @@ -265,33 +268,33 @@ private Info[] buildSurfaceShapes() { new Info("Sector", new SurfaceSector(Sector.fromDegrees(38, 40, -105, -103))), new Info("Polygon", new SurfacePolygon(surfaceLinePositions)),}; } - + private Info[] buildFreeShapes() { double elevation = 10e3; ArrayList positions = new ArrayList<>(); positions.add(new Position(Angle.fromDegrees(37.8484), Angle.fromDegrees(-119.9754), elevation)); positions.add(new Position(Angle.fromDegrees(39.3540), Angle.fromDegrees(-110.1526), elevation)); positions.add(new Position(Angle.fromDegrees(38.3540), Angle.fromDegrees(-100.1526), elevation)); - + ArrayList positions2 = new ArrayList<>(); positions2.add(new Position(Angle.fromDegrees(0), Angle.fromDegrees(-150), elevation)); positions2.add(new Position(Angle.fromDegrees(25), Angle.fromDegrees(-75), elevation)); positions2.add(new Position(Angle.fromDegrees(50), Angle.fromDegrees(0), elevation)); - + ArrayList positions3 = new ArrayList<>(); for (double lat = 42, lon = -100; lat <= 45; lat += .1, lon += .1) { positions3.add(new Position(Angle.fromDegrees(lat), Angle.fromDegrees(lon), elevation)); } - + ArrayList positions4 = new ArrayList<>(); positions4.add(new Position(Angle.fromDegrees(90), Angle.fromDegrees(-110), elevation)); positions4.add(new Position(Angle.fromDegrees(-90), Angle.fromDegrees(-110), elevation)); - + ArrayList positions5 = new ArrayList<>(); for (int i = 0; i < 100; i++) { positions5.add(Position.fromDegrees(38.0 + i * 0.0001, 30.0 + i * 0.0001, 1000.0 + i * 5.0)); } - + @SuppressWarnings({"UnnecessaryLocalVariable"}) Info[] infos = new Info[]{ new Info("Short Path", new Path(positions)), @@ -302,10 +305,10 @@ private Info[] buildFreeShapes() { new Info("Quad", new Quadrilateral(Sector.fromDegrees(38, 40, -104, -105), elevation)), new Info("None", null) }; - + return infos; } - + private JPanel makeShapeSelectionPanel() { final Info[] surfaceShapeInfos = this.buildSurfaceShapes(); GridLayout layout = new GridLayout(surfaceShapeInfos.length, 1); @@ -327,7 +330,7 @@ public void actionPerformed(ActionEvent actionEvent) { } } ssPanel.setBorder(this.createTitleBorder("Surface Shapes")); - + final Info[] freeShapeInfos = this.buildFreeShapes(); layout = new GridLayout(freeShapeInfos.length, 1); JPanel fsPanel = new JPanel(layout); @@ -346,38 +349,38 @@ public void actionPerformed(ActionEvent actionEvent) { } } fsPanel.setBorder(this.createTitleBorder("Path Shapes")); - + JPanel shapesPanel = new JPanel(new GridLayout(1, 2, 8, 1)); shapesPanel.add(fsPanel); shapesPanel.add(ssPanel); - + return shapesPanel; } - + private Border createTitleBorder(String title) { TitledBorder b = BorderFactory.createTitledBorder(title); // b.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); return new CompoundBorder(b, BorderFactory.createEmptyBorder(10, 10, 10, 10)); } - + private JPanel makeAttributesPanel() { JPanel panel = new JPanel(new GridLayout(1, 2, 8, 8)); panel.add(this.makePathAttributesPanel()); panel.add(this.makeInteriorAttributesPanel()); - + return panel; } - + private JPanel makePathAttributesPanel() { JPanel outerPanel = new JPanel(new BorderLayout(6, 6)); outerPanel.setBorder(this.createTitleBorder("Path Attributes")); - + GridLayout nameLayout = new GridLayout(0, 1, 6, 6); JPanel namePanel = new JPanel(nameLayout); - + GridLayout valueLayout = new GridLayout(0, 1, 6, 6); JPanel valuePanel = new JPanel(valueLayout); - + namePanel.add(new JLabel("Follow Terrain")); JCheckBox ckb = new JCheckBox(); ckb.setSelected(currentFollowTerrain); @@ -388,9 +391,9 @@ public void actionPerformed(ActionEvent actionEvent) { } }); valuePanel.add(ckb); - + JLabel label; - + namePanel.add(label = new JLabel("Conformance")); int[] values = new int[]{1, 2, 4, 8, 10, 15, 20, 30, 40, 50}; String[] strings = new String[values.length]; @@ -410,7 +413,7 @@ public void stateChanged(ChangeEvent changeEvent) { }); sp.setValue(Integer.toString(currentTerrainConformance) + " pixels"); valuePanel.add(sp); - + namePanel.add(label = new JLabel("Subsegments")); sp = new JSpinner(new SpinnerListModel(new String[]{"1", "2", "5", "10", "20", "40", "50"})); offTerrainOnlyItems.add(label); @@ -424,7 +427,7 @@ public void stateChanged(ChangeEvent changeEvent) { }); sp.setValue(Integer.toString(currentNumSubsegments)); valuePanel.add(sp); - + namePanel.add(new JLabel("Type")); final JComboBox cb = new JComboBox(new String[]{"Great Circle", "Linear", "Rhumb Line"}); cb.addActionListener(new ActionListener() { @@ -435,7 +438,7 @@ public void actionPerformed(ActionEvent actionEvent) { }); cb.setSelectedItem("Great Circle"); valuePanel.add(cb); - + namePanel.add(new JLabel("Style")); final JComboBox cb1 = new JComboBox(new String[]{"None", "Solid", "Dash"}); cb1.addActionListener(new ActionListener() { @@ -446,7 +449,7 @@ public void actionPerformed(ActionEvent actionEvent) { }); cb1.setSelectedItem("Solid"); valuePanel.add(cb1); - + namePanel.add(new JLabel("Width")); sp = new JSpinner(new SpinnerNumberModel(this.currentPathWidth, 1d, 10d, 1d)); sp.addChangeListener(new ChangeListener() { @@ -457,7 +460,7 @@ public void stateChanged(ChangeEvent changeEvent) { }); sp.setValue(currentPathWidth); valuePanel.add(sp); - + namePanel.add(new JLabel("Color")); JComboBox cb2 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb2.setSelectedItem(currentPathColor); @@ -468,7 +471,7 @@ public void actionPerformed(ActionEvent actionEvent) { } }); valuePanel.add(cb2); - + namePanel.add(new JLabel("Opacity")); sp = new JSpinner(new SpinnerNumberModel(this.currentPathOpacity, 0, 10, 1)); sp.addChangeListener(new ChangeListener() { @@ -478,7 +481,7 @@ public void stateChanged(ChangeEvent changeEvent) { } }); valuePanel.add(sp); - + namePanel.add(new JLabel("Offset")); sp = new JSpinner( new SpinnerListModel(new String[]{"0", "10", "100", "1000", "10000", "100000", "1000000"})); @@ -490,23 +493,23 @@ public void stateChanged(ChangeEvent changeEvent) { }); sp.setValue("0"); valuePanel.add(sp); - + outerPanel.add(namePanel, BorderLayout.WEST); outerPanel.add(valuePanel, BorderLayout.CENTER); - + return outerPanel; } - + private JPanel makeInteriorAttributesPanel() { JPanel outerPanel = new JPanel(new BorderLayout(6, 6)); outerPanel.setBorder(this.createTitleBorder("Surface Attributes")); - + GridLayout nameLayout = new GridLayout(0, 1, 6, 6); JPanel namePanel = new JPanel(nameLayout); - + GridLayout valueLayout = new GridLayout(0, 1, 6, 6); JPanel valuePanel = new JPanel(valueLayout); - + namePanel.add(new JLabel("Style")); final JComboBox cb1 = new JComboBox(new String[]{"None", "Solid"}); cb1.addActionListener(new ActionListener() { @@ -517,7 +520,7 @@ public void actionPerformed(ActionEvent actionEvent) { }); cb1.setSelectedItem("Solid"); valuePanel.add(cb1); - + namePanel.add(new JLabel("Opacity")); JSpinner sp = new JSpinner(new SpinnerNumberModel(this.currentBorderOpacity, 0, 10, 1)); sp.addChangeListener(new ChangeListener() { @@ -527,7 +530,7 @@ public void stateChanged(ChangeEvent changeEvent) { } }); valuePanel.add(sp); - + namePanel.add(new JLabel("Color")); final JComboBox cb2 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb2.setSelectedItem(currentInteriorColor); @@ -538,7 +541,7 @@ public void actionPerformed(ActionEvent actionEvent) { } }); valuePanel.add(cb2); - + namePanel.add(new JLabel("Border")); final JComboBox cb5 = new JComboBox(new String[]{"None", "Solid"}); cb5.addActionListener(new ActionListener() { @@ -549,7 +552,7 @@ public void actionPerformed(ActionEvent actionEvent) { }); cb5.setSelectedItem("Solid"); valuePanel.add(cb5); - + namePanel.add(new JLabel("Border Width")); sp = new JSpinner(new SpinnerNumberModel(this.currentBorderWidth, 1d, 10d, 1d)); sp.addChangeListener(new ChangeListener() { @@ -560,7 +563,7 @@ public void stateChanged(ChangeEvent changeEvent) { }); sp.setValue(currentBorderWidth); valuePanel.add(sp); - + namePanel.add(new JLabel("Border Color")); JComboBox cb4 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb4.setSelectedItem(currentBorderColor); @@ -571,7 +574,7 @@ public void actionPerformed(ActionEvent actionEvent) { } }); valuePanel.add(cb4); - + namePanel.add(new JLabel("Border Opacity")); sp = new JSpinner(new SpinnerNumberModel(this.currentBorderOpacity, 0, 10, 1)); sp.addChangeListener(new ChangeListener() { @@ -581,18 +584,18 @@ public void stateChanged(ChangeEvent changeEvent) { } }); valuePanel.add(sp); - + outerPanel.add(namePanel, BorderLayout.WEST); outerPanel.add(valuePanel, BorderLayout.CENTER); - + return outerPanel; } - + private void setupSelection() { this.wwjPanel.getWwd().addSelectListener(new SelectListener() { private WWIcon lastToolTipIcon = null; private BasicDragger dragger = new BasicDragger(AppFrame.this.wwjPanel.getWwd()); - + public void selected(SelectEvent event) { // Have hover selections show a picked icon's tool tip. if (event.getEventAction().equals(SelectEvent.HOVER)) { @@ -634,9 +637,9 @@ else if (event.getEventAction().equals(SelectEvent.DRAG_END) }); } } - + private static final String APP_NAME = "WorldWind Shapes"; - + static { if (Configuration.isMacOS()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); @@ -644,7 +647,7 @@ else if (event.getEventAction().equals(SelectEvent.DRAG_END) System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); } } - + public static void main(String[] args) { try { AppFrame frame = new AppFrame(); From 444c2fc10fe36429cf789760319d8000b18aae84 Mon Sep 17 00:00:00 2001 From: markpet49 Date: Wed, 18 Sep 2019 15:23:35 -0500 Subject: [PATCH 04/11] Deprecation fixes --- .../formats/georss/GeoRSSParser.java | 365 ++-- src/gov/nasa/worldwind/globes/FlatGlobe.java | 1 + .../nasa/worldwind/layers/AirspaceLayer.java | 27 + .../worldwind/layers/TerrainProfileLayer.java | 912 +++++----- .../layers/placename/PlaceNameLayer.java | 2 + .../nasa/worldwind/render/AbstractShape.java | 2 +- .../nasa/worldwind/render/ContourLine.java | 220 +-- src/gov/nasa/worldwind/render/Path.java | 22 + .../render/airspaces/AirspaceAttributes.java | 6 + .../airspaces/BasicAirspaceAttributes.java | 6 + .../terrain/HighResolutionTerrain.java | 1 + src/gov/nasa/worldwind/util/BasicDragger.java | 3 + .../util/measure/LengthMeasurer.java | 25 +- .../worldwind/util/measure/MeasureTool.java | 1537 ++++++++--------- .../view/BasicViewPropertyLimits.java | 7 + .../view/orbit/BasicOrbitViewLimits.java | 9 +- .../applications/glider/GliderImageLayer.java | 166 +- .../applications/sar/TerrainProfilePanel.java | 510 +++--- .../applications/sar/TrackController.java | 338 ++-- .../applications/sar/render/PlaneModel.java | 103 +- .../worldwindow/core/SimpleImporter.java | 93 +- .../features/MeasurementPanel.java | 287 ++- .../util/measuretool/WWOMeasureTool.java | 681 +++----- .../examples/ContextMenusOnShapes.java | 2 +- .../examples/KeepingObjectsInView.java | 260 ++- .../worldwindx/examples/LineBackground.java | 71 +- .../nasa/worldwindx/examples/LineBuilder.java | 282 ++- .../worldwindx/examples/MeasureToolPanel.java | 2 +- .../worldwindx/examples/MultiResPath.java | 2 +- src/gov/nasa/worldwindx/examples/Shapes.java | 259 ++- .../worldwindx/examples/SurfaceImages.java | 63 +- .../examples/util/ShapefileLoader.java | 1 + src/org/codehaus/jackson/JsonFactory.java | 8 + .../codehaus/jackson/annotate/JsonClass.java | 1 + .../jackson/annotate/JsonContentClass.java | 1 + .../codehaus/jackson/annotate/JsonGetter.java | 1 + .../jackson/annotate/JsonKeyClass.java | 1 + .../codehaus/jackson/annotate/JsonSetter.java | 1 + 38 files changed, 2805 insertions(+), 3473 deletions(-) diff --git a/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java b/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java index 6abc170a25..db2dbab4a5 100644 --- a/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java +++ b/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java @@ -5,6 +5,7 @@ */ package gov.nasa.worldwind.formats.georss; +import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.exception.WWRuntimeException; import gov.nasa.worldwind.geom.*; import gov.nasa.worldwind.render.*; @@ -22,31 +23,27 @@ * @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 + if (docString.length() < 1) { // avoid empty strings return null; + } - try - { + try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); @@ -54,56 +51,41 @@ 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) - { - String message = Logging.getMessage("GeoRSS.IOExceptionParsing", docString); - Logging.logger().log(Level.SEVERE, message, e); - throw new WWRuntimeException(message, e); - } - catch (SAXException e) - { + } catch (IOException | 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) - { - StringBuffer sb = new StringBuffer(); + if (qualifiers.length() > 0) { + StringBuilder sb = new StringBuilder(); sb.append(""); @@ -116,35 +98,14 @@ private static String fixNamespaceQualification(String xmlString) return xmlString; } - private static String surroundWithNameSpaces(String docString) - { - StringBuffer sb = new StringBuffer(); - sb.append(""); - sb.append(docString); - sb.append(""); -// System.out.println(sb.toString()); - - return sb.toString(); - } - - public static List 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,150 +113,147 @@ 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) - { - String message = Logging.getMessage("GeoRSS.IOExceptionParsing", file.getPath()); - Logging.logger().log(Level.SEVERE, message, e); - throw new WWRuntimeException(message, e); - } - catch (SAXException e) - { + } catch (IOException | 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); } - ArrayList shapeNodes = new ArrayList(); - ArrayList attributeNodes = new ArrayList(); + ArrayList shapeNodes = new ArrayList<>(); + ArrayList attributeNodes = new ArrayList<>(); // 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(); + 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")) - shape = makePointShape(node, attributeNodes); - - else if (localName.equals("where")) - shape = makeWhereShape(node); - - else if (localName.equals("line")) - shape = makeLineShape(node, attributeNodes); - - else if (localName.equals("polygon")) - shape = makePolygonShape(node, attributeNodes); - - else if (localName.equals("box")) - shape = makeBoxShape(node, attributeNodes); + switch (localName) { + case "point": + shape = makePointShape(node, attributeNodes); + break; + case "where": + shape = makeWhereShape(node); + break; + case "line": + shape = makeLineShape(node, attributeNodes); + break; + case "polygon": + shape = makePolygonShape(node, attributeNodes); + break; + case "box": + shape = makeBoxShape(node, attributeNodes); + break; + default: + break; + } - 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 +261,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) - { - Polyline pl = new Polyline(positions, elevation); - pl.setFilled(true); - pl.setPathType(Polyline.GREAT_CIRCLE); + if (elevation != 0) { + Path path = new Path(positions, elevation); + path.setAttributes(new BasicShapeAttributes()); + path.setPathType(AVKey.GREAT_CIRCLE); - return pl; - } - else - { + return path; + } 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 +331,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 +363,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) - { + ArrayList positions = new ArrayList<>(); + 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) - { - Polyline pl = new Polyline(positions, elevation); - pl.setPathType(Polyline.GREAT_CIRCLE); - return pl; - } - else - { - return new Polyline(positions, 0); + if (elevation != 0) { + Path path = new Path(positions, elevation); + path.setPathType(AVKey.GREAT_CIRCLE); + return path; + } else { + return new Path(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) + ArrayList arl = new ArrayList<>(); + 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 +457,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/globes/FlatGlobe.java b/src/gov/nasa/worldwind/globes/FlatGlobe.java index 65dadb11fd..ba887d6fa2 100644 --- a/src/gov/nasa/worldwind/globes/FlatGlobe.java +++ b/src/gov/nasa/worldwind/globes/FlatGlobe.java @@ -142,6 +142,7 @@ public GlobeStateKey getGlobeStateKey() * * @deprecated Use {@link #setProjection(GeographicProjection)}. */ + @Deprecated public void setProjection(String projection) { if (projection == null) diff --git a/src/gov/nasa/worldwind/layers/AirspaceLayer.java b/src/gov/nasa/worldwind/layers/AirspaceLayer.java index 2bba0a9536..d9eb1a30d0 100644 --- a/src/gov/nasa/worldwind/layers/AirspaceLayer.java +++ b/src/gov/nasa/worldwind/layers/AirspaceLayer.java @@ -19,6 +19,7 @@ * @version $Id: AirspaceLayer.java 2231 2014-08-15 19:03:12Z dcollins $ * @deprecated Use {@link RenderableLayer} instead. */ +@Deprecated public class AirspaceLayer extends AbstractLayer { private final java.util.Collection airspaces = new java.util.concurrent.ConcurrentLinkedQueue(); @@ -40,6 +41,7 @@ public AirspaceLayer() * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#addRenderable(gov.nasa.worldwind.render.Renderable)} * instead. */ + @Deprecated public void addAirspace(Airspace airspace) { if (airspace == null) @@ -69,6 +71,7 @@ public void addAirspace(Airspace airspace) * @throws IllegalStateException if a custom Iterable has been specified by a call to setRenderables. * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#addRenderables(Iterable)} instead. */ + @Deprecated public void addAirspaces(Iterable airspaces) { if (airspaces == null) @@ -104,6 +107,7 @@ public void addAirspaces(Iterable airspaces) * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#removeRenderable(gov.nasa.worldwind.render.Renderable)} * instead. */ + @Deprecated public void removeAirspace(Airspace airspace) { if (airspace == null) @@ -129,6 +133,7 @@ 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. */ + @Deprecated public void removeAllAirspaces() { if (this.airspacesOverride != null) @@ -157,6 +162,7 @@ private void clearAirspaces() * * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#getRenderables()} instead. */ + @Deprecated public Iterable getAirspaces() { if (this.airspacesOverride != null) @@ -204,6 +210,7 @@ private Iterable getActiveAirspaces() * * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#setRenderables(Iterable)} instead. */ + @Deprecated public void setAirspaces(Iterable airspaceIterable) { this.airspacesOverride = airspaceIterable; @@ -219,6 +226,7 @@ public void setAirspaces(Iterable airspaceIterable) * @deprecated Use {@link gov.nasa.worldwind.render.ShapeAttributes#isEnableAntialiasing()} on each Airspace * instance in the layer. */ + @Deprecated public boolean isEnableAntialiasing() { return false; // deprecated method @@ -232,6 +240,7 @@ public boolean isEnableAntialiasing() * @deprecated Use {@link gov.nasa.worldwind.render.ShapeAttributes#setEnableAntialiasing(boolean)} on each Airspace * instance in the layer. */ + @Deprecated public void setEnableAntialiasing(boolean enable) { // deprecated method @@ -245,6 +254,7 @@ public void setEnableAntialiasing(boolean enable) * @deprecated Control over airspace blending is no longer supported. Airspaces implicitly blend themselves with * other objects in the scene. */ + @Deprecated public boolean isEnableBlending() { return false; // deprecated method @@ -258,6 +268,7 @@ public boolean isEnableBlending() * @deprecated Control over airspace blending is no longer supported. Airspaces implicitly blend themselves with * other objects in the scene. */ + @Deprecated public void setEnableBlending(boolean enable) { // deprecated method @@ -271,6 +282,7 @@ public void setEnableBlending(boolean enable) * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#isEnableDepthOffset()} on each Airspace * instance in the layer. */ + @Deprecated public boolean isEnableDepthOffset() { return false; // deprecated method @@ -284,6 +296,7 @@ public boolean isEnableDepthOffset() * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#setEnableDepthOffset(boolean)} on each * Airspace instance in the layer. */ + @Deprecated public void setEnableDepthOffset(boolean enable) { // deprecated method @@ -297,6 +310,7 @@ public void setEnableDepthOffset(boolean enable) * @deprecated Use {@link gov.nasa.worldwind.render.ShapeAttributes#isEnableLighting()} on each Airspace instance in * the layer. */ + @Deprecated public boolean isEnableLighting() { return false; // deprecated method @@ -310,6 +324,7 @@ public boolean isEnableLighting() * @deprecated Use {@link gov.nasa.worldwind.render.ShapeAttributes#isEnableLighting()} on each Airspace instance in * the layer. */ + @Deprecated public void setEnableLighting(boolean enable) { // deprecated method @@ -322,6 +337,7 @@ public void setEnableLighting(boolean enable) * * @deprecated Control over drawing Airspace extents is no longer supported. */ + @Deprecated public boolean isDrawExtents() { return false; // deprecated method @@ -334,6 +350,7 @@ public boolean isDrawExtents() * * @deprecated Control over drawing Airspace extents is no longer supported. */ + @Deprecated public void setDrawExtents(boolean draw) { // deprecated method @@ -346,6 +363,7 @@ public void setDrawExtents(boolean draw) * * @deprecated Control over drawing Airspace in wireframe mode is no longer supported. */ + @Deprecated public boolean isDrawWireframe() { return false; // deprecated method @@ -358,6 +376,7 @@ public boolean isDrawWireframe() * * @deprecated Control over drawing Airspace in wireframe mode is no longer supported. */ + @Deprecated public void setDrawWireframe(boolean draw) { // deprecated method @@ -371,6 +390,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)}. */ + @Deprecated public Double getDepthOffsetFactor() { return 0d; // deprecated method @@ -384,6 +404,7 @@ public Double getDepthOffsetFactor() * @deprecated Control over Airspace depth factor is no longer supported. See {@link * gov.nasa.worldwind.render.airspaces.Airspace#setEnableDepthOffset(boolean)}. */ + @Deprecated public void setDepthOffsetFactor(Double factor) { // deprecated method @@ -397,6 +418,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)}. */ + @Deprecated public Double getDepthOffsetUnits() { return 0d; // deprecated method @@ -410,6 +432,7 @@ public Double getDepthOffsetUnits() * @deprecated Control over Airspace depth units is no longer supported. See {@link * gov.nasa.worldwind.render.airspaces.Airspace#setEnableDepthOffset(boolean)}. */ + @Deprecated public void setDepthOffsetUnits(Double units) { // deprecated method @@ -423,6 +446,7 @@ public void setDepthOffsetUnits(Double units) * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#isEnableBatchRendering()} on each Airspace * instance in the layer. */ + @Deprecated public boolean isEnableBatchRendering() { return false; // deprecated method @@ -436,6 +460,7 @@ public boolean isEnableBatchRendering() * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#setEnableBatchRendering(boolean)} on each * Airspace instance in the layer. */ + @Deprecated public void setEnableBatchRendering(boolean enableBatchRendering) { // deprecated method @@ -449,6 +474,7 @@ public void setEnableBatchRendering(boolean enableBatchRendering) * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#isEnableBatchPicking()} on each Airspace * instance in the layer. */ + @Deprecated public boolean isEnableBatchPicking() { return false; // deprecated method @@ -462,6 +488,7 @@ public boolean isEnableBatchPicking() * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#setEnableBatchPicking(boolean)} on each * Airspace instance in the layer. */ + @Deprecated public void setEnableBatchPicking(boolean enableBatchPicking) { // deprecated method diff --git a/src/gov/nasa/worldwind/layers/TerrainProfileLayer.java b/src/gov/nasa/worldwind/layers/TerrainProfileLayer.java index b76a337c3a..9a2385f8f2 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"; @@ -68,8 +69,8 @@ public class TerrainProfileLayer extends AbstractLayer implements PositionListen protected boolean showPickedLine = true; // True to show the picked position line on the terrain protected int pickedSample = -1; // Picked sample number if not -1 - Polyline selectionShape; // Shape showing section on the ground - Polyline pickedShape; // Shape showing actual pick position on the ground + Path selectionShape; // Shape showing section on the ground + Path pickedShape; // Shape showing actual pick position on the ground protected boolean keepProportions = false; // Keep graph distance/elevation proportions protected boolean zeroBased = true; // Pad graph elevation scale to include sea level if true protected String follow = FOLLOW_VIEW; // Profile position follow behavior @@ -80,7 +81,7 @@ public class TerrainProfileLayer extends AbstractLayer implements PositionListen protected Position objectPosition; // Object position if FOLLOW_OBJECT protected Angle objectHeading; // Object heading if FOLLOW_OBJECT protected ArrayList pathPositions; // Path position list if FOLLOW_PATH - protected int pathType = Polyline.GREAT_CIRCLE; + protected String pathType = AVKey.GREAT_CIRCLE; // Terrain profile data protected int samples = 250; // Number of position samples @@ -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); @@ -679,22 +623,59 @@ public void setPathPositions(ArrayList positions) this.pathPositions = positions; } - @SuppressWarnings({"UnusedDeclaration"}) - public int getPathType() - { + @Deprecated + public int getPathType() { + switch (pathType) { + case AVKey.LINEAR: + return Polyline.LINEAR; + case AVKey.RHUMB_LINE: + return Polyline.RHUMB_LINE; + case AVKey.GREAT_CIRCLE: + return Polyline.GREAT_CIRCLE; + default: + String message = Logging.getMessage("generic.ArgumentOutOfRange"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); + } + } + + public String getAVKeyPathType() { return this.pathType; } /** - * Sets the type of path to follow, one of {@link Polyline#GREAT_CIRCLE}, which computes each segment of the path as - * a great circle, or {@link Polyline#RHUMB_LINE}, which computes each segment of the path as a line of constant - * heading. + * Sets the type of path to follow, one of {@link AVKey#GREAT_CIRCLE}, which computes each segment of the path as a + * great circle, or {@link AVKey#RHUMB_LINE}, which computes each segment of the path as a line of constant heading. * - * @param type the type of path to follow. + * @param pathType the type of path to follow. */ - public void setPathType(int type) - { - this.pathType = type; + @Deprecated + public void setPathType(int pathType) { + switch (pathType) { + case Polyline.LINEAR: + this.pathType = AVKey.LINEAR; + break; + case Polyline.RHUMB_LINE: + this.pathType = AVKey.RHUMB_LINE; + break; + case Polyline.GREAT_CIRCLE: + this.pathType = AVKey.GREAT_CIRCLE; + break; + default: + String message = Logging.getMessage("generic.ArgumentOutOfRange"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); + } + } + + /** + * Sets the type of path to follow, one of {@link AVKey#GREAT_CIRCLE}, which computes each segment of the path as a + * great circle, or {@link AVKey#RHUMB_LINE}, which computes each segment of the path as a line of constant heading. + * + * @param pathType the type of path to follow. + */ + public void setPathType(String pathType) { + this.pathType = pathType; } /** @@ -703,8 +684,7 @@ public void setPathType(int type) * @return the Polyline used to render the profile line on the ground. */ @SuppressWarnings({"UnusedDeclaration"}) - public Polyline getProfileLine() - { + public Path getProfileLine() { return this.selectionShape; } @@ -714,8 +694,7 @@ public Polyline getProfileLine() * @return the Polyline used to render the picked position on the terrain. */ @SuppressWarnings({"UnusedDeclaration"}) - public Polyline getPickedLine() - { + public Path getPickedLine() { return this.selectionShape; } @@ -725,8 +704,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 +713,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 +723,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 +733,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 +793,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 +809,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 +836,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 +893,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 +926,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 +958,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 +971,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 +979,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 +1100,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 +1138,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 +1148,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 +1173,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 +1237,44 @@ 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) - { - 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 + positions[sample].getElevation() + this.length / 10)); + if (this.pickedShape == null) { + this.pickedShape = new Path(posList); + this.pickedShape.setPathType(AVKey.LINEAR); + var attrs = new BasicShapeAttributes(); + attrs.setOutlineWidth(2); + attrs.setOutlineMaterial(new Material(new Color(this.color.getRed(), + this.color.getGreen(), (int) (this.color.getBlue() * .8), (int) (255 * .8)))); + this.pickedShape.setAttributes(attrs); + } else { this.pickedShape.setPositions(posList); + } } } } @@ -1368,18 +1288,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 +1306,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 +1328,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 +1378,125 @@ 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) - { - this.selectionShape = new Polyline(Arrays.asList(this.positions)); - this.selectionShape.setLineWidth(2); + if (this.selectionShape == null) { + this.selectionShape = new Path(Arrays.asList(this.positions)); this.selectionShape.setFollowTerrain(true); - this.selectionShape.setColor(new Color(this.color.getRed(), - this.color.getGreen(), (int) (this.color.getBlue() * .5), (int) (255 * .8))); - } - else + var attrs = new BasicShapeAttributes(); + attrs.setOutlineWidth(2); + attrs.setOutlineMaterial(new Material(new Color(this.color.getRed(), + this.color.getGreen(), (int) (this.color.getBlue() * .5), (int) (255 * .8)))); + this.selectionShape.setAttributes(attrs); + } 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 +1504,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 +1514,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.equals(AVKey.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.equals(AVKey.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 +1544,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 +1583,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/placename/PlaceNameLayer.java b/src/gov/nasa/worldwind/layers/placename/PlaceNameLayer.java index 5db0ca0294..e30ce796a6 100644 --- a/src/gov/nasa/worldwind/layers/placename/PlaceNameLayer.java +++ b/src/gov/nasa/worldwind/layers/placename/PlaceNameLayer.java @@ -105,6 +105,7 @@ public PlaceNameLayer(PlaceNameServiceSet placeNameServiceSet) * * @deprecated This flag no longer has any effect. Placenames participate in global decluttering. */ + @Deprecated public boolean isCullNames() { return cullNames; @@ -115,6 +116,7 @@ public boolean isCullNames() * * @deprecated This flag no longer has any effect. Placenames participate in global decluttering. */ + @Deprecated public void setCullNames(boolean cullNames) { this.cullNames = cullNames; diff --git a/src/gov/nasa/worldwind/render/AbstractShape.java b/src/gov/nasa/worldwind/render/AbstractShape.java index 129f77caa8..4a6ba136ff 100644 --- a/src/gov/nasa/worldwind/render/AbstractShape.java +++ b/src/gov/nasa/worldwind/render/AbstractShape.java @@ -1218,7 +1218,7 @@ protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidate * * @deprecated Use the more general {@link #createPickedObject(int)} instead. */ - @SuppressWarnings({"UnusedParameters"}) + @Deprecated protected PickedObject createPickedObject(DrawContext dc, Color pickColor) { return this.createPickedObject(pickColor.getRGB()); diff --git a/src/gov/nasa/worldwind/render/ContourLine.java b/src/gov/nasa/worldwind/render/ContourLine.java index 864e7f25f2..568b8a5ae9 100644 --- a/src/gov/nasa/worldwind/render/ContourLine.java +++ b/src/gov/nasa/worldwind/render/ContourLine.java @@ -20,14 +20,14 @@ * @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; private double lineWidth = 1; private boolean enabled = true; - private ArrayList renderables = new ArrayList(); + private final ArrayList renderables = new ArrayList<>(); private boolean viewClippingEnabled = false; protected Object globeStateKey; @@ -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) - ((Polyline) r).setColor(color); + for (Renderable r : this.getRenderables()) { + if (r instanceof Path) { + ((Path) r).getActiveAttributes().setOutlineMaterial(new Material(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) - ((Polyline) r).setLineWidth(width); + for (Renderable r : this.getRenderables()) { + if (r instanceof Path) { + ((Path) r).getActiveAttributes().setOutlineWidth(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,41 +256,38 @@ 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 - makePolylinesConnected(dc, inter, this.maxConnectingDistance); + makePathsConnected(dc, inter, this.maxConnectingDistance); } } /** * 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,37 +331,34 @@ 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 makePathsConnected(DrawContext dc, ArrayList inter, int tolerance) { + if (inter == null) { return 0; + } Globe globe = dc.getGlobe(); Vec4 start, end, p; - Polyline line; + Path line; int tolerance2 = tolerance * tolerance; // distance squared in meters int count = 0; - while (inter.size() > 0) - { - ArrayList positions = new ArrayList(); + while (inter.size() > 0) { + ArrayList positions = new ArrayList<>(); // Start with first segment start = inter.remove(0).getIntersectionPoint(); end = inter.remove(0).getIntersectionPoint(); 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(); @@ -434,11 +396,13 @@ protected int makePolylinesConnected(DrawContext dc, ArrayList int i += 2; } // Create polyline - line = new Polyline(positions); + line = new Path(positions); line.setNumSubsegments(0); line.setFollowTerrain(true); - line.setColor(this.getColor()); - line.setLineWidth(this.getLineWidth()); + var attrs = new BasicShapeAttributes(); + attrs.setOutlineWidth(this.getLineWidth()); + attrs.setOutlineMaterial(new Material(this.getColor())); + line.setAttributes(attrs); this.getRenderables().add(line); count++; } diff --git a/src/gov/nasa/worldwind/render/Path.java b/src/gov/nasa/worldwind/render/Path.java index 0ef067fa48..a513645c47 100644 --- a/src/gov/nasa/worldwind/render/Path.java +++ b/src/gov/nasa/worldwind/render/Path.java @@ -710,6 +710,28 @@ public Path(Iterable positions) { this.measurer.setPathType(this.pathType); } + /** + * Creates a path with specified coordinates. + *

+ * Note: If fewer than two coordinates is specified, no path is drawn. + * + * @param coords the path coordinates. 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. + * @param elevation the elevation to use for the coordinates. + * + * @throws IllegalArgumentException if positions is null. + */ + public Path(Iterable coords, double elevation) { + ArrayList newPositions = new ArrayList<>(); + coords.forEach((c) -> { + newPositions.add(new Position(c, elevation)); + }); + this.setPositions(newPositions); + this.measurer.setFollowTerrain(this.followTerrain); + this.measurer.setPathType(this.pathType); + } + /** * Creates a path with positions specified via a generic list. *

diff --git a/src/gov/nasa/worldwind/render/airspaces/AirspaceAttributes.java b/src/gov/nasa/worldwind/render/airspaces/AirspaceAttributes.java index 107b79a691..dc72af204f 100644 --- a/src/gov/nasa/worldwind/render/airspaces/AirspaceAttributes.java +++ b/src/gov/nasa/worldwind/render/airspaces/AirspaceAttributes.java @@ -28,6 +28,7 @@ public interface AirspaceAttributes extends ShapeAttributes * * @deprecated Use {@link #getInteriorMaterial()} instead. */ + @Deprecated Material getMaterial(); /** @@ -38,6 +39,7 @@ public interface AirspaceAttributes extends ShapeAttributes * * @deprecated Use {@link #setInteriorMaterial(gov.nasa.worldwind.render.Material)} instead. */ + @Deprecated void setMaterial(Material material); /** @@ -49,6 +51,7 @@ public interface AirspaceAttributes extends ShapeAttributes * * @deprecated Use {@link #getInteriorOpacity()} instead. */ + @Deprecated double getOpacity(); /** @@ -60,6 +63,7 @@ public interface AirspaceAttributes extends ShapeAttributes * * @deprecated Use {@link #setInteriorOpacity(double)} instead. */ + @Deprecated void setOpacity(double opacity); /** @@ -73,6 +77,7 @@ public interface AirspaceAttributes extends ShapeAttributes * @throws IllegalArgumentException if the drawing context is null. * @deprecated Use {@link Material#apply(com.jogamp.opengl.GL2, int)} or make OpenGL state changes directly. */ + @Deprecated void applyInterior(DrawContext dc, boolean enableMaterial); /** @@ -86,5 +91,6 @@ public interface AirspaceAttributes extends ShapeAttributes * @throws IllegalArgumentException if the drawing context is null. * @deprecated Use {@link Material#apply(com.jogamp.opengl.GL2, int)} or make OpenGL state changes directly. */ + @Deprecated void applyOutline(DrawContext dc, boolean enableMaterial); } diff --git a/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java b/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java index cc0403e360..d0c3b48402 100644 --- a/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java +++ b/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java @@ -129,6 +129,7 @@ public void copy(AirspaceAttributes attributes) * * @deprecated Use {@link #getInteriorMaterial()} instead. */ + @Deprecated public Material getMaterial() { return this.getInteriorMaterial(); @@ -139,6 +140,7 @@ public Material getMaterial() * * @deprecated Use {@link #setInteriorMaterial(gov.nasa.worldwind.render.Material)} instead. */ + @Deprecated public void setMaterial(Material material) { if (material == null) @@ -156,6 +158,7 @@ public void setMaterial(Material material) * * @deprecated Use {@link #getInteriorOpacity()} instead. */ + @Deprecated public double getOpacity() { return this.getInteriorOpacity(); @@ -166,6 +169,7 @@ public double getOpacity() * * @deprecated Use {@link #setInteriorOpacity(double)} instead. */ + @Deprecated public void setOpacity(double opacity) { if (opacity < 0 || opacity > 1) @@ -183,6 +187,7 @@ public void setOpacity(double opacity) * * @deprecated Use {@link Material#apply(com.jogamp.opengl.GL2, int)} or make OpenGL state changes directly. */ + @Deprecated public void applyInterior(DrawContext dc, boolean enableMaterial) { if (dc == null) @@ -200,6 +205,7 @@ public void applyInterior(DrawContext dc, boolean enableMaterial) * * @deprecated Use {@link Material#apply(com.jogamp.opengl.GL2, int)} or make OpenGL state changes directly. */ + @Deprecated public void applyOutline(DrawContext dc, boolean enableMaterial) { if (dc == null) diff --git a/src/gov/nasa/worldwind/terrain/HighResolutionTerrain.java b/src/gov/nasa/worldwind/terrain/HighResolutionTerrain.java index 9c62d28b99..7ed5088017 100644 --- a/src/gov/nasa/worldwind/terrain/HighResolutionTerrain.java +++ b/src/gov/nasa/worldwind/terrain/HighResolutionTerrain.java @@ -341,6 +341,7 @@ public Double getElevation(LatLon location) * * @deprecated */ + @Deprecated public Intersection[] intersect(Line line) { if (line == null) diff --git a/src/gov/nasa/worldwind/util/BasicDragger.java b/src/gov/nasa/worldwind/util/BasicDragger.java index 86378aef73..48d3fd4d5c 100644 --- a/src/gov/nasa/worldwind/util/BasicDragger.java +++ b/src/gov/nasa/worldwind/util/BasicDragger.java @@ -65,6 +65,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. */ + @Deprecated public BasicDragger(WorldWindow wwd, boolean useTerrain) { this(wwd); @@ -85,6 +86,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. */ + @Deprecated public boolean isUseTerrain() { return false; @@ -95,6 +97,7 @@ public boolean isUseTerrain() * * @deprecated definition of dragging behavior now defined by the object in the {@link Draggable} interface. */ + @Deprecated public void setUseTerrain(boolean useTerrain) { // ignored - functionality deprecated diff --git a/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java b/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java index 2c5bdf1ce4..ce8c043fbd 100644 --- a/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java +++ b/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java @@ -19,7 +19,7 @@ * 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.

+ * pathType - AVKey.LINEAR, AVKey.RHUMB_LINE or AVKey.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.

@@ -71,9 +71,9 @@ public void setPositions(ArrayList positions, double elevation } ArrayList newPositions = new ArrayList<>(); - for (LatLon pos : positions) { + positions.forEach((pos) -> { newPositions.add(new Position(pos, elevation)); - } + }); setPositions(newPositions); } @@ -86,7 +86,7 @@ public void setPositions(Iterable positions) { } ArrayList newPositions = new ArrayList<>(); - for (Position p:positions) { + for (Position p : positions) { newPositions.add(p); } setPositions(newPositions); @@ -146,11 +146,12 @@ public String getAVKeyPathType() { } /** - * Sets the type of path used when subdividing long segments, one of Polyline.GREAT_CIRCLE, which draws segments as - * a great circle, Polyline.LINEAR, which determines the intermediate positions between segments by interpolating - * the segment endpoints, or Polyline.RHUMB_LINE, which draws segments as a line of constant heading. + * Sets the type of path used when subdividing long segments, one of AVKey.GREAT_CIRCLE, which draws segments as + * a great circle, AVKey.LINEAR, which determines the intermediate positions between segments by interpolating + * the segment endpoints, or AVKey.RHUMB_LINE, which draws segments as a line of constant heading. * * @param pathType the type of path to measure. + * @deprecated */ @Deprecated public void setPathType(int pathType) { @@ -177,9 +178,9 @@ public void setPathType(int pathType) { } /** - * Sets the type of path used when subdividing long segments, one of Polyline.GREAT_CIRCLE, which draws segments as - * a great circle, Polyline.LINEAR, which determines the intermediate positions between segments by interpolating - * the segment endpoints, or Polyline.RHUMB_LINE, which draws segments as a line of constant heading. + * Sets the type of path used when subdividing long segments, one of AVKey.GREAT_CIRCLE, which draws segments as + * a great circle, AVKey.LINEAR, which determines the intermediate positions between segments by interpolating + * the segment endpoints, or AVKey.RHUMB_LINE, which draws segments as a line of constant heading. * * @param pathType the type of path to measure. */ @@ -327,7 +328,7 @@ protected double computeLength(Globe globe, boolean followTerrain) { * 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 polylinePathType - one of - * Polyline.LINEAR, Polyline.RHUMB_LINE or Polyline.GREAT_CIRCLE. All position elevations will be either at the + * AVKey.LINEAR, AVKey.RHUMB_LINE or AVKey.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. @@ -349,7 +350,7 @@ protected static ArrayList subdividePositions(Globe globe, * 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 + * AVKey.LINEAR, AVKey.RHUMB_LINE or AVKey.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. diff --git a/src/gov/nasa/worldwind/util/measure/MeasureTool.java b/src/gov/nasa/worldwind/util/measure/MeasureTool.java index aa45ab9e9a..8cef714d46 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 Path or SurfaceShape by using + * {@link #setMeasureShape(Path)} 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"; @@ -124,13 +153,13 @@ public class MeasureTool extends AVListImpl implements Disposable protected final WorldWindow wwd; protected MeasureToolController controller; - protected ArrayList positions = new ArrayList(); - protected ArrayList controlPoints = new ArrayList(); + protected ArrayList positions = new ArrayList<>(); + protected ArrayList controlPoints = new ArrayList<>(); protected RenderableLayer applicationLayer; protected CustomRenderableLayer layer; protected CustomRenderableLayer controlPointsLayer; protected CustomRenderableLayer shapeLayer; - protected Polyline line; + protected Path line; protected SurfaceShape surfaceShape; protected ScreenAnnotation annotation; @@ -154,14 +183,16 @@ 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 { + + @Override + public void render(DrawContext dc) { + if (dc.isPickingMode() && !this.isPickEnabled()) { return; - if (!this.isEnabled()) + } + if (!this.isEnabled()) { return; + } super.render(dc); } @@ -172,8 +203,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 +211,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 +225,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 +234,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 +288,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 +306,7 @@ protected void setInitialLabels() this.setLabel(WIDTH_LABEL, Logging.getMessage(WIDTH_LABEL)); } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return this.wwd; } @@ -290,8 +315,7 @@ public WorldWindow getWwd() * * @return the tool's units format instance. */ - public UnitsFormat getUnitsFormat() - { + public UnitsFormat getUnitsFormat() { return this.unitsFormat; } @@ -302,10 +326,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 +336,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 +348,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 +357,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 +368,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 +391,7 @@ public String getLabel(String labelName) * * @return the MeasureToolController for this measure tool. */ - public MeasureToolController getController() - { + public MeasureToolController getController() { return this.controller; } @@ -384,10 +401,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 +412,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 +421,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 +430,7 @@ public RenderableLayer getLayer() * * @return the layer containing the measure shape and control points. */ - public RenderableLayer getApplicationLayer() - { + public RenderableLayer getApplicationLayer() { return applicationLayer; } @@ -425,8 +439,7 @@ public RenderableLayer getApplicationLayer() * * @return the polyline currently used to display lines and path. */ - public Polyline getLine() - { + public Path getLine() { return this.line; } @@ -435,8 +448,7 @@ public Polyline getLine() * * @return the surface shape currently used to display polygons. */ - public SurfaceShape getSurfaceShape() - { + public SurfaceShape getSurfaceShape() { return this.surfaceShape; } @@ -445,52 +457,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 +515,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 +524,7 @@ public ArrayList getControlPoints() * * @return the attributes associated with the control points. */ - public AnnotationAttributes getControlPointsAttributes() - { + public AnnotationAttributes getControlPointsAttributes() { return this.controlPointsAttributes; } @@ -523,29 +533,28 @@ 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) - { - this.line.setColor(color); + if (this.line != null) { + if (this.line.getAttributes() == null) { + this.line.setAttributes(new BasicShapeAttributes()); + } + this.line.getAttributes().setOutlineMaterial(new Material(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 +562,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 +585,74 @@ 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) - this.line.setLineWidth(width); - if (this.surfaceShape != null) - { + if (this.line != null) { + if (this.line.getAttributes() == null) { + this.line.setAttributes(new BasicShapeAttributes()); + } + this.line.getAttributes().setOutlineWidth(width); + } + 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) - this.line.setPathType(polylinePathTypeFromKey(type)); - if (this.surfaceShape != null) - this.surfaceShape.setPathType(type); - if (this.isRegularShape()) - this.updateShapeControlPoints(); - this.wwd.redraw(); - } - - @SuppressWarnings({"StringEquality"}) - protected static int polylinePathTypeFromKey(String type) - { - if (type != null && type == AVKey.GREAT_CIRCLE) - { - return Polyline.GREAT_CIRCLE; + if (this.line != null) { + this.line.setPathType(type); } - else if (type != null && (type == AVKey.RHUMB_LINE || type == AVKey.LOXODROME)) - { - return Polyline.RHUMB_LINE; - } - else - { - return Polyline.LINEAR; - } - } - - protected static String keyFromPolylinePathType(int type) - { - if (type == Polyline.GREAT_CIRCLE) - { - return AVKey.GREAT_CIRCLE; - } - else if (type == Polyline.RHUMB_LINE) - { - return AVKey.RHUMB_LINE; + if (this.surfaceShape != null) { + this.surfaceShape.setPathType(type); } - else - { - return AVKey.LINEAR; + if (this.isRegularShape()) { + this.updateShapeControlPoints(); } + this.wwd.redraw(); } - 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 +661,7 @@ public void clear() this.shapeRectangle = null; } - public boolean isMeasureShape(Object o) - { + public boolean isMeasureShape(Object o) { return o == this.shapeLayer; } @@ -701,8 +671,7 @@ public boolean isMeasureShape(Object o) * * @return the measure shape type. */ - public String getMeasureShapeType() - { + public String getMeasureShapeType() { return this.measureShapeType; } @@ -713,17 +682,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 +700,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 +712,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); } @@ -799,14 +758,12 @@ public void setMeasureShapeType(String shapeType, Position centerPosition, doubl } /** - * Set the measure shape to an existing Polyline. + * Set the measure shape to an existing Path. * - * @param line a Polyline instance. + * @param line a Path instance. */ - public void setMeasureShape(Polyline line) - { - if (line == null) - { + public void setMeasureShape(Path line) { + if (line == null) { String msg = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -815,22 +772,21 @@ 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 setFollowTerrain(line.isFollowTerrain()); - setPathType(keyFromPolylinePathType(line.getPathType())); + setPathType(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 +796,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 +806,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 +817,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 +828,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 +840,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 +869,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 +1010,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.isEmpty()) { 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 +1060,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 +1068,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 +1107,98 @@ 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)) - { - // Update the shape's center position - this.updateShapeCenter(control, newPosition); - } - else if (control.equals(NORTH_LEADER)) - { - // Update the shape's orientation. - this.updateShapeOrientation(control, newPosition); - } - else - { - // Update the shape's center position and dimensions. - this.updateShapeSize(control, newPosition); + protected void updateShapeProperties(String control, Position newPosition, String mode) { + switch (control) { + case CENTER: + // Update the shape's center position + this.updateShapeCenter(control, newPosition); + break; + case NORTH_LEADER: + // Update the shape's orientation. + this.updateShapeOrientation(control, newPosition); + break; + default: + // Update the shape's center position and dimensions. + this.updateShapeSize(control, newPosition); + break; } } - 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 +1209,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 +1225,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 +1263,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 +1274,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 +1291,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 +1315,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 +1334,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.isEmpty()) { 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 +1404,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 +1415,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 +1427,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 +1544,140 @@ 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)) - return LatLon.interpolate(this.pathType, 0.5, nw, ne); - else if (control.equals(EAST)) - return LatLon.interpolate(this.pathType, 0.5, ne, se); - else if (control.equals(SOUTH)) - return LatLon.interpolate(this.pathType, 0.5, sw, se); - else if (control.equals(WEST)) - return LatLon.interpolate(this.pathType, 0.5, sw, nw); + switch (control) { + case NORTH: + return LatLon.interpolate(this.pathType, 0.5, nw, ne); + case EAST: + return LatLon.interpolate(this.pathType, 0.5, ne, se); + case SOUTH: + return LatLon.interpolate(this.pathType, 0.5, sw, se); + case WEST: + return LatLon.interpolate(this.pathType, 0.5, sw, nw); + default: + break; + } 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)) - azimuth = Angle.ZERO; - else if (control.equals(EAST)) - azimuth = Angle.POS90; - else if (control.equals(SOUTH)) - azimuth = Angle.POS180; - else if (control.equals(WEST)) - azimuth = Angle.fromDegrees(270); - else if (control.equals(NORTHEAST)) - azimuth = Angle.fromRadians(Math.atan2(width, height)); - else if (control.equals(SOUTHEAST)) - azimuth = Angle.fromRadians(Math.atan2(width, -height)); - else if (control.equals(SOUTHWEST)) - azimuth = Angle.fromRadians(Math.atan2(-width, -height)); - else if (control.equals(NORTHWEST)) - azimuth = Angle.fromRadians(Math.atan2(-width, height)); - else if (control.equals(NORTH_LEADER)) - azimuth = Angle.ZERO; + switch (control) { + case NORTH: + azimuth = Angle.ZERO; + break; + case EAST: + azimuth = Angle.POS90; + break; + case SOUTH: + azimuth = Angle.POS180; + break; + case WEST: + azimuth = Angle.fromDegrees(270); + break; + case NORTHEAST: + azimuth = Angle.fromRadians(Math.atan2(width, height)); + break; + case SOUTHEAST: + azimuth = Angle.fromRadians(Math.atan2(width, -height)); + break; + case SOUTHWEST: + azimuth = Angle.fromRadians(Math.atan2(-width, -height)); + break; + case NORTHWEST: + azimuth = Angle.fromRadians(Math.atan2(-width, height)); + break; + case NORTH_LEADER: + azimuth = Angle.ZERO; + break; + default: + break; + } return azimuth != null ? computeNormalizedHeading(azimuth) : null; } - protected Angle computeControlPointAzimuthInShapeCoordinates(String control, Angle azimuth) - { - if (control.equals(NORTHEAST)) - return azimuth.subtract(this.shapeOrientation); - else if (control.equals(SOUTHEAST)) - return this.shapeOrientation.addDegrees(180).subtract(azimuth); - else if (control.equals(SOUTHWEST)) - return azimuth.subtract(this.shapeOrientation.addDegrees(180)); - else if (control.equals(NORTHWEST)) - return this.shapeOrientation.subtract(azimuth); + protected Angle computeControlPointAzimuthInShapeCoordinates(String control, Angle azimuth) { + switch (control) { + case NORTHEAST: + return azimuth.subtract(this.shapeOrientation); + case SOUTHEAST: + return this.shapeOrientation.addDegrees(180).subtract(azimuth); + case SOUTHWEST: + return azimuth.subtract(this.shapeOrientation.addDegrees(180)); + case NORTHWEST: + return this.shapeOrientation.subtract(azimuth); + default: + break; + } 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)) - { - pathLength = Angle.fromRadians((height / 2d) / globeRadius); - } - 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)) - { - double diag = Math.sqrt((width * width) / 4d + (height * height) / 4d); - pathLength = Angle.fromRadians(diag / globeRadius); - } - else if (control.equals(NORTH_LEADER)) - { - pathLength = Angle.fromRadians(3d / 4d * height / globeRadius); + switch (control) { + case NORTH: + case SOUTH: + pathLength = Angle.fromRadians((height / 2d) / globeRadius); + break; + case EAST: + case WEST: + pathLength = Angle.fromRadians((width / 2d) / globeRadius); + break; + case NORTHEAST: + case SOUTHEAST: + case SOUTHWEST: + case NORTHWEST: + double diag = Math.sqrt((width * width) / 4d + (height * height) / 4d); + pathLength = Angle.fromRadians(diag / globeRadius); + break; + case NORTH_LEADER: + pathLength = Angle.fromRadians(3d / 4d * height / globeRadius); + break; + default: + break; } 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,102 +1686,94 @@ 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 = new Path(); this.line.setFollowTerrain(this.isFollowTerrain()); - this.line.setLineWidth(this.getLineWidth()); - this.line.setColor(this.getLineColor()); - this.line.setPathType(polylinePathTypeFromKey(this.getPathType())); - //this.line.setNumSubsegments(this.followTerrain ? 10 : 1); + this.line.setPathType(this.getPathType()); + var attrs = new BasicShapeAttributes(); + attrs.setOutlineWidth(this.getLineWidth()); + attrs.setOutlineMaterial(new Material(this.getLineColor())); + this.line.setAttributes(attrs); 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 +1785,45 @@ 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)) - this.surfaceShape = new SurfaceQuad(this.shapeCenterPosition, - 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.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.surfaceShape = new SurfaceCircle(this.shapeCenterPosition, - this.shapeRectangle.width / 2, this.shapeIntervals); + switch (this.measureShapeType) { + case SHAPE_QUAD: + this.surfaceShape = new SurfaceQuad(this.shapeCenterPosition, + this.shapeRectangle.width, this.shapeRectangle.height, this.shapeOrientation); + break; + case SHAPE_SQUARE: + this.surfaceShape = new SurfaceSquare(this.shapeCenterPosition, + this.shapeRectangle.width); + break; + case SHAPE_ELLIPSE: + this.surfaceShape = new SurfaceEllipse(this.shapeCenterPosition, + this.shapeRectangle.width / 2, this.shapeRectangle.height / 2, this.shapeOrientation, + this.shapeIntervals); + break; + case SHAPE_CIRCLE: + this.surfaceShape = new SurfaceCircle(this.shapeCenterPosition, + this.shapeRectangle.width / 2, this.shapeIntervals); + break; + default: + break; + } ShapeAttributes attr = new BasicShapeAttributes(); attr.setInteriorMaterial(new Material(this.getFillColor())); @@ -1938,64 +1834,57 @@ 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() - { + @Override + 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 +1892,67 @@ 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) - { + @Override + 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 +1962,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 +2001,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 +2023,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 +2048,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 +2078,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 +2107,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 +2137,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 +2158,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 +2179,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 +2210,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/view/BasicViewPropertyLimits.java b/src/gov/nasa/worldwind/view/BasicViewPropertyLimits.java index 7460b3fac6..bc37efd98b 100644 --- a/src/gov/nasa/worldwind/view/BasicViewPropertyLimits.java +++ b/src/gov/nasa/worldwind/view/BasicViewPropertyLimits.java @@ -269,6 +269,7 @@ protected boolean isNonContinous2DGlobe(Globe globe) * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitHeading(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Angle)} instead. */ + @Deprecated public static Angle limitHeading(Angle angle, ViewPropertyLimits viewLimits) { if (angle == null) @@ -309,6 +310,7 @@ else if (angle.compareTo(limits[1]) > 0) * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitPitch(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Angle)} instead. */ + @Deprecated public static Angle limitPitch(Angle angle, ViewPropertyLimits viewLimits) { if (angle == null) @@ -348,6 +350,7 @@ else if (angle.compareTo(limits[1]) > 0) * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitRoll(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Angle)} instead. */ + @Deprecated public static Angle limitRoll(Angle angle, ViewPropertyLimits viewLimits) { if (angle == null) @@ -387,6 +390,7 @@ else if (angle.compareTo(limits[1]) > 0) * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitEyePosition(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Position)} instead. */ + @Deprecated public static double limitEyeElevation(double elevation, ViewPropertyLimits viewLimits) { if (viewLimits == null) @@ -420,6 +424,7 @@ else if (elevation > elevLimits[1]) * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitEyePosition(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Position)} instead. */ + @Deprecated public static LatLon limitEyePositionLocation(Angle latitude, Angle longitude, ViewPropertyLimits viewLimits) { if (latitude == null || longitude == null) @@ -464,6 +469,7 @@ else if (longitude.compareTo(limits.getMaxLongitude()) > 0) //******************** Restorable State ***********************// //**************************************************************// + @Override public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { rs.addStateValueAsSector(context, "eyeLocationLimits", this.eyeLocationLimits); @@ -475,6 +481,7 @@ public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObje rs.addStateValueAsDouble(context, "maxPitchDegrees", this.maxPitch.degrees); } + @Override public void restoreState(RestorableSupport rs, RestorableSupport.StateObject context) { Sector sector = rs.getStateValueAsSector(context, "eyeLocationLimits"); diff --git a/src/gov/nasa/worldwind/view/orbit/BasicOrbitViewLimits.java b/src/gov/nasa/worldwind/view/orbit/BasicOrbitViewLimits.java index 47d981185b..ba450a5ae5 100644 --- a/src/gov/nasa/worldwind/view/orbit/BasicOrbitViewLimits.java +++ b/src/gov/nasa/worldwind/view/orbit/BasicOrbitViewLimits.java @@ -157,7 +157,7 @@ public double limitZoom(View view, double value) * gov.nasa.worldwind.geom.Position)}, {@link #limitHeading(gov.nasa.worldwind.View, * gov.nasa.worldwind.geom.Angle)}, etc. */ - @SuppressWarnings("deprecation") + @Deprecated public static void applyLimits(OrbitView view, OrbitViewLimits viewLimits) { if (view == null) @@ -189,7 +189,7 @@ public static void applyLimits(OrbitView view, OrbitViewLimits viewLimits) * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitCenterPosition(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Position)} instead. */ - @SuppressWarnings("deprecation") + @Deprecated public static Position limitCenterPosition(Position position, OrbitViewLimits viewLimits) { if (position == null) @@ -221,6 +221,7 @@ public static Position limitCenterPosition(Position position, OrbitViewLimits vi * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitCenterPosition(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Position)} instead. */ + @Deprecated public static LatLon limitCenterLocation(Angle latitude, Angle longitude, OrbitViewLimits viewLimits) { if (latitude == null || longitude == null) @@ -271,6 +272,7 @@ else if (longitude.compareTo(limits.getMaxLongitude()) > 0) * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitCenterPosition(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Position)} instead. */ + @Deprecated public static double limitCenterElevation(double value, OrbitViewLimits viewLimits) { if (viewLimits == null) @@ -305,6 +307,7 @@ else if (value > limits[1]) * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitZoom(gov.nasa.worldwind.View, double)} instead. */ + @Deprecated public static double limitZoom(double value, OrbitViewLimits viewLimits) { if (viewLimits == null) @@ -333,6 +336,7 @@ else if (value > limits[1]) //******************** Restorable State ***********************// //**************************************************************// + @Override public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.getRestorableState(rs, context); @@ -344,6 +348,7 @@ public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObje rs.addStateValueAsDouble(context, "maxZoom", this.maxZoom); } + @Override public void restoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.restoreState(rs, context); diff --git a/src/gov/nasa/worldwindx/applications/glider/GliderImageLayer.java b/src/gov/nasa/worldwindx/applications/glider/GliderImageLayer.java index df8f23824a..294a63f602 100644 --- a/src/gov/nasa/worldwindx/applications/glider/GliderImageLayer.java +++ b/src/gov/nasa/worldwindx/applications/glider/GliderImageLayer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.glider; import gov.nasa.worldwind.layers.*; @@ -20,8 +19,8 @@ * @author tag * @version $Id: GliderImageLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GliderImageLayer extends AbstractLayer -{ +public class GliderImageLayer extends AbstractLayer { + public static final String GLIDER_IMAGE = "gov.nasa.worldwind.glider.Image"; protected GliderImage image; @@ -29,144 +28,133 @@ public class GliderImageLayer extends AbstractLayer protected RenderableLayer regionLayer = new RenderableLayer(); protected ImageListener imageListener = new ImageListener(); - public void dispose() - { - if (this.image != null) + @Override + public void dispose() { + if (this.image != null) { this.image.removePropertyChangeListener(this.imageListener); + } this.imageLayer.dispose(); this.regionLayer.dispose(); } - public void setImage(GliderImage image) throws IOException - { - if (image.getImageSource() instanceof String) + public void setImage(GliderImage image) throws IOException { + if (image.getImageSource() instanceof String) { ((SurfaceImageLayer) this.getImageLayer()).addImage((String) image.getImageSource(), image.getCorners()); - - else if (image.getImageSource() instanceof BufferedImage) + } else if (image.getImageSource() instanceof BufferedImage) { ((SurfaceImageLayer) this.getImageLayer()).addImage(image.getName(), (BufferedImage) image.getImageSource(), - image.getSector()); - else + image.getSector()); + } else { throw new IllegalArgumentException("Unsupported image source type"); + } this.setOpacity(image.opacity); - if (image != this.image) - { + if (image != this.image) { image.addPropertyChangeListener(this.imageListener); - if (this.image != null) + if (this.image != null) { this.image.removePropertyChangeListener(this.imageListener); + } } this.regionLayer.removeAllRenderables(); - if (image.getRegionsOfInterest() != null) - this.regionLayer.addRenderables(makePolylines(image.getRegionsOfInterest(), image.getAltitude())); + if (image.getRegionsOfInterest() != null) { + this.regionLayer.addRenderables(makePaths(image.getRegionsOfInterest(), image.getAltitude())); + } this.firePropertyChange(GliderImageLayer.GLIDER_IMAGE, this.image, this.image = image); } - public String getName() - { + @Override + public String getName() { return this.image != null ? this.image.getName() : "Unnamed Layer"; } - protected Layer getImageLayer() - { + protected Layer getImageLayer() { return this.imageLayer; } - protected void doRender(DrawContext dc) - { + @Override + protected void doRender(DrawContext dc) { // dummy method; rendering is performed by image and region layers } @Override - public void render(DrawContext dc) - { - if (!this.isEnabled()) + public void render(DrawContext dc) { + if (!this.isEnabled()) { return; + } this.imageLayer.render(dc); this.regionLayer.render(dc); } @Override - public void doPreRender(DrawContext dc) - { + public void doPreRender(DrawContext dc) { this.imageLayer.preRender(dc); this.regionLayer.preRender(dc); } - protected class ImageListener implements PropertyChangeListener - { - @SuppressWarnings({"StringEquality"}) - public void propertyChange(PropertyChangeEvent evt) - { - if (evt.getSource() != GliderImageLayer.this.image && evt.getPropagationId() != GliderImageLayer.this.image) - return; - - if (evt.getPropertyName() == GliderImage.GLIDER_IMAGE_SOURCE) - { - imageLayer.removeImage(((GliderImage) evt.getSource()).getName()); - - if (evt.getNewValue() != null) - { - try - { - GliderImageLayer.this.setImage((GliderImage) evt.getNewValue()); - } - catch (IOException e) - { - e.printStackTrace(); - } - } + protected class ImageListener implements PropertyChangeListener { - // Cause owner to repaint - evt.setPropagationId(GliderImageLayer.this); - GliderImageLayer.this.firePropertyChange(evt); + @Override + public void propertyChange(PropertyChangeEvent evt) { + if (evt.getSource() != GliderImageLayer.this.image && evt.getPropagationId() != GliderImageLayer.this.image) { + return; } - else if (evt.getPropertyName() == GliderImage.GLIDER_IMAGE_OPACITY) - { - if (evt.getNewValue() == null) - return; - - GliderImageLayer.this.imageLayer.setOpacity(((GliderImage) evt.getNewValue()).getOpacity()); - // Cause owner to repaint - evt.setPropagationId(GliderImageLayer.this); - GliderImageLayer.this.firePropertyChange(evt); - } - else if (evt.getPropertyName() == GliderRegionOfInterest.GLIDER_REGION_OF_INTEREST - || evt.getPropertyName() == GliderImage.GLIDER_REGIONS_OF_INTEREST) - { - GliderImageLayer.this.regionLayer.removeAllRenderables(); - - GliderRegionOfInterest.RegionSet regions = (GliderRegionOfInterest.RegionSet) evt.getNewValue(); - if (regions != null) - { - GliderImageLayer.this.regionLayer.addRenderables(makePolylines(regions, - GliderImageLayer.this.image.getAltitude())); + if (null != evt.getPropertyName()) { + switch (evt.getPropertyName()) { + case GliderImage.GLIDER_IMAGE_SOURCE: + imageLayer.removeImage(((GliderImage) evt.getSource()).getName()); + if (evt.getNewValue() != null) { + try { + GliderImageLayer.this.setImage((GliderImage) evt.getNewValue()); + } catch (IOException e) { + e.printStackTrace(); + } + } // Cause owner to repaint + evt.setPropagationId(GliderImageLayer.this); + GliderImageLayer.this.firePropertyChange(evt); + break; + case GliderImage.GLIDER_IMAGE_OPACITY: + if (evt.getNewValue() == null) { + return; + } + GliderImageLayer.this.imageLayer.setOpacity(((GliderImage) evt.getNewValue()).getOpacity()); + // Cause owner to repaint + evt.setPropagationId(GliderImageLayer.this); + GliderImageLayer.this.firePropertyChange(evt); + break; + case GliderRegionOfInterest.GLIDER_REGION_OF_INTEREST: + case GliderImage.GLIDER_REGIONS_OF_INTEREST: + GliderImageLayer.this.regionLayer.removeAllRenderables(); + GliderRegionOfInterest.RegionSet regions = (GliderRegionOfInterest.RegionSet) evt.getNewValue(); + if (regions != null) { + GliderImageLayer.this.regionLayer.addRenderables(makePaths(regions, + GliderImageLayer.this.image.getAltitude())); + } // Cause owner to repaint + evt.setPropagationId(GliderImageLayer.this); + GliderImageLayer.this.firePropertyChange(evt); + break; + default: + break; } - - // Cause owner to repaint - evt.setPropagationId(GliderImageLayer.this); - GliderImageLayer.this.firePropertyChange(evt); } } } - protected static List makePolylines(GliderRegionOfInterest.RegionSet regions, double altitude) - { - ArrayList polylines = new ArrayList(regions.regions.size()); + protected static List makePaths(GliderRegionOfInterest.RegionSet regions, double altitude) { + ArrayList paths = new ArrayList<>(regions.regions.size()); - for (GliderRegionOfInterest region : regions.regions) - { - Polyline p = new Polyline(region.getLocations(), altitude); - p.setClosed(true); - p.setColor(region.getColor()); + for (GliderRegionOfInterest region : regions.regions) { + Path p = new Path(region.getLocations(), altitude); + var attrs = new BasicShapeAttributes(); + attrs.setOutlineMaterial(new Material(region.getColor())); + p.setAttributes(attrs); p.setFollowTerrain(true); - polylines.add(p); + paths.add(p); } - return polylines; + return paths; } } diff --git a/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java b/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java index 62a53e2397..44fd469b0c 100644 --- a/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java +++ b/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java @@ -3,9 +3,9 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.sar; +import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.*; import gov.nasa.worldwind.util.*; import gov.nasa.worldwind.avlist.AVKey; @@ -16,7 +16,7 @@ import gov.nasa.worldwind.layers.Layer; import gov.nasa.worldwind.layers.ScalebarLayer; import gov.nasa.worldwind.layers.TerrainProfileLayer; -import gov.nasa.worldwind.render.Polyline; +import gov.nasa.worldwind.render.Path; import javax.swing.*; import javax.swing.border.*; @@ -31,8 +31,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 +40,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 +86,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 +124,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 +229,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 +442,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 +458,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 +475,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 +483,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); + this.tpl2.setPathType(AVKey.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 +609,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 +643,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..6a4a956f1f 100644 --- a/src/gov/nasa/worldwindx/applications/sar/TrackController.java +++ b/src/gov/nasa/worldwindx/applications/sar/TrackController.java @@ -5,6 +5,7 @@ */ package gov.nasa.worldwindx.applications.sar; +import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.WorldWindow; import gov.nasa.worldwind.event.*; import gov.nasa.worldwind.geom.*; @@ -22,8 +23,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 +51,110 @@ 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() - { - @SuppressWarnings({"StringEquality"}) - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { - if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_REMOVE) - removeTrack((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_MODIFY) - updateTrack((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_ENABLE) - enableTrack((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_DISABLE) - disableTrack((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_CURRENT) - trackCurrent((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_NAME) - trackName((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_DIRTY_BIT) - trackDirtyBit((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.BEGIN_TRACK_POINT_ENTRY) - beginTrackPointEntry(propertyChangeEvent); - else if (propertyChangeEvent.getPropertyName() == TrackController.END_TRACK_POINT_ENTRY) - endTrackPointEntry(propertyChangeEvent); - else if (propertyChangeEvent.getPropertyName() == TrackController.MOVE_TO_NEXT_POINT) - moveToNextTrackPoint(); - else if (propertyChangeEvent.getPropertyName() == TrackController.REMOVE_LAST_POINT) - removeLastTrackPoint(); + this.createPathTrackRepresentation(track); + + track.addPropertyChangeListener(new PropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { + if (null != propertyChangeEvent.getPropertyName()) { + switch (propertyChangeEvent.getPropertyName()) { + case TrackController.TRACK_REMOVE: + removeTrack((SARTrack) propertyChangeEvent.getSource()); + break; + case TrackController.TRACK_MODIFY: + updateTrack((SARTrack) propertyChangeEvent.getSource()); + break; + case TrackController.TRACK_ENABLE: + enableTrack((SARTrack) propertyChangeEvent.getSource()); + break; + case TrackController.TRACK_DISABLE: + disableTrack((SARTrack) propertyChangeEvent.getSource()); + break; + case TrackController.TRACK_CURRENT: + trackCurrent((SARTrack) propertyChangeEvent.getSource()); + break; + case TrackController.TRACK_NAME: + trackName((SARTrack) propertyChangeEvent.getSource()); + break; + case TrackController.TRACK_DIRTY_BIT: + trackDirtyBit((SARTrack) propertyChangeEvent.getSource()); + break; + case TrackController.BEGIN_TRACK_POINT_ENTRY: + beginTrackPointEntry(propertyChangeEvent); + break; + case TrackController.END_TRACK_POINT_ENTRY: + endTrackPointEntry(propertyChangeEvent); + break; + case TrackController.MOVE_TO_NEXT_POINT: + moveToNextTrackPoint(); + break; + case TrackController.REMOVE_LAST_POINT: + removeLastTrackPoint(); + break; + default: + break; + } + } } }); @@ -151,104 +162,106 @@ 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) - { - Polyline airPath = new Polyline(track); + private void createPathTrackRepresentation(SARTrack track) { + Path airPath = new Path(track); airPath.setOffset(track.getOffset()); - airPath.setPathType(Polyline.RHUMB_LINE); - airPath.setColor(track.getColor()); + airPath.setPathType(AVKey.RHUMB_LINE); + var attrs = new BasicShapeAttributes(); + attrs.setOutlineMaterial(new Material(track.getColor())); + airPath.setAttributes(attrs); - Polyline groundPath = new Polyline(track); + Path groundPath = new Path(track); groundPath.setFollowTerrain(true); - groundPath.setPathType(Polyline.RHUMB_LINE); - groundPath.setColor(track.getColor()); - groundPath.setStippleFactor(5); - groundPath.setStipplePattern((short) 0xAAAA); + groundPath.setPathType(AVKey.RHUMB_LINE); + attrs = new BasicShapeAttributes(); + attrs.setOutlineMaterial(new Material(track.getColor())); + attrs.setOutlineStippleFactor(5); + attrs.setOutlineStipplePattern((short) 0xAAAA); + groundPath.setAttributes(attrs); RenderableLayer layer = new RenderableLayer(); 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()) - { - Polyline line = (Polyline) r; + for (Renderable r : layer.getRenderables()) { + Path line = (Path) 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 +271,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 +302,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 +310,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()) - { - Polyline line = (Polyline) r; - line.setColor(color); + for (Renderable r : layer.getRenderables()) { + Path line = (Path) r; + line.getActiveAttributes().setOutlineMaterial(new Material(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()) - { - Polyline line = (Polyline) r; - line.setLineWidth(width); + for (Renderable r : layer.getRenderables()) { + Path line = (Path) r; + line.getActiveAttributes().setOutlineWidth(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/render/PlaneModel.java b/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java index 010a5d5a23..c8ad246402 100644 --- a/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java +++ b/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java @@ -3,14 +3,16 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.sar.render; +import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.geom.Angle; import gov.nasa.worldwind.geom.LatLon; import gov.nasa.worldwind.geom.Position; +import gov.nasa.worldwind.render.BasicShapeAttributes; import gov.nasa.worldwind.render.DrawContext; -import gov.nasa.worldwind.render.Polyline; +import gov.nasa.worldwind.render.Material; +import gov.nasa.worldwind.render.Path; import gov.nasa.worldwind.render.Renderable; import gov.nasa.worldwind.util.Logging; @@ -18,8 +20,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 $ */ @@ -35,33 +38,30 @@ public class PlaneModel implements Renderable { private double shadowScale = 1d; private Color shadowColor = Color.YELLOW; - private Polyline planeModel; - private Polyline shadowModel; + private Path planeModel; + private Path shadowModel; /** * 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 +70,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,88 +84,82 @@ 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); + this.planeModel = new Path(positions, this.position.getElevation()); + this.planeModel.setPathType(AVKey.LINEAR); this.planeModel.setFollowTerrain(false); this.planeModel.setNumSubsegments(1); - this.planeModel.setColor(this.color); + var attrs = new BasicShapeAttributes(); + attrs.setOutlineMaterial(new Material(this.color)); + this.planeModel.setAttributes(attrs); positions = computePlaneShape(dc, this.shadowScale * this.width, this.shadowScale * this.length); - this.shadowModel = new Polyline(positions, this.position.getElevation()); - this.shadowModel.setPathType(Polyline.LINEAR); + this.shadowModel = new Path(positions, this.position.getElevation()); + this.shadowModel.setPathType(AVKey.LINEAR); this.shadowModel.setFollowTerrain(true); - this.shadowModel.setColor(this.shadowColor); + attrs = new BasicShapeAttributes(); + attrs.setOutlineMaterial(new Material(this.shadowColor)); + this.shadowModel.setAttributes(attrs); } - 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 +181,7 @@ private ArrayList computePlaneShape(DrawContext dc, double width, double return positions; } -/* + /* private void renderPlane(DrawContext dc) { GL gl = dc.getGL(); @@ -224,5 +215,5 @@ private void renderPlane(DrawContext dc) gl.glPopAttrib(); } -*/ + */ } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/SimpleImporter.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/SimpleImporter.java index 15629a8081..af20e268a5 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.*; @@ -11,7 +10,7 @@ import gov.nasa.worldwind.ogc.kml.impl.KMLController; import gov.nasa.worldwind.util.*; import gov.nasa.worldwindx.applications.worldwindow.core.layermanager.*; -import gov.nasa.worldwindx.examples.util.ShapefileLoader; +import gov.nasa.worldwind.formats.shapefile.ShapefileLayerFactory; import javax.swing.*; import javax.xml.stream.XMLStreamException; @@ -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,78 @@ 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() - { - LayerPath path = new LayerPath(pathToParent != null ? pathToParent : getDefaultPathToParent(), + protected void addLayer(final Layer layer, final LayerPath pathToParent) { + SwingUtilities.invokeLater(() -> { + LayerPath path = new LayerPath(pathToParent != null ? pathToParent : getDefaultPathToParent(), layer.getName()); - doAddLayer(layer, path); - } + 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 +112,19 @@ protected void openKML(Object source) layer.addRenderable(kmlController); layer.setName(formName(source, null)); this.addLayer(layer, null); - } - catch (IOException e) - { - e.printStackTrace(); - } - catch (XMLStreamException e) - { + } catch (IOException | 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) - { - ShapefileLoader loader = new ShapefileLoader(); - - Layer layer = loader.createLayerFromSource(source); - if (layer != null) - { + protected void openShapefile(Object source) { + var factory = new ShapefileLayerFactory(); + Layer layer = (Layer) factory.createFromShapefileSource(source); + if (layer != null) { layer.setName(formName(source, null)); this.addLayer(layer, null); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/MeasurementPanel.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/MeasurementPanel.java index e60f23a572..78fecf9036 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/MeasurementPanel.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/MeasurementPanel.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; @@ -25,8 +24,8 @@ * @version $Id: MeasurementPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ @SuppressWarnings("unchecked") -public class MeasurementPanel extends AbstractFeaturePanel -{ +public class MeasurementPanel extends AbstractFeaturePanel { + private static final String NAME = "Measurement"; private WWOMeasureTool measureTool; @@ -44,13 +43,12 @@ public class MeasurementPanel extends AbstractFeaturePanel private Color fillColor = Color.WHITE; private String pathType = AVKey.GREAT_CIRCLE; - public MeasurementPanel(Registry registry) - { + public MeasurementPanel(Registry registry) { super(NAME + " Panel", Constants.FEATURE_MEASUREMENT_PANEL, new ShadedPanel(new BorderLayout()), registry); } - public void initialize(final Controller controller) - { + @Override + public void initialize(final Controller controller) { super.initialize(controller); JPanel np = new JPanel(); @@ -71,73 +69,71 @@ public void initialize(final Controller controller) this.makeToolListener(); } - public void setLayers(RenderableLayer shapeLayer, RenderableLayer controlPointsLayer) - { + public void setLayers(RenderableLayer shapeLayer, RenderableLayer controlPointsLayer) { this.shapeLayer = shapeLayer; this.controlPointsLayer = controlPointsLayer; this.shapeCombo.setSelectedItem(LINE); } - public RenderableLayer getShapeLayer() - { + public RenderableLayer getShapeLayer() { return this.shapeLayer; } - public Renderable getShape() - { + public Renderable getShape() { return this.measureTool != null ? this.measureTool.getShape() : null; } - public JComponent[] getDialogControls() - { + @Override + public JComponent[] getDialogControls() { return null; } - public WWOMeasureTool getMeasureTool() - { + public WWOMeasureTool getMeasureTool() { return this.measureTool; } - public void clearPanel() - { + public void clearPanel() { this.disposeCurrentMeasureTool(); this.shapeCombo.setSelectedItem(LINE); } - public void deletePanel() - { + public void deletePanel() { this.disposeCurrentMeasureTool(); } - public void setLineColor(Color color) - { - if (color == null || this.measureTool == null || this.measureTool.getShape() == null) + public void setLineColor(Color color) { + if (color == null || this.measureTool == null || this.measureTool.getShape() == null) { return; + } this.lineColor = new Color(color.getRed(), color.getGreen(), color.getBlue(), (int) (0.3 * color.getAlpha())); this.setShapeColor(this.measureTool.getShape(), this.lineColor, this.fillColor); } - public void setFillColor(Color color) - { - if (color == null || this.measureTool == null || this.measureTool.getShape() == null) + public void setFillColor(Color color) { + if (color == null || this.measureTool == null || this.measureTool.getShape() == null) { return; + } this.fillColor = color; this.setShapeColor(this.measureTool.getShape(), this.lineColor, this.fillColor); } - public void setShapeColor(Renderable shape, Color lineColor, Color fillColor) - { - if (shape instanceof Polyline) - ((Polyline) shape).setColor(lineColor); + public void setShapeColor(Renderable shape, Color lineColor, Color fillColor) { + if (shape instanceof Path) { + Path path = (Path) shape; + if (path.getAttributes() == null) { + path.setAttributes(new BasicShapeAttributes()); + } + path.getAttributes().setOutlineMaterial(new Material(lineColor)); + } - if (shape instanceof SurfaceShape) - { + if (shape instanceof SurfaceShape) { SurfaceShape sShape = (SurfaceShape) shape; ShapeAttributes attrs = sShape.getAttributes(); - if (attrs == null) + if (attrs == null) { attrs = new BasicShapeAttributes(); + } attrs.setInteriorMaterial(new Material(fillColor)); attrs.setInteriorOpacity(0.3); attrs.setDrawOutline(false); @@ -145,26 +141,27 @@ public void setShapeColor(Renderable shape, Color lineColor, Color fillColor) } } - protected void setPathType(String pathType) - { - if (pathType == null || this.measureTool == null || this.measureTool.getShape() == null) + protected void setPathType(String pathType) { + if (pathType == null || this.measureTool == null || this.measureTool.getShape() == null) { return; + } this.pathType = pathType; - if (this.measureTool.getShape() instanceof Polyline) - ((Polyline) this.measureTool.getShape()).setPathType(pathType); - else if (this.measureTool.getShape() instanceof SurfaceShape) + if (this.measureTool.getShape() instanceof Path) { + ((Path) this.measureTool.getShape()).setPathType(pathType); + } else if (this.measureTool.getShape() instanceof SurfaceShape) { ((SurfaceShape) this.measureTool.getShape()).setPathType(pathType); + } } - protected void installNewMeasureTool(String shapeType) - { + protected void installNewMeasureTool(String shapeType) { Renderable shape = this.makeMeasureShape(shapeType); this.measureTool = new WWOMeasureTool(this.controller.getWWd(), shape, - shapeType.equals(PATH) || shapeType.equals(FREEHAND) ? AVKey.SHAPE_PATH : null, this.controlPointsLayer); - if (shapeType.equals(FREEHAND)) + shapeType.equals(PATH) || shapeType.equals(FREEHAND) ? AVKey.SHAPE_PATH : null, this.controlPointsLayer); + if (shapeType.equals(FREEHAND)) { this.measureTool.setFreeHand(true); + } this.measureTool.setUnitsFormat(this.controller.getUnits()); this.setShapeColor(this.measureTool.getShape(), this.lineColor, this.fillColor); @@ -175,101 +172,100 @@ protected void installNewMeasureTool(String shapeType) this.measureTool.addPropertyChangeListener(this.toolListener); } - protected void disposeCurrentMeasureTool() - { - if (this.measureTool == null) + protected void disposeCurrentMeasureTool() { + if (this.measureTool == null) { return; + } this.shapeLayer.removeRenderable(this.measureTool.getShape()); - if (this.measureTool.getShape() instanceof Disposable) + if (this.measureTool.getShape() instanceof Disposable) { ((Disposable) this.measureTool.getShape()).dispose(); + } this.measureTool.removePropertyChangeListener(this.toolListener); this.measureTool.dispose(); this.measureTool = null; } - private Renderable makeMeasureShape(String shapeType) - { - if (shapeType.equals(LINE) || shapeType.equals(PATH) || shapeType.equals(FREEHAND)) - { - Polyline line = new Polyline(); + private Renderable makeMeasureShape(String shapeType) { + if (shapeType.equals(LINE) || shapeType.equals(PATH) || shapeType.equals(FREEHAND)) { + Path line = new Path(); line.setFollowTerrain(true); - line.setLineWidth(shapeType.equals(FREEHAND) ? 2 : 4); + var attrs = new BasicShapeAttributes(); + attrs.setOutlineWidth(shapeType.equals(FREEHAND) ? 2 : 4); + line.setAttributes(attrs); return line; } - if (shapeType.equals(CIRCLE)) + if (shapeType.equals(CIRCLE)) { return new SurfaceCircle(); - if (shapeType.equals(ELLIPSE)) + } + if (shapeType.equals(ELLIPSE)) { return new SurfaceEllipse(); - if (shapeType.equals(SQUARE)) + } + if (shapeType.equals(SQUARE)) { return new SurfaceSquare(); - if (shapeType.equals(RECTANGLE)) + } + if (shapeType.equals(RECTANGLE)) { return new SurfaceQuad(); - if (shapeType.equals(POLYGON)) + } + if (shapeType.equals(POLYGON)) { return new SurfacePolygon(); + } return null; } - private boolean layerContains(RenderableLayer layer, Renderable renderable) - { - for (Renderable r : layer.getRenderables()) - { - if (r == renderable) + private boolean layerContains(RenderableLayer layer, Renderable renderable) { + for (Renderable r : layer.getRenderables()) { + if (r == renderable) { return true; + } } return false; } - protected void makeToolListener() - { - this.toolListener = new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent event) - { - // The tool was armed / disarmed - if (event.getPropertyName().equals(WWOMeasureTool.EVENT_ARMED)) - { - if (getMeasureTool().isArmed()) - { - newButton.setEnabled(false); - pauseButton.setText("Pause"); - pauseButton.setEnabled(true); - endButton.setEnabled(true); - controller.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - ((Component) controller.getWWd()).requestFocus(); - } - else - { - newButton.setEnabled(true); - pauseButton.setText("Pause"); - pauseButton.setEnabled(false); - endButton.setEnabled(false); - controller.setCursor(Cursor.getDefaultCursor()); - } + protected void makeToolListener() { + this.toolListener = (PropertyChangeEvent event) -> { + // The tool was armed / disarmed + if (event.getPropertyName().equals(WWOMeasureTool.EVENT_ARMED)) { + if (getMeasureTool().isArmed()) { + newButton.setEnabled(false); + pauseButton.setText("Pause"); + pauseButton.setEnabled(true); + endButton.setEnabled(true); + controller.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); + ((Component) controller.getWWd()).requestFocus(); + } else { + newButton.setEnabled(true); + pauseButton.setText("Pause"); + pauseButton.setEnabled(false); + endButton.setEnabled(false); + controller.setCursor(Cursor.getDefaultCursor()); } - else if (event.getPropertyName().equals(WWOMeasureTool.EVENT_POSITION_ADD)) - { - if (getMeasureTool().getShape() != null - && !layerContains(getShapeLayer(), getMeasureTool().getShape())) - { - getShapeLayer().addRenderable(getMeasureTool().getShape()); - } - } // TODO: remove shape when it becomes undefined? such as no points in line - } + } else if (event.getPropertyName().equals(WWOMeasureTool.EVENT_POSITION_ADD)) { + if (getMeasureTool().getShape() != null + && !layerContains(getShapeLayer(), getMeasureTool().getShape())) { + getShapeLayer().addRenderable(getMeasureTool().getShape()); + } + } // TODO: remove shape when it becomes undefined? such as no points in line }; } - protected void updatePanelValues() - { - if (this.pathType.equals(AVKey.LINEAR)) - this.pathTypeCombo.setSelectedIndex(0); - else if (this.pathType.equals(AVKey.RHUMB_LINE)) - this.pathTypeCombo.setSelectedIndex(1); - else if (this.pathType.equals(AVKey.GREAT_CIRCLE)) - this.pathTypeCombo.setSelectedIndex(2); + protected void updatePanelValues() { + switch (this.pathType) { + case AVKey.LINEAR: + this.pathTypeCombo.setSelectedIndex(0); + break; + case AVKey.RHUMB_LINE: + this.pathTypeCombo.setSelectedIndex(1); + break; + case AVKey.GREAT_CIRCLE: + this.pathTypeCombo.setSelectedIndex(2); + break; + default: + break; + } } private static final String LINE = "Line"; @@ -284,8 +280,7 @@ else if (this.pathType.equals(AVKey.GREAT_CIRCLE)) private static final String RHUMB = "Rhumb"; private static final String LINEAR = "Linear"; - private void createComponents(JPanel panel) - { + private void createComponents(JPanel panel) { // Shape combo JPanel shapePanel = new JPanel(new GridLayout(1, 2, 5, 5)); shapePanel.setOpaque(false); @@ -293,17 +288,13 @@ private void createComponents(JPanel panel) shapePanel.add(new JLabel("Measurement Type:")); this.shapeCombo = new JComboBox( - new String[] {LINE, PATH, POLYGON, CIRCLE, ELLIPSE, SQUARE, RECTANGLE, FREEHAND}); + new String[]{LINE, PATH, POLYGON, CIRCLE, ELLIPSE, SQUARE, RECTANGLE, FREEHAND}); this.shapeCombo.setToolTipText("Choose a measurement type"); this.shapeCombo.setOpaque(false); - this.shapeCombo.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); - disposeCurrentMeasureTool(); - installNewMeasureTool(item); - } + this.shapeCombo.addActionListener((ActionEvent event) -> { + String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); + disposeCurrentMeasureTool(); + installNewMeasureTool(item); }); shapePanel.add(this.shapeCombo); @@ -313,24 +304,27 @@ public void actionPerformed(ActionEvent event) pathTypePanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); pathTypePanel.add(new JLabel("Route type:")); - this.pathTypeCombo = new JComboBox(new String[] {LINEAR, RHUMB, GREAT_CIRCLE}); + this.pathTypeCombo = new JComboBox(new String[]{LINEAR, RHUMB, GREAT_CIRCLE}); this.pathTypeCombo.setToolTipText("Choose a route type"); this.pathTypeCombo.setOpaque(false); this.pathTypeCombo.setSelectedIndex(2); - this.pathTypeCombo.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); - if (item.equals(LINEAR)) + this.pathTypeCombo.addActionListener((ActionEvent event) -> { + String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); + switch (item) { + case LINEAR: setPathType(AVKey.LINEAR); - else if (item.equals(RHUMB)) + break; + case RHUMB: setPathType(AVKey.RHUMB_LINE); - else if (item.equals(GREAT_CIRCLE)) + break; + case GREAT_CIRCLE: setPathType(AVKey.GREAT_CIRCLE); - - controller.redraw(); + break; + default: + break; } + + controller.redraw(); }); pathTypePanel.add(this.pathTypeCombo); @@ -343,15 +337,12 @@ else if (item.equals(GREAT_CIRCLE)) this.newButton = new JButton("Start"); this.newButton.setToolTipText("Start creating a measurement"); this.newButton.setOpaque(false); - this.newButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - getMeasureTool().clear(); - if (shapeLayer != null && measureTool.getShape() != null) - shapeLayer.removeRenderable(measureTool.getShape()); - getMeasureTool().setArmed(true); + this.newButton.addActionListener((ActionEvent actionEvent) -> { + getMeasureTool().clear(); + if (shapeLayer != null && measureTool.getShape() != null) { + shapeLayer.removeRenderable(measureTool.getShape()); } + getMeasureTool().setArmed(true); }); buttonPanel.add(this.newButton); this.newButton.setEnabled(true); @@ -359,16 +350,12 @@ public void actionPerformed(ActionEvent actionEvent) this.pauseButton = new JButton("Pause"); this.pauseButton.setToolTipText("Pause temporarily during measurement creation"); this.pauseButton.setOpaque(false); - this.pauseButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - getMeasureTool().setArmed(!getMeasureTool().isArmed()); - pauseButton.setText(!getMeasureTool().isArmed() ? "Resume" : "Pause"); - pauseButton.setEnabled(true); - ((Component) controller.getWWd()).setCursor(!getMeasureTool().isArmed() ? Cursor.getDefaultCursor() + this.pauseButton.addActionListener((ActionEvent actionEvent) -> { + getMeasureTool().setArmed(!getMeasureTool().isArmed()); + pauseButton.setText(!getMeasureTool().isArmed() ? "Resume" : "Pause"); + pauseButton.setEnabled(true); + ((Component) controller.getWWd()).setCursor(!getMeasureTool().isArmed() ? Cursor.getDefaultCursor() : Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - } }); buttonPanel.add(this.pauseButton); this.pauseButton.setEnabled(false); @@ -376,12 +363,8 @@ public void actionPerformed(ActionEvent actionEvent) this.endButton = new JButton("Finish"); this.endButton.setToolTipText("Press when measurement shape is complete"); this.endButton.setOpaque(false); - this.endButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - getMeasureTool().setArmed(false); - } + this.endButton.addActionListener((ActionEvent actionEvent) -> { + getMeasureTool().setArmed(false); }); buttonPanel.add(endButton); this.endButton.setEnabled(false); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/util/measuretool/WWOMeasureTool.java b/src/gov/nasa/worldwindx/applications/worldwindow/util/measuretool/WWOMeasureTool.java index 437dc382b0..ed051ac06e 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/util/measuretool/WWOMeasureTool.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/util/measuretool/WWOMeasureTool.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.util.measuretool; import gov.nasa.worldwind.*; @@ -26,10 +25,10 @@ * @version $Id: WWOMeasureTool.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class WWOMeasureTool extends AVListImpl - implements Disposable, MouseListener, MouseMotionListener, SelectListener, PositionListener, RenderingListener -{ - public interface MeasureDisplay - { + implements Disposable, MouseListener, MouseMotionListener, SelectListener, PositionListener, RenderingListener { + + public interface MeasureDisplay { + public void updateMeasureDisplay(Position position); public void addToLayer(RenderableLayer layer); @@ -59,8 +58,8 @@ public interface MeasureDisplay boolean isAnnotation(Object o); } - public interface ControlPoint - { + public interface ControlPoint { + public WWOMeasureTool getParent(); public Object setValue(String key, Object value); @@ -74,8 +73,8 @@ public interface ControlPoint public void highlight(boolean tf); } - public interface ControlPointList - { + public interface ControlPointList { + public int size(); public ControlPoint createControlPoint(Position position); @@ -120,7 +119,7 @@ public interface ControlPointList protected boolean showAnnotation = true; protected UnitsFormat unitsFormat = new UnitsFormat(); - protected ArrayList positions = new ArrayList(); + protected ArrayList positions = new ArrayList<>(); protected Rectangle2D.Double shapeRectangle = null; protected Position shapeCenterPosition = null; protected Angle shapeOrientation = null; @@ -137,17 +136,14 @@ public interface ControlPointList protected WWOMeasureTool.ControlPoint movingTarget; protected WWOMeasureTool.ControlPoint lastPickedObject; - public WWOMeasureTool(final WorldWindow wwd, Renderable shape, String lineType, RenderableLayer controlPointsLayer) - { - if (wwd == null) - { + public WWOMeasureTool(final WorldWindow wwd, Renderable shape, String lineType, RenderableLayer controlPointsLayer) { + if (wwd == null) { String msg = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (shape == null) - { + if (shape == null) { String msg = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -169,14 +165,14 @@ public WWOMeasureTool(final WorldWindow wwd, Renderable shape, String lineType, this.getWwd().addRenderingListener(this); this.shape = shape; - if (this.shape instanceof Polyline) - this.setMeasureShape((Polyline) this.shape, lineType); - else + if (this.shape instanceof Path) { + this.setMeasureShape((Path) this.shape, lineType); + } else { this.setMeasureShape((SurfaceShape) this.shape); + } } - public void dispose() - { + public void dispose() { this.getWwd().getInputHandler().removeMouseListener(this); this.getWwd().getInputHandler().removeMouseMotionListener(this); this.getWwd().removePositionListener(this); @@ -188,25 +184,20 @@ public void dispose() this.getControlPoints().clear(); } - protected ControlPointList createControlPoints() - { + protected ControlPointList createControlPoints() { return new WWOMeasureToolControlPoints(this); } - protected MeasureDisplay createMeasureDisplay() - { + protected MeasureDisplay createMeasureDisplay() { return new WWOMeasureDisplay(this); } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return this.wwd; } - 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); @@ -215,82 +206,66 @@ public void setUnitsFormat(UnitsFormat unitsFormat) this.unitsFormat = unitsFormat; } - public UnitsFormat getUnitsFormat() - { + public UnitsFormat getUnitsFormat() { return this.unitsFormat; } - public void setLabel(String labelName, String label) - { + public void setLabel(String labelName, String label) { this.measureDisplay.setLabel(labelName, label); } - public String getLabel(String labelName) - { + public String getLabel(String labelName) { return this.measureDisplay.getLabel(labelName); } - public Renderable getShape() - { + public Renderable getShape() { return this.shape; } - 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.getWwd().redraw(); } - public boolean isShowAnnotation() - { + public boolean isShowAnnotation() { return this.showAnnotation; } - public void setShowAnnotation(boolean state) - { + public void setShowAnnotation(boolean state) { this.showAnnotation = state; } - public boolean isUseRubberBand() - { + public boolean isUseRubberBand() { return this.useRubberBand; } - public void setUseRubberBand(boolean state) - { + public void setUseRubberBand(boolean state) { this.useRubberBand = state; } - public boolean isFreeHand() - { + public boolean isFreeHand() { return this.freeHand; } - public void setFreeHand(boolean state) - { + public void setFreeHand(boolean state) { this.freeHand = state; } - public double getFreeHandMinSpacing() - { + public double getFreeHandMinSpacing() { return this.freeHandMinSpacing; } - public void setFreeHandMinSpacing(double distance) - { + public void setFreeHandMinSpacing(double distance) { this.freeHandMinSpacing = distance; } - public void clear() - { - while (this.positions.size() > 0 || this.getControlPoints().size() > 0) - { + public void clear() { + while (this.positions.size() > 0 || this.getControlPoints().size() > 0) { this.removeControlPoint(); } @@ -299,63 +274,51 @@ public void clear() this.shapeRectangle = null; } - public String getMeasureShapeType() - { + public String getMeasureShapeType() { return this.measureShapeType; } - public ArrayList getPositions() - { + public ArrayList getPositions() { return this.positions; } - protected ControlPointList getControlPoints() - { + protected ControlPointList getControlPoints() { return this.controlPoints; } - protected ControlPoint createControlPoint(Position position) - { + protected ControlPoint createControlPoint(Position position) { return this.controlPoints.createControlPoint(position); } - public Rectangle2D.Double getShapeRectangle() - { + public Rectangle2D.Double getShapeRectangle() { return this.shapeRectangle; } - protected void setMeasureShape(Polyline line, String shapeType) - { - if (line == null) - { + protected void setMeasureShape(Path line, String shapeType) { + if (line == null) { String msg = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - this.setArmed(false); - this.clear(); this.shape = line; this.regularShape = false; // 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, "PositionIndex", i++); } // Set proper measure shape type this.measureShapeType = (shapeType != null && shapeType.equals(AVKey.SHAPE_PATH)) - ? AVKey.SHAPE_PATH : AVKey.SHAPE_LINE; + ? AVKey.SHAPE_PATH : AVKey.SHAPE_LINE; this.firePropertyChange(EVENT_POSITION_REPLACE, null, null); this.getWwd().redraw(); } - protected void setMeasureShape(SurfaceShape newShape) - { - if (newShape == null) - { + protected void setMeasureShape(SurfaceShape newShape) { + if (newShape == null) { String msg = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -364,8 +327,7 @@ protected void setMeasureShape(SurfaceShape newShape) this.setArmed(false); this.clear(); - if (newShape instanceof SurfaceQuad) - { + if (newShape instanceof SurfaceQuad) { this.shape = newShape; this.regularShape = true; this.measureShapeType = newShape instanceof SurfaceSquare ? AVKey.SHAPE_SQUARE : AVKey.SHAPE_QUAD; @@ -378,9 +340,7 @@ protected void setMeasureShape(SurfaceShape newShape) this.updateShapeControlPoints(); // Extract positions from shape this.updatePositionsFromShape(); - } - else if (newShape instanceof SurfaceEllipse) - { + } else if (newShape instanceof SurfaceEllipse) { // Set measure shape type this.shape = newShape; this.regularShape = true; @@ -389,14 +349,13 @@ else if (newShape instanceof SurfaceEllipse) SurfaceEllipse shape = ((SurfaceEllipse) newShape); 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 this.updateShapeControlPoints(); // Extract positions from shape this.updatePositionsFromShape(); - } - else // SurfacePolygon, SurfacePolyline, SurfaceSector, or some custom shape + } else // SurfacePolygon, SurfacePolyline, SurfaceSector, or some custom shape { // Set measure shape type this.shape = newShape; @@ -404,8 +363,7 @@ else if (newShape instanceof SurfaceEllipse) // 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), "PositionIndex", i); } } @@ -414,101 +372,85 @@ else if (newShape instanceof SurfaceEllipse) this.getWwd().redraw(); } - protected boolean isRegularShape() - { + protected boolean isRegularShape() { return this.regularShape; } // *** Metric accessors *** - - public double getLength() - { - if (this.shape == null) + public double getLength() { + if (this.shape == null) { return -1; + } - if (this.shape instanceof Polyline) - return ((Polyline) this.shape).getLength(); - else + if (this.shape instanceof Path) { + return ((Path) this.shape).getLength(); + } else { return ((SurfaceShape) this.shape).getPerimeter(this.getWwd().getModel().getGlobe()); + } } - public double getArea() - { - return this.shape != null && this.shape instanceof SurfaceShape ? - ((SurfaceShape) this.shape).getArea(this.getWwd().getModel().getGlobe(), true) : -1; + public double getArea() { + return this.shape != null && this.shape instanceof SurfaceShape + ? ((SurfaceShape) this.shape).getArea(this.getWwd().getModel().getGlobe(), true) : -1; } - public double getWidth() - { + public double getWidth() { return this.shapeRectangle != null ? this.shapeRectangle.width : -1; } - public double getHeight() - { + public double getHeight() { return this.shapeRectangle != null ? this.shapeRectangle.height : -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 cuurrent WorldWindow position. */ - public void addControlPoint() - { + /** + * Add a control point to the current measure shape at the cuurrent WorldWindow position. + */ + public void addControlPoint() { Position curPos = this.getWwd().getCurrentPosition(); - if (curPos == null) + if (curPos == null) { return; + } - if (this.isRegularShape()) - { + if (this.isRegularShape()) { // Regular shapes are defined in two steps: 1. center, 2. east point. - if (this.shapeCenterPosition == null) - { + if (this.shapeCenterPosition == null) { this.shapeCenterPosition = curPos; updateShapeControlPoints(); - } - else if (this.shapeRectangle == null) - { + } else if (this.shapeRectangle == null) { // Compute shape rectangle and heading, curPos being east of center updateShapeProperties("East", curPos); // Update or create control points updateShapeControlPoints(); } - } - else - { - if (!this.measureShapeType.equals(AVKey.SHAPE_POLYGON) || this.positions.size() <= 1) - { + } else { + if (!this.measureShapeType.equals(AVKey.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), "PositionIndex", - this.positions.size() - 1); - if (this.measureShapeType.equals(AVKey.SHAPE_POLYGON) && this.positions.size() == 2) - { + this.positions.size() - 1); + if (this.measureShapeType.equals(AVKey.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(AVKey.SHAPE_LINE) && this.positions.size() > 1) - { + if (this.measureShapeType.equals(AVKey.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), "PositionIndex", - this.positions.size() - 2); + this.positions.size() - 2); } } // Update screen shapes @@ -517,49 +459,43 @@ else if (this.shapeRectangle == null) this.getWwd().redraw(); } - /** 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.getControlPoints().size() > 1) - { + while (this.getControlPoints().size() > 1) { this.getControlPoints().remove(1); } - } - else if (this.shapeCenterPosition != null) - { + } else if (this.shapeCenterPosition != null) { this.shapeCenterPosition = null; this.getControlPoints().clear(); } - } - else - { - if (this.positions.size() == 0) + } else { + if (this.positions.size() == 0) { return; + } - if (!this.measureShapeType.equals(AVKey.SHAPE_POLYGON) || this.positions.size() == 1) - { + if (!this.measureShapeType.equals(AVKey.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.getControlPoints().size() > 0) + if (this.getControlPoints().size() > 0) { this.getControlPoints().remove(this.getControlPoints().size() - 1); + } } // Update screen shapes @@ -573,35 +509,33 @@ else if (this.shapeCenterPosition != null) * * @param point one of the shape control points. */ - public void moveControlPoint(ControlPoint point) - { - if (point == null) - { + public void moveControlPoint(ControlPoint point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (point.getValue("Control") != null) - { + if (point.getValue("Control") != null) { // Update shape properties updateShapeProperties((String) point.getValue("Control"), point.getPosition()); updateShapeControlPoints(); //positions = makeShapePositions(); } - if (point.getValue("PositionIndex") != null) - { + if (point.getValue("PositionIndex") != null) { int positionIndex = (Integer) point.getValue("PositionIndex"); // Update positions Position surfacePosition = computeSurfacePosition(point.getPosition()); positions.set(positionIndex, surfacePosition); // Update last pos too if polygon and first pos changed - if (measureShapeType.equals(AVKey.SHAPE_POLYGON) && positions.size() > 2 && positionIndex == 0) + if (measureShapeType.equals(AVKey.SHAPE_POLYGON) && positions.size() > 2 && positionIndex == 0) { positions.set(positions.size() - 1, surfacePosition); + } // Update heading for simple line - if (measureShapeType.equals(AVKey.SHAPE_LINE) && positions.size() > 1) + if (measureShapeType.equals(AVKey.SHAPE_LINE) && positions.size() > 1) { shapeOrientation = LatLon.greatCircleAzimuth(positions.get(0), positions.get(1)); + } } // Update rendered shapes @@ -612,128 +546,113 @@ public void moveControlPoint(ControlPoint point) * 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 (getControlPoints().size() > 0) - { + if (getControlPoints().size() > 0) { ControlPoint point = getControlPoints().get(0); 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(AVKey.SHAPE_POLYGON) || i < positions.size() - 1) + if (!this.measureShapeType.equals(AVKey.SHAPE_POLYGON) || i < positions.size() - 1) { getControlPoints().get(i).setPosition(new Position(newPos, 0)); + } } // Update heading for simple line - if (measureShapeType.equals(AVKey.SHAPE_LINE) && positions.size() > 1) + if (measureShapeType.equals(AVKey.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 = getWwd().getSceneController().getTerrain().getSurfacePoint(latLon.getLatitude(), - latLon.getLongitude()); - if (surfacePoint != null) + latLon.getLongitude()); + if (surfacePoint != null) { return getWwd().getModel().getGlobe().computePositionFromPoint(surfacePoint); - else + } else { return new Position(latLon, getWwd().getModel().getGlobe().getElevation(latLon.getLatitude(), - latLon.getLongitude())); + latLon.getLongitude())); + } } - protected void updateShapeProperties(String control, Position newPosition) - { - if (control.equals("Center")) - { + protected void updateShapeProperties(String control, Position newPosition) { + if (control.equals("Center")) { // Update center position this.shapeCenterPosition = newPosition; - } - else - { + } else { // Compute shape rectangle and heading double headingOffset = control.equals("East") ? 90 - : control.equals("South") ? 180 + : control.equals("South") ? 180 : control.equals("West") ? 270 - : 0; + : 0; this.shapeOrientation = LatLon.greatCircleAzimuth(this.shapeCenterPosition, newPosition) - .subtractDegrees(headingOffset); + .subtractDegrees(headingOffset); // Compute distance - have a minimal distance to avoid zero sized shape Angle distanceAngle = LatLon.greatCircleDistance(this.shapeCenterPosition, newPosition); double distance = Math.max(distanceAngle.radians * getWwd().getModel().getGlobe().getRadius(), .1); double width, height; - if (control.equals("East") || control.equals("West")) - { + if (control.equals("East") || control.equals("West")) { width = distance * 2; height = this.shapeRectangle != null ? this.shapeRectangle.height : width; if (this.measureShapeType.equals(AVKey.SHAPE_CIRCLE) || this.measureShapeType.equals( - AVKey.SHAPE_SQUARE)) - //noinspection SuspiciousNameCombination + AVKey.SHAPE_SQUARE)) //noinspection SuspiciousNameCombination + { height = width; - else if (this.isActive()) + } else if (this.isActive()) { height = width * .6; // during shape creation - } - else - { + } + } else { height = distance * 2; width = this.shapeRectangle != null ? this.shapeRectangle.width : height; if (this.measureShapeType.equals(AVKey.SHAPE_CIRCLE) || this.measureShapeType.equals( - AVKey.SHAPE_SQUARE)) - //noinspection SuspiciousNameCombination + AVKey.SHAPE_SQUARE)) //noinspection SuspiciousNameCombination + { width = height; - else if (this.isActive()) + } else if (this.isActive()) { width = height * 0.6; // during shape creation + } } this.shapeRectangle = new Rectangle2D.Double(0, 0, width, height); } } - protected void updateShapeControlPoints() - { - if (this.shapeCenterPosition != null && this.getControlPoints().size() < 1) - { + protected void updateShapeControlPoints() { + if (this.shapeCenterPosition != null && this.getControlPoints().size() < 1) { // Create center control point addControlPoint(Position.ZERO, "Control", "Center"); } - if (this.shapeCenterPosition != null) - { + if (this.shapeCenterPosition != null) { // Update center control point position this.getControlPoints().get(0).setPosition(new Position(this.shapeCenterPosition, 0)); } - if (this.shapeRectangle != null && this.getControlPoints().size() < 5) - { + if (this.shapeRectangle != null && this.getControlPoints().size() < 5) { // Add control points in four directions addControlPoint(Position.ZERO, "Control", "North"); addControlPoint(Position.ZERO, "Control", "East"); @@ -741,69 +660,59 @@ protected void updateShapeControlPoints() addControlPoint(Position.ZERO, "Control", "West"); } - if (this.shapeRectangle != null) - { + if (this.shapeRectangle != null) { Angle halfWidthAngle = Angle.fromRadians(this.shapeRectangle.width / 2 - / getWwd().getModel().getGlobe().getRadius()); + / getWwd().getModel().getGlobe().getRadius()); Angle halfHeightAngle = Angle.fromRadians(this.shapeRectangle.height / 2 - / getWwd().getModel().getGlobe().getRadius()); + / getWwd().getModel().getGlobe().getRadius()); // Update control points positions in four directions Position controlPos; // North controlPos = new Position(LatLon.greatCircleEndPosition( - this.shapeCenterPosition, this.shapeOrientation, halfHeightAngle), 0); + this.shapeCenterPosition, this.shapeOrientation, halfHeightAngle), 0); getControlPoints().get(1).setPosition(controlPos); // East controlPos = new Position(LatLon.greatCircleEndPosition( - this.shapeCenterPosition, this.shapeOrientation.addDegrees(90), halfWidthAngle), 0); + this.shapeCenterPosition, this.shapeOrientation.addDegrees(90), halfWidthAngle), 0); getControlPoints().get(2).setPosition(controlPos); // South controlPos = new Position(LatLon.greatCircleEndPosition( - this.shapeCenterPosition, this.shapeOrientation.addDegrees(180), halfHeightAngle), 0); + this.shapeCenterPosition, this.shapeOrientation.addDegrees(180), halfHeightAngle), 0); getControlPoints().get(3).setPosition(controlPos); // West controlPos = new Position(LatLon.greatCircleEndPosition( - this.shapeCenterPosition, this.shapeOrientation.addDegrees(270), halfWidthAngle), 0); + this.shapeCenterPosition, this.shapeOrientation.addDegrees(270), halfWidthAngle), 0); getControlPoints().get(4).setPosition(controlPos); } } - protected void updateMeasureShape() - { + protected void updateMeasureShape() { // Update line - if (this.measureShapeType.equals(AVKey.SHAPE_LINE) || this.measureShapeType.equals(AVKey.SHAPE_PATH)) - { + if (this.measureShapeType.equals(AVKey.SHAPE_LINE) || this.measureShapeType.equals(AVKey.SHAPE_PATH)) { // Update current line - if (this.positions.size() > 1 && this.shape != null) + if (this.positions.size() > 1 && this.shape != null) { ((Polyline) this.shape).setPositions(this.positions); - } - // Update polygon - else if (this.measureShapeType.equals(AVKey.SHAPE_POLYGON)) - { - if (this.shape != null) - { + } + } // Update polygon + else if (this.measureShapeType.equals(AVKey.SHAPE_POLYGON)) { + if (this.shape != null) { // Update current shape ((SurfacePolygon) this.shape).setLocations(this.positions); } - } - // Update regular shape - else if (this.isRegularShape()) - { - if (this.shape != null && this.shapeRectangle != null) - { + } // Update regular shape + else if (this.isRegularShape()) { + if (this.shape != null && this.shapeRectangle != null) { // Update current shape - if (this.measureShapeType.equals(AVKey.SHAPE_QUAD) || this.measureShapeType.equals(AVKey.SHAPE_SQUARE)) - { + if (this.measureShapeType.equals(AVKey.SHAPE_QUAD) || this.measureShapeType.equals(AVKey.SHAPE_SQUARE)) { ((SurfaceQuad) this.shape).setCenter(this.shapeCenterPosition); ((SurfaceQuad) this.shape).setSize(this.shapeRectangle.width, this.shapeRectangle.height); ((SurfaceQuad) this.shape).setHeading(this.shapeOrientation); } if (this.measureShapeType.equals(AVKey.SHAPE_ELLIPSE) || this.measureShapeType.equals( - AVKey.SHAPE_CIRCLE)) - { + AVKey.SHAPE_CIRCLE)) { ((SurfaceEllipse) this.shape).setCenter(this.shapeCenterPosition); ((SurfaceEllipse) this.shape).setRadii(this.shapeRectangle.width / 2, - this.shapeRectangle.height / 2); + this.shapeRectangle.height / 2); ((SurfaceEllipse) this.shape).setHeading(this.shapeOrientation); } // Update position from shape list with zero elevation @@ -812,53 +721,43 @@ else if (this.isRegularShape()) } } - protected void updatePositionsFromShape() - { + protected void updatePositionsFromShape() { Globe globe = this.getWwd().getModel().getGlobe(); this.positions.clear(); Iterable locations = ((SurfaceShape) this.shape).getLocations(globe); - if (locations != null) - { - for (LatLon latLon : locations) - { + if (locations != null) { + for (LatLon latLon : locations) { this.positions.add(new Position(latLon, 0)); } } } - protected void addControlPoint(Position position, String key, Object value) - { + protected void addControlPoint(Position position, String key, Object value) { ControlPoint controlPoint = createControlPoint(new Position(position, 0)); controlPoint.setValue(key, value); this.getControlPoints().add(controlPoint); } ///////////// Controller /////////////// - - protected boolean isActive() - { + protected boolean isActive() { return this.active; } - protected void setActive(boolean state) - { + protected void setActive(boolean state) { this.active = state; } - protected boolean isMoving() - { + protected boolean isMoving() { return this.moving; } - protected void setMoving(boolean state) - { + protected void setMoving(boolean state) { this.moving = state; } - public boolean isArmed() - { + public boolean isArmed() { return this.armed; } @@ -868,61 +767,49 @@ public boolean isArmed() * * @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.firePropertyChange(WWOMeasureTool.EVENT_ARMED, !armed, armed); } } // Handle mouse actions - public void mousePressed(MouseEvent mouseEvent) - { - if (this.isArmed() && this.useRubberBand && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if ((mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) - { - if (!mouseEvent.isControlDown()) - { + public void mousePressed(MouseEvent mouseEvent) { + if (this.isArmed() && this.useRubberBand && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if ((mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { + if (!mouseEvent.isControlDown()) { this.setActive(true); this.addControlPoint(); - if (this.getControlPoints().size() == 1) - { + if (this.getControlPoints().size() == 1) { this.addControlPoint(); // Simulate a second click } // Set the rubber band target to the last control point or the east one for regular shapes. rubberBandTarget = this.getControlPoints().get( - this.isRegularShape() ? 2 : this.getControlPoints().size() - 1); + this.isRegularShape() ? 2 : this.getControlPoints().size() - 1); this.firePropertyChange(WWOMeasureTool.EVENT_RUBBERBAND_START, null, null); } } mouseEvent.consume(); - } - else if (!this.isArmed() && mouseEvent.getButton() == MouseEvent.BUTTON1 && mouseEvent.isAltDown()) - { + } else if (!this.isArmed() && mouseEvent.getButton() == MouseEvent.BUTTON1 && mouseEvent.isAltDown()) { this.setMoving(true); this.movingTarget = this.lastPickedObject; mouseEvent.consume(); } } - public void mouseReleased(MouseEvent mouseEvent) - { - if (this.isArmed() && this.useRubberBand && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if (this.useRubberBand && this.getPositions().size() == 1) + public void mouseReleased(MouseEvent mouseEvent) { + if (this.isArmed() && this.useRubberBand && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if (this.useRubberBand && this.getPositions().size() == 1) { this.removeControlPoint(); + } this.setActive(false); rubberBandTarget = null; // Disarm after second control point of a line or regular shape autoDisarm(); mouseEvent.consume(); this.firePropertyChange(WWOMeasureTool.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(); @@ -930,14 +817,11 @@ else if (this.isMoving() && mouseEvent.getButton() == MouseEvent.BUTTON1) } // Handle single click for removing control points - public void mouseClicked(MouseEvent mouseEvent) - { - if (this.isArmed() && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if (mouseEvent.isControlDown()) + public void mouseClicked(MouseEvent mouseEvent) { + if (this.isArmed() && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if (mouseEvent.isControlDown()) { this.removeControlPoint(); - else if (!this.useRubberBand) - { + } else if (!this.useRubberBand) { this.addControlPoint(); // Disarm after second control point of a line or regular shape autoDisarm(); @@ -947,10 +831,8 @@ else if (!this.useRubberBand) } // Handle mouse motion - public void mouseDragged(MouseEvent mouseEvent) - { - if (this.isArmed() && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) - { + public void mouseDragged(MouseEvent mouseEvent) { + if (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. @@ -958,37 +840,36 @@ public void mouseDragged(MouseEvent mouseEvent) } } - public void mouseMoved(MouseEvent mouseEvent) - { + public void mouseMoved(MouseEvent mouseEvent) { } - public void mouseEntered(MouseEvent e) - { + public void mouseEntered(MouseEvent e) { }// Handle cursor position change for rubber band - public void mouseExited(MouseEvent e) - { + public void mouseExited(MouseEvent e) { } - public void moved(PositionEvent event) - { - if ((!this.active && !this.moving)) + public void moved(PositionEvent event) { + if ((!this.active && !this.moving)) { return; + } this.doMoved(); } // Handle dragging of control points - public void selected(SelectEvent event) - { - if ((this.isArmed() && this.useRubberBand)) + public void selected(SelectEvent event) { + if ((this.isArmed() && this.useRubberBand)) { return; + } - if (dragger == null) + if (dragger == null) { dragger = new BasicDragger(this.getWwd()); + } - if (event.getEventAction().equals(SelectEvent.ROLLOVER)) + if (event.getEventAction().equals(SelectEvent.ROLLOVER)) { highlight(event.getTopObject()); + } this.doSelected(event); } @@ -1002,40 +883,32 @@ public void stageChanged(RenderingEvent event) // TODO: Why? // } } - protected void doMoved() - { - if (this.active && rubberBandTarget != null && this.getWwd().getCurrentPosition() != null) - { + protected void doMoved() { + if (this.active && rubberBandTarget != null && this.getWwd().getCurrentPosition() != null) { if (!this.freeHand || (!this.getMeasureShapeType().equals(AVKey.SHAPE_PATH) - && !this.getMeasureShapeType().equals(AVKey.SHAPE_POLYGON))) - { + && !this.getMeasureShapeType().equals(AVKey.SHAPE_POLYGON))) { // Rubber band - Move control point and update shape Position lastPosition = rubberBandTarget.getPosition(); rubberBandTarget.setPosition(new Position(this.getWwd().getCurrentPosition(), 0)); this.moveControlPoint(rubberBandTarget); this.firePropertyChange(WWOMeasureTool.EVENT_POSITION_REPLACE, - lastPosition, rubberBandTarget.getPosition()); + lastPosition, rubberBandTarget.getPosition()); this.getWwd().redraw(); - } - else - { + } else { // Free hand - Compute distance from current control point (rubber band target) Position lastPosition = rubberBandTarget.getPosition(); Position newPosition = this.getWwd().getCurrentPosition(); double distance = LatLon.greatCircleDistance(lastPosition, newPosition).radians - * this.getWwd().getModel().getGlobe().getRadius(); - if (distance >= freeHandMinSpacing) - { + * this.getWwd().getModel().getGlobe().getRadius(); + if (distance >= freeHandMinSpacing) { // Add new control point this.addControlPoint(); rubberBandTarget = this.getControlPoints().get( - this.getControlPoints().size() - 1); + this.getControlPoints().size() - 1); this.getWwd().redraw(); } } - } - else if (this.moving && movingTarget != null && this.getWwd().getCurrentPosition() != null) - { + } else if (this.moving && movingTarget != null && this.getWwd().getCurrentPosition() != null) { // Moving the whole shape Position lastPosition = movingTarget.getPosition(); Position newPosition = this.getWwd().getCurrentPosition(); @@ -1044,8 +917,7 @@ else if (this.moving && movingTarget != null && this.getWwd().getCurrentPosition } } - 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); this.moveMeasureShape(azimuthAngle, distanceAngle); @@ -1054,132 +926,121 @@ protected void moveToPosition(Position oldPosition, Position newPosition) protected EventListenerList eventListeners = new EventListenerList(); - public void addSelectListener(SelectListener listener) - { + public void addSelectListener(SelectListener listener) { this.eventListeners.add(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); } } }); } - protected void doSelected(SelectEvent event) - { - if (event.getTopObject() != null) - { - if (event.getTopObject() instanceof WWOMeasureTool.ControlPoint) - { + protected void doSelected(SelectEvent event) { + if (event.getTopObject() != null) { + if (event.getTopObject() instanceof WWOMeasureTool.ControlPoint) { WWOMeasureTool.ControlPoint point = (WWOMeasureTool.ControlPoint) event.getTopObject(); // Check whether this control point belongs to our measure tool - if (point.getParent() != this) + if (point.getParent() != this) { return; + } // Have rollover events highlight the rolled-over object. - if (event.getEventAction().equals(SelectEvent.ROLLOVER) && !this.dragger.isDragging()) - { + if (event.getEventAction().equals(SelectEvent.ROLLOVER) && !this.dragger.isDragging()) { this.highlight(point); - } - // Have drag events drag the selected object. + } // Have drag events drag the selected object. else if (movingTarget == null && (event.getEventAction().equals(SelectEvent.DRAG_END) - || event.getEventAction().equals(SelectEvent.DRAG))) - { + || event.getEventAction().equals(SelectEvent.DRAG))) { this.dragSelected(event); } - } - else if (measureDisplay.isAnnotation(event.getTopObject())) - { + } else if (measureDisplay.isAnnotation(event.getTopObject())) { Position pos = null; - if (event.getObjects().getTerrainObject() != null) + if (event.getObjects().getTerrainObject() != null) { pos = event.getObjects().getTerrainObject().getPosition(); + } - if (isShowAnnotation()) + if (isShowAnnotation()) { measureDisplay.updateMeasureDisplay(pos); - } - else if (event.getTopObject() == shape) - { - for (SelectListener listener : eventListeners.getListeners(SelectListener.class)) - { + } + } else if (event.getTopObject() == shape) { + for (SelectListener listener : eventListeners.getListeners(SelectListener.class)) { listener.selected(event); } Position pos = null; - if (event.getObjects().getTerrainObject() != null) + if (event.getObjects().getTerrainObject() != null) { pos = event.getObjects().getTerrainObject().getPosition(); + } - if (isShowAnnotation()) + if (isShowAnnotation()) { measureDisplay.updateMeasureDisplay(pos); - } - else - { - if (isShowAnnotation()) + } + } else { + if (isShowAnnotation()) { measureDisplay.updateMeasureDisplay(null); + } } } } - protected void dragSelected(SelectEvent event) - { + protected void dragSelected(SelectEvent event) { WWOMeasureTool.ControlPoint point = (WWOMeasureTool.ControlPoint) event.getTopObject(); LatLon lastPosition = point.getPosition(); - if (point.getValue("PositionIndex") != null) + if (point.getValue("PositionIndex") != null) { lastPosition = this.getPositions().get((Integer) point.getValue("PositionIndex")); + } // Delegate dragging computations to a dragger. this.dragger.selected(event); this.moveControlPoint(point); - if (this.isShowAnnotation()) + if (this.isShowAnnotation()) { this.measureDisplay.updateMeasureDisplay(point.getPosition()); + } this.firePropertyChange(WWOMeasureTool.EVENT_POSITION_REPLACE, - lastPosition, point.getPosition()); + lastPosition, point.getPosition()); this.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 - + } if (o != null && o instanceof WWOMeasureTool.ControlPoint - && ((WWOMeasureTool.ControlPoint) o).getParent() != this) + && ((WWOMeasureTool.ControlPoint) o).getParent() != this) { return; // Does not belong to this measure tool - + } // Turn off highlight if on. - if (this.lastPickedObject != null) - { + if (this.lastPickedObject != null) { this.lastPickedObject.highlight(false); this.lastPickedObject = null; - if (this.isShowAnnotation()) + if (this.isShowAnnotation()) { this.measureDisplay.updateMeasureDisplay(null); + } } // Turn on highlight if object selected. - if (o != null && o instanceof WWOMeasureTool.ControlPoint) - { + if (o != null && o instanceof WWOMeasureTool.ControlPoint) { this.lastPickedObject = (WWOMeasureTool.ControlPoint) o; this.lastPickedObject.highlight(true); - if (this.isShowAnnotation()) + if (this.isShowAnnotation()) { this.measureDisplay.updateMeasureDisplay(this.lastPickedObject.getPosition()); + } } } - protected void autoDisarm() - { + protected void autoDisarm() { // Disarm after second control point of a line or regular shape - if (this.isRegularShape() || this.getMeasureShapeType().equals(AVKey.SHAPE_LINE)) - if (this.getControlPoints().size() > 1) + if (this.isRegularShape() || this.getMeasureShapeType().equals(AVKey.SHAPE_LINE)) { + if (this.getControlPoints().size() > 1) { this.setArmed(false); + } + } } } diff --git a/src/gov/nasa/worldwindx/examples/ContextMenusOnShapes.java b/src/gov/nasa/worldwindx/examples/ContextMenusOnShapes.java index 2d9cb46803..03ea947495 100644 --- a/src/gov/nasa/worldwindx/examples/ContextMenusOnShapes.java +++ b/src/gov/nasa/worldwindx/examples/ContextMenusOnShapes.java @@ -195,7 +195,7 @@ public AppFrame() // Create and set an attribute bundle. PointPlacemarkAttributes attrs = new PointPlacemarkAttributes(); - attrs.setAntiAliasHint(Polyline.ANTIALIAS_FASTEST); + attrs.setAntiAliasHint(WorldWind.ANTIALIAS_FASTEST); attrs.setLineMaterial(Material.WHITE); attrs.setLineWidth(2d); attrs.setImageAddress("images/pushpins/push-pin-yellow.png"); diff --git a/src/gov/nasa/worldwindx/examples/KeepingObjectsInView.java b/src/gov/nasa/worldwindx/examples/KeepingObjectsInView.java index a26dd6c379..9e158b6f0d 100644 --- a/src/gov/nasa/worldwindx/examples/KeepingObjectsInView.java +++ b/src/gov/nasa/worldwindx/examples/KeepingObjectsInView.java @@ -36,16 +36,15 @@ * @author dcollins * @version $Id: KeepingObjectsInView.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class KeepingObjectsInView extends ApplicationTemplate -{ - public static class AppFrame extends ApplicationTemplate.AppFrame - { +public class KeepingObjectsInView extends ApplicationTemplate { + + public static class AppFrame extends ApplicationTemplate.AppFrame { + protected Iterable objectsToTrack; protected ViewController viewController; protected RenderableLayer helpLayer; - public AppFrame() - { + public AppFrame() { // Create an iterable of the objects we want to keep in view. this.objectsToTrack = createObjectsToTrack(); // Set up a view controller to keep the objects in view. @@ -57,40 +56,35 @@ public AppFrame() this.initSwingComponents(); // Set up a one-shot timer to zoom to the objects once the app launches. - Timer timer = new Timer(1000, new ActionListener() - { - public void actionPerformed(ActionEvent e) - { - enableHelpAnnotation(); - viewController.gotoScene(); - } + Timer timer = new Timer(1000, (ActionEvent e) -> { + enableHelpAnnotation(); + viewController.gotoScene(); }); timer.setRepeats(false); timer.start(); } - protected void enableHelpAnnotation() - { - if (this.helpLayer != null) + protected void enableHelpAnnotation() { + if (this.helpLayer != null) { return; + } this.helpLayer = new RenderableLayer(); this.helpLayer.addRenderable(createHelpAnnotation(getWwd())); insertBeforePlacenames(this.getWwd(), this.helpLayer); } - protected void disableHelpAnnotation() - { - if (this.helpLayer == null) + protected void disableHelpAnnotation() { + if (this.helpLayer == null) { return; + } this.getWwd().getModel().getLayers().remove(this.helpLayer); this.helpLayer.removeAllRenderables(); this.helpLayer = null; } - protected void addObjectsToWorldWindow(Iterable objectsToTrack) - { + protected void addObjectsToWorldWindow(Iterable objectsToTrack) { // Set up a layer to render the icons. Disable WWIcon view clipping, since view tracking works best when an // icon's screen rectangle is known even when the icon is outside the view frustum. IconLayer iconLayer = new IconLayer(); @@ -104,26 +98,24 @@ protected void addObjectsToWorldWindow(Iterable objectsToTrack) insertBeforePlacenames(this.getWwd(), shapesLayer); // Add the objects to track to the layers. - for (Object o : objectsToTrack) - { - if (o instanceof WWIcon) + for (Object o : objectsToTrack) { + if (o instanceof WWIcon) { iconLayer.addIcon((WWIcon) o); - else if (o instanceof Renderable) + } else if (o instanceof Renderable) { shapesLayer.addRenderable((Renderable) o); + } } // Set up a SelectListener to drag the spheres. - this.getWwd().addSelectListener(new SelectListener() - { + this.getWwd().addSelectListener(new SelectListener() { protected BasicDragger dragger = new BasicDragger(getWwd()); - public void selected(SelectEvent event) - { + @Override + public void selected(SelectEvent event) { // Delegate dragging computations to a dragger. this.dragger.selected(event); - if (event.getEventAction().equals(SelectEvent.DRAG)) - { + if (event.getEventAction().equals(SelectEvent.DRAG)) { disableHelpAnnotation(); viewController.sceneChanged(); } @@ -131,27 +123,18 @@ public void selected(SelectEvent event) }); } - protected void initSwingComponents() - { + protected void initSwingComponents() { // Create a checkbox to enable/disable the view controller. JCheckBox checkBox = new JCheckBox("Enable view tracking", true); checkBox.setAlignmentX(Component.LEFT_ALIGNMENT); - checkBox.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - boolean selected = ((AbstractButton) event.getSource()).isSelected(); - viewController.setEnabled(selected); - } + checkBox.addActionListener((ActionEvent event) -> { + boolean selected = ((AbstractButton) event.getSource()).isSelected(); + viewController.setEnabled(selected); }); JButton button = new JButton("Go to objects"); button.setAlignmentX(Component.LEFT_ALIGNMENT); - button.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - viewController.gotoScene(); - } + button.addActionListener((ActionEvent event) -> { + viewController.gotoScene(); }); Box box = Box.createVerticalBox(); box.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30)); // top, left, bottom, right @@ -163,19 +146,17 @@ public void actionPerformed(ActionEvent event) } } - public static Iterable createObjectsToTrack() - { + public static Iterable createObjectsToTrack() { ArrayList objects = new ArrayList(); Sector sector = Sector.fromDegrees(35, 45, -110, -100); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { LatLon randLocation1, randLocation2; // Add a UserFacingIcon. randLocation1 = randomLocation(sector); WWIcon icon = new UserFacingIcon("gov/nasa/worldwindx/examples/images/antenna.png", - new Position(randLocation1, 0)); + new Position(randLocation1, 0)); icon.setSize(new Dimension(64, 64)); icon.setValue(AVKey.FEEDBACK_ENABLED, Boolean.TRUE); objects.add(icon); @@ -188,18 +169,20 @@ public static Iterable createObjectsToTrack() airspace.setAttributes(new BasicAirspaceAttributes(Material.GREEN, 1d)); objects.add(airspace); - // Add a Polyline. + // Add a Path. randLocation1 = randomLocation(sector); randLocation2 = randomLocation(sector); - Polyline polyline = new Polyline(Arrays.asList(randLocation1, randLocation2), 0d); - polyline.setFollowTerrain(true); - polyline.setColor(Color.RED); - polyline.setLineWidth(3); - objects.add(polyline); + Path path = new Path(Arrays.asList(randLocation1, randLocation2), 0d); + path.setFollowTerrain(true); + var attrs = new BasicShapeAttributes(); + attrs.setOutlineWidth(3); + attrs.setOutlineMaterial(new Material(Color.RED)); + path.setAttributes(attrs); + objects.add(path); // Add a SurfaceCircle. randLocation1 = randomLocation(sector); - ShapeAttributes attrs = new BasicShapeAttributes(); + attrs = new BasicShapeAttributes(); attrs.setInteriorMaterial(Material.BLUE); attrs.setOutlineMaterial(new Material(WWUtil.makeColorBrighter(Color.BLUE))); attrs.setInteriorOpacity(0.5); @@ -210,20 +193,18 @@ public static Iterable createObjectsToTrack() return objects; } - protected static LatLon randomLocation(Sector sector) - { + protected static LatLon randomLocation(Sector sector) { return new LatLon( - Angle.mix(Math.random(), sector.getMinLatitude(), sector.getMaxLatitude()), - Angle.mix(Math.random(), sector.getMinLongitude(), sector.getMaxLongitude())); + Angle.mix(Math.random(), sector.getMinLatitude(), sector.getMaxLatitude()), + Angle.mix(Math.random(), sector.getMinLongitude(), sector.getMaxLongitude())); } - public static Annotation createHelpAnnotation(WorldWindow wwd) - { + public static Annotation createHelpAnnotation(WorldWindow wwd) { String text = "The view tracks the antenna icons," - + " the red lines," - + " the green spheres," - + " and the blue circles." - + " Drag any object out of the window to track it."; + + " the red lines," + + " the green spheres," + + " and the blue circles." + + " Drag any object out of the window to track it."; Rectangle viewport = ((Component) wwd).getBounds(); Point screenPoint = new Point(viewport.width / 2, viewport.height / 3); @@ -245,9 +226,8 @@ public static Annotation createHelpAnnotation(WorldWindow wwd) //**************************************************************// //******************** View Controller ***********************// //**************************************************************// + public static class ViewController { - public static class ViewController - { protected static final double SMOOTHING_FACTOR = 0.96; protected boolean enabled = true; @@ -255,47 +235,39 @@ public static class ViewController protected ViewAnimator animator; protected Iterable objectsToTrack; - public ViewController(WorldWindow wwd) - { + public ViewController(WorldWindow wwd) { this.wwd = wwd; } - public boolean isEnabled() - { + public boolean isEnabled() { return this.enabled; } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { this.enabled = enabled; - if (this.animator != null) - { + if (this.animator != null) { this.animator.stop(); this.animator = null; } } - public Iterable getObjectsToTrack() - { + public Iterable getObjectsToTrack() { return this.objectsToTrack; } - public void setObjectsToTrack(Iterable iterable) - { + public void setObjectsToTrack(Iterable iterable) { this.objectsToTrack = iterable; } - public boolean isSceneContained(View view) - { + public boolean isSceneContained(View view) { ExtentVisibilitySupport vs = new ExtentVisibilitySupport(); this.addExtents(vs); return vs.areExtentsContained(view); } - public Vec4[] computeViewLookAtForScene(View view) - { + public Vec4[] computeViewLookAtForScene(View view) { Globe globe = this.wwd.getModel().getGlobe(); double ve = this.wwd.getSceneController().getVerticalExaggeration(); @@ -305,16 +277,15 @@ public Vec4[] computeViewLookAtForScene(View view) return vs.computeViewLookAtContainingExtents(globe, ve, view); } - public Position computePositionFromPoint(Vec4 point) - { + public Position computePositionFromPoint(Vec4 point) { return this.wwd.getModel().getGlobe().computePositionFromPoint(point); } - public void gotoScene() - { + public void gotoScene() { Vec4[] lookAtPoints = this.computeViewLookAtForScene(this.wwd.getView()); - if (lookAtPoints == null || lookAtPoints.length != 3) + if (lookAtPoints == null || lookAtPoints.length != 3) { return; + } Position centerPos = this.wwd.getModel().getGlobe().computePositionFromPoint(lookAtPoints[1]); double zoom = lookAtPoints[0].distanceTo3(lookAtPoints[1]); @@ -323,18 +294,18 @@ public void gotoScene() this.wwd.getView().goTo(centerPos, zoom); } - public void sceneChanged() - { + public void sceneChanged() { OrbitView view = (OrbitView) this.wwd.getView(); - if (!this.isEnabled()) + if (!this.isEnabled()) { return; + } - if (this.isSceneContained(view)) + if (this.isSceneContained(view)) { return; + } - if (this.animator == null || !this.animator.hasNext()) - { + if (this.animator == null || !this.animator.hasNext()) { this.animator = new ViewAnimator(SMOOTHING_FACTOR, view, this); this.animator.start(); view.stopAnimations(); @@ -343,52 +314,47 @@ public void sceneChanged() } } - protected void addExtents(ExtentVisibilitySupport vs) - { + protected void addExtents(ExtentVisibilitySupport vs) { // Compute screen extents for WWIcons which have feedback information from their IconRenderer. Iterable iterable = this.getObjectsToTrack(); - if (iterable == null) + if (iterable == null) { return; + } ArrayList extentHolders = new ArrayList(); - ArrayList screenExtents = - new ArrayList(); + ArrayList screenExtents + = new ArrayList(); - for (Object o : iterable) - { - if (o == null) + for (Object o : iterable) { + if (o == null) { continue; + } - if (o instanceof ExtentHolder) - { + if (o instanceof ExtentHolder) { extentHolders.add((ExtentHolder) o); - } - else if (o instanceof AVList) - { + } else if (o instanceof AVList) { AVList avl = (AVList) o; Object b = avl.getValue(AVKey.FEEDBACK_ENABLED); - if (b == null || !Boolean.TRUE.equals(b)) + if (b == null || !Boolean.TRUE.equals(b)) { continue; + } - if (avl.getValue(AVKey.FEEDBACK_REFERENCE_POINT) != null) - { + if (avl.getValue(AVKey.FEEDBACK_REFERENCE_POINT) != null) { screenExtents.add(new ExtentVisibilitySupport.ScreenExtent( - (Vec4) avl.getValue(AVKey.FEEDBACK_REFERENCE_POINT), - (Rectangle) avl.getValue(AVKey.FEEDBACK_SCREEN_BOUNDS))); + (Vec4) avl.getValue(AVKey.FEEDBACK_REFERENCE_POINT), + (Rectangle) avl.getValue(AVKey.FEEDBACK_SCREEN_BOUNDS))); } } } - if (!extentHolders.isEmpty()) - { + if (!extentHolders.isEmpty()) { Globe globe = this.wwd.getModel().getGlobe(); double ve = this.wwd.getSceneController().getVerticalExaggeration(); vs.setExtents(ExtentVisibilitySupport.extentsFromExtentHolders(extentHolders, globe, ve)); } - if (!screenExtents.isEmpty()) - { + if (!screenExtents.isEmpty()) { vs.setScreenExtents(screenExtents); } } @@ -397,9 +363,8 @@ else if (o instanceof AVList) //**************************************************************// //******************** View Animator *************************// //**************************************************************// + public static class ViewAnimator extends BasicAnimator { - public static class ViewAnimator extends BasicAnimator - { protected static final double LOCATION_EPSILON = 1.0e-9; protected static final double ALTITUDE_EPSILON = 0.1; @@ -409,46 +374,35 @@ public static class ViewAnimator extends BasicAnimator protected Position centerPosition; protected double zoom; - public ViewAnimator(final double smoothing, OrbitView view, ViewController viewController) - { - super(new Interpolator() - { - public double nextInterpolant() - { - return 1d - smoothing; - } - }); + public ViewAnimator(final double smoothing, OrbitView view, ViewController viewController) { + super(() -> 1d - smoothing); this.view = view; this.viewController = viewController; } - public void stop() - { + @Override + public void stop() { super.stop(); this.haveTargets = false; } - protected void setImpl(double interpolant) - { + @Override + protected void setImpl(double interpolant) { this.updateTargetValues(); - if (!this.haveTargets) - { + if (!this.haveTargets) { this.stop(); return; } - if (this.valuesMeetCriteria(this.centerPosition, this.zoom)) - { + if (this.valuesMeetCriteria(this.centerPosition, this.zoom)) { this.view.setCenterPosition(this.centerPosition); this.view.setZoom(this.zoom); this.stop(); - } - else - { + } else { Position newCenterPos = Position.interpolateGreatCircle(interpolant, this.view.getCenterPosition(), - this.centerPosition); + this.centerPosition); double newZoom = WWMath.mix(interpolant, this.view.getZoom(), this.zoom); this.view.setCenterPosition(newCenterPos); this.view.setZoom(newZoom); @@ -457,37 +411,37 @@ protected void setImpl(double interpolant) this.view.firePropertyChange(AVKey.VIEW, null, this); } - protected void updateTargetValues() - { - if (this.viewController.isSceneContained(this.view)) + protected void updateTargetValues() { + if (this.viewController.isSceneContained(this.view)) { return; + } Vec4[] lookAtPoints = this.viewController.computeViewLookAtForScene(this.view); - if (lookAtPoints == null || lookAtPoints.length != 3) + if (lookAtPoints == null || lookAtPoints.length != 3) { return; + } this.centerPosition = this.viewController.computePositionFromPoint(lookAtPoints[1]); this.zoom = lookAtPoints[0].distanceTo3(lookAtPoints[1]); - if (this.zoom < view.getZoom()) + if (this.zoom < view.getZoom()) { this.zoom = view.getZoom(); + } this.haveTargets = true; } - protected boolean valuesMeetCriteria(Position centerPos, double zoom) - { + protected boolean valuesMeetCriteria(Position centerPos, double zoom) { Angle cd = LatLon.greatCircleDistance(this.view.getCenterPosition(), centerPos); double ed = Math.abs(this.view.getCenterPosition().getElevation() - centerPos.getElevation()); double zd = Math.abs(this.view.getZoom() - zoom); return cd.degrees < LOCATION_EPSILON - && ed < ALTITUDE_EPSILON - && zd < ALTITUDE_EPSILON; + && ed < ALTITUDE_EPSILON + && zd < ALTITUDE_EPSILON; } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("Keeping Objects In View", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/LineBackground.java b/src/gov/nasa/worldwindx/examples/LineBackground.java index 7f820e6d72..810fc5a27d 100644 --- a/src/gov/nasa/worldwindx/examples/LineBackground.java +++ b/src/gov/nasa/worldwindx/examples/LineBackground.java @@ -3,9 +3,9 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.examples; +import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.View; import gov.nasa.worldwind.geom.*; import gov.nasa.worldwind.layers.RenderableLayer; @@ -17,22 +17,19 @@ /** * Illustrates how to display lines that stand out from the background imagery. The technique is to draw behind the line * a slightly wider, slightly opaque line in a contrasting color. This backing line makes the primary line stand out - * more than it otherwise would. This example shows how to do this for both SurfacePolyline and terrain-conforming - * Polyline. + * more than it otherwise would. This example shows how to do this for both SurfacePolyline and terrain-conforming Path. * * @author tag * @version $Id: LineBackground.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class LineBackground extends ApplicationTemplate -{ - public static class AppFrame extends ApplicationTemplate.AppFrame - { - public AppFrame() - { +public class LineBackground extends ApplicationTemplate { + + public static class AppFrame extends ApplicationTemplate.AppFrame { + + public AppFrame() { super(true, true, false); - try - { + try { // Specify attributes for the foreground line. ShapeAttributes foregroundAttrs = new BasicShapeAttributes(); foregroundAttrs.setOutlineMaterial(new Material(Color.BLUE)); @@ -46,11 +43,11 @@ public AppFrame() backgroundAttrs.setOutlineWidth(foregroundAttrs.getOutlineWidth() + 2); // Create the primary line as a SurfacePolyline and set its attributes. - SurfacePolyline si1 = new SurfacePolyline(new ArrayList(Arrays.asList( - LatLon.fromDegrees(33.7, 119.6), - LatLon.fromDegrees(33.5, 125), - LatLon.fromDegrees(35.1, 129.1), - LatLon.fromDegrees(35.8, 127.1) + SurfacePolyline si1 = new SurfacePolyline(new ArrayList<>(Arrays.asList( + LatLon.fromDegrees(33.7, 119.6), + LatLon.fromDegrees(33.5, 125), + LatLon.fromDegrees(35.1, 129.1), + LatLon.fromDegrees(35.8, 127.1) ))); si1.setClosed(true); si1.setAttributes(foregroundAttrs); @@ -61,29 +58,22 @@ public AppFrame() si2.setAttributes(backgroundAttrs); // Now do the same for the Polyline version, which is placed 2 degrees above the SurfacePolyline. - ArrayList plPoints = new ArrayList(); - for (LatLon ll : si1.getLocations()) - { + ArrayList plPoints = new ArrayList<>(); + for (LatLon ll : si1.getLocations()) { plPoints.add(ll.add(LatLon.fromDegrees(2, 0))); // add 2 degrees of latitude to separate the lines } - Polyline pl1 = new Polyline(plPoints, 0); // the primary Polyline - pl1.setFollowTerrain(true); - pl1.setClosed(true); - pl1.setPathType(Polyline.RHUMB_LINE); - pl1.setColor(foregroundAttrs.getOutlineMaterial().getDiffuse()); - pl1.setLineWidth(foregroundAttrs.getOutlineWidth()); - pl1.setStipplePattern(foregroundAttrs.getOutlineStipplePattern()); - pl1.setStippleFactor(foregroundAttrs.getOutlineStippleFactor()); + Path path1 = new Path(plPoints, 0); // the primary Path + path1.setFollowTerrain(true); + path1.setPathType(AVKey.RHUMB_LINE); + path1.setAttributes(foregroundAttrs); - Polyline pl2 = new Polyline(plPoints, 0); // the background Polyline - pl2.setFollowTerrain(true); - pl2.setClosed(true); - pl2.setPathType(Polyline.RHUMB_LINE); + Path path2 = new Path(plPoints, 0); // the background Path + path2.setFollowTerrain(true); + path2.setPathType(AVKey.RHUMB_LINE); float[] c = backgroundAttrs.getOutlineMaterial().getDiffuse().getColorComponents(new float[3]); - pl2.setColor(new Color(c[0], c[1], c[2], (float) backgroundAttrs.getOutlineOpacity())); - pl2.setLineWidth(backgroundAttrs.getOutlineWidth()); - pl2.setStipplePattern(backgroundAttrs.getOutlineStipplePattern()); - pl2.setStippleFactor(backgroundAttrs.getOutlineStippleFactor()); + var attrs = new BasicShapeAttributes(backgroundAttrs); + attrs.setOutlineMaterial(new Material(new Color(c[0], c[1], c[2], (float) backgroundAttrs.getOutlineOpacity()))); + path2.setAttributes(attrs); // Add all the lines to the scene. RenderableLayer layer = new RenderableLayer(); @@ -91,24 +81,21 @@ public AppFrame() layer.setPickEnabled(false); layer.addRenderable(si2); layer.addRenderable(si1); - layer.addRenderable(pl1); // Must draw the primary Polyline before drawing the background Polyline - layer.addRenderable(pl2); + layer.addRenderable(path1); // Must draw the primary Path before drawing the background Path + layer.addRenderable(path2); insertBeforeCompass(this.getWwd(), layer); // Move the view to the line locations. View view = getWwd().getView(); view.setEyePosition(Position.fromDegrees(35.3, 124.6, 1500e3)); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind Line Backgrounds", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/LineBuilder.java b/src/gov/nasa/worldwindx/examples/LineBuilder.java index 338aaeee54..aa861f97fa 100644 --- a/src/gov/nasa/worldwindx/examples/LineBuilder.java +++ b/src/gov/nasa/worldwindx/examples/LineBuilder.java @@ -20,26 +20,26 @@ import java.util.*; /** - * A utility class to interactively build a polyline. When armed, the class monitors mouse events and adds new positions - * to a polyline as the user identifies them. The interaction sequence for creating a line is as follows:
  • Arm - * the line builder by calling its {@link #setArmed(boolean)} method with an argument of true.
  • Place the - * cursor at the first desired polyline position. Press and release mouse button one.
  • Press button one near - * the next desired position, drag the mouse to the exact position, then release the button. The proposed line segment - * will echo while the mouse is dragged. Continue selecting new positions this way until the polyline contains all - * desired positions.
  • Disarm the LineBuilder object by calling its {@link #setArmed(boolean)} - * method with an argument of false.
+ * A utility class to interactively build a path. When armed, the class monitors mouse events and adds new positions to + * a path as the user identifies them. The interaction sequence for creating a line is as follows:
  • Arm the + * line builder by calling its {@link #setArmed(boolean)} method with an argument of true.
  • Place the cursor + * at the first desired path position. Press and release mouse button one.
  • Press button one near the next + * desired position, drag the mouse to the exact position, then release the button. The proposed line segment will echo + * while the mouse is dragged. Continue selecting new positions this way until the path contains all desired positions. + *
  • Disarm the LineBuilder object by calling its {@link #setArmed(boolean)} method with an + * argument of false.
*

* While the line builder is armed, pressing and immediately releasing mouse button one while also pressing the control - * key (Ctl) removes the last position from the polyline.

+ * key (Ctl) removes the last position from the path.

*

* Mouse events the line builder acts on while armed are marked as consumed. These events are mouse pressed, released, * clicked and dragged. These events are not acted on while the line builder is not armed. The builder can be - * continuously armed and rearmed to allow intervening maneuvering of the globe while building a polyline. A user can - * add positions, pause entry, maneuver the view, then continue entering positions.

+ * continuously armed and rearmed to allow intervening maneuvering of the globe while building a path. A user can add + * positions, pause entry, maneuver the view, then continue entering positions.

*

* Arming and disarming the line builder does not change the contents or attributes of the line builder's layer.

*

- * The polyline and a layer containing it may be specified when a LineBuilder is constructed.

+ * The path and a layer containing it may be specified when a LineBuilder is constructed.

*

* This class contains a main method implementing an example program illustrating use of * LineBuilder.

@@ -47,50 +47,42 @@ * @author tag * @version $Id: LineBuilder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class LineBuilder extends AVListImpl -{ +public class LineBuilder extends AVListImpl { + private final WorldWindow wwd; private boolean armed = false; - private ArrayList positions = new ArrayList(); + private ArrayList positions = new ArrayList<>(); private final RenderableLayer layer; - private final Polyline line; + private final Path line; private boolean active = false; /** - * Construct a new line builder using the specified polyline and layer and drawing events from the specified world - * window. Either or both the polyline and the layer may be null, in which case the necessary object is created. + * Construct a new line builder using the specified path and layer and drawing events from the specified world + * window. Either or both the path and the layer may be null, in which case the necessary object is created. * - * @param wwd the WorldWindow to draw events from. - * @param lineLayer the layer holding the polyline. May be null, in which case a new layer is created. - * @param polyline the polyline object to build. May be null, in which case a new polyline is created. + * @param wwd the WorldWindow to draw events from. + * @param lineLayer the layer holding the path. May be null, in which case a new layer is created. + * @param path the path object to build. May be null, in which case a new path is created. */ - public LineBuilder(final WorldWindow wwd, RenderableLayer lineLayer, Polyline polyline) - { + public LineBuilder(final WorldWindow wwd, RenderableLayer lineLayer, Path path) { this.wwd = wwd; - if (polyline != null) - { - line = polyline; - } - else - { - this.line = new Polyline(); + if (path != null) { + line = path; + } else { + this.line = new Path(); this.line.setFollowTerrain(true); } this.layer = lineLayer != null ? lineLayer : new RenderableLayer(); this.layer.addRenderable(this.line); this.wwd.getModel().getLayers().add(this.layer); - this.wwd.getInputHandler().addMouseListener(new MouseAdapter() - { - public void mousePressed(MouseEvent mouseEvent) - { - if (armed && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if (armed && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) - { - if (!mouseEvent.isControlDown()) - { + this.wwd.getInputHandler().addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent mouseEvent) { + if (armed && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if (armed && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { + if (!mouseEvent.isControlDown()) { active = true; addPosition(); } @@ -99,85 +91,80 @@ public void mousePressed(MouseEvent mouseEvent) } } - public void mouseReleased(MouseEvent mouseEvent) - { - if (armed && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if (positions.size() == 1) + @Override + public void mouseReleased(MouseEvent mouseEvent) { + if (armed && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if (positions.size() == 1) { removePosition(); + } active = false; mouseEvent.consume(); } } - public void mouseClicked(MouseEvent mouseEvent) - { - if (armed && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if (mouseEvent.isControlDown()) + @Override + public void mouseClicked(MouseEvent mouseEvent) { + if (armed && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if (mouseEvent.isControlDown()) { removePosition(); + } mouseEvent.consume(); } } }); - this.wwd.getInputHandler().addMouseMotionListener(new MouseMotionAdapter() - { - public void mouseDragged(MouseEvent mouseEvent) - { - if (armed && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) - { - // Don't update the polyline here because the wwd current cursor position will not + this.wwd.getInputHandler().addMouseMotionListener(new MouseMotionAdapter() { + @Override + public void mouseDragged(MouseEvent mouseEvent) { + if (armed && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { + // Don't update the path 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.wwd.addPositionListener(new PositionListener() - { - public void moved(PositionEvent event) - { - if (!active) - return; - - if (positions.size() == 1) - addPosition(); - else - replacePosition(); + this.wwd.addPositionListener((PositionEvent event) -> { + if (!active) { + return; + } + + if (positions.size() == 1) { + addPosition(); + } else { + replacePosition(); } }); } /** - * Returns the layer holding the polyline being created. + * Returns the layer holding the path being created. * - * @return the layer containing the polyline. + * @return the layer containing the path. */ - public RenderableLayer getLayer() - { + public RenderableLayer getLayer() { return this.layer; } /** - * Returns the layer currently used to display the polyline. + * Returns the layer currently used to display the path. * - * @return the layer holding the polyline. + * @return the layer holding the path. */ - public Polyline getLine() - { + public Path getLine() { return this.line; } /** - * Removes all positions from the polyline. + * Removes all positions from the path. */ - public void clear() - { - while (this.positions.size() > 0) + public void clear() { + while (this.positions.size() > 0) { this.removePosition(); + } } /** @@ -185,27 +172,25 @@ public void clear() * * @return true if armed, false if not armed. */ - public boolean isArmed() - { + public boolean isArmed() { return this.armed; } /** - * Arms and disarms the line builder. When armed, the line builder monitors user input and builds the polyline in + * Arms and disarms the line builder. When armed, the line builder monitors user input and builds the path in * response to the actions mentioned in the overview above. When disarmed, the line builder ignores all user input. * * @param armed true to arm the line builder, false to disarm it. */ - public void setArmed(boolean armed) - { + public void setArmed(boolean armed) { this.armed = armed; } - private void addPosition() - { + private void addPosition() { Position curPos = this.wwd.getCurrentPosition(); - if (curPos == null) + if (curPos == null) { return; + } this.positions.add(curPos); this.line.setPositions(this.positions); @@ -213,15 +198,16 @@ private void addPosition() this.wwd.redraw(); } - private void replacePosition() - { + private void replacePosition() { Position curPos = this.wwd.getCurrentPosition(); - if (curPos == null) + if (curPos == null) { return; + } int index = this.positions.size() - 1; - if (index < 0) + if (index < 0) { index = 0; + } Position currentLastPosition = this.positions.get(index); this.positions.set(index, curPos); @@ -230,10 +216,10 @@ private void replacePosition() this.wwd.redraw(); } - private void removePosition() - { - if (this.positions.size() == 0) + private void removePosition() { + if (this.positions.isEmpty()) { return; + } Position currentLastPosition = this.positions.get(this.positions.size() - 1); this.positions.remove(this.positions.size() - 1); @@ -245,9 +231,8 @@ private void removePosition() // ===================== Control Panel ======================= // // The following code is an example program illustrating LineBuilder usage. It is not required by the // LineBuilder class, itself. + private static class LinePanel extends JPanel { - private static class LinePanel extends JPanel - { private final WorldWindow wwd; private final LineBuilder lineBuilder; private JButton newButton; @@ -255,66 +240,48 @@ private static class LinePanel extends JPanel private JButton endButton; private JLabel[] pointLabels; - public LinePanel(WorldWindow wwd, LineBuilder lineBuilder) - { + public LinePanel(WorldWindow wwd, LineBuilder lineBuilder) { super(new BorderLayout()); this.wwd = wwd; this.lineBuilder = lineBuilder; this.makePanel(new Dimension(200, 400)); - lineBuilder.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { - fillPointsPanel(); - } + lineBuilder.addPropertyChangeListener((PropertyChangeEvent propertyChangeEvent) -> { + fillPointsPanel(); }); } - private void makePanel(Dimension size) - { + private void makePanel(Dimension size) { JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 5)); newButton = new JButton("New"); - newButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - lineBuilder.clear(); - lineBuilder.setArmed(true); - pauseButton.setText("Pause"); - pauseButton.setEnabled(true); - endButton.setEnabled(true); - newButton.setEnabled(false); - ((Component) wwd).setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - } + newButton.addActionListener((ActionEvent actionEvent) -> { + lineBuilder.clear(); + lineBuilder.setArmed(true); + pauseButton.setText("Pause"); + pauseButton.setEnabled(true); + endButton.setEnabled(true); + newButton.setEnabled(false); + ((Component) wwd).setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); }); buttonPanel.add(newButton); newButton.setEnabled(true); pauseButton = new JButton("Pause"); - pauseButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - lineBuilder.setArmed(!lineBuilder.isArmed()); - pauseButton.setText(!lineBuilder.isArmed() ? "Resume" : "Pause"); - ((Component) wwd).setCursor(Cursor.getDefaultCursor()); - } + pauseButton.addActionListener((ActionEvent actionEvent) -> { + lineBuilder.setArmed(!lineBuilder.isArmed()); + pauseButton.setText(!lineBuilder.isArmed() ? "Resume" : "Pause"); + ((Component) wwd).setCursor(Cursor.getDefaultCursor()); }); buttonPanel.add(pauseButton); pauseButton.setEnabled(false); endButton = new JButton("End"); - endButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - lineBuilder.setArmed(false); - newButton.setEnabled(true); - pauseButton.setEnabled(false); - pauseButton.setText("Pause"); - endButton.setEnabled(false); - ((Component) wwd).setCursor(Cursor.getDefaultCursor()); - } + endButton.addActionListener((ActionEvent actionEvent) -> { + lineBuilder.setArmed(false); + newButton.setEnabled(true); + pauseButton.setEnabled(false); + pauseButton.setText("Pause"); + endButton.setEnabled(false); + ((Component) wwd).setCursor(Cursor.getDefaultCursor()); }); buttonPanel.add(endButton); endButton.setEnabled(false); @@ -323,8 +290,7 @@ public void actionPerformed(ActionEvent actionEvent) pointPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.pointLabels = new JLabel[20]; - for (int i = 0; i < this.pointLabels.length; i++) - { + for (int i = 0; i < this.pointLabels.length; i++) { this.pointLabels[i] = new JLabel(""); pointPanel.add(this.pointLabels[i]); } @@ -336,33 +302,34 @@ public void actionPerformed(ActionEvent actionEvent) // Put the point panel in a scroll bar. JScrollPane scrollPane = new JScrollPane(dummyPanel); scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); - if (size != null) + if (size != null) { scrollPane.setPreferredSize(size); + } // Add the buttons, scroll bar and inner panel to a titled panel that will resize with the main window. JPanel outerPanel = new JPanel(new BorderLayout()); outerPanel.setBorder( - new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Line"))); + new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Line"))); outerPanel.setToolTipText("Line control and info"); outerPanel.add(buttonPanel, BorderLayout.NORTH); outerPanel.add(scrollPane, BorderLayout.CENTER); this.add(outerPanel, BorderLayout.CENTER); } - private void fillPointsPanel() - { + private void fillPointsPanel() { int i = 0; - for (Position pos : lineBuilder.getLine().getPositions()) - { - if (i == this.pointLabels.length) + for (Position pos : lineBuilder.getLine().getPositions()) { + if (i == this.pointLabels.length) { break; + } String las = String.format("Lat %7.4f\u00B0", pos.getLatitude().getDegrees()); String los = String.format("Lon %7.4f\u00B0", pos.getLongitude().getDegrees()); pointLabels[i++].setText(las + " " + los); } - for (; i < this.pointLabels.length; i++) + for (; i < this.pointLabels.length; i++) { pointLabels[i++].setText(""); + } } } @@ -371,10 +338,10 @@ private void fillPointsPanel() * * @deprecated */ - public static class AppFrame extends ApplicationTemplate.AppFrame - { - public AppFrame() - { + @Deprecated + public static class AppFrame extends ApplicationTemplate.AppFrame { + + public AppFrame() { super(true, false, false); LineBuilder lineBuilder = new LineBuilder(this.getWwd(), null, null); @@ -382,14 +349,7 @@ public AppFrame() } } - /** - * Marked as deprecated to keep it out of the javadoc. - * - * @param args the arguments passed to the program. - * @deprecated - */ - public static void main(String[] args) - { + public static void main(String[] args) { //noinspection deprecation ApplicationTemplate.start("WorldWind Line Builder", LineBuilder.AppFrame.class); } diff --git a/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java b/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java index 50ed4f77f1..5f7c053695 100644 --- a/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java +++ b/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java @@ -424,7 +424,7 @@ public void actionPerformed(ActionEvent actionEvent) public void actionPerformed(ActionEvent actionEvent) { shapeCombo.setSelectedIndex(1); - measureTool.setMeasureShape(new Polyline(PATH)); + measureTool.setMeasureShape(new Path(PATH)); } }); presetPanel.add(bt); diff --git a/src/gov/nasa/worldwindx/examples/MultiResPath.java b/src/gov/nasa/worldwindx/examples/MultiResPath.java index ae9cefaedb..f59c642609 100644 --- a/src/gov/nasa/worldwindx/examples/MultiResPath.java +++ b/src/gov/nasa/worldwindx/examples/MultiResPath.java @@ -80,7 +80,7 @@ protected void addShape(Position origin) attrs.setDrawInterior(false); attrs.setOutlineMaterial(Material.RED); - MultiResolutionPath path = new MultiResolutionPath(positions); + Path path = new Path(positions); // Indicate that dots are to be drawn at each specified path position. path.setShowPositions(true); diff --git a/src/gov/nasa/worldwindx/examples/Shapes.java b/src/gov/nasa/worldwindx/examples/Shapes.java index 84dadfd96f..b43a6526ce 100644 --- a/src/gov/nasa/worldwindx/examples/Shapes.java +++ b/src/gov/nasa/worldwindx/examples/Shapes.java @@ -86,19 +86,16 @@ public AppFrame() { this.setLocation(x, y); this.setResizable(true); - wwjPanel.getWwd().addRenderingListener(new RenderingListener() { - public void stageChanged(RenderingEvent event) { - if (!event.getStage().equals(RenderingEvent.BEFORE_BUFFER_SWAP)) { - return; - } - - if (currentShape instanceof Path) { - Path p = (Path) currentShape; - String length = Double.toString(p.getLength()); - textRenderer.beginRendering(wwjPanel.getWidth(), wwjPanel.getHeight()); - textRenderer.draw(length, 100, 100); - textRenderer.endRendering(); - } + wwjPanel.getWwd().addRenderingListener((RenderingEvent event) -> { + if (!event.getStage().equals(RenderingEvent.BEFORE_BUFFER_SWAP)) { + return; + } + if (currentShape instanceof Path) { + Path p1 = (Path) currentShape; + String length = Double.toString(p1.getLength()); + textRenderer.beginRendering(wwjPanel.getWidth(), wwjPanel.getHeight()); + textRenderer.draw(length, 100, 100); + textRenderer.endRendering(); } }); @@ -131,13 +128,13 @@ public void stageChanged(RenderingEvent event) { private ArrayList offTerrainOnlyItems = new ArrayList<>(); private void update() { - for (JComponent c : onTerrainOnlyItems) { + onTerrainOnlyItems.forEach((c) -> { c.setEnabled(currentFollowTerrain); - } + }); - for (JComponent c : offTerrainOnlyItems) { + offTerrainOnlyItems.forEach((c) -> { c.setEnabled(!currentFollowTerrain); - } + }); if (this.currentShape instanceof SurfaceShape) { SurfaceShape shape = (SurfaceShape) currentShape; @@ -151,14 +148,21 @@ private void update() { float alpha = currentBorderOpacity >= 10 ? 1f : currentBorderOpacity <= 0 ? 0f : currentBorderOpacity / 10f; Color color = null; - if (currentBorderColor.equals("Yellow")) { - color = new Color(1f, 1f, 0f); - } else if (currentBorderColor.equals("Red")) { - color = new Color(1f, 0f, 0f); - } else if (currentBorderColor.equals("Green")) { - color = new Color(0f, 1f, 0f); - } else if (currentBorderColor.equals("Blue")) { - color = new Color(0f, 0f, 1f); + switch (currentBorderColor) { + case "Yellow": + color = new Color(1f, 1f, 0f); + break; + case "Red": + color = new Color(1f, 0f, 0f); + break; + case "Green": + color = new Color(0f, 1f, 0f); + break; + case "Blue": + color = new Color(0f, 0f, 1f); + break; + default: + break; } attr.setDrawOutline(true); @@ -173,14 +177,21 @@ private void update() { float alpha = currentInteriorOpacity >= 10 ? 1f : currentInteriorOpacity <= 0 ? 0f : currentInteriorOpacity / 10f; Color color = null; - if (currentInteriorColor.equals("Yellow")) { - color = new Color(1f, 1f, 0f); - } else if (currentInteriorColor.equals("Red")) { - color = new Color(1f, 0f, 0f); - } else if (currentInteriorColor.equals("Green")) { - color = new Color(0f, 1f, 0f); - } else if (currentInteriorColor.equals("Blue")) { - color = new Color(0f, 0f, 1f); + switch (currentInteriorColor) { + case "Yellow": + color = new Color(1f, 1f, 0f); + break; + case "Red": + color = new Color(1f, 0f, 0f); + break; + case "Green": + color = new Color(0f, 1f, 0f); + break; + case "Blue": + color = new Color(0f, 0f, 1f); + break; + default: + break; } attr.setInteriorMaterial(new Material(color)); @@ -195,14 +206,21 @@ private void update() { float alpha = currentPathOpacity >= 10 ? 1f : currentPathOpacity <= 0 ? 0f : currentPathOpacity / 10f; Color color = null; - if (currentPathColor.equals("Yellow")) { - color = new Color(1f, 1f, 0f, alpha); - } else if (currentPathColor.equals("Red")) { - color = new Color(1f, 0f, 0f, alpha); - } else if (currentPathColor.equals("Green")) { - color = new Color(0f, 1f, 0f, alpha); - } else if (currentPathColor.equals("Blue")) { - color = new Color(0f, 0f, 1f, alpha); + switch (currentPathColor) { + case "Yellow": + color = new Color(1f, 1f, 0f, alpha); + break; + case "Red": + color = new Color(1f, 0f, 0f, alpha); + break; + case "Green": + color = new Color(0f, 1f, 0f, alpha); + break; + case "Blue": + color = new Color(0f, 0f, 1f, alpha); + break; + default: + break; } if (currentShape instanceof Path) { @@ -250,11 +268,6 @@ private Info[] buildSurfaceShapes() { LatLon position = new LatLon(Angle.fromDegrees(38), Angle.fromDegrees(-105)); ArrayList surfaceLinePositions = new ArrayList<>(); -// surfaceLinePositions.add(LatLon.fromDegrees(37.8484, -119.9754)); -// surfaceLinePositions.add(LatLon.fromDegrees(38.3540, -119.1526)); - -// surfaceLinePositions.add(new LatLon(Angle.fromDegrees(0), Angle.fromDegrees(-150))); -// surfaceLinePositions.add(new LatLon(Angle.fromDegrees(60), Angle.fromDegrees(0))); surfaceLinePositions.add(position); surfaceLinePositions.add(LatLon.fromDegrees(39, -104)); surfaceLinePositions.add(LatLon.fromDegrees(39, -105)); @@ -295,7 +308,6 @@ private Info[] buildFreeShapes() { positions5.add(Position.fromDegrees(38.0 + i * 0.0001, 30.0 + i * 0.0001, 1000.0 + i * 5.0)); } - @SuppressWarnings({"UnnecessaryLocalVariable"}) Info[] infos = new Info[]{ new Info("Short Path", new Path(positions)), new Info("Long Path", new Path(positions2)), @@ -316,12 +328,9 @@ private JPanel makeShapeSelectionPanel() { ButtonGroup group = new ButtonGroup(); for (final Info info : surfaceShapeInfos) { JRadioButton b = new JRadioButton(info.name); - b.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - currentShape = (Renderable) info.object; - update(); - } + b.addActionListener((ActionEvent actionEvent) -> { + currentShape = (Renderable) info.object; + update(); }); group.add(b); ssPanel.add(b); @@ -336,11 +345,9 @@ public void actionPerformed(ActionEvent actionEvent) { JPanel fsPanel = new JPanel(layout); for (final Info info : freeShapeInfos) { JRadioButton b = new JRadioButton(info.name); - b.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent actionEvent) { - currentShape = (Renderable) info.object; - update(); - } + b.addActionListener((ActionEvent actionEvent) -> { + currentShape = (Renderable) info.object; + update(); }); group.add(b); fsPanel.add(b); @@ -359,7 +366,6 @@ public void actionPerformed(ActionEvent actionEvent) { private Border createTitleBorder(String title) { TitledBorder b = BorderFactory.createTitledBorder(title); -// b.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); return new CompoundBorder(b, BorderFactory.createEmptyBorder(10, 10, 10, 10)); } @@ -384,11 +390,9 @@ private JPanel makePathAttributesPanel() { namePanel.add(new JLabel("Follow Terrain")); JCheckBox ckb = new JCheckBox(); ckb.setSelected(currentFollowTerrain); - ckb.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent actionEvent) { - currentFollowTerrain = ((JCheckBox) actionEvent.getSource()).isSelected(); - update(); - } + ckb.addActionListener((ActionEvent actionEvent) -> { + currentFollowTerrain = ((JCheckBox) actionEvent.getSource()).isSelected(); + update(); }); valuePanel.add(ckb); @@ -404,12 +408,10 @@ public void actionPerformed(ActionEvent actionEvent) { new SpinnerListModel(strings)); onTerrainOnlyItems.add(label); onTerrainOnlyItems.add(sp); - sp.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent changeEvent) { - String v = (String) ((JSpinner) changeEvent.getSource()).getValue(); - currentTerrainConformance = Integer.parseInt(v.substring(0, v.indexOf(" "))); - update(); - } + sp.addChangeListener((ChangeEvent changeEvent) -> { + String v = (String) ((JSpinner) changeEvent.getSource()).getValue(); + currentTerrainConformance = Integer.parseInt(v.substring(0, v.indexOf(" "))); + update(); }); sp.setValue(Integer.toString(currentTerrainConformance) + " pixels"); valuePanel.add(sp); @@ -418,45 +420,37 @@ public void stateChanged(ChangeEvent changeEvent) { sp = new JSpinner(new SpinnerListModel(new String[]{"1", "2", "5", "10", "20", "40", "50"})); offTerrainOnlyItems.add(label); offTerrainOnlyItems.add(sp); - sp.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent changeEvent) { - String v = (String) ((JSpinner) changeEvent.getSource()).getValue(); - currentNumSubsegments = Integer.parseInt(v); - update(); - } + sp.addChangeListener((ChangeEvent changeEvent) -> { + String v = (String) ((JSpinner) changeEvent.getSource()).getValue(); + currentNumSubsegments = Integer.parseInt(v); + update(); }); sp.setValue(Integer.toString(currentNumSubsegments)); valuePanel.add(sp); namePanel.add(new JLabel("Type")); final JComboBox cb = new JComboBox(new String[]{"Great Circle", "Linear", "Rhumb Line"}); - cb.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent actionEvent) { - currentPathType = (String) cb.getSelectedItem(); - update(); - } + cb.addActionListener((ActionEvent actionEvent) -> { + currentPathType = (String) cb.getSelectedItem(); + update(); }); cb.setSelectedItem("Great Circle"); valuePanel.add(cb); namePanel.add(new JLabel("Style")); final JComboBox cb1 = new JComboBox(new String[]{"None", "Solid", "Dash"}); - cb1.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent actionEvent) { - currentPathStyle = (String) cb1.getSelectedItem(); - update(); - } + cb1.addActionListener((ActionEvent actionEvent) -> { + currentPathStyle = (String) cb1.getSelectedItem(); + update(); }); cb1.setSelectedItem("Solid"); valuePanel.add(cb1); namePanel.add(new JLabel("Width")); sp = new JSpinner(new SpinnerNumberModel(this.currentPathWidth, 1d, 10d, 1d)); - sp.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent changeEvent) { - currentPathWidth = (Double) ((JSpinner) changeEvent.getSource()).getValue(); - update(); - } + sp.addChangeListener((ChangeEvent changeEvent) -> { + currentPathWidth = (Double) ((JSpinner) changeEvent.getSource()).getValue(); + update(); }); sp.setValue(currentPathWidth); valuePanel.add(sp); @@ -464,32 +458,26 @@ public void stateChanged(ChangeEvent changeEvent) { namePanel.add(new JLabel("Color")); JComboBox cb2 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb2.setSelectedItem(currentPathColor); - cb2.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent actionEvent) { - currentPathColor = (String) ((JComboBox) actionEvent.getSource()).getSelectedItem(); - update(); - } + cb2.addActionListener((ActionEvent actionEvent) -> { + currentPathColor = (String) ((JComboBox) actionEvent.getSource()).getSelectedItem(); + update(); }); valuePanel.add(cb2); namePanel.add(new JLabel("Opacity")); sp = new JSpinner(new SpinnerNumberModel(this.currentPathOpacity, 0, 10, 1)); - sp.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent changeEvent) { - currentPathOpacity = (Integer) ((JSpinner) changeEvent.getSource()).getValue(); - update(); - } + sp.addChangeListener((ChangeEvent changeEvent) -> { + currentPathOpacity = (Integer) ((JSpinner) changeEvent.getSource()).getValue(); + update(); }); valuePanel.add(sp); namePanel.add(new JLabel("Offset")); sp = new JSpinner( new SpinnerListModel(new String[]{"0", "10", "100", "1000", "10000", "100000", "1000000"})); - sp.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent changeEvent) { - currentOffset = Float.parseFloat((String) ((JSpinner) changeEvent.getSource()).getValue()); - update(); - } + sp.addChangeListener((ChangeEvent changeEvent) -> { + currentOffset = Float.parseFloat((String) ((JSpinner) changeEvent.getSource()).getValue()); + update(); }); sp.setValue("0"); valuePanel.add(sp); @@ -512,54 +500,44 @@ private JPanel makeInteriorAttributesPanel() { namePanel.add(new JLabel("Style")); final JComboBox cb1 = new JComboBox(new String[]{"None", "Solid"}); - cb1.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent actionEvent) { - currentInteriorStyle = (String) cb1.getSelectedItem(); - update(); - } + cb1.addActionListener((ActionEvent actionEvent) -> { + currentInteriorStyle = (String) cb1.getSelectedItem(); + update(); }); cb1.setSelectedItem("Solid"); valuePanel.add(cb1); namePanel.add(new JLabel("Opacity")); JSpinner sp = new JSpinner(new SpinnerNumberModel(this.currentBorderOpacity, 0, 10, 1)); - sp.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent changeEvent) { - currentInteriorOpacity = (Integer) ((JSpinner) changeEvent.getSource()).getValue(); - update(); - } + sp.addChangeListener((ChangeEvent changeEvent) -> { + currentInteriorOpacity = (Integer) ((JSpinner) changeEvent.getSource()).getValue(); + update(); }); valuePanel.add(sp); namePanel.add(new JLabel("Color")); final JComboBox cb2 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb2.setSelectedItem(currentInteriorColor); - cb2.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent actionEvent) { - currentInteriorColor = (String) ((JComboBox) actionEvent.getSource()).getSelectedItem(); - update(); - } + cb2.addActionListener((ActionEvent actionEvent) -> { + currentInteriorColor = (String) ((JComboBox) actionEvent.getSource()).getSelectedItem(); + update(); }); valuePanel.add(cb2); namePanel.add(new JLabel("Border")); final JComboBox cb5 = new JComboBox(new String[]{"None", "Solid"}); - cb5.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent actionEvent) { - currentBorderStyle = (String) cb5.getSelectedItem(); - update(); - } + cb5.addActionListener((ActionEvent actionEvent) -> { + currentBorderStyle = (String) cb5.getSelectedItem(); + update(); }); cb5.setSelectedItem("Solid"); valuePanel.add(cb5); namePanel.add(new JLabel("Border Width")); sp = new JSpinner(new SpinnerNumberModel(this.currentBorderWidth, 1d, 10d, 1d)); - sp.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent changeEvent) { - currentBorderWidth = (Double) ((JSpinner) changeEvent.getSource()).getValue(); - update(); - } + sp.addChangeListener((ChangeEvent changeEvent) -> { + currentBorderWidth = (Double) ((JSpinner) changeEvent.getSource()).getValue(); + update(); }); sp.setValue(currentBorderWidth); valuePanel.add(sp); @@ -567,21 +545,17 @@ public void stateChanged(ChangeEvent changeEvent) { namePanel.add(new JLabel("Border Color")); JComboBox cb4 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb4.setSelectedItem(currentBorderColor); - cb4.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent actionEvent) { - currentBorderColor = (String) ((JComboBox) actionEvent.getSource()).getSelectedItem(); - update(); - } + cb4.addActionListener((ActionEvent actionEvent) -> { + currentBorderColor = (String) ((JComboBox) actionEvent.getSource()).getSelectedItem(); + update(); }); valuePanel.add(cb4); namePanel.add(new JLabel("Border Opacity")); sp = new JSpinner(new SpinnerNumberModel(this.currentBorderOpacity, 0, 10, 1)); - sp.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent changeEvent) { - currentBorderOpacity = (Integer) ((JSpinner) changeEvent.getSource()).getValue(); - update(); - } + sp.addChangeListener((ChangeEvent changeEvent) -> { + currentBorderOpacity = (Integer) ((JSpinner) changeEvent.getSource()).getValue(); + update(); }); valuePanel.add(sp); @@ -594,8 +568,9 @@ public void stateChanged(ChangeEvent changeEvent) { private void setupSelection() { this.wwjPanel.getWwd().addSelectListener(new SelectListener() { private WWIcon lastToolTipIcon = null; - private BasicDragger dragger = new BasicDragger(AppFrame.this.wwjPanel.getWwd()); + private final BasicDragger dragger = new BasicDragger(AppFrame.this.wwjPanel.getWwd()); + @Override public void selected(SelectEvent event) { // Have hover selections show a picked icon's tool tip. if (event.getEventAction().equals(SelectEvent.HOVER)) { diff --git a/src/gov/nasa/worldwindx/examples/SurfaceImages.java b/src/gov/nasa/worldwindx/examples/SurfaceImages.java index 80ba88657a..8e6fcc3855 100644 --- a/src/gov/nasa/worldwindx/examples/SurfaceImages.java +++ b/src/gov/nasa/worldwindx/examples/SurfaceImages.java @@ -5,6 +5,7 @@ */ package gov.nasa.worldwindx.examples; +import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.formats.tiff.GeotiffImageReaderSpi; import gov.nasa.worldwind.geom.LatLon; import gov.nasa.worldwind.layers.RenderableLayer; @@ -21,10 +22,9 @@ * @author tag * @version $Id: SurfaceImages.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class SurfaceImages extends ApplicationTemplate -{ - static - { +public class SurfaceImages extends ApplicationTemplate { + + static { IIORegistry reg = IIORegistry.getDefaultInstance(); reg.registerServiceProvider(GeotiffImageReaderSpi.inst()); } @@ -32,37 +32,37 @@ public class SurfaceImages extends ApplicationTemplate protected static final String GEORSS_ICON_PATH = "gov/nasa/worldwindx/examples/images/georss.png"; protected static final String TEST_PATTERN = "gov/nasa/worldwindx/examples/images/antenna.png"; - public static class AppFrame extends ApplicationTemplate.AppFrame - { - public AppFrame() - { + public static class AppFrame extends ApplicationTemplate.AppFrame { + + public AppFrame() { super(true, true, false); - try - { - SurfaceImage si1 = new SurfaceImage(GEORSS_ICON_PATH, new ArrayList(Arrays.asList( - LatLon.fromDegrees(20d, -115d), - LatLon.fromDegrees(20d, -105d), - LatLon.fromDegrees(32d, -102d), - LatLon.fromDegrees(30d, -115d) + try { + SurfaceImage si1 = new SurfaceImage(GEORSS_ICON_PATH, new ArrayList<>(Arrays.asList( + LatLon.fromDegrees(20d, -115d), + LatLon.fromDegrees(20d, -105d), + LatLon.fromDegrees(32d, -102d), + LatLon.fromDegrees(30d, -115d) ))); - SurfaceImage si2 = new SurfaceImage(TEST_PATTERN, new ArrayList(Arrays.asList( - LatLon.fromDegrees(37.8677, -105.1668), - LatLon.fromDegrees(37.8677, -104.8332), - LatLon.fromDegrees(38.1321, -104.8326), - LatLon.fromDegrees(38.1321, -105.1674) + SurfaceImage si2 = new SurfaceImage(TEST_PATTERN, new ArrayList<>(Arrays.asList( + LatLon.fromDegrees(37.8677, -105.1668), + LatLon.fromDegrees(37.8677, -104.8332), + LatLon.fromDegrees(38.1321, -104.8326), + LatLon.fromDegrees(38.1321, -105.1674) ))); - Polyline boundary = new Polyline(si1.getCorners(), 0); + Path boundary = new Path(si1.getCorners(), 0); boundary.setFollowTerrain(true); - boundary.setClosed(true); - boundary.setPathType(Polyline.RHUMB_LINE); - boundary.setColor(new Color(0, 255, 0)); + boundary.setPathType(AVKey.RHUMB_LINE); + var attrs = new BasicShapeAttributes(); + attrs.setOutlineMaterial(new Material(new Color(0, 255, 0))); + boundary.setAttributes(attrs); - Polyline boundary2 = new Polyline(si2.getCorners(), 0); + Path boundary2 = new Path(si2.getCorners(), 0); boundary2.setFollowTerrain(true); - boundary2.setClosed(true); - boundary2.setPathType(Polyline.RHUMB_LINE); - boundary2.setColor(new Color(0, 255, 0)); + boundary2.setPathType(AVKey.RHUMB_LINE); + attrs = new BasicShapeAttributes(); + attrs.setOutlineMaterial(new Material(new Color(0, 255, 0))); + boundary2.setAttributes(attrs); RenderableLayer layer = new RenderableLayer(); layer.setName("Surface Images"); @@ -73,16 +73,13 @@ public AppFrame() layer.addRenderable(boundary2); insertBeforeCompass(this.getWwd(), layer); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind Surface Images", SurfaceImages.AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/util/ShapefileLoader.java b/src/gov/nasa/worldwindx/examples/util/ShapefileLoader.java index 96258bfd45..ab07156d00 100644 --- a/src/gov/nasa/worldwindx/examples/util/ShapefileLoader.java +++ b/src/gov/nasa/worldwindx/examples/util/ShapefileLoader.java @@ -31,6 +31,7 @@ * @version $Id: ShapefileLoader.java 2326 2014-09-17 22:35:45Z dcollins $ * @deprecated Use {@link ShapefileLayerFactory} instead. */ +@Deprecated public class ShapefileLoader { protected static final RandomShapeAttributes randomAttrs = new RandomShapeAttributes(); diff --git a/src/org/codehaus/jackson/JsonFactory.java b/src/org/codehaus/jackson/JsonFactory.java index 37bd8a539f..125c63ca37 100644 --- a/src/org/codehaus/jackson/JsonFactory.java +++ b/src/org/codehaus/jackson/JsonFactory.java @@ -190,6 +190,7 @@ public final boolean isEnabled(JsonParser.Feature f) { * @param f Undocumented. * @deprecated Use {@link #enable(JsonParser.Feature)} instead */ + @Deprecated public final void enableParserFeature(JsonParser.Feature f) { enable(f); } @@ -198,6 +199,7 @@ public final void enableParserFeature(JsonParser.Feature f) { * @param f Undocumented. * @deprecated Use {@link #disable(JsonParser.Feature)} instead */ + @Deprecated public final void disableParserFeature(JsonParser.Feature f) { disable(f); } @@ -207,6 +209,7 @@ public final void disableParserFeature(JsonParser.Feature f) { * @param state Undocumented. * @deprecated Use {@link #configure(JsonParser.Feature, boolean)} instead */ + @Deprecated public final void setParserFeature(JsonParser.Feature f, boolean state) { configure(f, state); } @@ -216,6 +219,7 @@ public final void setParserFeature(JsonParser.Feature f, boolean state) { * @return Undocumented. * @deprecated Use {@link #isEnabled(JsonParser.Feature)} instead */ + @Deprecated public final boolean isParserFeatureEnabled(JsonParser.Feature f) { return (_parserFeatures & f.getMask()) != 0; } @@ -288,6 +292,7 @@ public final boolean isEnabled(JsonGenerator.Feature f) { * @param f Undocumented. * @deprecated Use {@link #enable(JsonGenerator.Feature)} instead */ + @Deprecated public final void enableGeneratorFeature(JsonGenerator.Feature f) { enable(f); } @@ -296,6 +301,7 @@ public final void enableGeneratorFeature(JsonGenerator.Feature f) { * @param f Undocumented. * @deprecated Use {@link #disable(JsonGenerator.Feature)} instead */ + @Deprecated public final void disableGeneratorFeature(JsonGenerator.Feature f) { disable(f); } @@ -305,6 +311,7 @@ public final void disableGeneratorFeature(JsonGenerator.Feature f) { * @param state Undocumented. * @deprecated Use {@link #configure(JsonGenerator.Feature, boolean)} instead */ + @Deprecated public final void setGeneratorFeature(JsonGenerator.Feature f, boolean state) { configure(f, state); } @@ -314,6 +321,7 @@ public final void setGeneratorFeature(JsonGenerator.Feature f, boolean state) { * @return Undocumented. * @deprecated Use {@link #isEnabled(JsonGenerator.Feature)} instead */ + @Deprecated public final boolean isGeneratorFeatureEnabled(JsonGenerator.Feature f) { return isEnabled(f); } diff --git a/src/org/codehaus/jackson/annotate/JsonClass.java b/src/org/codehaus/jackson/annotate/JsonClass.java index f91a16c45b..d6be7a2f80 100644 --- a/src/org/codehaus/jackson/annotate/JsonClass.java +++ b/src/org/codehaus/jackson/annotate/JsonClass.java @@ -30,6 +30,7 @@ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotation +@Deprecated public @interface JsonClass { /** diff --git a/src/org/codehaus/jackson/annotate/JsonContentClass.java b/src/org/codehaus/jackson/annotate/JsonContentClass.java index 6412413243..3f0d5d789c 100644 --- a/src/org/codehaus/jackson/annotate/JsonContentClass.java +++ b/src/org/codehaus/jackson/annotate/JsonContentClass.java @@ -27,6 +27,7 @@ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotation +@Deprecated public @interface JsonContentClass { /** diff --git a/src/org/codehaus/jackson/annotate/JsonGetter.java b/src/org/codehaus/jackson/annotate/JsonGetter.java index f262f32632..efe8942757 100644 --- a/src/org/codehaus/jackson/annotate/JsonGetter.java +++ b/src/org/codehaus/jackson/annotate/JsonGetter.java @@ -22,6 +22,7 @@ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotation +@Deprecated public @interface JsonGetter { /** diff --git a/src/org/codehaus/jackson/annotate/JsonKeyClass.java b/src/org/codehaus/jackson/annotate/JsonKeyClass.java index a93d8a1e58..9de10398f3 100644 --- a/src/org/codehaus/jackson/annotate/JsonKeyClass.java +++ b/src/org/codehaus/jackson/annotate/JsonKeyClass.java @@ -29,6 +29,7 @@ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotation +@Deprecated public @interface JsonKeyClass { /** diff --git a/src/org/codehaus/jackson/annotate/JsonSetter.java b/src/org/codehaus/jackson/annotate/JsonSetter.java index ac969df9e9..c9cfcff2db 100644 --- a/src/org/codehaus/jackson/annotate/JsonSetter.java +++ b/src/org/codehaus/jackson/annotate/JsonSetter.java @@ -19,6 +19,7 @@ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotation +@Deprecated public @interface JsonSetter { /** From 510cf0c6762b00c9ebd38d3e187cc9d4bb0f7f88 Mon Sep 17 00:00:00 2001 From: markpet49 Date: Thu, 19 Sep 2019 18:24:23 -0500 Subject: [PATCH 05/11] Deprecation/Lint fixes --- src/gov/nasa/worldwind/WorldWind.java | 4 +- src/gov/nasa/worldwind/awt/KeyEventState.java | 190 ++- .../worldwind/cache/BasicMemoryCache.java | 16 - .../shapefile/ShapefileRecordMultiPoint.java | 12 +- .../shapefile/ShapefileRecordNull.java | 12 +- .../shapefile/ShapefileRecordPoint.java | 12 +- .../shapefile/ShapefileRecordPolygon.java | 12 +- .../shapefile/ShapefileRecordPolyline.java | 12 +- .../formats/tiff/GeotiffImageReader.java | 2 +- .../worldwind/formats/tiff/GeotiffReader.java | 622 +++------ .../worldwind/layers/GraticuleSupport.java | 2 +- .../render/AbstractBrowserBalloon.java | 4 +- src/gov/nasa/worldwind/render/Path.java | 2 +- .../airspaces/BasicAirspaceAttributes.java | 2 +- .../symbology/TacticalGraphicLabel.java | 9 +- .../worldwind/util/BasicNamespaceContext.java | 90 +- .../nasa/worldwind/util/HTTPFileUpload.java | 283 ++--- .../nasa/worldwind/util/JOGLVersionInfo.java | 56 +- src/gov/nasa/worldwind/util/Logging.java | 5 +- .../worldwind/util/MessageStrings.properties | 1 + .../util/dashboard/DashboardController.java | 63 +- .../nasa/worldwind/util/gdal/GDALUtils.java | 1121 ++++++----------- .../util/webview/AbstractWebView.java | 11 - .../util/webview/WindowsWebView.java | 4 +- .../view/firstperson/BasicFlyView.java | 178 +-- .../worldwind/view/orbit/FlatOrbitView.java | 1 + .../dataimporter/DataInstallerApp.java | 4 +- .../worldwindx/applications/sar/SAR2.java | 32 +- .../worldwindx/applications/sar/ViewMenu.java | 4 +- .../worldwindow/core/Registry.java | 2 +- .../util/measuretool/WWOMeasureTool.java | 2 +- .../worldwindx/examples/AirspaceBuilder.java | 14 +- .../examples/ApplicationTemplate.java | 183 +-- .../worldwindx/examples/ExtrudedShapes.java | 4 +- .../worldwindx/examples/GazetteerApp.java | 3 +- .../worldwindx/examples/GazetteerPanel.java | 9 +- .../examples/GetBestElevations.java | 2 +- .../examples/TerrainIntersections.java | 6 +- .../examples/WorldWindDiagnostics.java | 2 +- .../layermanager/LayerManagerApp.java | 4 +- .../examples/lineofsight/LinesOfSight.java | 6 +- .../shapebuilder/ExtrudedPolygonBuilder.java | 2 +- .../shapebuilder/RigidShapeBuilder.java | 12 +- .../examples/util/ButtonAnnotation.java | 2 +- .../worldwindx/examples/view/AddAnimator.java | 3 +- .../formats/georss/GeoRSSParserTest.java | 32 +- 46 files changed, 1165 insertions(+), 1889 deletions(-) diff --git a/src/gov/nasa/worldwind/WorldWind.java b/src/gov/nasa/worldwind/WorldWind.java index 4b10a24957..b6aefe5a9b 100644 --- a/src/gov/nasa/worldwind/WorldWind.java +++ b/src/gov/nasa/worldwind/WorldWind.java @@ -211,8 +211,8 @@ public static Object createComponent(String className) throws WWRuntimeException try { - Class c = Class.forName(className.trim()); - return c.newInstance(); + Class c = Class.forName(className.trim()); + return c.getConstructor().newInstance(); } catch (Exception e) { diff --git a/src/gov/nasa/worldwind/awt/KeyEventState.java b/src/gov/nasa/worldwind/awt/KeyEventState.java index 86889c05b7..ed9d7f3ef7 100644 --- a/src/gov/nasa/worldwind/awt/KeyEventState.java +++ b/src/gov/nasa/worldwind/awt/KeyEventState.java @@ -5,6 +5,7 @@ */ package gov.nasa.worldwind.awt; +import gov.nasa.worldwind.util.Logging; import java.awt.event.*; import java.util.*; @@ -12,232 +13,221 @@ * @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; } } - protected Map keyStateMap = new HashMap(); - protected int modifiers; + protected Map keyStateMap = new HashMap<>(); protected int modifiersEx; - 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()) - { - //Integer key = (KeyEvent) o; + for (Object o : this.keyStateMap.keySet()) { 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() - { - return this.modifiers; + /** + * @return The same value as {@link #getModifiersEx()}. + * @deprecated Use {@link #getModifiersEx()} instead + */ + @Deprecated + public int getModifiers() { + String msg = Logging.getMessage("generic.OperationDeprecatedAndChanged", "getModifiers", "getModifiersEx"); + Logging.logger().severe(msg); + return this.modifiersEx; } - public int getModifiersEx() - { + /** + * @return The extended event modifiers. + */ + public int getModifiersEx() { return this.modifiersEx; } - public int getMouseModifiers() - { - return this.mouseModifiers; + /** + * @return The same value as {@link #getMouseModifiersEx()}. + * @deprecated Use {@link #getMouseModifiersEx()} instead + */ + @Deprecated + public int getMouseModifiers() { + String msg = Logging.getMessage("generic.OperationDeprecatedAndChanged", "getMouseModifiers", "getMouseModifiersEx"); + Logging.logger().severe(msg); + return this.mouseModifiersEx; } - public int getMouseModifiersEx() - { + /** + * @return The extended mouse event modifiers. + */ + public int getMouseModifiersEx() { return this.mouseModifiersEx; } - public void clearKeyState() - { + public void clearKeyState() { this.keyStateMap.clear(); - this.modifiers = 0; this.modifiersEx = 0; - this.mouseModifiers = 0; this.mouseModifiersEx = 0; } @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)); - this.setModifiers(e.getModifiers()); this.setModifiersEx(e.getModifiersEx()); } @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) - { + @Override + 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) - { + @Override + public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } - public void mouseExited(java.awt.event.MouseEvent mouseEvent) - { - + @Override + 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) - { - this.modifiers = modifiers; + /** + * @param modifiers Unused. + * @deprecated Use {@link #setModifiersEx(int)} instead + */ + @Deprecated + protected void setModifiers(int modifiers) { + String msg = Logging.getMessage("generic.OperationDeprecatedAndChanged", "setModifiers", "setModifiersEx"); + Logging.logger().severe(msg); } - 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) - { - this.mouseModifiers = modifiers; + /** + * @param modifiers Unused. + * @deprecated Use {@link #setMouseModifiersEx(int)} instead + */ + @Deprecated + protected void setMouseModifiers(int modifiers) { + String msg = Logging.getMessage("generic.OperationDeprecatedAndChanged", "setMouseModifiers", "setMouseModifiersEx"); + Logging.logger().severe(msg); } - - 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/cache/BasicMemoryCache.java b/src/gov/nasa/worldwind/cache/BasicMemoryCache.java index a2c3c2eefe..8791abbb0a 100644 --- a/src/gov/nasa/worldwind/cache/BasicMemoryCache.java +++ b/src/gov/nasa/worldwind/cache/BasicMemoryCache.java @@ -408,20 +408,4 @@ public String toString() return "MemoryCache " + this.name + " max size = " + this.getCapacity() + " current size = " + this.currentUsedCapacity.get() + " number of items: " + this.getNumObjects(); } - - @Override - 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 - { - super.finalize(); - } - } } diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordMultiPoint.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordMultiPoint.java index 76c53356ed..004763010e 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordMultiPoint.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordMultiPoint.java @@ -30,7 +30,17 @@ public class ShapefileRecordMultiPoint extends ShapefileRecord protected double[] mRange; // will be null if no measures protected double[] mValues; // will be null if no measures - /** {@inheritDoc} */ + /** + * Constructs a record instance from the given {@link java.nio.ByteBuffer}. The buffer's current position must be + * 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. + * + * @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. + */ public ShapefileRecordMultiPoint(Shapefile shapeFile, ByteBuffer buffer) { super(shapeFile, buffer); diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordNull.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordNull.java index 599422247f..aeef6d34da 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordNull.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordNull.java @@ -17,7 +17,17 @@ */ public class ShapefileRecordNull extends ShapefileRecord { - /** {@inheritDoc} */ + /** + * Constructs a record instance from the given {@link java.nio.ByteBuffer}. The buffer's current position must be + * 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. + * + * @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. + */ public ShapefileRecordNull(Shapefile shapeFile, ByteBuffer buffer) { super(shapeFile, buffer); diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPoint.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPoint.java index c6c87df29e..713adcf67a 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPoint.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPoint.java @@ -26,7 +26,17 @@ 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} */ + /** + * Constructs a record instance from the given {@link java.nio.ByteBuffer}. The buffer's current position must be + * 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. + * + * @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. + */ public ShapefileRecordPoint(Shapefile shapeFile, ByteBuffer buffer) { super(shapeFile, buffer); diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolygon.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolygon.java index d713d98322..811ded4206 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolygon.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolygon.java @@ -30,7 +30,17 @@ */ public class ShapefileRecordPolygon extends ShapefileRecordPolyline { - /** {@inheritDoc} */ + /** + * Constructs a record instance from the given {@link java.nio.ByteBuffer}. The buffer's current position must be + * 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. + * + * @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. + */ public ShapefileRecordPolygon(Shapefile shapeFile, ByteBuffer buffer) { super(shapeFile, buffer); diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolyline.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolyline.java index 3dd5591b80..103ce4e307 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolyline.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolyline.java @@ -33,7 +33,17 @@ public class ShapefileRecordPolyline extends ShapefileRecord protected double[] mRange; // will be null if no measures protected double[] mValues; // will be null if no measures - /** {@inheritDoc} */ + /** + * Constructs a record instance from the given {@link java.nio.ByteBuffer}. The buffer's current position must be + * 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. + * + * @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. + */ public ShapefileRecordPolyline(Shapefile shapeFile, ByteBuffer buffer) { super(shapeFile, buffer); diff --git a/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReader.java b/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReader.java index b90ab87fec..037fc255da 100644 --- a/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReader.java +++ b/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReader.java @@ -585,7 +585,7 @@ private void readGeoKeys(TiffIFDEntry entry) throws IOException GeoKey key = new GeoKey(); key.key = keyValRec[i]; if (keyValRec[i + 1] == 0) - key.value = new Integer(keyValRec[i + 3]); + key.value = Integer.valueOf(keyValRec[i + 3]); else { // TODO: This isn't quite right.... diff --git a/src/gov/nasa/worldwind/formats/tiff/GeotiffReader.java b/src/gov/nasa/worldwind/formats/tiff/GeotiffReader.java index f8dad56f85..8cdbb55db8 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,21 +24,20 @@ * @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; private RandomAccessFile sourceFile; private FileChannel theChannel; - private GeoCodec gc = new GeoCodec(); + private final GeoCodec gc = new GeoCodec(); 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,110 +47,81 @@ 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); } -// public AVList getMetadata() throws IOException -// { -// return this.getMetadata(0); -// } - - public void close() - { - try - { - this.sourceFile.close(); - } - catch (Exception ex) - { /* best effort */ } + public void close() { + this.dispose(); } - 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 +130,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 +151,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 +215,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,151 +234,116 @@ 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); } long offset = stripOffsets[0]; -// 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 +351,77 @@ 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) - { -// 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 +429,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 +451,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 +462,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 +485,71 @@ 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 +587,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 +600,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 +620,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 +646,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,94 +663,62 @@ 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)) - { -// int[] v = this.gc.getGeoKeyAsInts( GeoTiff.GeoKey.GeogAngularUnits ); -// int unit = ( null != v && v.length > 0 ) ? v[0] : GeoTiff.Undefined; -// -// if( unit == GeoTiff.Unit.Angular.Angular_Degree ) -// else if( unit == GeoTiff.Unit.Angular.Angular_Radian ) - } - -// AVKey.PROJECTION_DATUM Optional, -// 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 +726,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 +746,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 +801,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,12 +812,9 @@ 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 +826,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 +851,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 +868,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 +883,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 +895,15 @@ private void checkImageIndex(int imageIndex) throws IOException * Make sure we release this resource... * */ - public void dispose() - { - try - { + @Override + 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 - { - this.dispose(); - super.finalize(); - } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/layers/GraticuleSupport.java b/src/gov/nasa/worldwind/layers/GraticuleSupport.java index ba980af0b6..1d1c912f62 100644 --- a/src/gov/nasa/worldwind/layers/GraticuleSupport.java +++ b/src/gov/nasa/worldwind/layers/GraticuleSupport.java @@ -204,7 +204,7 @@ private AVList initRenderingParams(AVList params) if (params.getValue(GraticuleRenderingParams.KEY_LINE_WIDTH) == null) //noinspection UnnecessaryBoxing - params.setValue(GraticuleRenderingParams.KEY_LINE_WIDTH, new Double(1)); + params.setValue(GraticuleRenderingParams.KEY_LINE_WIDTH, Double.valueOf(1)); if (params.getValue(GraticuleRenderingParams.KEY_LINE_STYLE) == null) params.setValue(GraticuleRenderingParams.KEY_LINE_STYLE, GraticuleRenderingParams.VALUE_LINE_STYLE_SOLID); diff --git a/src/gov/nasa/worldwind/render/AbstractBrowserBalloon.java b/src/gov/nasa/worldwind/render/AbstractBrowserBalloon.java index 7adaadb778..5e207801ff 100644 --- a/src/gov/nasa/worldwind/render/AbstractBrowserBalloon.java +++ b/src/gov/nasa/worldwind/render/AbstractBrowserBalloon.java @@ -2170,7 +2170,7 @@ protected void handleMouseEvent(MouseEvent event) if (event instanceof MouseWheelEvent) { this.webView.sendEvent( - new MouseWheelEvent((Component) event.getSource(), event.getID(), event.getWhen(), event.getModifiers(), + new MouseWheelEvent((Component) event.getSource(), event.getID(), event.getWhen(), event.getModifiersEx(), webViewPoint.x, webViewPoint.y, event.getClickCount(), event.isPopupTrigger(), ((MouseWheelEvent) event).getScrollType(), ((MouseWheelEvent) event).getScrollAmount(), ((MouseWheelEvent) event).getWheelRotation())); @@ -2178,7 +2178,7 @@ protected void handleMouseEvent(MouseEvent event) else { this.webView.sendEvent( - new MouseEvent((Component) event.getSource(), event.getID(), event.getWhen(), event.getModifiers(), + new MouseEvent((Component) event.getSource(), event.getID(), event.getWhen(), event.getModifiersEx(), webViewPoint.x, webViewPoint.y, event.getClickCount(), event.isPopupTrigger(), event.getButton())); } } diff --git a/src/gov/nasa/worldwind/render/Path.java b/src/gov/nasa/worldwind/render/Path.java index a513645c47..40b811c390 100644 --- a/src/gov/nasa/worldwind/render/Path.java +++ b/src/gov/nasa/worldwind/render/Path.java @@ -2556,7 +2556,7 @@ protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLS /** * Specifies an offset, in meters, to add to the path points when the path's altitude mode is - * {@link WorldWind.CLAMP_TO_GROUND}. See {@link #setAltitudeMode(int) }. + * {@link WorldWind#CLAMP_TO_GROUND}. See {@link #setAltitudeMode(int) }. * * @param offset the path offset in meters. */ diff --git a/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java b/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java index d0c3b48402..ed6359e882 100644 --- a/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java +++ b/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java @@ -119,7 +119,7 @@ public AirspaceAttributes copy() } /** {@inheritDoc} */ - public void copy(AirspaceAttributes attributes) + public void copy(ShapeAttributes attributes) { super.copy(attributes); } diff --git a/src/gov/nasa/worldwind/symbology/TacticalGraphicLabel.java b/src/gov/nasa/worldwind/symbology/TacticalGraphicLabel.java index 37cb523b66..6f23030dd2 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalGraphicLabel.java +++ b/src/gov/nasa/worldwind/symbology/TacticalGraphicLabel.java @@ -847,7 +847,14 @@ protected Angle computeRotation(Vec4 screenPoint, Vec4 orientationScreenPoint) } } - /** {@inheritDoc} */ + /** + * Causes this Renderable to render itself using the provided draw context. + * + * @param dc the DrawContext to be used + * + * @throws IllegalArgumentException if the draw context is null. + * @see DrawContext + */ public void render(DrawContext dc) { // This render method is called twice during frame generation. It's first called as a Renderable diff --git a/src/gov/nasa/worldwind/util/BasicNamespaceContext.java b/src/gov/nasa/worldwind/util/BasicNamespaceContext.java index 51fbd048f5..ee27d7bf27 100644 --- a/src/gov/nasa/worldwind/util/BasicNamespaceContext.java +++ b/src/gov/nasa/worldwind/util/BasicNamespaceContext.java @@ -16,22 +16,23 @@ * @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"; - private Map urisByPrefix = new HashMap(); - private Map> prefixesByURI = new HashMap>(); + private final Map urisByPrefix = new HashMap<>(); + private final 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,39 @@ 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 - { - Set set = new HashSet(); + } else { + Set set = new HashSet<>(); set.add(prefix); this.prefixesByURI.put(namespaceURI, set); } } - /** {@inheritDoc} */ - public String getNamespaceURI(String prefix) - { - if (prefix == null) - { + /** + * {@inheritDoc} + */ + @Override + 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} + */ + @Override + public String getPrefix(String namespaceURI) { + if (namespaceURI == null) { String message = Logging.getMessage("nullValue.NamespaceURIIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -110,23 +104,23 @@ public String getPrefix(String namespaceURI) return (String) this.getPrefixes(namespaceURI).next(); } - /** {@inheritDoc} */ - public Iterator getPrefixes(String namespaceURI) - { - if (namespaceURI == null) - { + /** + * {@inheritDoc} + */ + @Override + 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)) - { - return Collections.unmodifiableSet(this.prefixesByURI.get(namespaceURI)).iterator(); - } - else - { - return Collections.EMPTY_SET.iterator(); + Set returnSet; + if (this.prefixesByURI.containsKey(namespaceURI)) { + returnSet = this.prefixesByURI.get(namespaceURI); + } else { + returnSet = new HashSet<>(); } + return Collections.unmodifiableSet(returnSet).iterator(); } } diff --git a/src/gov/nasa/worldwind/util/HTTPFileUpload.java b/src/gov/nasa/worldwind/util/HTTPFileUpload.java index 05c3b94af9..f0e41b876a 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; @@ -19,10 +17,16 @@ import java.nio.ByteBuffer; import java.util.*; import java.util.logging.Level; +import java.beans.PropertyChangeSupport; +import java.beans.PropertyChangeListener; + +/** + * Synchronous file upload using HTTP POST as a multi-part form data + */ +public class HTTPFileUpload { + + private final PropertyChangeSupport propertyChangeSupport; -/** 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**********"; @@ -30,7 +34,7 @@ public class HTTPFileUpload extends java.util.Observable protected final URL url; - protected ArrayList filesToUpload = new ArrayList(); + protected ArrayList filesToUpload = new ArrayList<>(); protected String requestMethod = "POST"; protected AVList requestProperties = new AVListImpl(); @@ -39,70 +43,61 @@ public class HTTPFileUpload extends java.util.Observable protected long totalBytesUploaded = (long) 0; protected int totalFilesUploaded = 0; protected int totalFilesFailed = 0; + protected float lastProgress = 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); } this.url = url; - + propertyChangeSupport = new PropertyChangeSupport(this); this.setRequestMethod("POST"); this.setRequestProperty("Connection", "Keep-Alive"); this.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); 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 +106,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 +123,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); @@ -146,41 +136,20 @@ public void setRequestProperty(String name, String value) this.requestProperties.setValue(name, value); } -// public void add(String stringToUpload, String name) -// { -// if (stringToUpload == null) -// { -// throw new IllegalArgumentException("String to upload is null"); -// } -// -// if (name == null) -// throw new IllegalArgumentException("String name to upload is null"); -// -// if (stringToUpload.length() == 0) -// throw new IllegalArgumentException("String to upload is empty"); -// -// 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 +162,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 +202,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 +219,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 +241,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 +256,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 +316,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 +336,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 +349,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 +377,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 +399,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 +422,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()) - { + this.requestProperties.getEntries().forEach((requestProperty) -> { 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 +440,35 @@ 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() - { - double progress = (double) 100 * (double) this.totalBytesUploaded / (double) this.totalBytesToUpload; + public void addPropertyChangeListener(PropertyChangeListener listener) { + this.propertyChangeSupport.addPropertyChangeListener(listener); + } + + public void removePropertyChangeListener(PropertyChangeListener listener) { + this.propertyChangeSupport.removePropertyChangeListener(listener); + } - this.setChanged(); - this.notifyObservers(new Float(progress)); + protected void notifyProgress() { + float progress = (float) 100 * (float) this.totalBytesUploaded / (float) this.totalBytesToUpload; + + if (progress != lastProgress) { + this.propertyChangeSupport.firePropertyChange("progress", lastProgress, progress); + lastProgress = progress; + } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/JOGLVersionInfo.java b/src/gov/nasa/worldwind/util/JOGLVersionInfo.java index d6d44029c0..845e636ce3 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 -{ - private static JOGLVersionInfo svi = new JOGLVersionInfo(); - private Package p; +public class JOGLVersionInfo { - private JOGLVersionInfo() - { + private static final JOGLVersionInfo svi = new JOGLVersionInfo(); + private final Package p; + + 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) + p = classLoader.getDefinedPackage(pkgName); + 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/Logging.java b/src/gov/nasa/worldwind/util/Logging.java index 0af0083035..d4dccf003b 100644 --- a/src/gov/nasa/worldwind/util/Logging.java +++ b/src/gov/nasa/worldwind/util/Logging.java @@ -12,16 +12,15 @@ import java.util.*; import java.util.logging.Level; import java.util.logging.*; - /** * This class of static methods provides the interface to logging for WorldWind components. Logging is performed via - * {@link java.util.logging}. The default logger name is gov.nasa.worldwind. The logger name is + * {@link java.util.logging.Logger}. The default logger name is gov.nasa.worldwind. The logger name is * configurable via {@link gov.nasa.worldwind.Configuration}. * * @author tag * @version $Id: Logging.java 1171 2013-02-11 21:45:02Z dcollins $ * @see gov.nasa.worldwind.Configuration - * @see java.util.logging + * @see java.util.logging.Logger */ public class Logging { diff --git a/src/gov/nasa/worldwind/util/MessageStrings.properties b/src/gov/nasa/worldwind/util/MessageStrings.properties index 307b230143..23648972f4 100644 --- a/src/gov/nasa/worldwind/util/MessageStrings.properties +++ b/src/gov/nasa/worldwind/util/MessageStrings.properties @@ -230,6 +230,7 @@ generic.OffsetIsInvalid=Offset is invalid {0} generic.OGCServiceException=OGC service exception: {0} generic.OpacityOutOfRange=Opacity {0} is out of range generic.OperationCancelled=Operation {0} cancelled +generic.OperationDeprecatedAndChanged=Operation {0} has been deprecated and its behavior has changed. Upgrade to {1}. generic.OverviewRasterCreated=Overview raster created {0} generic.OverviewRasterNotFound=Overview raster not found {0} generic.OwnerIsInvalid=Invalid owner {0} diff --git a/src/gov/nasa/worldwind/util/dashboard/DashboardController.java b/src/gov/nasa/worldwind/util/dashboard/DashboardController.java index 9f3ed0b72c..46b7670863 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,62 @@ public DashboardController(WorldWindow wwd, Component component) wwd.getInputHandler().addMouseListener(this); } - public void dispose() - { - if (this.dialog != null) - { + @Override + 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) - { + @Override + 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.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) != 0 + && (event.getModifiersEx() & InputEvent.ALT_DOWN_MASK) != 0 + && (event.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) != 0)) { raiseDialog(); + } } - public void mousePressed(MouseEvent e) - { + @Override + public void mousePressed(MouseEvent e) { } - public void mouseReleased(MouseEvent e) - { + @Override + public void mouseReleased(MouseEvent e) { } - public void mouseEntered(MouseEvent e) - { + @Override + public void mouseEntered(MouseEvent e) { } - public void mouseExited(MouseEvent e) - { + @Override + public void mouseExited(MouseEvent e) { } } diff --git a/src/gov/nasa/worldwind/util/gdal/GDALUtils.java b/src/gov/nasa/worldwind/util/gdal/GDALUtils.java index 4e8e1cfa02..5b55108f56 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,20 +1654,18 @@ 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) - { - fieldSysPaths_accessible = fieldSysPaths.isAccessible(); - if (!fieldSysPaths_accessible) - { + if (null != fieldSysPaths) { + try { fieldSysPaths.setAccessible(true); + fieldSysPaths_accessible = true; + } catch (InaccessibleObjectException ioex) { + fieldSysPaths_accessible = false; } - originalClassLoader = fieldSysPaths.get(newClassLoader); // Reset it to null so that whenever "System.loadLibrary" is called, @@ -2002,19 +1674,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 +1690,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/webview/AbstractWebView.java b/src/gov/nasa/worldwind/util/webview/AbstractWebView.java index 066a65e8aa..1b9ae58b46 100644 --- a/src/gov/nasa/worldwind/util/webview/AbstractWebView.java +++ b/src/gov/nasa/worldwind/util/webview/AbstractWebView.java @@ -29,17 +29,6 @@ public abstract class AbstractWebView extends WWObjectImpl implements WebView, D /** Indicates whether the WebView is active. */ protected boolean active; - /** - * Overridden to ensure that the WebView's native resources are disposed when the WebView is reclaimed by the - * garbage collector. This does nothing if the WebView's owner has already called {@link #dispose()}. - */ - @Override - protected void finalize() throws Throwable - { - this.dispose(); - super.finalize(); - } - /** {@inheritDoc} */ public Dimension getFrameSize() { diff --git a/src/gov/nasa/worldwind/util/webview/WindowsWebView.java b/src/gov/nasa/worldwind/util/webview/WindowsWebView.java index 947e063531..bb8f19bd43 100644 --- a/src/gov/nasa/worldwind/util/webview/WindowsWebView.java +++ b/src/gov/nasa/worldwind/util/webview/WindowsWebView.java @@ -435,13 +435,13 @@ protected MouseEvent convertToWindows(MouseEvent e) if (e instanceof MouseWheelEvent) { - return new MouseWheelEvent((Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiers(), x, y, + return new MouseWheelEvent((Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiersEx(), x, y, 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, + return new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiersEx(), x, y, e.getClickCount(), e.isPopupTrigger(), e.getButton()); } } diff --git a/src/gov/nasa/worldwind/view/firstperson/BasicFlyView.java b/src/gov/nasa/worldwind/view/firstperson/BasicFlyView.java index c28f64bb21..1422fc0786 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,82 +44,63 @@ 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) - { - double elevation = ((FlyViewLimits) this.viewLimits).limitEyeElevation( - eyePosition, this.getGlobe()); - LatLon location = BasicViewPropertyLimits.limitEyePositionLocation( - eyePosition.getLatitude(), eyePosition.getLongitude(), this.viewLimits); - this.eyePosition = new Position(location, elevation); - } - else - { - LatLon location = BasicViewPropertyLimits.limitEyePositionLocation( - eyePosition.getLatitude(), eyePosition.getLongitude(), this.viewLimits); - this.eyePosition = new Position(location, eyePosition.getElevation()); - this.eyePosition = eyePosition; - } - + this.eyePosition = this.viewLimits.limitEyePosition(this, 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 +108,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 +119,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 +141,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 +156,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 +168,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 +191,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 +217,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 +245,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 +258,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,22 +271,15 @@ 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) - { - Position eyePos = ViewUtil.normalizedEyePosition(viewState.getPosition()); - LatLon limitedLocation = BasicViewPropertyLimits.limitEyePositionLocation( - this.eyePosition.getLatitude(), - this.eyePosition.getLongitude(), this.getViewPropertyLimits()); - this.eyePosition = new Position(limitedLocation, eyePos.getElevation()); + if (viewState.getPosition() != null) { + this.eyePosition = this.viewLimits.limitEyePosition(this, this.eyePosition); } this.setHeading(viewState.getHeading()); @@ -329,41 +288,36 @@ 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); } this.heading = ViewUtil.normalizedHeading(heading); - this.heading = BasicViewPropertyLimits.limitHeading(this.heading, this.getViewPropertyLimits()); + this.heading = this.viewLimits.limitHeading(this, this.heading); this.updateModelViewStateID(); } @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); } this.pitch = ViewUtil.normalizedPitch(pitch); - this.pitch = BasicViewPropertyLimits.limitPitch(this.pitch, this.getViewPropertyLimits()); + this.pitch = this.viewLimits.limitPitch(this, this.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/orbit/FlatOrbitView.java b/src/gov/nasa/worldwind/view/orbit/FlatOrbitView.java index 45ae5a89c6..038fd5f261 100644 --- a/src/gov/nasa/worldwind/view/orbit/FlatOrbitView.java +++ b/src/gov/nasa/worldwind/view/orbit/FlatOrbitView.java @@ -13,6 +13,7 @@ * @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. */ +@Deprecated public class FlatOrbitView extends BasicOrbitView { // TODO: make configurable diff --git a/src/gov/nasa/worldwindx/applications/dataimporter/DataInstallerApp.java b/src/gov/nasa/worldwindx/applications/dataimporter/DataInstallerApp.java index 57fafdc826..360f794999 100644 --- a/src/gov/nasa/worldwindx/applications/dataimporter/DataInstallerApp.java +++ b/src/gov/nasa/worldwindx/applications/dataimporter/DataInstallerApp.java @@ -134,7 +134,7 @@ else if (Configuration.isWindowsOS()) } } - public static AppFrame start(String appName, Class appFrameClass) + public static AppFrame start(String appName, Class appFrameClass) { if (Configuration.isMacOS() && appName != null) { @@ -143,7 +143,7 @@ public static AppFrame start(String appName, Class appFrameClass) try { - final AppFrame frame = (AppFrame) appFrameClass.newInstance(); + final AppFrame frame = (AppFrame) appFrameClass.getConstructor().newInstance(); frame.setTitle(appName); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); java.awt.EventQueue.invokeLater(new Runnable() diff --git a/src/gov/nasa/worldwindx/applications/sar/SAR2.java b/src/gov/nasa/worldwindx/applications/sar/SAR2.java index b0540ba57f..0c30340601 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SAR2.java +++ b/src/gov/nasa/worldwindx/applications/sar/SAR2.java @@ -785,7 +785,7 @@ public void windowClosed(WindowEvent event) newTrack.setText("New Track..."); newTrack.setMnemonic('N'); newTrack.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); newTrack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) @@ -800,7 +800,7 @@ public void actionPerformed(ActionEvent e) openTrackFile.setText("Open Track File..."); openTrackFile.setMnemonic('O'); openTrackFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); openTrackFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) @@ -815,7 +815,7 @@ public void actionPerformed(ActionEvent e) openTrackURL.setText("Open Track URL..."); openTrackURL.setMnemonic('U'); openTrackURL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); openTrackURL.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) @@ -831,7 +831,7 @@ public void actionPerformed(ActionEvent e) removeTrack.setMnemonic('C'); removeTrack.setAccelerator(KeyStroke.getKeyStroke( Configuration.isMacOS() ? KeyEvent.VK_W : KeyEvent.VK_F4, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); removeTrack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) @@ -849,7 +849,7 @@ public void actionPerformed(ActionEvent e) saveTrack.setText("Save Track"); saveTrack.setMnemonic('S'); saveTrack.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); saveTrack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) @@ -866,7 +866,7 @@ public void actionPerformed(ActionEvent event) saveTrackAs.setText("Save Track As..."); saveTrackAs.setMnemonic('A'); saveTrackAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + java.awt.Event.SHIFT_MASK)); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() + java.awt.event.InputEvent.SHIFT_DOWN_MASK)); saveTrackAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) @@ -882,7 +882,7 @@ public void actionPerformed(ActionEvent event) screenShot.setIcon(null); // Make sure the menu items displays only text. screenShot.setMnemonic('T'); screenShot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); fileMenu.add(screenShot); //-------- @@ -892,7 +892,7 @@ public void actionPerformed(ActionEvent event) bulkDownload.setText("Bulk download..."); bulkDownload.setMnemonic('B'); bulkDownload.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); bulkDownload.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) @@ -982,7 +982,7 @@ public void actionPerformed(ActionEvent event) metersMenuItem.setText("Meters"); metersMenuItem.setMnemonic('M'); metersMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); metersMenuItem.setActionCommand(UNIT_METRIC); metersMenuItem.addActionListener(new ActionListener() { @@ -998,7 +998,7 @@ public void actionPerformed(ActionEvent e) feetMenuItem.setText("Feet"); feetMenuItem.setMnemonic('F'); feetMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, - java.awt.event.InputEvent.ALT_MASK)); + java.awt.event.InputEvent.ALT_DOWN_MASK)); feetMenuItem.setActionCommand(UNIT_IMPERIAL); feetMenuItem.addActionListener(new ActionListener() { @@ -1020,7 +1020,7 @@ public void actionPerformed(ActionEvent e) angleDDMenuItem.setText("Angles DD"); angleDDMenuItem.setMnemonic('D'); angleDDMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); angleDDMenuItem.setActionCommand(Angle.ANGLE_FORMAT_DD); angleDDMenuItem.addActionListener(new ActionListener() { @@ -1036,7 +1036,7 @@ public void actionPerformed(ActionEvent e) angleDMSMenuItem.setText("Angles DMS"); angleDMSMenuItem.setMnemonic('S'); angleDMSMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, - java.awt.event.InputEvent.ALT_MASK)); + java.awt.event.InputEvent.ALT_DOWN_MASK)); angleDMSMenuItem.setActionCommand(Angle.ANGLE_FORMAT_DMS); angleDMSMenuItem.addActionListener(new ActionListener() { @@ -1064,7 +1064,7 @@ public void actionPerformed(ActionEvent e) newAnnotation.setText("New Annotation..."); newAnnotation.setMnemonic('N'); newAnnotation.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); newAnnotation.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) @@ -1079,7 +1079,7 @@ public void actionPerformed(ActionEvent e) removeAnnotation.setText("Remove Annotation"); removeAnnotation.setMnemonic('R'); removeAnnotation.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + java.awt.Event.SHIFT_MASK)); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() + java.awt.event.InputEvent.SHIFT_DOWN_MASK)); removeAnnotation.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) @@ -1094,7 +1094,7 @@ public void actionPerformed(ActionEvent event) showAnnotations.setText("Show Annotations"); showAnnotations.setMnemonic('S'); showAnnotations.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, - java.awt.event.InputEvent.ALT_MASK)); + java.awt.event.InputEvent.ALT_DOWN_MASK)); showAnnotations.setSelected(true); showAnnotations.addItemListener(new ItemListener() { @@ -1135,7 +1135,7 @@ public void itemStateChanged(ItemEvent e) sarHelp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); else sarHelp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_HELP, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); sarHelp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) diff --git a/src/gov/nasa/worldwindx/applications/sar/ViewMenu.java b/src/gov/nasa/worldwindx/applications/sar/ViewMenu.java index 1786a1e69b..e65f741627 100644 --- a/src/gov/nasa/worldwindx/applications/sar/ViewMenu.java +++ b/src/gov/nasa/worldwindx/applications/sar/ViewMenu.java @@ -45,7 +45,7 @@ public void setWwd(WorldWindow wwdInstance) // Terrain profile JMenuItem mi = new JMenuItem("Terrain profile..."); mi.setMnemonic('T'); - mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) @@ -58,7 +58,7 @@ public void actionPerformed(ActionEvent event) // Cloud ceiling contour mi = new JMenuItem("Cloud Contour..."); mi.setMnemonic('C'); - mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/Registry.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/Registry.java index 77b7baf96d..ee2c9ccc5d 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/Registry.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/Registry.java @@ -41,7 +41,7 @@ public Object createObject(String className) try { - return Class.forName(className.trim()).newInstance(); + return Class.forName(className.trim()).getConstructor().newInstance(); } catch (Exception e) { diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/util/measuretool/WWOMeasureTool.java b/src/gov/nasa/worldwindx/applications/worldwindow/util/measuretool/WWOMeasureTool.java index ed051ac06e..aa2f5e2f92 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/util/measuretool/WWOMeasureTool.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/util/measuretool/WWOMeasureTool.java @@ -691,7 +691,7 @@ protected void updateMeasureShape() { if (this.measureShapeType.equals(AVKey.SHAPE_LINE) || this.measureShapeType.equals(AVKey.SHAPE_PATH)) { // Update current line if (this.positions.size() > 1 && this.shape != null) { - ((Polyline) this.shape).setPositions(this.positions); + ((Path) this.shape).setPositions(this.positions); } } // Update polygon else if (this.measureShapeType.equals(AVKey.SHAPE_POLYGON)) { diff --git a/src/gov/nasa/worldwindx/examples/AirspaceBuilder.java b/src/gov/nasa/worldwindx/examples/AirspaceBuilder.java index 62400a145e..736bb03392 100644 --- a/src/gov/nasa/worldwindx/examples/AirspaceBuilder.java +++ b/src/gov/nasa/worldwindx/examples/AirspaceBuilder.java @@ -1266,8 +1266,8 @@ protected void loadAirspacesFromPath(String path, Collection airspaces try { - Class c = Class.forName(tokens[0]); - Airspace airspace = (Airspace) c.newInstance(); + Class c = Class.forName(tokens[0]); + Airspace airspace = (Airspace) c.getConstructor().newInstance(); BufferedReader input = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry))); String s = input.readLine(); airspace.restoreState(s); @@ -1329,8 +1329,8 @@ public boolean accept(File dir, String name) String[] name = file.getName().split("-"); try { - Class c = Class.forName(name[0]); - Airspace airspace = (Airspace) c.newInstance(); + Class c = Class.forName(name[0]); + Airspace airspace = (Airspace) c.getConstructor().newInstance(); BufferedReader input = new BufferedReader(new FileReader(file)); String s = input.readLine(); airspace.restoreState(s); @@ -1514,7 +1514,7 @@ public static void makeMenuBar(JFrame frame, final AirspaceBuilderController con { JMenuItem item = new JMenuItem("Open..."); item.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.setActionCommand(OPEN); item.addActionListener(controller); menu.add(item); @@ -1526,7 +1526,7 @@ public static void makeMenuBar(JFrame frame, final AirspaceBuilderController con item = new JMenuItem("Save..."); item.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.setActionCommand(SAVE); item.addActionListener(controller); menu.add(item); @@ -1575,7 +1575,7 @@ public void actionPerformed(ActionEvent e) { JMenuItem item = new JMenuItem("Deselect"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.setActionCommand(CLEAR_SELECTION); item.addActionListener(controller); menu.add(item); diff --git a/src/gov/nasa/worldwindx/examples/ApplicationTemplate.java b/src/gov/nasa/worldwindx/examples/ApplicationTemplate.java index bc06a341f7..7523795fea 100644 --- a/src/gov/nasa/worldwindx/examples/ApplicationTemplate.java +++ b/src/gov/nasa/worldwindx/examples/ApplicationTemplate.java @@ -24,17 +24,16 @@ * * @version $Id: ApplicationTemplate.java 2115 2014-07-01 17:58:16Z tgaskins $ */ -public class ApplicationTemplate -{ - public static class AppPanel extends JPanel - { +public class ApplicationTemplate { + + public static class AppPanel extends JPanel { + protected WorldWindow wwd; protected StatusBar statusBar; protected ToolTipController toolTipController; protected HighlightController highlightController; - public AppPanel(Dimension canvasSize, boolean includeStatusBar) - { + public AppPanel(Dimension canvasSize, boolean includeStatusBar) { super(new BorderLayout()); this.wwd = this.createWorldWindow(); @@ -48,8 +47,7 @@ public AppPanel(Dimension canvasSize, boolean includeStatusBar) this.wwd.addSelectListener(new ClickAndGoSelectListener(this.getWwd(), WorldMapLayer.class)); this.add((Component) this.wwd, BorderLayout.CENTER); - if (includeStatusBar) - { + if (includeStatusBar) { this.statusBar = new StatusBar(); this.add(statusBar, BorderLayout.PAGE_END); this.statusBar.setEventSource(wwd); @@ -60,24 +58,21 @@ public AppPanel(Dimension canvasSize, boolean includeStatusBar) this.highlightController = new HighlightController(this.getWwd(), SelectEvent.ROLLOVER); } - protected WorldWindow createWorldWindow() - { + protected WorldWindow createWorldWindow() { return new WorldWindowGLCanvas(); } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return wwd; } - public StatusBar getStatusBar() - { + public StatusBar getStatusBar() { return statusBar; } } - protected static class AppFrame extends JFrame - { + protected static class AppFrame extends JFrame { + private Dimension canvasSize = new Dimension(1000, 800); protected AppPanel wwjPanel; @@ -85,32 +80,27 @@ protected static class AppFrame extends JFrame protected LayerPanel layerPanel; protected StatisticsPanel statsPanel; - public AppFrame() - { + public AppFrame() { this.initialize(true, true, false); } - public AppFrame(Dimension size) - { + public AppFrame(Dimension size) { this.canvasSize = size; this.initialize(true, true, false); } - public AppFrame(boolean includeStatusBar, boolean includeLayerPanel, boolean includeStatsPanel) - { + public AppFrame(boolean includeStatusBar, boolean includeLayerPanel, boolean includeStatsPanel) { this.initialize(includeStatusBar, includeLayerPanel, includeStatsPanel); } - protected void initialize(boolean includeStatusBar, boolean includeLayerPanel, boolean includeStatsPanel) - { + protected void initialize(boolean includeStatusBar, boolean includeLayerPanel, boolean includeStatsPanel) { // Create the WorldWindow. this.wwjPanel = this.createAppPanel(this.canvasSize, includeStatusBar); this.wwjPanel.setPreferredSize(canvasSize); // Put the pieces together. this.getContentPane().add(wwjPanel, BorderLayout.CENTER); - if (includeLayerPanel) - { + if (includeLayerPanel) { this.controlPanel = new JPanel(new BorderLayout(10, 10)); this.layerPanel = new LayerPanel(this.getWwd()); this.controlPanel.add(this.layerPanel, BorderLayout.CENTER); @@ -118,8 +108,7 @@ protected void initialize(boolean includeStatusBar, boolean includeLayerPanel, b this.getContentPane().add(this.controlPanel, BorderLayout.WEST); } - if (includeStatsPanel || System.getProperty("gov.nasa.worldwind.showStatistics") != null) - { + if (includeStatsPanel || System.getProperty("gov.nasa.worldwind.showStatistics") != null) { this.statsPanel = new StatisticsPanel(this.wwjPanel.getWwd(), new Dimension(250, canvasSize.height)); this.getContentPane().add(this.statsPanel, BorderLayout.EAST); } @@ -130,30 +119,23 @@ protected void initialize(boolean includeStatusBar, boolean includeLayerPanel, b this.getWwd().addSelectListener(new ViewControlsSelectListener(this.getWwd(), viewControlsLayer)); // Register a rendering exception listener that's notified when exceptions occur during rendering. - this.wwjPanel.getWwd().addRenderingExceptionListener(new RenderingExceptionListener() - { - public void exceptionThrown(Throwable t) - { - if (t instanceof WWAbsentRequirementException) - { - String message = "Computer does not meet minimum graphics requirements.\n"; - message += "Please install up-to-date graphics driver and try again.\n"; - message += "Reason: " + t.getMessage() + "\n"; - message += "This program will end when you press OK."; - - JOptionPane.showMessageDialog(AppFrame.this, message, "Unable to Start Program", + this.wwjPanel.getWwd().addRenderingExceptionListener((Throwable t) -> { + if (t instanceof WWAbsentRequirementException) { + String message = "Computer does not meet minimum graphics requirements.\n"; + message += "Please install up-to-date graphics driver and try again.\n"; + message += "Reason: " + t.getMessage() + "\n"; + message += "This program will end when you press OK."; + + JOptionPane.showMessageDialog(AppFrame.this, message, "Unable to Start Program", JOptionPane.ERROR_MESSAGE); - System.exit(-1); - } + System.exit(-1); } }); // Search the layer list for layers that are also select listeners and register them with the World // Window. This enables interactive layers to be included without specific knowledge of them here. - for (Layer layer : this.wwjPanel.getWwd().getModel().getLayers()) - { - if (layer instanceof SelectListener) - { + for (Layer layer : this.wwjPanel.getWwd().getModel().getLayers()) { + if (layer instanceof SelectListener) { this.getWwd().addSelectListener((SelectListener) layer); } } @@ -165,28 +147,23 @@ public void exceptionThrown(Throwable t) this.setResizable(true); } - protected AppPanel createAppPanel(Dimension canvasSize, boolean includeStatusBar) - { + protected AppPanel createAppPanel(Dimension canvasSize, boolean includeStatusBar) { return new AppPanel(canvasSize, includeStatusBar); } - public Dimension getCanvasSize() - { + public Dimension getCanvasSize() { return canvasSize; } - public AppPanel getWwjPanel() - { + public AppPanel getWwjPanel() { return wwjPanel; } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return this.wwjPanel.getWwd(); } - public StatusBar getStatusBar() - { + public StatusBar getStatusBar() { return this.wwjPanel.getStatusBar(); } @@ -194,86 +171,78 @@ public StatusBar getStatusBar() * @deprecated Use getControlPanel instead. * @return This application's layer panel. */ - public LayerPanel getLayerPanel() - { + @Deprecated + public LayerPanel getLayerPanel() { return this.layerPanel; } - public JPanel getControlPanel() - { + public JPanel getControlPanel() { return this.controlPanel; } - public StatisticsPanel getStatsPanel() - { + public StatisticsPanel getStatsPanel() { return statsPanel; } - public void setToolTipController(ToolTipController controller) - { - if (this.wwjPanel.toolTipController != null) + public void setToolTipController(ToolTipController controller) { + if (this.wwjPanel.toolTipController != null) { this.wwjPanel.toolTipController.dispose(); + } this.wwjPanel.toolTipController = controller; } - public void setHighlightController(HighlightController controller) - { - if (this.wwjPanel.highlightController != null) + public void setHighlightController(HighlightController controller) { + if (this.wwjPanel.highlightController != null) { this.wwjPanel.highlightController.dispose(); + } this.wwjPanel.highlightController = controller; } } - public static void insertBeforeCompass(WorldWindow wwd, Layer layer) - { + public static void insertBeforeCompass(WorldWindow wwd, Layer layer) { // Insert the layer into the layer list just before the compass. int compassPosition = 0; LayerList layers = wwd.getModel().getLayers(); - for (Layer l : layers) - { - if (l instanceof CompassLayer) + for (Layer l : layers) { + if (l instanceof CompassLayer) { compassPosition = layers.indexOf(l); + } } layers.add(compassPosition, layer); } - public static void insertBeforePlacenames(WorldWindow wwd, Layer layer) - { + public static void insertBeforePlacenames(WorldWindow wwd, Layer layer) { // Insert the layer into the layer list just before the placenames. int compassPosition = 0; LayerList layers = wwd.getModel().getLayers(); - for (Layer l : layers) - { - if (l instanceof PlaceNameLayer) + for (Layer l : layers) { + if (l instanceof PlaceNameLayer) { compassPosition = layers.indexOf(l); + } } layers.add(compassPosition, layer); } - public static void insertAfterPlacenames(WorldWindow wwd, Layer layer) - { + public static void insertAfterPlacenames(WorldWindow wwd, Layer layer) { // Insert the layer into the layer list just after the placenames. int compassPosition = 0; LayerList layers = wwd.getModel().getLayers(); - for (Layer l : layers) - { - if (l instanceof PlaceNameLayer) + for (Layer l : layers) { + if (l instanceof PlaceNameLayer) { compassPosition = layers.indexOf(l); + } } layers.add(compassPosition + 1, layer); } - public static void insertBeforeLayerName(WorldWindow wwd, Layer layer, String targetName) - { + public static void insertBeforeLayerName(WorldWindow wwd, Layer layer, String targetName) { // Insert the layer into the layer list just before the target layer. int targetPosition = 0; LayerList layers = wwd.getModel().getLayers(); - for (Layer l : layers) - { - if (l.getName().indexOf(targetName) != -1) - { + for (Layer l : layers) { + if (l.getName().contains(targetName)) { targetPosition = layers.indexOf(l); break; } @@ -281,53 +250,39 @@ public static void insertBeforeLayerName(WorldWindow wwd, Layer layer, String ta layers.add(targetPosition, layer); } - static - { + static { System.setProperty("java.net.useSystemProxies", "true"); - if (Configuration.isMacOS()) - { + if (Configuration.isMacOS()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "WorldWind Application"); System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); System.setProperty("apple.awt.brushMetalLook", "true"); - } - else if (Configuration.isWindowsOS()) - { + } else if (Configuration.isWindowsOS()) { System.setProperty("sun.awt.noerasebackground", "true"); // prevents flashing during window resizing } } - public static AppFrame start(String appName, Class appFrameClass) - { - if (Configuration.isMacOS() && appName != null) - { + public static AppFrame start(String appName, Class appFrameClass) { + if (Configuration.isMacOS() && appName != null) { System.setProperty("com.apple.mrj.application.apple.menu.about.name", appName); } - try - { - final AppFrame frame = (AppFrame) appFrameClass.newInstance(); + try { + final AppFrame frame = (AppFrame) appFrameClass.getConstructor().newInstance(); frame.setTitle(appName); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - java.awt.EventQueue.invokeLater(new Runnable() - { - public void run() - { - frame.setVisible(true); - } + java.awt.EventQueue.invokeLater(() -> { + frame.setVisible(true); }); return frame; - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); return null; } } - public static void main(String[] args) - { + public static void main(String[] args) { // Call the static start method like this from the main method of your derived class. // Substitute your application's name for the first argument. ApplicationTemplate.start("WorldWind Application", AppFrame.class); diff --git a/src/gov/nasa/worldwindx/examples/ExtrudedShapes.java b/src/gov/nasa/worldwindx/examples/ExtrudedShapes.java index 08a39fc7a3..f869bede3e 100644 --- a/src/gov/nasa/worldwindx/examples/ExtrudedShapes.java +++ b/src/gov/nasa/worldwindx/examples/ExtrudedShapes.java @@ -148,8 +148,8 @@ protected static void loadAirspacesFromPath(String path, Collection ai try { - Class c = Class.forName(tokens[0]); - Airspace airspace = (Airspace) c.newInstance(); + Class c = Class.forName(tokens[0]); + Airspace airspace = (Airspace) c.getConstructor().newInstance(); BufferedReader input = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry))); String s = input.readLine(); airspace.restoreState(s); diff --git a/src/gov/nasa/worldwindx/examples/GazetteerApp.java b/src/gov/nasa/worldwindx/examples/GazetteerApp.java index 0d066f4005..8edddd4991 100644 --- a/src/gov/nasa/worldwindx/examples/GazetteerApp.java +++ b/src/gov/nasa/worldwindx/examples/GazetteerApp.java @@ -6,6 +6,7 @@ package gov.nasa.worldwindx.examples; import java.awt.*; +import java.lang.reflect.InvocationTargetException; /** * Example of integrating a gazetteer search function using the {@link gov.nasa.worldwind.poi.YahooGazetteer}. @@ -19,7 +20,7 @@ public class GazetteerApp extends ApplicationTemplate { public static class AppFrame extends ApplicationTemplate.AppFrame { - public AppFrame() throws IllegalAccessException, InstantiationException, ClassNotFoundException + public AppFrame() throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException { super(true, false, false); diff --git a/src/gov/nasa/worldwindx/examples/GazetteerPanel.java b/src/gov/nasa/worldwindx/examples/GazetteerPanel.java index fdb45be90e..4fdd80f855 100644 --- a/src/gov/nasa/worldwindx/examples/GazetteerPanel.java +++ b/src/gov/nasa/worldwindx/examples/GazetteerPanel.java @@ -24,6 +24,7 @@ import java.net.URL; import java.util.ArrayList; import java.util.regex.*; +import java.lang.reflect.InvocationTargetException; /** * Gazetteer search panel that allows the user to enter a search term in a text field. When a search is performed the @@ -50,9 +51,11 @@ public class GazetteerPanel extends JPanel * @throws IllegalAccessException if the gazetteer class does not expose a publicly accessible no-arg constructor. * @throws InstantiationException if an exception occurs while instantiating the the gazetteer class. * @throws ClassNotFoundException if the gazetteer class cannot be found. + * @throws java.lang.NoSuchMethodException if the gazetteer class doesn't have a default constructor. + * @throws java.lang.reflect.InvocationTargetException if the gazetteer class construction fails. */ public GazetteerPanel(final WorldWindow wwd, String gazetteerClassName) - throws IllegalAccessException, InstantiationException, ClassNotFoundException + throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException { super(new BorderLayout()); @@ -145,7 +148,7 @@ public void run() } private Gazetteer constructGazetteer(String className) - throws ClassNotFoundException, IllegalAccessException, InstantiationException + throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { if (className == null || className.length() == 0) { @@ -153,7 +156,7 @@ private Gazetteer constructGazetteer(String className) } Class c = Class.forName(className.trim()); - Object o = c.newInstance(); + Object o = c.getConstructor().newInstance(); if (!(o instanceof Gazetteer)) throw new IllegalArgumentException("Gazetteer class name is null"); diff --git a/src/gov/nasa/worldwindx/examples/GetBestElevations.java b/src/gov/nasa/worldwindx/examples/GetBestElevations.java index e00365c114..32fa1b824f 100644 --- a/src/gov/nasa/worldwindx/examples/GetBestElevations.java +++ b/src/gov/nasa/worldwindx/examples/GetBestElevations.java @@ -90,7 +90,7 @@ public AppFrame() { public void mouseClicked(MouseEvent mouseEvent) { - if ((mouseEvent.getModifiers() & ActionEvent.SHIFT_MASK) == 0) + if ((mouseEvent.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) == 0) return; mouseEvent.consume(); diff --git a/src/gov/nasa/worldwindx/examples/TerrainIntersections.java b/src/gov/nasa/worldwindx/examples/TerrainIntersections.java index ca1a9b4802..bc4c0fe813 100644 --- a/src/gov/nasa/worldwindx/examples/TerrainIntersections.java +++ b/src/gov/nasa/worldwindx/examples/TerrainIntersections.java @@ -107,7 +107,7 @@ public AppFrame() public void mouseClicked(MouseEvent mouseEvent) { // Control-Click cancels any currently running operation. - if ((mouseEvent.getModifiers() & ActionEvent.CTRL_MASK) != 0) + if ((mouseEvent.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) != 0) { if (calculationDispatchThread != null && calculationDispatchThread.isAlive()) calculationDispatchThread.interrupt(); @@ -115,7 +115,7 @@ public void mouseClicked(MouseEvent mouseEvent) } // Alt-Click repeats the most recent calculations. - if ((mouseEvent.getModifiers() & ActionEvent.ALT_MASK) != 0) + if ((mouseEvent.getModifiersEx() & InputEvent.ALT_DOWN_MASK) != 0) { if (previousCurrentPosition == null) return; @@ -127,7 +127,7 @@ public void mouseClicked(MouseEvent mouseEvent) } // Perform the intersection tests in response to Shift-Click. - if ((mouseEvent.getModifiers() & ActionEvent.SHIFT_MASK) == 0) + if ((mouseEvent.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) == 0) return; mouseEvent.consume(); // tell the rest of WW that this event has been processed diff --git a/src/gov/nasa/worldwindx/examples/WorldWindDiagnostics.java b/src/gov/nasa/worldwindx/examples/WorldWindDiagnostics.java index af4de8adbb..d07a298d4e 100644 --- a/src/gov/nasa/worldwindx/examples/WorldWindDiagnostics.java +++ b/src/gov/nasa/worldwindx/examples/WorldWindDiagnostics.java @@ -122,7 +122,7 @@ public void init(GLAutoDrawable glAutoDrawable) { getClass().getClassLoader().loadClass(pkgName + ".GL"); - Package p = Package.getPackage(pkgName); + Package p = getClass().getClassLoader().getDefinedPackage(pkgName); if (p == null) { sb.append("WARNING: Package.getPackage(" + pkgName + ") is null\n"); diff --git a/src/gov/nasa/worldwindx/examples/layermanager/LayerManagerApp.java b/src/gov/nasa/worldwindx/examples/layermanager/LayerManagerApp.java index 4aa095be2a..f8dd493d2f 100644 --- a/src/gov/nasa/worldwindx/examples/layermanager/LayerManagerApp.java +++ b/src/gov/nasa/worldwindx/examples/layermanager/LayerManagerApp.java @@ -101,7 +101,7 @@ else if (Configuration.isWindowsOS()) } } - public static AppFrame start(String appName, Class appFrameClass) + public static AppFrame start(String appName, Class appFrameClass) { if (Configuration.isMacOS() && appName != null) { @@ -110,7 +110,7 @@ public static AppFrame start(String appName, Class appFrameClass) try { - final AppFrame frame = (AppFrame) appFrameClass.newInstance(); + final AppFrame frame = (AppFrame) appFrameClass.getConstructor().newInstance(); frame.setTitle(appName); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); java.awt.EventQueue.invokeLater(new Runnable() diff --git a/src/gov/nasa/worldwindx/examples/lineofsight/LinesOfSight.java b/src/gov/nasa/worldwindx/examples/lineofsight/LinesOfSight.java index 3091152de2..50a17333d5 100644 --- a/src/gov/nasa/worldwindx/examples/lineofsight/LinesOfSight.java +++ b/src/gov/nasa/worldwindx/examples/lineofsight/LinesOfSight.java @@ -133,7 +133,7 @@ public AppFrame() public void mouseClicked(MouseEvent mouseEvent) { // Control-Click cancels any currently running operation. - if ((mouseEvent.getModifiers() & ActionEvent.CTRL_MASK) != 0) + if ((mouseEvent.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) != 0) { if (calculationDispatchThread != null && calculationDispatchThread.isAlive()) calculationDispatchThread.interrupt(); @@ -141,7 +141,7 @@ public void mouseClicked(MouseEvent mouseEvent) } // Alt-Click repeats the most recent calculations. - if ((mouseEvent.getModifiers() & ActionEvent.ALT_MASK) != 0) + if ((mouseEvent.getModifiersEx() & InputEvent.ALT_DOWN_MASK) != 0) { if (previousCurrentPosition == null) return; @@ -153,7 +153,7 @@ public void mouseClicked(MouseEvent mouseEvent) } // Perform the intersection tests in response to Shift-Click. - if ((mouseEvent.getModifiers() & ActionEvent.SHIFT_MASK) == 0) + if ((mouseEvent.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) == 0) return; mouseEvent.consume(); // tell the rest of WW that this event has been processed diff --git a/src/gov/nasa/worldwindx/examples/shapebuilder/ExtrudedPolygonBuilder.java b/src/gov/nasa/worldwindx/examples/shapebuilder/ExtrudedPolygonBuilder.java index f04463b013..cd19307174 100644 --- a/src/gov/nasa/worldwindx/examples/shapebuilder/ExtrudedPolygonBuilder.java +++ b/src/gov/nasa/worldwindx/examples/shapebuilder/ExtrudedPolygonBuilder.java @@ -920,7 +920,7 @@ public static void makeMenuBar(JFrame frame, final PolygonBuilderController cont { JMenuItem item = new JMenuItem("Deselect"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.setActionCommand(CLEAR_SELECTION); item.addActionListener(controller); menu.add(item); diff --git a/src/gov/nasa/worldwindx/examples/shapebuilder/RigidShapeBuilder.java b/src/gov/nasa/worldwindx/examples/shapebuilder/RigidShapeBuilder.java index b926f763ae..3e688d7345 100644 --- a/src/gov/nasa/worldwindx/examples/shapebuilder/RigidShapeBuilder.java +++ b/src/gov/nasa/worldwindx/examples/shapebuilder/RigidShapeBuilder.java @@ -1664,8 +1664,8 @@ public boolean accept(File dir, String name) String[] name = file.getName().split("-"); try { - Class c = Class.forName(name[0]); - AbstractShape newShape = (AbstractShape) c.newInstance(); + Class c = Class.forName(name[0]); + AbstractShape newShape = (AbstractShape) c.getConstructor().newInstance(); BufferedReader input = new BufferedReader(new FileReader(file)); String s = input.readLine(); newShape.restoreState(s); @@ -1841,14 +1841,14 @@ public static void makeMenuBar(JFrame frame, final AbstractShapeBuilderControlle { JMenuItem item = new JMenuItem("Open..."); item.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.setActionCommand(OPEN); item.addActionListener(controller); menu.add(item); item = new JMenuItem("Save..."); item.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.setActionCommand(SAVE); item.addActionListener(controller); menu.add(item); @@ -1878,7 +1878,7 @@ public void actionPerformed(ActionEvent e) { JMenuItem item = new JMenuItem(mode.getMode()); item.setAccelerator(KeyStroke.getKeyStroke(mode.getShortcut(), - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) @@ -1914,7 +1914,7 @@ public void actionPerformed(ActionEvent e) { JMenuItem item = new JMenuItem("Deselect"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.setActionCommand(CLEAR_SELECTION); item.addActionListener(controller); menu.add(item); diff --git a/src/gov/nasa/worldwindx/examples/util/ButtonAnnotation.java b/src/gov/nasa/worldwindx/examples/util/ButtonAnnotation.java index 2ef53b13df..05f58d62fb 100644 --- a/src/gov/nasa/worldwindx/examples/util/ButtonAnnotation.java +++ b/src/gov/nasa/worldwindx/examples/util/ButtonAnnotation.java @@ -179,7 +179,7 @@ protected boolean isButtonTrigger(SelectEvent e) protected void onButtonPressed(SelectEvent e) { java.awt.event.MouseEvent mouseEvent = e.getMouseEvent(); - this.fireActionPerformed(mouseEvent.getID(), mouseEvent.getWhen(), mouseEvent.getModifiers()); + this.fireActionPerformed(mouseEvent.getID(), mouseEvent.getWhen(), mouseEvent.getModifiersEx()); } //**************************************************************// diff --git a/src/gov/nasa/worldwindx/examples/view/AddAnimator.java b/src/gov/nasa/worldwindx/examples/view/AddAnimator.java index ddcde97575..eb2835b5a5 100644 --- a/src/gov/nasa/worldwindx/examples/view/AddAnimator.java +++ b/src/gov/nasa/worldwindx/examples/view/AddAnimator.java @@ -15,6 +15,7 @@ import javax.swing.*; import javax.swing.border.*; import java.awt.*; +import java.lang.reflect.InvocationTargetException; /** * This example demonstrates the use of {@link gov.nasa.worldwind.view.firstperson.BasicFlyView} with a {@link @@ -36,7 +37,7 @@ public class ViewDisplay extends JPanel public class FlyViewGazetteerPanel extends GazetteerPanel { FlyViewGazetteerPanel(final WorldWindow wwd, String FlyViewGazetteerPanel) - throws IllegalAccessException, InstantiationException, ClassNotFoundException + throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException { super(wwd, FlyViewGazetteerPanel); } diff --git a/test/gov/nasa/worldwind/formats/georss/GeoRSSParserTest.java b/test/gov/nasa/worldwind/formats/georss/GeoRSSParserTest.java index 6feb266211..4c155f0e8e 100644 --- a/test/gov/nasa/worldwind/formats/georss/GeoRSSParserTest.java +++ b/test/gov/nasa/worldwind/formats/georss/GeoRSSParserTest.java @@ -56,9 +56,9 @@ public void testSimple_Line() assertTrue("", shapes.size() != 0); assertNotNull("", shapes.get(0)); // is translated to a WWJ Polyline. - assertTrue("", shapes.get(0) instanceof Polyline); + assertTrue("", shapes.get(0) instanceof Path); - Polyline shape = (Polyline) shapes.get(0); + Path shape = (Path) shapes.get(0); java.util.List positions = (java.util.List) shape.getPositions(); assertNotNull("", positions); assertEquals("", 3, positions.size()); @@ -80,9 +80,9 @@ public void testSimple_LineWithElevation() assertTrue("", shapes.size() != 0); assertNotNull("", shapes.get(0)); // is translated to a WWJ Polyline. - assertTrue("", shapes.get(0) instanceof Polyline); + assertTrue("", shapes.get(0) instanceof Path); - Polyline shape = (Polyline) shapes.get(0); + Path shape = (Path) shapes.get(0); java.util.List positions = (java.util.List) shape.getPositions(); assertNotNull("", positions); assertEquals("", 3, positions.size()); @@ -128,9 +128,9 @@ public void testSimple_PolygonWithElevation() assertTrue("", shapes.size() != 0); assertNotNull("", shapes.get(0)); // is translated to a WWJ Polyline when an elevation is specified. - assertTrue("", shapes.get(0) instanceof Polyline); + assertTrue("", shapes.get(0) instanceof Path); - Polyline shape = (Polyline) shapes.get(0); + Path shape = (Path) shapes.get(0); java.util.List positions = (java.util.List) shape.getPositions(); assertNotNull("", positions); assertEquals("", 4, positions.size()); @@ -224,10 +224,10 @@ public void testGML_Line() assertNotNull("", shapes); assertTrue("", shapes.size() != 0); assertNotNull("", shapes.get(0)); - // is translated to a WWJ Polyline. - assertTrue("", shapes.get(0) instanceof Polyline); + // is translated to a WWJ Path. + assertTrue("", shapes.get(0) instanceof Path); - Polyline shape = (Polyline) shapes.get(0); + Path shape = (Path) shapes.get(0); java.util.List positions = (java.util.List) shape.getPositions(); assertNotNull("", positions); assertEquals("", 3, positions.size()); @@ -438,14 +438,14 @@ public void test_MultipleShapes() assertNotNull("", shapes.get(0)); assertNotNull("", shapes.get(1)); // is translated to a WWJ Polyline. - assertTrue("", shapes.get(0) instanceof Polyline); + assertTrue("", shapes.get(0) instanceof Path); // is translated to a WWJ Polyline when an elevation is specified. - assertTrue("", shapes.get(1) instanceof Polyline); + assertTrue("", shapes.get(1) instanceof Path); - Polyline shape; + Path shape; java.util.List positions; - shape = (Polyline) shapes.get(0); + shape = (Path) shapes.get(0); positions = (java.util.List) shape.getPositions(); assertNotNull("", positions); assertEquals("", 3, positions.size()); @@ -453,7 +453,7 @@ public void test_MultipleShapes() assertEquals("", Position.fromDegrees(46.46, -109.48, 0.0), positions.get(1)); assertEquals("", Position.fromDegrees(43.84, -109.86, 0.0), positions.get(2)); - shape = (Polyline) shapes.get(1); + shape = (Path) shapes.get(1); positions = (java.util.List) shape.getPositions(); assertNotNull("", positions); assertEquals("", 3, positions.size()); @@ -474,9 +474,9 @@ public void test_CommaDelimitedCoordinates() assertTrue("", shapes.size() != 0); assertNotNull("", shapes.get(0)); // is translated to a WWJ Polyline. - assertTrue("", shapes.get(0) instanceof Polyline); + assertTrue("", shapes.get(0) instanceof Path); - Polyline shape = (Polyline) shapes.get(0); + Path shape = (Path) shapes.get(0); java.util.List positions = (java.util.List) shape.getPositions(); assertNotNull("", positions); assertEquals("", 3, positions.size()); From 9f047a20160dab59c1c729b0d4264ba2aecd4a6c Mon Sep 17 00:00:00 2001 From: markpet49 Date: Thu, 19 Sep 2019 18:33:05 -0500 Subject: [PATCH 06/11] Revert Polyline formatting --- src/gov/nasa/worldwind/render/Polyline.java | 793 +++++++++++--------- 1 file changed, 454 insertions(+), 339 deletions(-) diff --git a/src/gov/nasa/worldwind/render/Polyline.java b/src/gov/nasa/worldwind/render/Polyline.java index bfe9225287..807b1c52f9 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,60 +72,68 @@ 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 + 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); @@ -133,7 +141,8 @@ 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); @@ -143,12 +152,15 @@ 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); @@ -157,17 +169,19 @@ 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(); } @@ -175,13 +189,15 @@ 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; } /** @@ -193,14 +209,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); } /** @@ -213,18 +229,21 @@ 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; } @@ -236,14 +255,16 @@ 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; } @@ -251,15 +272,17 @@ public double getOffset() { * Specifies an offset, in meters, to add to the path points when the path's follow-terrain attribute is true. See * {@link #setFollowTerrain(boolean)}. * - * @param offset the path offset in meters. + * @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; } @@ -270,20 +293,22 @@ 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()); - } } /** @@ -293,21 +318,25 @@ 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; } @@ -318,15 +347,16 @@ 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; } @@ -337,15 +367,16 @@ 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; } @@ -355,25 +386,31 @@ 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); @@ -381,9 +418,8 @@ public void setHighlightColor(Color highlightColor) { this.highlightColor = highlightColor; - if (this.surfaceShape != null) { + if (this.surfaceShape != null) this.surfaceShape.getHighlightAttributes().setOutlineMaterial(new Material(this.highlightColor)); - } } /** @@ -391,22 +427,25 @@ 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); @@ -417,39 +456,45 @@ 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; } @@ -459,9 +504,10 @@ 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; } @@ -472,7 +518,8 @@ 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; } @@ -481,15 +528,17 @@ 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); @@ -511,68 +560,81 @@ 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); @@ -589,20 +651,24 @@ 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 { - ArrayList temp = new ArrayList<>(); + } + 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); @@ -610,26 +676,27 @@ 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()); @@ -640,36 +707,42 @@ 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; } @@ -679,27 +752,31 @@ 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()); @@ -708,27 +785,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); @@ -736,15 +813,20 @@ 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(); @@ -753,81 +835,87 @@ 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); @@ -841,44 +929,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; @@ -887,123 +975,135 @@ protected void makeVertices(DrawContext dc) { 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); } @@ -1022,7 +1122,8 @@ protected ArrayList makeSegment(DrawContext dc, Position posA, Position po } @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) @@ -1035,48 +1136,55 @@ 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); @@ -1087,15 +1195,16 @@ 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); @@ -1109,13 +1218,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); @@ -1128,30 +1237,32 @@ 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); } @@ -1160,45 +1271,50 @@ 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()); } } } @@ -1219,7 +1335,8 @@ 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); } @@ -1235,19 +1352,24 @@ 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); @@ -1255,39 +1377,42 @@ 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) { - ArrayList newPositions = new ArrayList<>(); + 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)); - } } } } @@ -1298,73 +1423,63 @@ 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()); - } } } } From bded4d0451d28cc9c44fc98d2554dd5cd17e4c5f Mon Sep 17 00:00:00 2001 From: markpet49 Date: Fri, 20 Sep 2019 17:44:19 -0500 Subject: [PATCH 07/11] Formatting adjustments --- nbproject/configs/GeoRSS.properties | 1 + nbproject/configs/ViewControls.properties | 1 + .../configs/WorldWindDiagnostics.properties | 1 + src/gov/nasa/worldwindx/examples/GeoRSS.java | 143 +++++++++--------- .../worldwindx/examples/ViewControls.java | 119 +++++---------- 5 files changed, 113 insertions(+), 152 deletions(-) create mode 100644 nbproject/configs/GeoRSS.properties create mode 100644 nbproject/configs/ViewControls.properties create mode 100644 nbproject/configs/WorldWindDiagnostics.properties diff --git a/nbproject/configs/GeoRSS.properties b/nbproject/configs/GeoRSS.properties new file mode 100644 index 0000000000..1d8c38a093 --- /dev/null +++ b/nbproject/configs/GeoRSS.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.GeoRSS diff --git a/nbproject/configs/ViewControls.properties b/nbproject/configs/ViewControls.properties new file mode 100644 index 0000000000..dc913ab1de --- /dev/null +++ b/nbproject/configs/ViewControls.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.ViewControls diff --git a/nbproject/configs/WorldWindDiagnostics.properties b/nbproject/configs/WorldWindDiagnostics.properties new file mode 100644 index 0000000000..a9526b4436 --- /dev/null +++ b/nbproject/configs/WorldWindDiagnostics.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.WorldWindDiagnostics diff --git a/src/gov/nasa/worldwindx/examples/GeoRSS.java b/src/gov/nasa/worldwindx/examples/GeoRSS.java index 55aa7541b0..1cbf0e9662 100644 --- a/src/gov/nasa/worldwindx/examples/GeoRSS.java +++ b/src/gov/nasa/worldwindx/examples/GeoRSS.java @@ -16,12 +16,11 @@ * @author dcollins * @version $Id: GeoRSS.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class GeoRSS extends ApplicationTemplate -{ - private static class AppFrame extends ApplicationTemplate.AppFrame - { - public AppFrame() - { +public class GeoRSS extends ApplicationTemplate { + + private static class AppFrame extends ApplicationTemplate.AppFrame { + + public AppFrame() { super(true, true, false); RenderableLayer layer = this.buildGeoRSSLayer(); @@ -29,90 +28,90 @@ public AppFrame() insertBeforePlacenames(this.getWwd(), layer); } - private RenderableLayer buildGeoRSSLayer() - { + private RenderableLayer buildGeoRSSLayer() { RenderableLayer layer = new RenderableLayer(); java.util.List shapes; shapes = GeoRSSParser.parseShapes(GeoRSS_DOCSTRING_A); - if (shapes != null) + if (shapes != null) { addRenderables(layer, shapes); + } shapes = GeoRSSParser.parseShapes(GeoRSS_DOCSTRING_B); - if (shapes != null) + if (shapes != null) { addRenderables(layer, shapes); + } return layer; } - private void addRenderables(RenderableLayer layer, Iterable renderables) - { - for (Renderable r : renderables) + private void addRenderables(RenderableLayer layer, Iterable renderables) { + for (Renderable r : renderables) { layer.addRenderable(r); + } } } - private static final String GeoRSS_DOCSTRING_A = - "" + - "" + - " Earthquakes" + - " International earthquake observation labs" + - " " + - " 2005-12-13T18:30:02Z" + - " " + - " Dr. Thaddeus Remor" + - " tremor@quakelab.edu" + - " " + - " urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6" + - " " + - " M 3.2, Mona Passage" + - " " + - " urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a" + - " 2005-08-17T07:02:32Z" + - "

We just had a big one." + - " " + - " " + - " " + - " " + - " " + - " 45.256 -110.45 46.46 -109.48 43.84 -109.86 45.256 -110.45" + - " " + - " " + - " " + - " " + - " " + - " " + - ""; + private static final String GeoRSS_DOCSTRING_A + = "" + + "" + + " Earthquakes" + + " International earthquake observation labs" + + " " + + " 2005-12-13T18:30:02Z" + + " " + + " Dr. Thaddeus Remor" + + " tremor@quakelab.edu" + + " " + + " urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6" + + " " + + " M 3.2, Mona Passage" + + " " + + " urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a" + + " 2005-08-17T07:02:32Z" + + " We just had a big one." + + " " + + " " + + " " + + " " + + " " + + " 45.256 -110.45 46.46 -109.48 43.84 -109.86 45.256 -110.45" + + " " + + " " + + " " + + " " + + " " + + " " + + ""; - private static final String GeoRSS_DOCSTRING_B = - "" + - " scribble" + - " http://example.com/atom" + - " Christopher Schmidt" + - "" + - " http://example.com/19.atom" + - " " + - " Feature #19" + - " Some content." + - " " + - " 23.1811523438 -159.609375 " + - " 22.5 -161.564941406 " + - " 20.654296875 -160.422363281 " + - " 18.4350585938 -156.247558594 " + - " 18.3471679688 -154.731445312 " + - " 19.951171875 -153.588867188 " + - " 21.8188476562 -155.983886719" + - " 23.02734375 -158.994140625" + - " 23.0932617188 -159.631347656" + - " " + - "" + - ""; + private static final String GeoRSS_DOCSTRING_B + = "" + + " scribble" + + " http://example.com/atom" + + " Christopher Schmidt" + + "" + + " http://example.com/19.atom" + + " " + + " Feature #19" + + " Some content." + + " " + + " 23.1811523438 -159.609375 " + + " 22.5 -161.564941406 " + + " 20.654296875 -160.422363281 " + + " 18.4350585938 -156.247558594 " + + " 18.3471679688 -154.731445312 " + + " 19.951171875 -153.588867188 " + + " 21.8188476562 -155.983886719" + + " 23.02734375 -158.994140625" + + " 23.0932617188 -159.631347656" + + " " + + "" + + ""; - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind GeoRSS", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/ViewControls.java b/src/gov/nasa/worldwindx/examples/ViewControls.java index 6940447b32..5342b288b5 100644 --- a/src/gov/nasa/worldwindx/examples/ViewControls.java +++ b/src/gov/nasa/worldwindx/examples/ViewControls.java @@ -15,8 +15,8 @@ import java.awt.event.*; /** - * Shows the {@link gov.nasa.worldwind.layers.ViewControlsLayer} and allows you to adjust its size, orientation, - * and available controls. + * Shows the {@link gov.nasa.worldwind.layers.ViewControlsLayer} and allows you to adjust its size, orientation, and + * available controls. * * @author Patrick Murris * @version $Id: ViewControls.java 2109 2014-06-30 16:52:38Z tgaskins $ @@ -24,21 +24,18 @@ * @see gov.nasa.worldwind.layers.ViewControlsSelectListener * @see gov.nasa.worldwind.layers.CompassLayer */ -public class ViewControls extends ApplicationTemplate -{ - public static class AppFrame extends ApplicationTemplate.AppFrame - { +public class ViewControls extends ApplicationTemplate { + + public static class AppFrame extends ApplicationTemplate.AppFrame { + protected ViewControlsLayer viewControlsLayer; - public AppFrame() - { + public AppFrame() { super(true, true, false); // Find ViewControls layer and keep reference to it - for (Layer layer : this.getWwd().getModel().getLayers()) - { - if (layer instanceof ViewControlsLayer) - { + for (Layer layer : this.getWwd().getModel().getLayers()) { + if (layer instanceof ViewControlsLayer) { viewControlsLayer = (ViewControlsLayer) layer; } } @@ -47,12 +44,11 @@ public AppFrame() this.getControlPanel().add(makeControlPanel(), BorderLayout.SOUTH); } - private JPanel makeControlPanel() - { + private JPanel makeControlPanel() { JPanel controlPanel = new JPanel(); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS)); controlPanel.setBorder( - new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("View Controls"))); + new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("View Controls"))); controlPanel.setToolTipText("Select active view controls"); // Radio buttons - layout @@ -61,24 +57,16 @@ private JPanel makeControlPanel() ButtonGroup group = new ButtonGroup(); JRadioButton button = new JRadioButton("Horizontal", true); group.add(button); - button.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - viewControlsLayer.setLayout(AVKey.HORIZONTAL); - getWwd().redraw(); - } + button.addActionListener((ActionEvent actionEvent) -> { + viewControlsLayer.setLayout(AVKey.HORIZONTAL); + getWwd().redraw(); }); layoutPanel.add(button); button = new JRadioButton("Vertical", false); group.add(button); - button.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - viewControlsLayer.setLayout(AVKey.VERTICAL); - getWwd().redraw(); - } + button.addActionListener((ActionEvent actionEvent) -> { + viewControlsLayer.setLayout(AVKey.VERTICAL); + getWwd().redraw(); }); layoutPanel.add(button); @@ -87,13 +75,9 @@ public void actionPerformed(ActionEvent actionEvent) scalePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); scalePanel.add(new JLabel("Scale:")); JSlider scaleSlider = new JSlider(1, 20, 10); - scaleSlider.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent event) - { - viewControlsLayer.setScale(((JSlider) event.getSource()).getValue() / 10d); - getWwd().redraw(); - } + scaleSlider.addChangeListener((ChangeEvent event) -> { + viewControlsLayer.setScale(((JSlider) event.getSource()).getValue() / 10d); + getWwd().redraw(); }); scalePanel.add(scaleSlider); @@ -103,73 +87,49 @@ public void stateChanged(ChangeEvent event) JCheckBox check = new JCheckBox("Pan"); check.setSelected(true); - check.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - viewControlsLayer.setShowPanControls(((JCheckBox) actionEvent.getSource()).isSelected()); - getWwd().redraw(); - } + check.addActionListener((ActionEvent actionEvent) -> { + viewControlsLayer.setShowPanControls(((JCheckBox) actionEvent.getSource()).isSelected()); + getWwd().redraw(); }); checkPanel.add(check); check = new JCheckBox("Look"); check.setSelected(false); - check.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - viewControlsLayer.setShowLookControls(((JCheckBox) actionEvent.getSource()).isSelected()); - getWwd().redraw(); - } + check.addActionListener((ActionEvent actionEvent) -> { + viewControlsLayer.setShowLookControls(((JCheckBox) actionEvent.getSource()).isSelected()); + getWwd().redraw(); }); checkPanel.add(check); check = new JCheckBox("Zoom"); check.setSelected(true); - check.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - viewControlsLayer.setShowZoomControls(((JCheckBox) actionEvent.getSource()).isSelected()); - getWwd().redraw(); - } + check.addActionListener((ActionEvent actionEvent) -> { + viewControlsLayer.setShowZoomControls(((JCheckBox) actionEvent.getSource()).isSelected()); + getWwd().redraw(); }); checkPanel.add(check); check = new JCheckBox("Heading"); check.setSelected(true); - check.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - viewControlsLayer.setShowHeadingControls(((JCheckBox) actionEvent.getSource()).isSelected()); - getWwd().redraw(); - } + check.addActionListener((ActionEvent actionEvent) -> { + viewControlsLayer.setShowHeadingControls(((JCheckBox) actionEvent.getSource()).isSelected()); + getWwd().redraw(); }); checkPanel.add(check); check = new JCheckBox("Pitch"); check.setSelected(true); - check.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - viewControlsLayer.setShowPitchControls(((JCheckBox) actionEvent.getSource()).isSelected()); - getWwd().redraw(); - } + check.addActionListener((ActionEvent actionEvent) -> { + viewControlsLayer.setShowPitchControls(((JCheckBox) actionEvent.getSource()).isSelected()); + getWwd().redraw(); }); checkPanel.add(check); check = new JCheckBox("Field of view"); check.setSelected(false); - check.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - viewControlsLayer.setShowFovControls(((JCheckBox) actionEvent.getSource()).isSelected()); - getWwd().redraw(); - } + check.addActionListener((ActionEvent actionEvent) -> { + viewControlsLayer.setShowFovControls(((JCheckBox) actionEvent.getSource()).isSelected()); + getWwd().redraw(); }); checkPanel.add(check); @@ -180,8 +140,7 @@ public void actionPerformed(ActionEvent actionEvent) } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind View Controls", AppFrame.class); } } From fafca83e37a75bd78370b282254ea0bf531da514 Mon Sep 17 00:00:00 2001 From: markpet49 Date: Wed, 2 Oct 2019 16:39:26 -0500 Subject: [PATCH 08/11] GeoRSS fixes --- .../formats/georss/GeoRSSParser.java | 15 +- src/gov/nasa/worldwindx/examples/GeoRSS.java | 31 ++ .../formats/georss/GeoRSSParserTest.java | 302 ++++++++---------- 3 files changed, 178 insertions(+), 170 deletions(-) diff --git a/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java b/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java index db2dbab4a5..0d09f226f3 100644 --- a/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java +++ b/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java @@ -283,8 +283,9 @@ private static Renderable makePolygonShape(Node node, Iterable attrs) { if (elevation != 0) { Path path = new Path(positions, elevation); path.setAttributes(new BasicShapeAttributes()); + path.getAttributes().setOutlineMaterial(Material.WHITE); + path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); - return path; } else { return new SurfacePolygon(positions); @@ -382,13 +383,17 @@ private static Renderable makeLineShape(Node node, Iterable attrs) { } double elevation = attrs != null ? getElevation(node, attrs) : 0d; + Path path; if (elevation != 0) { - Path path = new Path(positions, elevation); - path.setPathType(AVKey.GREAT_CIRCLE); - return path; + path = new Path(positions, elevation); } else { - return new Path(positions, 0); + path = new Path(positions, 0); } + path.setAttributes(new BasicShapeAttributes()); + path.getAttributes().setOutlineMaterial(Material.WHITE); + path.setFollowTerrain(true); + path.setPathType(AVKey.GREAT_CIRCLE); + return path; } @SuppressWarnings({"UnusedDeclaration"}) diff --git a/src/gov/nasa/worldwindx/examples/GeoRSS.java b/src/gov/nasa/worldwindx/examples/GeoRSS.java index 1cbf0e9662..9f37658970 100644 --- a/src/gov/nasa/worldwindx/examples/GeoRSS.java +++ b/src/gov/nasa/worldwindx/examples/GeoRSS.java @@ -42,6 +42,11 @@ private RenderableLayer buildGeoRSSLayer() { addRenderables(layer, shapes); } + shapes = GeoRSSParser.parseShapes(GeoRSS_DOCSTRING_C); + if (shapes != null) { + addRenderables(layer, shapes); + } + return layer; } @@ -111,6 +116,32 @@ private void addRenderables(RenderableLayer layer, Iterable renderab + "" + ""; + private static final String GeoRSS_DOCSTRING_C + = "" + + "" + + " An X" + + " Line test" + + " " + + " 2005-12-13T18:30:02Z" + + " " + + " NASA" + + " nasa@nasa.gov" + + " " + + " urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6" + + " " + + " An X" + + " " + + " urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a" + + " 2005-08-17T07:02:32Z" + + " Test" + + " 45 -95 44 -94" + + " 45 -94 44 -95" + + " 1000" + + " " + + ""; + public static void main(String[] args) { ApplicationTemplate.start("WorldWind GeoRSS", AppFrame.class); } diff --git a/test/gov/nasa/worldwind/formats/georss/GeoRSSParserTest.java b/test/gov/nasa/worldwind/formats/georss/GeoRSSParserTest.java index 4c155f0e8e..3c03f4c7bb 100644 --- a/test/gov/nasa/worldwind/formats/georss/GeoRSSParserTest.java +++ b/test/gov/nasa/worldwind/formats/georss/GeoRSSParserTest.java @@ -15,17 +15,15 @@ @SuppressWarnings("deprecation") @RunWith(JUnit4.class) -public class GeoRSSParserTest -{ +public class GeoRSSParserTest { ////////////////////////////////////////////////////////// // GeoRSS-Simple Parsing Tests ////////////////////////////////////////////////////////// @Test - public void testSimple_Point() - { + public void testSimple_Point() { String xmlString = createExampleGeoRSS( - "45.256 -71.92"); + "45.256 -71.92"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // is not translated to any renderable shape. @@ -33,11 +31,10 @@ public void testSimple_Point() } @Test - public void testSimple_PointWithElevation() - { + public void testSimple_PointWithElevation() { String xmlString = createExampleGeoRSS( - "45.256 -71.92" + - "313"); + "45.256 -71.92" + + "313"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // is not translated to any renderable shape. @@ -45,17 +42,16 @@ public void testSimple_PointWithElevation() } @Test - public void testSimple_Line() - { + public void testSimple_Line() { String xmlString = createExampleGeoRSS( - "45.256 -110.45 46.46 -109.48 43.84 -109.86"); + "45.256 -110.45 46.46 -109.48 43.84 -109.86"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. assertNotNull("", shapes); assertTrue("", shapes.size() != 0); assertNotNull("", shapes.get(0)); - // is translated to a WWJ Polyline. + // is translated to a WWJ Path. assertTrue("", shapes.get(0) instanceof Path); Path shape = (Path) shapes.get(0); @@ -68,18 +64,17 @@ public void testSimple_Line() } @Test - public void testSimple_LineWithElevation() - { + public void testSimple_LineWithElevation() { String xmlString = createExampleGeoRSS( - "45.256 -110.45 46.46 -109.48 43.84 -109.86" + - "313"); + "45.256 -110.45 46.46 -109.48 43.84 -109.86" + + "313"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. assertNotNull("", shapes); assertTrue("", shapes.size() != 0); assertNotNull("", shapes.get(0)); - // is translated to a WWJ Polyline. + // is translated to a WWJ Path. assertTrue("", shapes.get(0) instanceof Path); Path shape = (Path) shapes.get(0); @@ -92,10 +87,9 @@ public void testSimple_LineWithElevation() } @Test - public void testSimple_Polygon() - { + public void testSimple_Polygon() { String xmlString = createExampleGeoRSS( - "45.256 -110.45 46.46 -109.48 43.84 -109.86 45.256 -110.45"); + "45.256 -110.45 46.46 -109.48 43.84 -109.86 45.256 -110.45"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. @@ -116,18 +110,17 @@ public void testSimple_Polygon() } @Test - public void testSimple_PolygonWithElevation() - { + public void testSimple_PolygonWithElevation() { String xmlString = createExampleGeoRSS( - "45.256 -110.45 46.46 -109.48 43.84 -109.86 45.256 -110.45" + - "313"); + "45.256 -110.45 46.46 -109.48 43.84 -109.86 45.256 -110.45" + + "313"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. assertNotNull("", shapes); assertTrue("", shapes.size() != 0); assertNotNull("", shapes.get(0)); - // is translated to a WWJ Polyline when an elevation is specified. + // is translated to a WWJ Path when an elevation is specified. assertTrue("", shapes.get(0) instanceof Path); Path shape = (Path) shapes.get(0); @@ -141,10 +134,9 @@ public void testSimple_PolygonWithElevation() } @Test - public void testSimple_Box() - { + public void testSimple_Box() { String xmlString = createExampleGeoRSS( - "42.943 -71.032 43.039 -69.856"); + "42.943 -71.032 43.039 -69.856"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. @@ -165,11 +157,10 @@ public void testSimple_Box() } @Test - public void testSimple_BoxWithElevation() - { + public void testSimple_BoxWithElevation() { String xmlString = createExampleGeoRSS( - "42.943 -71.032 43.039 -69.856" + - "313"); + "42.943 -71.032 43.039 -69.856" + + "313"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. @@ -191,16 +182,14 @@ public void testSimple_BoxWithElevation() ////////////////////////////////////////////////////////// // GeoRSS-GML Parsing Tests ////////////////////////////////////////////////////////// - @Test - public void testGML_Point() - { + public void testGML_Point() { String xmlString = createExampleGeoRSS( - "" + - " " + - " 45.256 -71.92" + - " " + - ""); + "" + + " " + + " 45.256 -71.92" + + " " + + ""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // is not translated to any renderable shape. @@ -208,16 +197,15 @@ public void testGML_Point() } @Test - public void testGML_Line() - { + public void testGML_Line() { String xmlString = createExampleGeoRSS( - "" + - " " + - " " + - " 45.256 -110.45 46.46 -109.48 43.84 -109.86" + - " " + - " " + - ""); + "" + + " " + + " " + + " 45.256 -110.45 46.46 -109.48 43.84 -109.86" + + " " + + " " + + ""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. @@ -237,20 +225,19 @@ public void testGML_Line() } @Test - public void testGML_Polygon() - { + public void testGML_Polygon() { String xmlString = createExampleGeoRSS( - "" + - " " + - " " + - " " + - " " + - " 45.256 -110.45 46.46 -109.48 43.84 -109.86 45.256 -110.45" + - " " + - " " + - " " + - " " + - ""); + "" + + " " + + " " + + " " + + " " + + " 45.256 -110.45 46.46 -109.48 43.84 -109.86 45.256 -110.45" + + " " + + " " + + " " + + " " + + ""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. @@ -271,15 +258,14 @@ public void testGML_Polygon() } @Test - public void testGML_Box() - { + public void testGML_Box() { String xmlString = createExampleGeoRSS( - "" + - " " + - " 42.943 -71.032" + - " 43.039 -69.856" + - " " + - ""); + "" + + " " + + " 42.943 -71.032" + + " 43.039 -69.856" + + " " + + ""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. @@ -302,116 +288,106 @@ public void testGML_Box() ////////////////////////////////////////////////////////// // Exceptional Condition Tests ////////////////////////////////////////////////////////// - @Test - public void testSimple_PointNotEnoughPairs() - { + public void testSimple_PointNotEnoughPairs() { String xmlString = createExampleGeoRSS( - ""); + ""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); assertNull("", shapes); } @Test - public void testSimple_LineNotEnoughPairs() - { + public void testSimple_LineNotEnoughPairs() { String xmlString = createExampleGeoRSS( - "45.256 -110.45"); + "45.256 -110.45"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); assertNull("", shapes); } @Test - public void testSimple_PolygonNotEnoughPairs() - { + public void testSimple_PolygonNotEnoughPairs() { String xmlString = createExampleGeoRSS( - "45.256 -110.45 46.46 -109.48 43.84 -109.86"); + "45.256 -110.45 46.46 -109.48 43.84 -109.86"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); assertNull("", shapes); } @Test - public void testSimple_BoxNotEnoughPairs() - { + public void testSimple_BoxNotEnoughPairs() { String xmlString = createExampleGeoRSS( - "42.943 -71.032"); + "42.943 -71.032"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); assertNull("", shapes); } @Test - public void testGML_PointNotEnoughPairs() - { + public void testGML_PointNotEnoughPairs() { String xmlString = createExampleGeoRSS( - "" + - " " + - " " + - " " + - ""); + "" + + " " + + " " + + " " + + ""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); assertNull("", shapes); } @Test - public void testGML_LineNotEnoughPairs() - { + public void testGML_LineNotEnoughPairs() { String xmlString = createExampleGeoRSS( - "" + - " " + - " " + - " 45.256 -110.45" + - " " + - " " + - ""); + "" + + " " + + " " + + " 45.256 -110.45" + + " " + + " " + + ""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); assertNull("", shapes); } @Test - public void testGML_PolygonNotEnoughPairs() - { + public void testGML_PolygonNotEnoughPairs() { String xmlString = createExampleGeoRSS( - "" + - " " + - " " + - " " + - " " + - " 45.256 -110.45 46.46 -109.48 43.84 -109.86" + - " " + - " " + - " " + - " " + - ""); + "" + + " " + + " " + + " " + + " " + + " 45.256 -110.45 46.46 -109.48 43.84 -109.86" + + " " + + " " + + " " + + " " + + ""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); assertNull("", shapes); } @Test - public void testGML_BoxMissingElement() - { + public void testGML_BoxMissingElement() { String xmlString = createExampleGeoRSS( - "" + - " " + - " 42.943 -71.032" + - // The next line would normally be included. + "" + + " " + + " 42.943 -71.032" + + // The next line would normally be included. // " 43.039 -69.856" + - " " + - ""); + " " + + ""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); assertNull("", shapes); } @Test - public void test_NoShapes() - { + public void test_NoShapes() { String xmlString = createExampleGeoRSS(""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); @@ -419,17 +395,16 @@ public void test_NoShapes() } @Test - public void test_MultipleShapes() - { + public void test_MultipleShapes() { String xmlString = createExampleGeoRSS( - "45.256 -110.45 46.46 -109.48 43.84 -109.86" + - "" + - " " + - " " + - " 45.256 -110.45 46.46 -109.48 43.84 -109.86" + - " " + - " " + - ""); + "45.256 -110.45 46.46 -109.48 43.84 -109.86" + + "" + + " " + + " " + + " 45.256 -110.45 46.46 -109.48 43.84 -109.86" + + " " + + " " + + ""); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. @@ -437,9 +412,9 @@ public void test_MultipleShapes() assertTrue("", shapes.size() >= 2); assertNotNull("", shapes.get(0)); assertNotNull("", shapes.get(1)); - // is translated to a WWJ Polyline. + // is translated to a WWJ Path. assertTrue("", shapes.get(0) instanceof Path); - // is translated to a WWJ Polyline when an elevation is specified. + // is translated to a WWJ Path when an elevation is specified. assertTrue("", shapes.get(1) instanceof Path); Path shape; @@ -463,17 +438,16 @@ public void test_MultipleShapes() } @Test - public void test_CommaDelimitedCoordinates() - { + public void test_CommaDelimitedCoordinates() { String xmlString = createExampleGeoRSS( - "45.256, -110.45, 46.46, -109.48, 43.84, -109.86"); + "45.256, -110.45, 46.46, -109.48, 43.84, -109.86"); java.util.List shapes = GeoRSSParser.parseShapes(xmlString); // Parsed shapes list should have at least one non-null element. assertNotNull("", shapes); assertTrue("", shapes.size() != 0); assertNotNull("", shapes.get(0)); - // is translated to a WWJ Polyline. + // is translated to a WWJ Path. assertTrue("", shapes.get(0) instanceof Path); Path shape = (Path) shapes.get(0); @@ -488,32 +462,30 @@ public void test_CommaDelimitedCoordinates() ////////////////////////////////////////////////////////// // Helper Methods ////////////////////////////////////////////////////////// - - private static String createExampleGeoRSS(String georssXml) - { - String xmlString = - "" + - "" + - " Earthquakes" + - " International earthquake observation labs" + - " " + - " 2005-12-13T18:30:02Z" + - " " + - " Dr. Thaddeus Remor" + - " tremor@quakelab.edu" + - " " + - " urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6" + - " " + - " M 3.2, Mona Passage" + - " " + - " urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a" + - " 2005-08-17T07:02:32Z" + - " We just had a big one." + - " {0}" + - " " + - ""; + private static String createExampleGeoRSS(String georssXml) { + String xmlString + = "" + + "" + + " Earthquakes" + + " International earthquake observation labs" + + " " + + " 2005-12-13T18:30:02Z" + + " " + + " Dr. Thaddeus Remor" + + " tremor@quakelab.edu" + + " " + + " urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6" + + " " + + " M 3.2, Mona Passage" + + " " + + " urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a" + + " 2005-08-17T07:02:32Z" + + " We just had a big one." + + " {0}" + + " " + + ""; return java.text.MessageFormat.format(xmlString, georssXml); } } From cce1239474edb14635361402068d5750580696b2 Mon Sep 17 00:00:00 2001 From: markpet49 Date: Fri, 11 Oct 2019 17:32:34 -0500 Subject: [PATCH 09/11] Deprecation bug fixes --- nbproject/configs/AirspaceBuilder.properties | 1 + nbproject/configs/Balloons.properties | 1 + .../configs/ContextMenusOnShapes.properties | 1 + nbproject/configs/ContourLines.properties | 1 + nbproject/configs/DataInstallerApp.properties | 1 + .../configs/DebuggingGLErrors.properties | 1 + nbproject/configs/ExtrudedShapes.properties | 1 + nbproject/configs/FlatWorld.properties | 1 + .../configs/GetBestElevations.properties | 1 + nbproject/configs/GliderTestApp.properties | 1 + nbproject/configs/Graticule.properties | 1 + nbproject/configs/ImportImagery.properties | 1 + .../configs/KeepObjectsInView.properties | 1 + nbproject/configs/LayerManagerApp.properties | 1 + nbproject/configs/LineBackground.properties | 1 + nbproject/configs/LinesOfSight.properties | 1 + nbproject/configs/MeasureToolUsage.properties | 1 + nbproject/configs/MultiResPath.properties | 1 + nbproject/configs/SARApp.properties | 1 + nbproject/configs/SurfaceImages.properties | 1 + .../configs/TerrainIntersections.properties | 1 + nbproject/configs/TerrainProfiler.properties | 1 + nbproject/configs/ViewLookAround.properties | 1 + nbproject/configs/WorldWindow.properties | 1 + .../formats/georss/GeoRSSParser.java | 155 ++- src/gov/nasa/worldwind/geom/Position.java | 137 +-- .../layers/AbstractGraticuleLayer.java | 3 +- .../worldwind/layers/TerrainProfileLayer.java | 62 +- .../nasa/worldwind/render/ContourLine.java | 16 +- src/gov/nasa/worldwind/render/Path.java | 55 +- .../graphics/areas/AirfieldZone.java | 3 +- .../milstd2525/graphics/areas/Ambush.java | 3 +- .../graphics/areas/AttackByFirePosition.java | 3 +- .../milstd2525/graphics/areas/Dummy.java | 3 +- .../milstd2525/graphics/areas/SearchArea.java | 3 +- .../graphics/areas/SectorRangeFan.java | 3 +- .../graphics/lines/AbstractAxisArrow.java | 3 +- .../graphics/lines/DirectionOfAttack.java | 3 +- .../graphics/lines/FireSupportLine.java | 3 +- .../graphics/lines/HoldingLine.java | 3 +- .../graphics/lines/InfiltrationLane.java | 3 +- .../graphics/lines/LinearTarget.java | 3 +- .../milstd2525/graphics/lines/PhaseLine.java | 3 +- .../lines/PrincipleDirectionOfFire.java | 3 +- .../graphics/lines/PullUpPoint.java | 3 +- .../milstd2525/graphics/lines/Route.java | 3 +- .../nasa/worldwind/util/HTTPFileUpload.java | 2 + .../nasa/worldwind/util/OGLTextRenderer.java | 19 - src/gov/nasa/worldwind/util/ShapeEditor.java | 3 +- .../nasa/worldwind/util/gdal/GDALUtils.java | 47 +- .../worldwind/util/measure/AreaMeasurer.java | 10 +- .../util/measure/LengthMeasurer.java | 39 +- .../worldwind/util/measure/MeasureTool.java | 13 +- .../dataimporter/DataInstallerApp.java | 64 +- .../dataimporter/FileSetHighlighter.java | 3 +- .../FileStoreSectorHighlighter.java | 3 +- .../applications/glider/GliderImageLayer.java | 4 +- .../applications/glider/GliderTestApp.java | 126 +-- .../applications/sar/TerrainProfilePanel.java | 2 - .../applications/sar/TrackController.java | 2 +- .../applications/sar/render/PlaneModel.java | 4 +- .../worldwindow/config/AppConfiguration.xml | 9 +- .../worldwindow/core/Controller.java | 1 + .../features/MeasurementPanel.java | 4 +- .../worldwindx/examples/AirspaceBuilder.java | 1004 +++++++---------- .../nasa/worldwindx/examples/Balloons.java | 38 +- .../examples/ContextMenusOnShapes.java | 141 ++- .../examples/ContourBuilderExample.java | 3 +- .../worldwindx/examples/ContourLines.java | 43 +- .../examples/DebuggingGLErrors.java | 25 +- .../worldwindx/examples/ExtrudedShapes.java | 80 +- .../examples/GetBestElevations.java | 87 +- .../examples/KeepingObjectsInView.java | 8 +- .../worldwindx/examples/LineBackground.java | 6 +- .../nasa/worldwindx/examples/LineBuilder.java | 2 +- .../worldwindx/examples/MeasureToolPanel.java | 461 ++++---- .../worldwindx/examples/MeasureToolUsage.java | 82 +- .../worldwindx/examples/MultiResPath.java | 49 +- .../examples/PathPositionColors.java | 3 +- src/gov/nasa/worldwindx/examples/Paths.java | 16 +- .../worldwindx/examples/ShapeEditing.java | 3 +- src/gov/nasa/worldwindx/examples/Shapes.java | 157 +-- .../worldwindx/examples/SurfaceImages.java | 6 +- .../examples/TerrainIntersections.java | 280 ++--- .../worldwindx/examples/TerrainProfiler.java | 144 +-- .../worldwindx/examples/ViewLookAround.java | 109 +- .../examples/WorldWindDiagnostics.java | 149 ++- 87 files changed, 1623 insertions(+), 2128 deletions(-) create mode 100644 nbproject/configs/AirspaceBuilder.properties create mode 100644 nbproject/configs/Balloons.properties create mode 100644 nbproject/configs/ContextMenusOnShapes.properties create mode 100644 nbproject/configs/ContourLines.properties create mode 100644 nbproject/configs/DataInstallerApp.properties create mode 100644 nbproject/configs/DebuggingGLErrors.properties create mode 100644 nbproject/configs/ExtrudedShapes.properties create mode 100644 nbproject/configs/FlatWorld.properties create mode 100644 nbproject/configs/GetBestElevations.properties create mode 100644 nbproject/configs/GliderTestApp.properties create mode 100644 nbproject/configs/Graticule.properties create mode 100644 nbproject/configs/ImportImagery.properties create mode 100644 nbproject/configs/KeepObjectsInView.properties create mode 100644 nbproject/configs/LayerManagerApp.properties create mode 100644 nbproject/configs/LineBackground.properties create mode 100644 nbproject/configs/LinesOfSight.properties create mode 100644 nbproject/configs/MeasureToolUsage.properties create mode 100644 nbproject/configs/MultiResPath.properties create mode 100644 nbproject/configs/SARApp.properties create mode 100644 nbproject/configs/SurfaceImages.properties create mode 100644 nbproject/configs/TerrainIntersections.properties create mode 100644 nbproject/configs/TerrainProfiler.properties create mode 100644 nbproject/configs/ViewLookAround.properties create mode 100644 nbproject/configs/WorldWindow.properties diff --git a/nbproject/configs/AirspaceBuilder.properties b/nbproject/configs/AirspaceBuilder.properties new file mode 100644 index 0000000000..a0b267ffee --- /dev/null +++ b/nbproject/configs/AirspaceBuilder.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.AirspaceBuilder diff --git a/nbproject/configs/Balloons.properties b/nbproject/configs/Balloons.properties new file mode 100644 index 0000000000..98b5ac83b7 --- /dev/null +++ b/nbproject/configs/Balloons.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.Balloons diff --git a/nbproject/configs/ContextMenusOnShapes.properties b/nbproject/configs/ContextMenusOnShapes.properties new file mode 100644 index 0000000000..221d601aa3 --- /dev/null +++ b/nbproject/configs/ContextMenusOnShapes.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.ContextMenusOnShapes diff --git a/nbproject/configs/ContourLines.properties b/nbproject/configs/ContourLines.properties new file mode 100644 index 0000000000..f59881b4e8 --- /dev/null +++ b/nbproject/configs/ContourLines.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.ContourLines diff --git a/nbproject/configs/DataInstallerApp.properties b/nbproject/configs/DataInstallerApp.properties new file mode 100644 index 0000000000..3f5a442b37 --- /dev/null +++ b/nbproject/configs/DataInstallerApp.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.applications.dataimporter.DataInstallerApp diff --git a/nbproject/configs/DebuggingGLErrors.properties b/nbproject/configs/DebuggingGLErrors.properties new file mode 100644 index 0000000000..6808468088 --- /dev/null +++ b/nbproject/configs/DebuggingGLErrors.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.DebuggingGLErrors diff --git a/nbproject/configs/ExtrudedShapes.properties b/nbproject/configs/ExtrudedShapes.properties new file mode 100644 index 0000000000..ad2d3acbf9 --- /dev/null +++ b/nbproject/configs/ExtrudedShapes.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.ExtrudedShapes diff --git a/nbproject/configs/FlatWorld.properties b/nbproject/configs/FlatWorld.properties new file mode 100644 index 0000000000..0bb69bc87c --- /dev/null +++ b/nbproject/configs/FlatWorld.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.FlatWorld diff --git a/nbproject/configs/GetBestElevations.properties b/nbproject/configs/GetBestElevations.properties new file mode 100644 index 0000000000..4b6b3a701e --- /dev/null +++ b/nbproject/configs/GetBestElevations.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.GetBestElevations diff --git a/nbproject/configs/GliderTestApp.properties b/nbproject/configs/GliderTestApp.properties new file mode 100644 index 0000000000..64125681af --- /dev/null +++ b/nbproject/configs/GliderTestApp.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.applications.glider.GliderTestApp diff --git a/nbproject/configs/Graticule.properties b/nbproject/configs/Graticule.properties new file mode 100644 index 0000000000..6db1cb02ea --- /dev/null +++ b/nbproject/configs/Graticule.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.Graticule diff --git a/nbproject/configs/ImportImagery.properties b/nbproject/configs/ImportImagery.properties new file mode 100644 index 0000000000..f97fe3aef4 --- /dev/null +++ b/nbproject/configs/ImportImagery.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.dataimport.ImportImagery diff --git a/nbproject/configs/KeepObjectsInView.properties b/nbproject/configs/KeepObjectsInView.properties new file mode 100644 index 0000000000..0ef5fd2b90 --- /dev/null +++ b/nbproject/configs/KeepObjectsInView.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.KeepingObjectsInView diff --git a/nbproject/configs/LayerManagerApp.properties b/nbproject/configs/LayerManagerApp.properties new file mode 100644 index 0000000000..f8c9f7fe5e --- /dev/null +++ b/nbproject/configs/LayerManagerApp.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.layermanager.LayerManagerApp diff --git a/nbproject/configs/LineBackground.properties b/nbproject/configs/LineBackground.properties new file mode 100644 index 0000000000..63cd15cdac --- /dev/null +++ b/nbproject/configs/LineBackground.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.LineBackground diff --git a/nbproject/configs/LinesOfSight.properties b/nbproject/configs/LinesOfSight.properties new file mode 100644 index 0000000000..3ba5750dec --- /dev/null +++ b/nbproject/configs/LinesOfSight.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.lineofsight.LinesOfSight diff --git a/nbproject/configs/MeasureToolUsage.properties b/nbproject/configs/MeasureToolUsage.properties new file mode 100644 index 0000000000..38a1f45146 --- /dev/null +++ b/nbproject/configs/MeasureToolUsage.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.MeasureToolUsage diff --git a/nbproject/configs/MultiResPath.properties b/nbproject/configs/MultiResPath.properties new file mode 100644 index 0000000000..ca88bb3bad --- /dev/null +++ b/nbproject/configs/MultiResPath.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.MultiResPath diff --git a/nbproject/configs/SARApp.properties b/nbproject/configs/SARApp.properties new file mode 100644 index 0000000000..e0186f2ccd --- /dev/null +++ b/nbproject/configs/SARApp.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.applications.sar.SARApp diff --git a/nbproject/configs/SurfaceImages.properties b/nbproject/configs/SurfaceImages.properties new file mode 100644 index 0000000000..de838eb4f1 --- /dev/null +++ b/nbproject/configs/SurfaceImages.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.SurfaceImages diff --git a/nbproject/configs/TerrainIntersections.properties b/nbproject/configs/TerrainIntersections.properties new file mode 100644 index 0000000000..b288c6fb80 --- /dev/null +++ b/nbproject/configs/TerrainIntersections.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.TerrainIntersections diff --git a/nbproject/configs/TerrainProfiler.properties b/nbproject/configs/TerrainProfiler.properties new file mode 100644 index 0000000000..d1000873e7 --- /dev/null +++ b/nbproject/configs/TerrainProfiler.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.TerrainProfiler diff --git a/nbproject/configs/ViewLookAround.properties b/nbproject/configs/ViewLookAround.properties new file mode 100644 index 0000000000..1180a98ce5 --- /dev/null +++ b/nbproject/configs/ViewLookAround.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.ViewLookAround diff --git a/nbproject/configs/WorldWindow.properties b/nbproject/configs/WorldWindow.properties new file mode 100644 index 0000000000..1e966431e8 --- /dev/null +++ b/nbproject/configs/WorldWindow.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.applications.worldwindow.WorldWindow diff --git a/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java b/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java index 0d09f226f3..877be40eb3 100644 --- a/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java +++ b/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java @@ -5,6 +5,7 @@ */ package gov.nasa.worldwind.formats.georss; +import gov.nasa.worldwind.WorldWind; import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.exception.WWRuntimeException; import gov.nasa.worldwind.geom.*; @@ -24,38 +25,38 @@ * @version $Id: GeoRSSParser.java 1171 2013-02-11 21:45:02Z dcollins $ */ 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) { return parseShapes(fixNamespaceQualification(fragmentString)); } - + 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 { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new InputSource(new StringReader(docString))); - + List shapes = parseShapes(doc); - + if (shapes == null || shapes.size() < 1) { Logging.logger().log(Level.WARNING, "GeoRSS.NoShapes", docString); return null; } - + return shapes; } catch (ParserConfigurationException e) { String message = Logging.getMessage("GeoRSS.ParserConfigurationException"); @@ -67,23 +68,23 @@ public static List parseShapes(String docString) { throw new WWRuntimeException(message, e); } } - + private static String fixNamespaceQualification(String xmlString) { String lcaseString = xmlString.toLowerCase(); StringBuffer qualifiers = new StringBuffer(); - + 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)) { qualifiers.append(" xmlns:gml=\""); qualifiers.append(GML_URI); qualifiers.append("\""); } - + if (qualifiers.length() > 0) { StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(xmlString); sb.append(""); - + return sb.toString(); } - + return xmlString; } - + public static List parseShapes(File file) { if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - + try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(false); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(file); - + List shapes = parseShapes(doc); - + if (shapes == null || shapes.size() < 1) { Logging.logger().log(Level.WARNING, "GeoRSS.NoShapes", file.getPath()); return null; } - + return shapes; } catch (ParserConfigurationException e) { String message = Logging.getMessage("GeoRSS.ParserConfigurationException"); @@ -129,14 +130,14 @@ public static List parseShapes(File file) { throw new WWRuntimeException(message, e); } } - + public static List parseShapes(Document xmlDoc) { if (xmlDoc == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - + ArrayList shapeNodes = new ArrayList<>(); ArrayList attributeNodes = new ArrayList<>(); @@ -145,22 +146,22 @@ public static List parseShapes(Document xmlDoc) { if (nodes != null && nodes.getLength() > 0) { addNodes(shapeNodes, nodes); } - + nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "point"); if (nodes != null && nodes.getLength() > 0) { addNodes(shapeNodes, nodes); } - + nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "line"); if (nodes != null && nodes.getLength() > 0) { addNodes(shapeNodes, nodes); } - + nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "polygon"); if (nodes != null && nodes.getLength() > 0) { addNodes(shapeNodes, nodes); } - + nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "box"); if (nodes != null && nodes.getLength() > 0) { addNodes(shapeNodes, nodes); @@ -171,21 +172,21 @@ public static List parseShapes(Document xmlDoc) { if (nodes != null && nodes.getLength() > 0) { addNodes(attributeNodes, nodes); } - + nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "elev"); if (nodes != null && nodes.getLength() > 0) { addNodes(attributeNodes, nodes); } - + ArrayList shapes = new ArrayList<>(); - + if (shapeNodes.size() < 1) { return null; // No warning here. Let the calling method inform of this case. } for (Node node : shapeNodes) { Renderable shape = null; String localName = node.getLocalName(); - + switch (localName) { case "point": shape = makePointShape(node, attributeNodes); @@ -205,146 +206,145 @@ public static List parseShapes(Document xmlDoc) { default: break; } - + if (shape != null) { shapes.add(shape); } } - + return shapes; } - + 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) { Node typeNode = findChildByLocalName(node, "Polygon"); if (typeNode != null) { return makeGMLPolygonShape(typeNode); } - + typeNode = findChildByLocalName(node, "Envelope"); if (typeNode != null) { return makeGMLEnvelopeShape(typeNode); } - + typeNode = findChildByLocalName(node, "LineString"); if (typeNode != null) { return makeGMLineStringShape(typeNode); } - + typeNode = findChildByLocalName(node, "Point"); if (typeNode != null) { return makeGMLPointShape(typeNode); } - + Logging.logger().log(Level.WARNING, "GeoRSS.MissingElementContent", "where"); return null; } - + private static Renderable makeGMLPolygonShape(Node node) { Node n = findChildByLocalName(node, "exterior"); if (n == null) { Logging.logger().log(Level.WARNING, "GeoRSS.MissingElement", "exterior"); return null; } - + n = findChildByLocalName(n, "LinearRing"); if (n == null) { Logging.logger().log(Level.WARNING, "GeoRSS.MissingElement", "LinearRing"); return null; } - + return makePolygonShape(n, null); } - + private static Renderable makePolygonShape(Node node, Iterable attrs) { String valuesString = node.getTextContent(); 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) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", node.getLocalName()); return null; } - + ArrayList positions = new ArrayList<>(); 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) { Path path = new Path(positions, elevation); path.setAttributes(new BasicShapeAttributes()); path.getAttributes().setOutlineMaterial(Material.WHITE); - path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); return path; } else { return new SurfacePolygon(positions); } } - + private static Renderable makeGMLEnvelopeShape(Node node) { Node n = findChildByLocalName(node, "lowerCorner"); if (n == null) { Logging.logger().log(Level.WARNING, "GeoRSS.MissingElement", " lowerCorner"); return null; } - + String lowerCornerString = n.getTextContent(); if (lowerCornerString == null) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", " lowerCorner"); return null; } - + n = findChildByLocalName(node, "upperCorner"); if (n == null) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", " upperCorner"); return null; } - + String upperCornerString = n.getTextContent(); if (upperCornerString == null) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", " upperCorner"); return null; } - + ArrayList lv = getDoubleValues(lowerCornerString); if (lv.size() != 2) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", " lowerCorner"); return null; } - + ArrayList uv = getDoubleValues(upperCornerString); if (uv.size() != 2) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", " upperCorner"); return null; } - + 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) { String valuesString = node.getTextContent(); if (valuesString == null) { Logging.logger().log(Level.WARNING, "GeoRSS.NoCoordinates", node.getLocalName()); return null; } - + ArrayList p = getDoubleValues(valuesString); if (p.size() != 4) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", node.getLocalName()); return null; } - + double elevation = getElevation(node, attrs); if (elevation != 0) { return new Quadrilateral(LatLon.fromDegrees(p.get(0), p.get(1)), @@ -353,35 +353,35 @@ private static Renderable makeBoxShape(Node node, Iterable attrs) { return new SurfaceSector(Sector.fromDegrees(p.get(0), p.get(2), p.get(1), p.get(3))); } } - + private static Renderable makeGMLineStringShape(Node node) { Node n = findChildByLocalName(node, "posList"); if (n == null) { Logging.logger().log(Level.WARNING, "GeoRSS.MissingElement", "posList"); return null; } - + return makeLineShape(n, null); } - + private static Renderable makeLineShape(Node node, Iterable attrs) { String valuesString = node.getTextContent(); if (valuesString == null) { Logging.logger().log(Level.WARNING, "GeoRSS.NoCoordinates", node.getLocalName()); return null; } - + ArrayList values = getDoubleValues(valuesString); 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) { positions.add(LatLon.fromDegrees(values.get(i), values.get(i + 1))); } - + double elevation = attrs != null ? getElevation(node, attrs) : 0d; Path path; if (elevation != 0) { @@ -391,63 +391,62 @@ private static Renderable makeLineShape(Node node, Iterable attrs) { } path.setAttributes(new BasicShapeAttributes()); path.getAttributes().setOutlineMaterial(Material.WHITE); - path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); return path; } - + @SuppressWarnings({"UnusedDeclaration"}) 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) { return null; // No shape provided for points. Expect app to use icons. } - + private static Node findChildByLocalName(Node parent, String localName) { NodeList children = parent.getChildNodes(); if (children == null || children.getLength() < 1) { return null; } - + for (int i = 0; i < children.getLength(); i++) { String ln = children.item(i).getLocalName(); 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)) { continue; } - + if (attrib.getParentNode().equals(shapeNode.getParentNode())) { return attrib; } } - + return null; } - + private static ArrayList getDoubleValues(String stringValues) { String[] tokens = stringValues.trim().split("[ ,\n]"); if (tokens.length < 1) { return null; } - + ArrayList arl = new ArrayList<>(); for (String s : tokens) { if (s == null || s.length() < 1) { continue; } - + double d; try { d = Double.parseDouble(s); @@ -455,16 +454,16 @@ private static ArrayList getDoubleValues(String stringValues) { Logging.logger().log(Level.SEVERE, "GeoRSS.NumberFormatException", s); continue; } - + arl.add(d); } - + return arl; } - + private static double getElevation(Node shapeNode, Iterable attrs) { double elevation = 0d; - + Node elevNode = findSiblingAttribute("elev", attrs, shapeNode); if (elevNode != null) { ArrayList ev = getDoubleValues(elevNode.getTextContent()); @@ -474,7 +473,7 @@ private static double getElevation(Node shapeNode, Iterable attrs) { Logging.logger().log(Level.WARNING, "GeoRSS.MissingElementContent", "elev"); } } - + return elevation; } } diff --git a/src/gov/nasa/worldwind/geom/Position.java b/src/gov/nasa/worldwind/geom/Position.java index 8b53b08813..a43e62255f 100644 --- a/src/gov/nasa/worldwind/geom/Position.java +++ b/src/gov/nasa/worldwind/geom/Position.java @@ -14,46 +14,44 @@ * @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; } + public Position(Position that) { + this(that.latitude, that.longitude, that.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 +61,7 @@ public PositionList(List list) * * @return this position's elevation */ - public double getElevation() - { + public double getElevation() { return this.elevation; } @@ -73,21 +70,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 +100,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 +135,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 +168,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 +187,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 +217,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 +242,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 +255,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 +281,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 +294,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 +324,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/layers/AbstractGraticuleLayer.java b/src/gov/nasa/worldwind/layers/AbstractGraticuleLayer.java index 111b77beba..34c22d7ebb 100644 --- a/src/gov/nasa/worldwind/layers/AbstractGraticuleLayer.java +++ b/src/gov/nasa/worldwind/layers/AbstractGraticuleLayer.java @@ -721,9 +721,8 @@ protected Object createLineRenderable(Iterable positions, St { Path path = new Path(positions); path.setPathType(pathType); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setTerrainConformance(1); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); return path; } diff --git a/src/gov/nasa/worldwind/layers/TerrainProfileLayer.java b/src/gov/nasa/worldwind/layers/TerrainProfileLayer.java index 9a2385f8f2..380212cbe2 100644 --- a/src/gov/nasa/worldwind/layers/TerrainProfileLayer.java +++ b/src/gov/nasa/worldwind/layers/TerrainProfileLayer.java @@ -98,14 +98,17 @@ public class TerrainProfileLayer extends AbstractLayer implements PositionListen protected class OrderedIcon implements OrderedRenderable { + @Override public double getDistanceFromEye() { return 0; } + @Override public void pick(DrawContext dc, Point pickPoint) { TerrainProfileLayer.this.drawProfile(dc); } + @Override public void render(DrawContext dc) { TerrainProfileLayer.this.drawProfile(dc); } @@ -152,7 +155,7 @@ public boolean getIsMaximized() { } /** - * Set wheter the profile graph should be maximized - displays over the whole viewport. + * Set whether the profile graph should be maximized - displays over the whole viewport. * * @param state true if the profile should be maximized. */ @@ -679,9 +682,9 @@ public void setPathType(String pathType) { } /** - * Get the Polyline used to render the profile line on the ground. + * Get the Path used to render the profile line on the ground. * - * @return the Polyline used to render the profile line on the ground. + * @return the Path used to render the profile line on the ground. */ @SuppressWarnings({"UnusedDeclaration"}) public Path getProfileLine() { @@ -689,9 +692,9 @@ public Path getProfileLine() { } /** - * Get the Polyline used to render the picked position on the terrain. + * Get the Path used to render the picked position on the terrain. * - * @return the Polyline used to render the picked position on the terrain. + * @return the Path used to render the picked position on the terrain. */ @SuppressWarnings({"UnusedDeclaration"}) public Path getPickedLine() { @@ -1185,14 +1188,15 @@ protected Color getBackgroundColor(Color color) { // ** Dimensions and positionning ************************************************************ 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)) { - return (this.toViewportScale) * viewport.width / this.size.width; - } else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) { - return 1d; - } else { - return 1d; + switch (this.resizeBehavior) { + case AVKey.RESIZE_SHRINK_ONLY: + return Math.min(1d, (this.toViewportScale) * viewport.width / this.size.width); + case AVKey.RESIZE_STRETCH: + return (this.toViewportScale) * viewport.width / this.size.width; + case AVKey.RESIZE_KEEP_FIXED_SIZE: + return 1d; + default: + return 1d; } } @@ -1259,8 +1263,8 @@ protected Position computePickPosition(DrawContext dc, Vec4 locationSW, Dimensio if (sample >= 0 && sample < this.samples) { pickPosition = this.positions[sample]; this.pickedSample = sample; - // Update polyline indicator - ArrayList posList = new ArrayList(); + // Update path 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)); @@ -1328,11 +1332,13 @@ protected int computeObjectSample(LatLon pos) { } // ** Position listener impl. ************************************************************ + @Override public void moved(PositionEvent event) { this.positions = null; } // ** Select listener impl. ************************************************************ + @Override public void selected(SelectEvent event) { if (event.hasObjects() && event.getEventAction().equals(SelectEvent.LEFT_CLICK)) { if (event.getMouseEvent() != null && event.getMouseEvent().isConsumed()) { @@ -1355,6 +1361,7 @@ public void selected(SelectEvent event) { } // ** Property change listener *********************************************************** + @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { this.positions = null; } @@ -1401,14 +1408,21 @@ protected void computeProfile(DrawContext dc) { // Find center position View view = this.wwd.getView(); Position groundPos = null; - if (this.follow.equals(FOLLOW_VIEW)) { - groundPos = this.computeViewCenterPosition(dc); - } else if (this.follow.equals(FOLLOW_CURSOR)) { - groundPos = this.computeCursorPosition(dc); - } else if (this.follow.equals(FOLLOW_EYE)) { - groundPos = view.getEyePosition(); - } else if (this.follow.equals(FOLLOW_OBJECT)) { - groundPos = this.objectPosition; + switch (this.follow) { + case FOLLOW_VIEW: + groundPos = this.computeViewCenterPosition(dc); + break; + case FOLLOW_CURSOR: + groundPos = this.computeCursorPosition(dc); + break; + case FOLLOW_EYE: + groundPos = view.getEyePosition(); + break; + case FOLLOW_OBJECT: + groundPos = this.objectPosition; + break; + default: + break; } // Compute profile if we can if ((this.follow.equals(FOLLOW_VIEW) && groundPos != null) @@ -1429,7 +1443,7 @@ protected void computeProfile(DrawContext dc) { // Update shape on ground if (this.selectionShape == null) { this.selectionShape = new Path(Arrays.asList(this.positions)); - this.selectionShape.setFollowTerrain(true); + this.selectionShape.setSurfacePath(true); var attrs = new BasicShapeAttributes(); attrs.setOutlineWidth(2); attrs.setOutlineMaterial(new Material(new Color(this.color.getRed(), diff --git a/src/gov/nasa/worldwind/render/ContourLine.java b/src/gov/nasa/worldwind/render/ContourLine.java index 568b8a5ae9..0ff9da8784 100644 --- a/src/gov/nasa/worldwind/render/ContourLine.java +++ b/src/gov/nasa/worldwind/render/ContourLine.java @@ -5,6 +5,7 @@ */ package gov.nasa.worldwind.render; +import gov.nasa.worldwind.WorldWind; import gov.nasa.worldwind.geom.*; import gov.nasa.worldwind.globes.Globe; import gov.nasa.worldwind.util.*; @@ -204,6 +205,7 @@ public List getRenderables() { return this.renderables; } + @Override public void render(DrawContext dc) { if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); @@ -257,7 +259,7 @@ protected void makeContourLine(DrawContext dc) { Intersection[] interArray = dc.getSurfaceGeometry().intersect(this.getElevation() * ve, this.getSector()); if (interArray != null) { - ArrayList inter = new ArrayList( + ArrayList inter = new ArrayList<>( Arrays.asList(interArray)); // Filter intersection segment list @@ -266,7 +268,7 @@ protected void makeContourLine(DrawContext dc) { } inter = filterIntersections(dc, inter); - // Create polyline segments + // Create path segments makePathsConnected(dc, inter, this.maxConnectingDistance); } } @@ -328,14 +330,14 @@ 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. + * Add a set of Path 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 tolerance how far in meter can two points be considered connected. * - * @return the number of Polyline objects added. + * @return the number of Path objects added. */ protected int makePathsConnected(DrawContext dc, ArrayList inter, int tolerance) { if (inter == null) { @@ -395,10 +397,10 @@ protected int makePathsConnected(DrawContext dc, ArrayList inter, // Next segment i += 2; } - // Create polyline + // Create path line = new Path(positions); line.setNumSubsegments(0); - line.setFollowTerrain(true); + line.setSurfacePath(true); var attrs = new BasicShapeAttributes(); attrs.setOutlineWidth(this.getLineWidth()); attrs.setOutlineMaterial(new Material(this.getColor())); diff --git a/src/gov/nasa/worldwind/render/Path.java b/src/gov/nasa/worldwind/render/Path.java index 40b811c390..a2f4b9374d 100644 --- a/src/gov/nasa/worldwind/render/Path.java +++ b/src/gov/nasa/worldwind/render/Path.java @@ -831,6 +831,22 @@ public void setPositions(Iterable positions) { this.reset(); } + /** + * Convenience method for migration from Polyline.setClosed. Simply appends a copy of the starting Position to the + * end of the position list. + */ + public void makeClosed() { + if (this.positions != null && this.positions.iterator().hasNext()) { + ArrayList newPositions = new ArrayList<>(); + this.positions.forEach((p) -> { + newPositions.add(new Position(p)); + }); + + newPositions.add(new Position(newPositions.get(0))); + this.setPositions(newPositions); + } + } + /** * 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. @@ -1152,15 +1168,48 @@ protected boolean shouldUseVBOs(DrawContext dc) { /** * Indicates whether this Path's defining positions and the positions in between are located on the underlying - * terrain.This returns true if this Path's altitude mode is WorldWind.CLAMP_TO_GROUND and - * the follow-terrain property is true. Otherwise this returns false. + * terrain. This returns true if this Path's altitude mode is WorldWind.CLAMP_TO_GROUND + * and the follow-terrain property is true. Otherwise this returns false. * * @param dc The current draw context. * @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) { - return (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND && this.isFollowTerrain()) || dc.is2DGlobe(); + return this.isSurfacePath() || dc.is2DGlobe(); + } + + /** + * Indicates whether this Path's defining positions and the positions in between are located on the underlying + * terrain. This returns true if this Path's altitude mode is WorldWind.CLAMP_TO_GROUND + * and the follow-terrain property is true. Otherwise this returns false. + * + * @return true if this Path's positions and the positions in between are located on the underlying + * terrain, and false otherwise. + */ + public boolean isSurfacePath() { + return (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND && this.isFollowTerrain()); + } + + /** + * Sets whether this Path's defining positions and the positions in between are located on the underlying terrain. + * + * If the surfacePath parameter is true this Path's altitude mode is set to WorldWind.CLAMP_TO_GROUND + * and the follow terrain property is set to true. + * + * If the surfacePath parameter is false this Path's altitude mode and follow terrain property are returned to their + * defaults. + * + * @param surfacePath whether or not this Path should be located on the underlying terrain. + */ + public void setSurfacePath(boolean surfacePath) { + if (surfacePath) { + this.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); + this.setFollowTerrain(true); + } else { + this.setAltitudeMode(Path.DEFAULT_ALTITUDE_MODE); + this.setFollowTerrain(false); + } } @Override 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..a7d3fd7e85 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AirfieldZone.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AirfieldZone.java @@ -133,8 +133,7 @@ protected List createAirfieldPaths(DrawContext dc) protected void configurePath(Path path) { path.setDelegateOwner(this); - path.setFollowTerrain(true); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); + path.setSurfacePath(true); path.setAttributes(this.activeShapeAttributes); } } 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..6999b3749b 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Ambush.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Ambush.java @@ -610,9 +610,8 @@ protected List computeArrowheadPositions(DrawContext dc, Position tip, protected Path createPath(List positions) { Path path = new Path(positions); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..ad7029e9f3 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AttackByFirePosition.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AttackByFirePosition.java @@ -378,9 +378,8 @@ protected List computeArrowheadPositions(DrawContext dc, Position base protected Path createPath(List positions) { Path path = new Path(positions); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..25c6c42727 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Dummy.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Dummy.java @@ -113,9 +113,8 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) protected Path createPath() { Path path = new Path(); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); return path; } 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..3e2a0a15b0 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SearchArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SearchArea.java @@ -496,9 +496,8 @@ protected void determineActiveAttributes() protected Path createPath(List positions) { Path path = new Path(positions); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..0c1deae351 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SectorRangeFan.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SectorRangeFan.java @@ -1059,9 +1059,8 @@ protected void determineActiveAttributes() protected Path createPath(List positions) { Path path = new Path(positions); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..82076d23cf 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AbstractAxisArrow.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AbstractAxisArrow.java @@ -417,9 +417,8 @@ protected void createLinePositions(List leftPositions, List protected Path createPath() { Path path = new Path(); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..f018570102 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttack.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttack.java @@ -356,9 +356,8 @@ protected List computeArrowheadPositions(DrawContext dc, Vec4 tip, Vec protected Path createPath(List positions) { Path path = new Path(positions); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..7ed1cbf958 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/FireSupportLine.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/FireSupportLine.java @@ -433,9 +433,8 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) protected Path createPath() { Path path = new Path(); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..253cc381ba 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/HoldingLine.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/HoldingLine.java @@ -409,9 +409,8 @@ protected void determineLabelPositions(DrawContext dc) protected Path createPath() { Path path = new Path(); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..537e03cccd 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/InfiltrationLane.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/InfiltrationLane.java @@ -404,9 +404,8 @@ protected void determineLabelPositions(DrawContext dc) protected Path createPath(List positions) { Path path = new Path(positions); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/LinearTarget.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/LinearTarget.java index 6d7ddb6731..cca09b5b5b 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/LinearTarget.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/LinearTarget.java @@ -423,9 +423,8 @@ protected Offset getBottomLabelOffset() protected Path createPath(List positions) { Path path = new Path(positions); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..4d34ec46d8 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PhaseLine.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PhaseLine.java @@ -125,9 +125,8 @@ protected void applyDelegateOwner(Object owner) protected Path createPath() { Path path = new Path(); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..b0c30a1132 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PrincipleDirectionOfFire.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PrincipleDirectionOfFire.java @@ -464,9 +464,8 @@ protected void determineActiveAttributes() protected Path createPath(List positions) { Path path = new Path(positions); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..ca8fc0e195 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PullUpPoint.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PullUpPoint.java @@ -154,9 +154,8 @@ protected void determineLabelPositions(DrawContext dc) protected Path createPath() { Path path = new Path(); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this); path.setAttributes(this.getActiveShapeAttributes()); return path; 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..23e79eeaae 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Route.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Route.java @@ -588,9 +588,8 @@ protected Position computeMainLabelPosition(DrawContext dc, TacticalGraphicLabel protected Path createPath(Position start, Position end) { Path path = new Path(start, end); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setPathType(AVKey.GREAT_CIRCLE); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; diff --git a/src/gov/nasa/worldwind/util/HTTPFileUpload.java b/src/gov/nasa/worldwind/util/HTTPFileUpload.java index f0e41b876a..81370cf302 100644 --- a/src/gov/nasa/worldwind/util/HTTPFileUpload.java +++ b/src/gov/nasa/worldwind/util/HTTPFileUpload.java @@ -22,7 +22,9 @@ /** * Synchronous file upload using HTTP POST as a multi-part form data + * @deprecated */ +@Deprecated public class HTTPFileUpload { private final PropertyChangeSupport propertyChangeSupport; diff --git a/src/gov/nasa/worldwind/util/OGLTextRenderer.java b/src/gov/nasa/worldwind/util/OGLTextRenderer.java index 6d32390642..968dc17689 100644 --- a/src/gov/nasa/worldwind/util/OGLTextRenderer.java +++ b/src/gov/nasa/worldwind/util/OGLTextRenderer.java @@ -68,25 +68,6 @@ protected void initialize() { this.setSmoothing(DEFAULT_SMOOTHING); this.setUseVertexArrays(DEFAULT_USE_VERTEX_ARRAYS); - -// if (System.getProperty("gov.nasa.worldwind.textRenderer.DisableGlyphCache") != null) -// { -// try -// { -// Field field = TextRenderer.class.getDeclaredField("DISABLE_GLYPH_CACHE"); -// field.setAccessible(true); -// Field modifiersField = Field.class.getDeclaredField("modifiers"); -// modifiersField.setAccessible(true); -// modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); -// field.setBoolean(TextRenderer.class, true); -// boolean tf = field.getBoolean(this); -// System.out.println(tf); -// } -// catch (Exception e) -// { -// // TODO: issue a warning -// } -// } } //**************************************************************// diff --git a/src/gov/nasa/worldwind/util/ShapeEditor.java b/src/gov/nasa/worldwind/util/ShapeEditor.java index f99199a214..95ba17f5db 100644 --- a/src/gov/nasa/worldwind/util/ShapeEditor.java +++ b/src/gov/nasa/worldwind/util/ShapeEditor.java @@ -1269,8 +1269,7 @@ protected void updateOrientationLine(Position centerPosition, Position controlPo } else if (this.getShapeAltitudeMode() == WorldWind.CLAMP_TO_GROUND) { - rotationLine.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); - rotationLine.setFollowTerrain(true); + rotationLine.setSurfacePath(true); } else { diff --git a/src/gov/nasa/worldwind/util/gdal/GDALUtils.java b/src/gov/nasa/worldwind/util/gdal/GDALUtils.java index 5b55108f56..9befae2184 100644 --- a/src/gov/nasa/worldwind/util/gdal/GDALUtils.java +++ b/src/gov/nasa/worldwind/util/gdal/GDALUtils.java @@ -64,6 +64,7 @@ public class GDALUtils { private static class GDALLibraryLoader implements gdal.LibraryLoader { + @Override public void load(String libName) throws UnsatisfiedLinkError { if (WWUtil.isEmpty(libName)) { String message = Logging.getMessage("nullValue.LibraryIsNull"); @@ -272,7 +273,7 @@ protected static String findGdalDataFolder() { protected static String buildPathString(String[] folders, boolean addDefaultValues) { String del = System.getProperty("path.separator"); - StringBuffer path = new StringBuffer(); + StringBuilder path = new StringBuilder(); path.append("lib-external/gdal").append(del); @@ -291,7 +292,7 @@ protected static String buildPathString(String[] folders, boolean addDefaultValu } protected static void listAllRegisteredDrivers() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < gdal.GetDriverCount(); i++) { Driver drv = gdal.GetDriver(i); String msg = Logging.getMessage("gdal.DriverDetails", drv.getShortName(), drv.getLongName(), @@ -477,8 +478,6 @@ protected static DataRaster composeImageDataRaster(Dataset ds, AVList params) throw new IllegalArgumentException(message); } - BufferedImage img = null; - int width = ds.getRasterXSize(); int height = ds.getRasterYSize(); int bandCount = ds.getRasterCount(); @@ -496,7 +495,7 @@ protected static DataRaster composeImageDataRaster(Dataset ds, AVList params) int[] offsets = new int[bandCount]; int imgSize = width * height; - int bandDataType = 0, buf_size = 0; + int bandDataType = 0; double maxValue = -Double.MAX_VALUE; @@ -510,7 +509,7 @@ protected static DataRaster composeImageDataRaster(Dataset ds, AVList params) } bandDataType = imageBand.getDataType(); - buf_size = imgSize * (gdal.GetDataTypeSize(bandDataType) / 8); + int buf_size = imgSize * (gdal.GetDataTypeSize(bandDataType) / 8); ByteBuffer data = ByteBuffer.allocateDirect(buf_size); data.order(ByteOrder.nativeOrder()); @@ -561,11 +560,9 @@ protected static DataRaster composeImageDataRaster(Dataset ds, AVList params) actualBitsPerColor = (Integer) params.getValue(AVKey.RASTER_BAND_ACTUAL_BITS_PER_PIXEL); } else if (maxValue > 0d) { actualBitsPerColor = (int) Math.ceil(Math.log(maxValue) / Math.log(2d)); - } else { - actualBitsPerColor = bitsPerColor; } - int[] reqBandOrder = bandsOrder; + int[] reqBandOrder; try { reqBandOrder = extractBandOrder(ds, params); if (null == reqBandOrder || 0 == reqBandOrder.length) { @@ -670,6 +667,7 @@ protected static DataRaster composeImageDataRaster(Dataset ds, AVList params) ColorModel cm; Band band1 = ds.GetRasterBand(1); + BufferedImage img; if (band1.GetRasterColorInterpretation() == gdalconstConstants.GCI_PaletteIndex) { cm = band1.GetRasterColorTable().getIndexColorModel(gdal.GetDataTypeSize(bandDataType)); img = new BufferedImage(cm, raster, false, null); @@ -718,11 +716,9 @@ protected static DataRaster composeImageDataRaster(Dataset ds, AVList params) img = new BufferedImage(cm, raster, false, null); } - if (null != img) { - if (AVListImpl.getBooleanValue(params, AVKey.BLACK_GAPS_DETECTION, false)) { - // remove voids - img = detectVoidsAndMakeThemTransparent(img); - } + if (AVListImpl.getBooleanValue(params, AVKey.BLACK_GAPS_DETECTION, false)) { + // remove voids + img = detectVoidsAndMakeThemTransparent(img); } return BufferedImageRaster.wrap(img, params); @@ -775,7 +771,7 @@ protected static void scanFill(BufferedImage sourceImage) { return; } - ArrayList voids = new ArrayList(); + ArrayList voids = new ArrayList<>(); voids.add(0); // a=r=g=b=0 voids.add(0xFF << 24); // a=255, r=g=b=0 voids.add(0xFFFFFFFF); // a=255, r=g=b=255 @@ -1327,8 +1323,6 @@ public static AVList extractRasterParameters(Dataset ds, AVList params, boolean } if (null != srs) { - Sector sector = null; - if (!params.hasKey(AVKey.SPATIAL_REFERENCE_WKT)) { params.setValue(AVKey.SPATIAL_REFERENCE_WKT, srs.ExportToWkt()); } @@ -1338,20 +1332,16 @@ public static AVList extractRasterParameters(Dataset ds, AVList params, boolean String msg = Logging.getMessage("generic.UnknownCoordinateSystem", proj_wkt); Logging.logger().severe(msg); return params; -// throw new WWRuntimeException(msg); } // save area in image's native CS and Projection GDAL.Area area = new GDAL.Area(srs, ds); - - if (null != area) { - params.setValue(AVKey.GDAL_AREA, area); - sector = area.getSector(); - if (null != sector) { - params.setValue(AVKey.SECTOR, sector); - LatLon origin = new LatLon(sector.getMaxLatitude(), sector.getMinLongitude()); - params.setValue(AVKey.ORIGIN, origin); - } + Sector sector = area.getSector(); + params.setValue(AVKey.GDAL_AREA, area); + 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) { @@ -1390,9 +1380,6 @@ public static AVList extractRasterParameters(Dataset ds, AVList params, boolean // 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) { diff --git a/src/gov/nasa/worldwind/util/measure/AreaMeasurer.java b/src/gov/nasa/worldwind/util/measure/AreaMeasurer.java index cd5001601a..b3dbf07f22 100644 --- a/src/gov/nasa/worldwind/util/measure/AreaMeasurer.java +++ b/src/gov/nasa/worldwind/util/measure/AreaMeasurer.java @@ -52,6 +52,7 @@ public AreaMeasurer(ArrayList positions) { super(positions); } + @Override protected void clearCachedValues() { super.clearCachedValues(); this.subdividedPositions = null; @@ -59,6 +60,7 @@ protected void clearCachedValues() { this.surfaceArea = -1; } + @Override public void setPositions(ArrayList positions) { Sector oldSector = getBoundingSector(); super.setPositions(positions); // will call clearCachedData() @@ -113,6 +115,7 @@ public void setAreaTerrainSamplingSteps(double steps) { * short. * @throws IllegalArgumentException if globe is null. */ + @Override public double getArea(Globe globe) { return this.isFollowTerrain() ? getSurfaceArea(globe) : getProjectedArea(globe); } @@ -145,10 +148,12 @@ public double getProjectedArea(Globe globe) { return this.projectedArea; } + @Override public double getPerimeter(Globe globe) { return getLength(globe); } + @Override public double getWidth(Globe globe) { if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); @@ -165,6 +170,7 @@ public double getWidth(Globe globe) { return -1; } + @Override public double getHeight(Globe globe) { if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); @@ -201,7 +207,7 @@ protected double computeProjectedAreaGeometry(Globe globe) { // Subdivide long segments if needed if (this.subdividedPositions == null) { this.subdividedPositions = subdividePositions(globe, getPositions(), getMaxSegmentLength(), - isFollowTerrain(), getAVKeyPathType()); + isFollowTerrain(), getAVKeyPathType()); } // First: tessellate polygon int verticesCount = this.subdividedPositions.size() - 1; // trim last pos which is same as first @@ -224,7 +230,7 @@ protected double computeProjectedAreaGeometry(Globe globe) { 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); + indices[idx + 1] * 3, indices[idx + 2] * 3); } return area; } diff --git a/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java b/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java index ce8c043fbd..108d54ffc0 100644 --- a/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java +++ b/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java @@ -125,6 +125,14 @@ public void setFollowTerrain(boolean followTerrain) { } } + /** + * Get the type of path used when subdividing long segments, one of Polyline.GREAT_CIRCLE, which draws segments as a + * great circle, Polyline.LINEAR, which determines the intermediate positions between segments by interpolating the + * segment endpoints, or Polyline.RHUMB_LINE, which draws segments as a line of constant heading. + * + * @return The path type + * @deprecated Superseded by {@link getAVKeyPathType} + */ @Deprecated public int getPathType() { switch (pathType) { @@ -141,17 +149,24 @@ public int getPathType() { } } + /** + * Get the type of path used when subdividing long segments, one of AVKey.GREAT_CIRCLE, which draws segments as a + * great circle, AVKey.LINEAR, which determines the intermediate positions between segments by interpolating the + * segment endpoints, or AVKey.RHUMB_LINE, which draws segments as a line of constant heading. + * + * @return The path type + */ public String getAVKeyPathType() { return this.pathType; } /** - * Sets the type of path used when subdividing long segments, one of AVKey.GREAT_CIRCLE, which draws segments as - * a great circle, AVKey.LINEAR, which determines the intermediate positions between segments by interpolating - * the segment endpoints, or AVKey.RHUMB_LINE, which draws segments as a line of constant heading. + * Sets the type of path used when subdividing long segments, one of AVKey.GREAT_CIRCLE, which draws segments as a + * great circle, AVKey.LINEAR, which determines the intermediate positions between segments by interpolating the + * segment endpoints, or AVKey.RHUMB_LINE, which draws segments as a line of constant heading. * * @param pathType the type of path to measure. - * @deprecated + * @deprecated Superseded by {@link setPathType(String)} */ @Deprecated public void setPathType(int pathType) { @@ -178,9 +193,9 @@ public void setPathType(int pathType) { } /** - * Sets the type of path used when subdividing long segments, one of AVKey.GREAT_CIRCLE, which draws segments as - * a great circle, AVKey.LINEAR, which determines the intermediate positions between segments by interpolating - * the segment endpoints, or AVKey.RHUMB_LINE, which draws segments as a line of constant heading. + * Sets the type of path used when subdividing long segments, one of AVKey.GREAT_CIRCLE, which draws segments as a + * great circle, AVKey.LINEAR, which determines the intermediate positions between segments by interpolating the + * segment endpoints, or AVKey.RHUMB_LINE, which draws segments as a line of constant heading. * * @param pathType the type of path to measure. */ @@ -327,9 +342,9 @@ protected double computeLength(Globe globe, boolean followTerrain) { /** * 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 polylinePathType - one of - * AVKey.LINEAR, AVKey.RHUMB_LINE or AVKey.GREAT_CIRCLE. All position elevations will be either at the - * terrain surface if followTerrain is true, or interpolated according to the original elevations.

+ * If needed, new intermediate positions will be created along lines that follow the given PathType - one of + * AVKey.LINEAR, AVKey.RHUMB_LINE or AVKey.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 @@ -350,8 +365,8 @@ protected static ArrayList subdividePositions(Globe globe, * 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 - * AVKey.LINEAR, AVKey.RHUMB_LINE or AVKey.GREAT_CIRCLE. All position elevations will be either at the - * terrain surface if followTerrain is true, or interpolated according to the original elevations.

+ * AVKey.LINEAR, AVKey.RHUMB_LINE or AVKey.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 diff --git a/src/gov/nasa/worldwind/util/measure/MeasureTool.java b/src/gov/nasa/worldwind/util/measure/MeasureTool.java index 8cef714d46..ce0488c7e0 100644 --- a/src/gov/nasa/worldwind/util/measure/MeasureTool.java +++ b/src/gov/nasa/worldwind/util/measure/MeasureTool.java @@ -435,9 +435,9 @@ public RenderableLayer getApplicationLayer() { } /** - * Returns the polyline currently used to display lines and path. + * Returns the path currently used to display lines and path. * - * @return the polyline currently used to display lines and path. + * @return the path currently used to display lines and path. */ public Path getLine() { return this.line; @@ -888,6 +888,11 @@ public void setFollowTerrain(boolean followTerrain) { this.followTerrain = followTerrain; if (this.line != null) { this.line.setFollowTerrain(followTerrain); + if (followTerrain) { + this.line.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); + } else { + this.line.setAltitudeMode(WorldWind.ABSOLUTE); + } } } @@ -1746,9 +1751,9 @@ protected void updateMeasureShape() { // Update line if (this.measureShapeType.equals(SHAPE_LINE) || this.measureShapeType.equals(SHAPE_PATH)) { if (this.positions.size() > 1 && this.line == null) { - // Init polyline + // Init path this.line = new Path(); - this.line.setFollowTerrain(this.isFollowTerrain()); + setFollowTerrain(this.isFollowTerrain()); this.line.setPathType(this.getPathType()); var attrs = new BasicShapeAttributes(); attrs.setOutlineWidth(this.getLineWidth()); diff --git a/src/gov/nasa/worldwindx/applications/dataimporter/DataInstallerApp.java b/src/gov/nasa/worldwindx/applications/dataimporter/DataInstallerApp.java index 360f794999..295be9dd41 100644 --- a/src/gov/nasa/worldwindx/applications/dataimporter/DataInstallerApp.java +++ b/src/gov/nasa/worldwindx/applications/dataimporter/DataInstallerApp.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.dataimporter; import gov.nasa.worldwind.*; @@ -26,19 +25,17 @@ * @author tag * @version $Id: DataInstallerApp.java 1180 2013-02-15 18:40:47Z tgaskins $ */ -public class DataInstallerApp -{ +public class DataInstallerApp { // Most of this code was taken from ApplicationTemplate. - public static class AppPanel extends JPanel - { + public static class AppPanel extends JPanel { + protected WorldWindow wwd; protected StatusBar statusBar; protected ToolTipController toolTipController; protected HighlightController highlightController; - public AppPanel() - { + public AppPanel() { super(new BorderLayout()); this.wwd = new WorldWindowGLCanvas(); @@ -63,20 +60,18 @@ public AppPanel() } // This is the application's main frame. - public static class AppFrame extends JFrame - { + public static class AppFrame extends JFrame { + protected AppPanel wwjPanel; protected LayerAndElevationManagerPanel layerManagerPanel; - public AppFrame() - { + public AppFrame() { initialize(); WWUtil.alignComponent(null, this, AVKey.CENTER); } - protected void initialize() - { + protected void initialize() { // Create the WorldWindow. this.wwjPanel = new AppPanel(); @@ -98,10 +93,8 @@ protected void initialize() // Search the layer list for layers that are also select listeners and register them with the World // Window. This enables interactive layers to be included without specific knowledge of them here. - for (Layer layer : this.getWwd().getModel().getLayers()) - { - if (layer instanceof SelectListener) - { + for (Layer layer : this.getWwd().getModel().getLayers()) { + if (layer instanceof SelectListener) { this.getWwd().addSelectListener((SelectListener) layer); } } @@ -113,58 +106,43 @@ protected void initialize() this.setResizable(true); } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return this.wwjPanel.wwd; } } - static - { + static { System.setProperty("java.net.useSystemProxies", "true"); - if (Configuration.isMacOS()) - { + if (Configuration.isMacOS()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "WorldWind Application"); System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); - } - else if (Configuration.isWindowsOS()) - { + } else if (Configuration.isWindowsOS()) { System.setProperty("sun.awt.noerasebackground", "true"); // prevents flashing during window resizing } } - public static AppFrame start(String appName, Class appFrameClass) - { - if (Configuration.isMacOS() && appName != null) - { + public static AppFrame start(String appName, Class appFrameClass) { + if (Configuration.isMacOS() && appName != null) { System.setProperty("com.apple.mrj.application.apple.menu.about.name", appName); } - try - { + try { final AppFrame frame = (AppFrame) appFrameClass.getConstructor().newInstance(); frame.setTitle(appName); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - java.awt.EventQueue.invokeLater(new Runnable() - { - public void run() - { - frame.setVisible(true); - } + java.awt.EventQueue.invokeLater(() -> { + frame.setVisible(true); }); return frame; - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(java.util.logging.Level.SEVERE, "Exception at application start", e); return null; } } - public static void main(String[] args) - { + public static void main(String[] args) { start("Data Installer", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/applications/dataimporter/FileSetHighlighter.java b/src/gov/nasa/worldwindx/applications/dataimporter/FileSetHighlighter.java index 33512902bf..b34b777ae6 100644 --- a/src/gov/nasa/worldwindx/applications/dataimporter/FileSetHighlighter.java +++ b/src/gov/nasa/worldwindx/applications/dataimporter/FileSetHighlighter.java @@ -154,8 +154,7 @@ protected void populateLayer(FileSet fileSet, RenderableLayer layer) positions.add(new Position(locations.get(0), 0)); // to form a closed path Path path = new Path(positions); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setAttributes(attrs); layer.addRenderable(path); diff --git a/src/gov/nasa/worldwindx/applications/dataimporter/FileStoreSectorHighlighter.java b/src/gov/nasa/worldwindx/applications/dataimporter/FileStoreSectorHighlighter.java index 9ed42d6f4e..7480705410 100644 --- a/src/gov/nasa/worldwindx/applications/dataimporter/FileStoreSectorHighlighter.java +++ b/src/gov/nasa/worldwindx/applications/dataimporter/FileStoreSectorHighlighter.java @@ -137,8 +137,7 @@ protected void populateLayer(FileStoreDataSet dataSet, RenderableLayer layer) positions.add(new Position(locations.get(0), 0)); // to form a closed path Path path = new Path(positions); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setAttributes(attrs); layer.addRenderable(path); diff --git a/src/gov/nasa/worldwindx/applications/glider/GliderImageLayer.java b/src/gov/nasa/worldwindx/applications/glider/GliderImageLayer.java index 294a63f602..53721561af 100644 --- a/src/gov/nasa/worldwindx/applications/glider/GliderImageLayer.java +++ b/src/gov/nasa/worldwindx/applications/glider/GliderImageLayer.java @@ -5,6 +5,7 @@ */ package gov.nasa.worldwindx.applications.glider; +import gov.nasa.worldwind.WorldWind; import gov.nasa.worldwind.layers.*; import gov.nasa.worldwind.render.*; @@ -151,7 +152,8 @@ protected static List makePaths(GliderRegionOfInterest.RegionSet reg var attrs = new BasicShapeAttributes(); attrs.setOutlineMaterial(new Material(region.getColor())); p.setAttributes(attrs); - p.setFollowTerrain(true); + p.setSurfacePath(true); + p.makeClosed(); paths.add(p); } diff --git a/src/gov/nasa/worldwindx/applications/glider/GliderTestApp.java b/src/gov/nasa/worldwindx/applications/glider/GliderTestApp.java index aeb0bf1251..15272581d7 100644 --- a/src/gov/nasa/worldwindx/applications/glider/GliderTestApp.java +++ b/src/gov/nasa/worldwindx/applications/glider/GliderTestApp.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.glider; import gov.nasa.worldwind.WorldWindow; @@ -24,32 +23,28 @@ * @author tag * @version $Id: GliderTestApp.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class GliderTestApp extends ApplicationTemplate -{ - public static class GliderAppPanel extends AppPanel - { - public GliderAppPanel(Dimension canvasSize, boolean includeStatusBar) - { +public class GliderTestApp extends ApplicationTemplate { + + public static class GliderAppPanel extends AppPanel { + + public GliderAppPanel(Dimension canvasSize, boolean includeStatusBar) { super(canvasSize, includeStatusBar); } @Override - protected WorldWindow createWorldWindow() - { + protected WorldWindow createWorldWindow() { return new GliderWorldWindow(); } } - public static class GliderAppFrame extends AppFrame - { - public GliderAppFrame() - { + public static class GliderAppFrame extends AppFrame { + + public GliderAppFrame() { super(true, true, false); } @Override - protected AppPanel createAppPanel(Dimension canvasSize, boolean includeStatusBar) - { + protected AppPanel createAppPanel(Dimension canvasSize, boolean includeStatusBar) { return new GliderAppPanel(canvasSize, includeStatusBar); } } @@ -62,8 +57,7 @@ protected AppPanel createAppPanel(Dimension canvasSize, boolean includeStatusBar protected static String cloudImagePath = "gov/nasa/worldwindx/examples/images/GLIDERTestImage-800x519.jpg"; - protected static float[][] makeField(List corners, int width, int height, Angle angle) - { + protected static float[][] makeField(List corners, int width, int height, Angle angle) { Sector sector = Sector.boundingSector(corners); double dLat = sector.getDeltaLatDegrees() / (height - 1d); double dLon = sector.getDeltaLonDegrees() / (width - 1d); @@ -71,10 +65,8 @@ protected static float[][] makeField(List corners, int width, int height float[] lons = new float[width * height]; float[] lats = new float[lons.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++) { lons[j * width + i] = (float) (sector.getMinLongitude().degrees + i * dLon); lats[j * width + i] = (float) (sector.getMaxLatitude().degrees - j * dLat); } @@ -87,10 +79,8 @@ protected static float[][] makeField(List corners, int width, int height float cx = (float) c.getLongitude().degrees; float cy = (float) c.getLatitude().degrees; - 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; float x = lons[index]; @@ -101,43 +91,38 @@ protected static float[][] makeField(List corners, int width, int height } } - return new float[][] {lats, lons}; + return new float[][]{lats, lons}; } - protected static ArrayList makeBorder(float[][] field, int width, int height, ArrayList latLons) - { - for (int i = 0; i < width; i++) - { + protected static ArrayList makeBorder(float[][] field, int width, int height, ArrayList latLons) { + for (int i = 0; i < width; i++) { latLons.add(LatLon.fromDegrees(field[0][i], field[1][i])); } - for (int i = 2 * width - 1; i < height * width; i += width) - { + for (int i = 2 * width - 1; i < height * width; i += width) { latLons.add(LatLon.fromDegrees(field[0][i], field[1][i])); } - for (int i = width * height - 2; i > width * (height - 1); i--) - { + for (int i = width * height - 2; i > width * (height - 1); i--) { latLons.add(LatLon.fromDegrees(field[0][i], field[1][i])); } - for (int i = width * (height - 2); i > 0; i -= width) - { + for (int i = width * (height - 2); i > 0; i -= width) { latLons.add(LatLon.fromDegrees(field[0][i], field[1][i])); } return latLons; } - public static void main(String[] args) - { + private static double opacityIncrement = -0.1; + + public static void main(String[] args) { final ImageUtil.AlignedImage projectedImage; final String imageName; final BufferedImage testImage; - final ArrayList latLons = new ArrayList(); + final ArrayList latLons = new ArrayList<>(); final AppFrame frame = start("GLIDER Test Application", GliderAppFrame.class); InputStream stream = null; - try - { + try { stream = WWIO.openFileOrResourceStream(cloudImagePath, null); testImage = ImageIO.read(stream); long start = System.currentTimeMillis(); @@ -146,48 +131,37 @@ public static void main(String[] args) projectedImage = GliderImage.alignImage(testImage, field[0], field[1]); System.out.printf("Image projected, %d ms\n", System.currentTimeMillis() - start); imageName = WWIO.getFilename(cloudImagePath); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); return; - } - finally - { + } finally { WWIO.closeStream(stream, cloudImagePath); } - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - final GliderImage image = new GliderImage(imageName, projectedImage, 100); - final GliderRegionOfInterest regionOfInterest = new GliderRegionOfInterest(latLons, Color.RED); - image.addRegionOfInterest(regionOfInterest); - - final javax.swing.Timer timer = new javax.swing.Timer(1000, new ActionListener() - { - @SuppressWarnings( {"StringEquality"}) - public void actionPerformed(ActionEvent evt) - { - try - { - if (((GliderWorldWindow) ((GliderAppFrame) frame).getWwd()).getImages().size() == 0) - { - System.out.println("ADDING"); - ((GliderWorldWindow) ((GliderAppFrame) frame).getWwd()).addImage(image); - image.releaseImageSource(); - } - } - catch (IOException e) - { - e.printStackTrace(); + SwingUtilities.invokeLater(() -> { + final GliderImage image = new GliderImage(imageName, projectedImage, 100); + final GliderRegionOfInterest regionOfInterest = new GliderRegionOfInterest(latLons, Color.RED); + image.addRegionOfInterest(regionOfInterest); + + final javax.swing.Timer timer = new javax.swing.Timer(1000, (ActionEvent evt) -> { + try { + if (((GliderWorldWindow) ((GliderAppFrame) frame).getWwd()).getImages().isEmpty()) { + System.out.println("ADDING"); + ((GliderWorldWindow) ((GliderAppFrame) frame).getWwd()).addImage(image); + image.releaseImageSource(); + } else { + double opacity = image.getOpacity() + opacityIncrement; + image.setOpacity(opacity); + if (opacity <= 0.1 || opacity >= 1.0) { + opacityIncrement *= -1.0; } } - }); - timer.setRepeats(false); - timer.start(); - } + } catch (IOException e) { + e.printStackTrace(); + } + }); + timer.setRepeats(true); + timer.start(); }); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java b/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java index 44fd469b0c..299da78d64 100644 --- a/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java +++ b/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java @@ -5,7 +5,6 @@ */ package gov.nasa.worldwindx.applications.sar; -import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.*; import gov.nasa.worldwind.util.*; import gov.nasa.worldwind.avlist.AVKey; @@ -16,7 +15,6 @@ import gov.nasa.worldwind.layers.Layer; import gov.nasa.worldwind.layers.ScalebarLayer; import gov.nasa.worldwind.layers.TerrainProfileLayer; -import gov.nasa.worldwind.render.Path; import javax.swing.*; import javax.swing.border.*; diff --git a/src/gov/nasa/worldwindx/applications/sar/TrackController.java b/src/gov/nasa/worldwindx/applications/sar/TrackController.java index 6a4a956f1f..093edaf65b 100644 --- a/src/gov/nasa/worldwindx/applications/sar/TrackController.java +++ b/src/gov/nasa/worldwindx/applications/sar/TrackController.java @@ -179,7 +179,7 @@ private void createPathTrackRepresentation(SARTrack track) { airPath.setAttributes(attrs); Path groundPath = new Path(track); - groundPath.setFollowTerrain(true); + groundPath.setSurfacePath(true); groundPath.setPathType(AVKey.RHUMB_LINE); attrs = new BasicShapeAttributes(); attrs.setOutlineMaterial(new Material(track.getColor())); diff --git a/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java b/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java index c8ad246402..bd400f04dc 100644 --- a/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java +++ b/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java @@ -148,7 +148,7 @@ private void createRenderables(DrawContext dc) { positions = computePlaneShape(dc, this.shadowScale * this.width, this.shadowScale * this.length); this.shadowModel = new Path(positions, this.position.getElevation()); this.shadowModel.setPathType(AVKey.LINEAR); - this.shadowModel.setFollowTerrain(true); + this.shadowModel.setSurfacePath(true); attrs = new BasicShapeAttributes(); attrs.setOutlineMaterial(new Material(this.shadowColor)); this.shadowModel.setAttributes(attrs); @@ -160,7 +160,7 @@ private void clearRenderables() { } private ArrayList computePlaneShape(DrawContext dc, double width, double length) { - ArrayList positions = new ArrayList(); + ArrayList positions = new ArrayList<>(); LatLon center = this.position; double hl = length / 2; double hw = width / 2; diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/config/AppConfiguration.xml b/src/gov/nasa/worldwindx/applications/worldwindow/config/AppConfiguration.xml index 516d6d7328..b6d82a81cb 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/config/AppConfiguration.xml +++ b/src/gov/nasa/worldwindx/applications/worldwindow/config/AppConfiguration.xml @@ -8,7 +8,7 @@ - + @@ -30,15 +30,18 @@ - + + - + + + \ No newline at end of file diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/Controller.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/Controller.java index 41ad319d8d..3d254da8b0 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/Controller.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/Controller.java @@ -257,6 +257,7 @@ public Object getRegisteredObject(String objectID) } catch (Exception e) { + e.printStackTrace(); return null; } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/MeasurementPanel.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/MeasurementPanel.java index 78fecf9036..a545cd0da1 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/MeasurementPanel.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/MeasurementPanel.java @@ -13,6 +13,7 @@ import gov.nasa.worldwindx.applications.worldwindow.util.*; import gov.nasa.worldwindx.applications.worldwindow.util.measuretool.WWOMeasureTool; +import java.util.ArrayList; import javax.swing.*; import javax.swing.border.*; import java.awt.*; @@ -190,7 +191,8 @@ protected void disposeCurrentMeasureTool() { private Renderable makeMeasureShape(String shapeType) { if (shapeType.equals(LINE) || shapeType.equals(PATH) || shapeType.equals(FREEHAND)) { Path line = new Path(); - line.setFollowTerrain(true); + line.setPositions(new ArrayList<>()); + line.setSurfacePath(true); var attrs = new BasicShapeAttributes(); attrs.setOutlineWidth(shapeType.equals(FREEHAND) ? 2 : 4); line.setAttributes(attrs); diff --git a/src/gov/nasa/worldwindx/examples/AirspaceBuilder.java b/src/gov/nasa/worldwindx/examples/AirspaceBuilder.java index 736bb03392..76a9d34821 100644 --- a/src/gov/nasa/worldwindx/examples/AirspaceBuilder.java +++ b/src/gov/nasa/worldwindx/examples/AirspaceBuilder.java @@ -55,14 +55,15 @@ * by holding the Shift key then left-click any blue sphere at a vertex and drag it. *

Demo Shapes

*

- * Select File -> Load Demo Shapes to display a set of polygon airspace shapes built with this editor. The - * data for these shapes is located in the WorldWind project under src/gov/nasa/worldwindx/examples/data/AirspaceBuilder-DemoShapes.zip. + * Select File -> Load Demo Shapes to display a set of polygon airspace shapes built with this editor. + * The data for these shapes is located in the WorldWind project under + * src/gov/nasa/worldwindx/examples/data/AirspaceBuilder-DemoShapes.zip. * * @author dcollins * @version $Id: AirspaceBuilder.java 2231 2014-08-15 19:03:12Z dcollins $ */ -public class AirspaceBuilder extends ApplicationTemplate -{ +public class AirspaceBuilder extends ApplicationTemplate { + protected static final String AIRSPACE_LAYER_NAME = "Airspace Shapes"; protected static final String CLEAR_SELECTION = "AirspaceBuilder.ClearSelection"; protected static final String SIZE_NEW_SHAPES_TO_VIEWPORT = "AirspaceBuilder.SizeNewShapesToViewport"; @@ -75,14 +76,13 @@ public class AirspaceBuilder extends ApplicationTemplate protected static final String SAVE = "AirspaceBuilder.Save"; protected static final String SELECTION_CHANGED = "AirspaceBuilder.SelectionChanged"; protected static final String DEMO_AIRSPACES_PATH - = "gov/nasa/worldwindx/examples/data/AirspaceBuilder-DemoShapes.zip"; + = "gov/nasa/worldwindx/examples/data/AirspaceBuilder-DemoShapes.zip"; //**************************************************************// //******************** Airspace Builder Model ****************// //**************************************************************// + protected static class AirspaceEntry extends WWObjectImpl { - protected static class AirspaceEntry extends WWObjectImpl - { protected Airspace airspace; protected AirspaceEditor editor; protected AirspaceAttributes attributes; @@ -90,181 +90,152 @@ protected static class AirspaceEntry extends WWObjectImpl protected boolean selected = false; protected boolean intersecting = false; - public AirspaceEntry(Airspace airspace, AirspaceEditor editor) - { + public AirspaceEntry(Airspace airspace, AirspaceEditor editor) { this.airspace = airspace; this.editor = editor; this.attributes = this.airspace.getAttributes(); } - public boolean isEditing() - { + public boolean isEditing() { return this.editing; } - public void setEditing(boolean editing) - { + public void setEditing(boolean editing) { this.editing = editing; this.updateAttributes(); } - public boolean isSelected() - { + public boolean isSelected() { return this.selected; } - public void setSelected(boolean selected) - { + public void setSelected(boolean selected) { this.selected = selected; this.updateAttributes(); } - public boolean isIntersecting() - { + public boolean isIntersecting() { return this.intersecting; } - public void setIntersecting(boolean intersecting) - { + public void setIntersecting(boolean intersecting) { this.intersecting = intersecting; this.updateAttributes(); } - public String getName() - { + public String getName() { return this.getStringValue(AVKey.DISPLAY_NAME); } - public void setName(String name) - { + public void setName(String name) { this.setValue(AVKey.DISPLAY_NAME, name); } - public Airspace getAirspace() - { + public Airspace getAirspace() { return airspace; } - public AirspaceEditor getEditor() - { + public AirspaceEditor getEditor() { return editor; } - public AirspaceAttributes getAttributes() - { + public AirspaceAttributes getAttributes() { return this.attributes; } - public String toString() - { + @Override + public String toString() { return this.getName(); } - public Object getValue(String key) - { + @Override + public Object getValue(String key) { Object value = super.getValue(key); - if (value == null) - { + if (value == null) { value = this.airspace.getValue(key); } return value; } - public Object setValue(String key, Object value) - { - if (AVKey.DISPLAY_NAME.equals(key)) - { + @Override + public Object setValue(String key, Object value) { + if (AVKey.DISPLAY_NAME.equals(key)) { return this.airspace.setValue(key, value); - } - else - { + } else { return super.setValue(key, value); } } - protected void updateAttributes() - { - if (this.isSelected() && this.isIntersecting()) - { + protected void updateAttributes() { + if (this.isSelected() && this.isIntersecting()) { this.airspace.setAttributes(getSelectionAndIntersectionAttributes()); - } - else if (this.isSelected()) - { + } else if (this.isSelected()) { this.airspace.setAttributes(getSelectionAttributes()); - } - else if (this.isIntersecting()) - { + } else if (this.isIntersecting()) { this.airspace.setAttributes(getIntersectionAttributes()); - } - else - { + } else { this.airspace.setAttributes(this.getAttributes()); } } } - protected static class AirspaceBuilderModel extends AbstractTableModel - { + protected static class AirspaceBuilderModel extends AbstractTableModel { + protected static String[] columnName = {"Name"}; protected static Class[] columnClass = {String.class}; protected static String[] columnAttribute = {AVKey.DISPLAY_NAME}; - protected ArrayList entryList = new ArrayList(); + protected ArrayList entryList = new ArrayList<>(); - public AirspaceBuilderModel() - { + public AirspaceBuilderModel() { } - public String getColumnName(int columnIndex) - { + @Override + public String getColumnName(int columnIndex) { return columnName[columnIndex]; } - public Class getColumnClass(int columnIndex) - { + @Override + public Class getColumnClass(int columnIndex) { return columnClass[columnIndex]; } - public int getRowCount() - { + @Override + public int getRowCount() { return this.entryList.size(); } - public int getColumnCount() - { + @Override + public int getColumnCount() { return 1; } - public boolean isCellEditable(int rowIndex, int columnIndex) - { + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } - public Object getValueAt(int rowIndex, int columnIndex) - { + @Override + public Object getValueAt(int rowIndex, int columnIndex) { AirspaceEntry entry = this.entryList.get(rowIndex); return entry.getValue(columnAttribute[columnIndex]); } - public void setValueAt(Object aObject, int rowIndex, int columnIndex) - { + @Override + public void setValueAt(Object aObject, int rowIndex, int columnIndex) { AirspaceEntry entry = this.entryList.get(rowIndex); String key = columnAttribute[columnIndex]; entry.setValue(key, aObject); } - public java.util.List getEntries() - { + public java.util.List getEntries() { return Collections.unmodifiableList(this.entryList); } - public void setEntries(Iterable entries) - { + public void setEntries(Iterable entries) { this.entryList.clear(); - if (entries != null) - { - for (AirspaceEntry entry : entries) - { + if (entries != null) { + for (AirspaceEntry entry : entries) { this.entryList.add(entry); } } @@ -272,68 +243,59 @@ public void setEntries(Iterable entries) this.fireTableDataChanged(); } - public void addEntry(AirspaceEntry entry) - { + public void addEntry(AirspaceEntry entry) { this.entryList.add(entry); int index = this.entryList.size() - 1; this.fireTableRowsInserted(index, index); } - public void removeEntry(AirspaceEntry entry) - { + public void removeEntry(AirspaceEntry entry) { int index = this.entryList.indexOf(entry); - if (index != -1) - { + if (index != -1) { this.entryList.remove(entry); this.fireTableRowsDeleted(index, index); } } - public void removeAllEntries() - { + public void removeAllEntries() { this.entryList.clear(); this.fireTableDataChanged(); } - public AirspaceEntry getEntry(int index) - { + public AirspaceEntry getEntry(int index) { return this.entryList.get(index); } - public AirspaceEntry setEntry(int index, AirspaceEntry entry) - { + public AirspaceEntry setEntry(int index, AirspaceEntry entry) { return this.entryList.set(index, entry); } - public int getIndexForEntry(AirspaceEntry entry) - { + public int getIndexForEntry(AirspaceEntry entry) { return this.entryList.indexOf(entry); } } - protected static AirspaceFactory[] defaultAirspaceFactories = new AirspaceFactory[] - { - new PolygonAirspaceFactory(), - new SphereAirspaceFactory() - }; + protected static AirspaceFactory[] defaultAirspaceFactories = new AirspaceFactory[]{ + new PolygonAirspaceFactory(), + new SphereAirspaceFactory() + }; protected static final double DEFAULT_SHAPE_SIZE_METERS = 200000.0; // 200 km - protected interface AirspaceFactory - { + protected interface AirspaceFactory { + Airspace createAirspace(WorldWindow wwd, boolean fitShapeToViewport); AirspaceEditor createEditor(Airspace airspace); } - protected static class PolygonAirspaceFactory implements AirspaceFactory - { - public PolygonAirspaceFactory() - { + protected static class PolygonAirspaceFactory implements AirspaceFactory { + + public PolygonAirspaceFactory() { } - public Airspace createAirspace(WorldWindow wwd, boolean fitShapeToViewport) - { + @Override + public Airspace createAirspace(WorldWindow wwd, boolean fitShapeToViewport) { Polygon poly = new Polygon(); poly.setAttributes(getDefaultAttributes()); poly.setValue(AVKey.DISPLAY_NAME, getNextName(toString())); @@ -344,33 +306,32 @@ public Airspace createAirspace(WorldWindow wwd, boolean fitShapeToViewport) return poly; } - public AirspaceEditor createEditor(Airspace airspace) - { + @Override + public AirspaceEditor createEditor(Airspace airspace) { PolygonEditor editor = new PolygonEditor(); editor.setPolygon((Polygon) airspace); setEditorAttributes(editor); return editor; } - protected void initializePolygon(WorldWindow wwd, Polygon polygon, boolean fitShapeToViewport) - { + protected void initializePolygon(WorldWindow wwd, Polygon polygon, boolean fitShapeToViewport) { // Creates a rectangle in the center of the viewport. Attempts to guess at a reasonable size and height. Position position = ShapeUtils.getNewShapePosition(wwd); Angle heading = ShapeUtils.getNewShapeHeading(wwd, true); - double sizeInMeters = fitShapeToViewport ? - ShapeUtils.getViewportScaleFactor(wwd) : DEFAULT_SHAPE_SIZE_METERS; + double sizeInMeters = fitShapeToViewport + ? ShapeUtils.getViewportScaleFactor(wwd) : DEFAULT_SHAPE_SIZE_METERS; java.util.List locations = ShapeUtils.createSquareInViewport(wwd, position, heading, sizeInMeters); double maxElevation = -Double.MAX_VALUE; Globe globe = wwd.getModel().getGlobe(); - for (LatLon ll : locations) - { + for (LatLon ll : locations) { double e = globe.getElevation(ll.getLatitude(), ll.getLongitude()); - if (e > maxElevation) + if (e > maxElevation) { maxElevation = e; + } } polygon.setAltitudes(0.0, maxElevation + sizeInMeters); @@ -378,20 +339,19 @@ protected void initializePolygon(WorldWindow wwd, Polygon polygon, boolean fitSh polygon.setLocations(locations); } - public String toString() - { + @Override + public String toString() { return "Polygon"; } } - protected static class SphereAirspaceFactory implements AirspaceFactory - { - public SphereAirspaceFactory() - { + protected static class SphereAirspaceFactory implements AirspaceFactory { + + public SphereAirspaceFactory() { } - public Airspace createAirspace(WorldWindow wwd, boolean fitShapeToViewport) - { + @Override + public Airspace createAirspace(WorldWindow wwd, boolean fitShapeToViewport) { SphereAirspace sphere = new SphereAirspace(); sphere.setAttributes(getDefaultAttributes()); sphere.setValue(AVKey.DISPLAY_NAME, getNextName(toString())); @@ -402,33 +362,31 @@ public Airspace createAirspace(WorldWindow wwd, boolean fitShapeToViewport) return sphere; } - public AirspaceEditor createEditor(Airspace airspace) - { + @Override + public AirspaceEditor createEditor(Airspace airspace) { SphereAirspaceEditor editor = new SphereAirspaceEditor(); editor.setSphere((SphereAirspace) airspace); setEditorAttributes(editor); return editor; } - protected void initializeSphere(WorldWindow wwd, SphereAirspace sphere, boolean fitShapeToViewport) - { + protected void initializeSphere(WorldWindow wwd, SphereAirspace sphere, boolean fitShapeToViewport) { // Creates a sphere in the center of the viewport. Attempts to guess at a reasonable size and height. Position position = ShapeUtils.getNewShapePosition(wwd); - double sizeInMeters = fitShapeToViewport ? - ShapeUtils.getViewportScaleFactor(wwd) : DEFAULT_SHAPE_SIZE_METERS; + double sizeInMeters = fitShapeToViewport + ? ShapeUtils.getViewportScaleFactor(wwd) : DEFAULT_SHAPE_SIZE_METERS; sphere.setLocation(new LatLon(position)); sphere.setRadius(sizeInMeters / 2.0); } - public String toString() - { + @Override + public String toString() { return "Sphere"; } } - public static AirspaceAttributes getDefaultAttributes() - { + public static AirspaceAttributes getDefaultAttributes() { AirspaceAttributes attributes = new BasicAirspaceAttributes(); attributes.setInteriorMaterial(new Material(Color.BLACK, Color.LIGHT_GRAY, Color.DARK_GRAY, Color.BLACK, 0.0f)); attributes.setOutlineMaterial(Material.DARK_GRAY); @@ -439,8 +397,7 @@ public static AirspaceAttributes getDefaultAttributes() return attributes; } - public static AirspaceAttributes getSelectionAttributes() - { + public static AirspaceAttributes getSelectionAttributes() { AirspaceAttributes attributes = new BasicAirspaceAttributes(); attributes.setInteriorMaterial(Material.WHITE); attributes.setOutlineMaterial(Material.BLACK); @@ -451,47 +408,39 @@ public static AirspaceAttributes getSelectionAttributes() return attributes; } - public static AirspaceAttributes getIntersectionAttributes() - { + public static AirspaceAttributes getIntersectionAttributes() { AirspaceAttributes attributes = new BasicAirspaceAttributes(); attributes.setInteriorMaterial(Material.RED); attributes.setInteriorOpacity(0.95); return attributes; } - public static AirspaceAttributes getSelectionAndIntersectionAttributes() - { + public static AirspaceAttributes getSelectionAndIntersectionAttributes() { AirspaceAttributes attributes = new BasicAirspaceAttributes(); attributes.setInteriorMaterial(Material.ORANGE); attributes.setInteriorOpacity(0.8); return attributes; } - public static void setEditorAttributes(AirspaceEditor editor) - { + public static void setEditorAttributes(AirspaceEditor editor) { editor.setUseRubberBand(true); editor.setKeepControlPointsAboveTerrain(true); } - public static String getNextName(String base) - { + public static String getNextName(String base) { StringBuilder sb = new StringBuilder(); sb.append(base); sb.append(nextEntryNumber++); return sb.toString(); } - protected static AirspaceEditor getEditorFor(Airspace airspace) - { - if (airspace instanceof Polygon) - { + protected static AirspaceEditor getEditorFor(Airspace airspace) { + if (airspace instanceof Polygon) { PolygonEditor editor = new PolygonEditor(); editor.setPolygon((Polygon) airspace); setEditorAttributes(editor); return editor; - } - else if (airspace instanceof SphereAirspace) - { + } else if (airspace instanceof SphereAirspace) { SphereAirspaceEditor editor = new SphereAirspaceEditor(); editor.setSphere((SphereAirspace) airspace); setEditorAttributes(editor); @@ -506,55 +455,44 @@ else if (airspace instanceof SphereAirspace) //**************************************************************// //******************** Airspace Builder Panel ****************// //**************************************************************// - @SuppressWarnings("unchecked") - protected static class AirspaceBuilderPanel extends JPanel - { + protected static class AirspaceBuilderPanel extends JPanel { + protected JComboBox factoryComboBox; protected JTable entryTable; protected boolean ignoreSelectEvents = false; - public AirspaceBuilderPanel(AirspaceBuilderModel model, AirspaceBuilderController controller) - { + public AirspaceBuilderPanel(AirspaceBuilderModel model, AirspaceBuilderController controller) { this.initComponents(model, controller); } - public int[] getSelectedIndices() - { + public int[] getSelectedIndices() { return this.entryTable.getSelectedRows(); } - public void setSelectedIndices(int[] indices) - { + public void setSelectedIndices(int[] indices) { this.ignoreSelectEvents = true; - if (indices != null && indices.length != 0) - { - for (int index : indices) - { + if (indices != null && indices.length != 0) { + for (int index : indices) { this.entryTable.setRowSelectionInterval(index, index); } - } - else - { + } else { this.entryTable.clearSelection(); } this.ignoreSelectEvents = false; } - public AirspaceFactory getSelectedFactory() - { + public AirspaceFactory getSelectedFactory() { return (AirspaceFactory) this.factoryComboBox.getSelectedItem(); } - public void setSelectedFactory(AirspaceFactory factory) - { + public void setSelectedFactory(AirspaceFactory factory) { this.factoryComboBox.setSelectedItem(factory); } - protected void initComponents(AirspaceBuilderModel model, final AirspaceBuilderController controller) - { + protected void initComponents(AirspaceBuilderModel model, final AirspaceBuilderController controller) { final JCheckBox resizeNewShapesCheckBox; final JCheckBox enableEditCheckBox; @@ -604,14 +542,9 @@ protected void initComponents(AirspaceBuilderModel model, final AirspaceBuilderC this.entryTable.setColumnSelectionAllowed(false); this.entryTable.setRowSelectionAllowed(true); this.entryTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - this.entryTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() - { - public void valueChanged(ListSelectionEvent e) - { - if (!ignoreSelectEvents) - { - controller.actionPerformed(new ActionEvent(e.getSource(), -1, SELECTION_CHANGED)); - } + this.entryTable.getSelectionModel().addListSelectionListener((ListSelectionEvent e) -> { + if (!ignoreSelectEvents) { + controller.actionPerformed(new ActionEvent(e.getSource(), -1, SELECTION_CHANGED)); } }); this.entryTable.setToolTipText("Click to select
Double-Click to rename"); @@ -649,18 +582,11 @@ public void valueChanged(ListSelectionEvent e) this.add(entryPanel, BorderLayout.CENTER); this.add(selectionPanel, BorderLayout.EAST); - controller.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent e) - { - if (SIZE_NEW_SHAPES_TO_VIEWPORT.equals(e.getPropertyName())) - { - resizeNewShapesCheckBox.setSelected(controller.isResizeNewShapesToViewport()); - } - else if (ENABLE_EDIT.equals(e.getPropertyName())) - { - enableEditCheckBox.setSelected(controller.isEnableEdit()); - } + controller.addPropertyChangeListener((PropertyChangeEvent e) -> { + if (SIZE_NEW_SHAPES_TO_VIEWPORT.equals(e.getPropertyName())) { + resizeNewShapesCheckBox.setSelected(controller.isResizeNewShapesToViewport()); + } else if (ENABLE_EDIT.equals(e.getPropertyName())) { + enableEditCheckBox.setSelected(controller.isEnableEdit()); } }); } @@ -669,10 +595,9 @@ else if (ENABLE_EDIT.equals(e.getPropertyName())) //**************************************************************// //******************** Airspace Builder Controller ***********// //**************************************************************// - protected static class AirspaceBuilderController extends WWObjectImpl implements ActionListener, MouseListener, - AirspaceEditListener - { + AirspaceEditListener { + protected AppFrame app; protected AirspaceBuilderModel model; protected AirspaceBuilderPanel view; @@ -684,8 +609,7 @@ protected static class AirspaceBuilderController extends WWObjectImpl implements // UI components. protected JFileChooser fileChooser; - public AirspaceBuilderController(AppFrame app) - { + public AirspaceBuilderController(AppFrame app) { this.app = app; this.editorController = new AirspaceEditorController(); @@ -694,245 +618,217 @@ public AirspaceBuilderController(AppFrame app) this.app.getWwd().getInputHandler().addMouseListener(this); } - public AppFrame getApp() - { + public AppFrame getApp() { return this.app; } - public AirspaceBuilderModel getModel() - { + public AirspaceBuilderModel getModel() { return this.model; } - public void setModel(AirspaceBuilderModel model) - { + public void setModel(AirspaceBuilderModel model) { this.model = model; } - public AirspaceBuilderPanel getView() - { + public AirspaceBuilderPanel getView() { return this.view; } - public void setView(AirspaceBuilderPanel view) - { + public void setView(AirspaceBuilderPanel view) { this.view = view; } - public boolean isEnabled() - { + public boolean isEnabled() { return this.enabled; } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { this.enabled = enabled; getView().setEnabled(enabled); getApp().setEnabled(enabled); } - public boolean isEnableEdit() - { + public boolean isEnableEdit() { return this.enableEdit; } - public void setEnableEdit(boolean enable) - { + public void setEnableEdit(boolean enable) { this.enableEdit = enable; this.handleEnableEdit(enable); this.firePropertyChange(ENABLE_EDIT, null, enable); } - public boolean isResizeNewShapesToViewport() - { + public boolean isResizeNewShapesToViewport() { return this.resizeNewShapes; } - public void setResizeNewShapesToViewport(boolean resize) - { + public void setResizeNewShapesToViewport(boolean resize) { this.resizeNewShapes = resize; this.firePropertyChange(SIZE_NEW_SHAPES_TO_VIEWPORT, null, resize); } - public void actionPerformed(ActionEvent e) - { - if (!this.isEnabled()) - { + @Override + public void actionPerformed(ActionEvent e) { + if (!this.isEnabled()) { return; } - if (NEW_AIRSPACE.equals(e.getActionCommand())) - { - this.createNewEntry(this.getView().getSelectedFactory()); - } - else if (CLEAR_SELECTION.equals(e.getActionCommand())) - { - this.selectEntry(null, true); - } - else if (SIZE_NEW_SHAPES_TO_VIEWPORT.equals(e.getActionCommand())) - { - if (e.getSource() instanceof AbstractButton) - { - boolean selected = ((AbstractButton) e.getSource()).isSelected(); - this.setResizeNewShapesToViewport(selected); - } - } - else if (ENABLE_EDIT.equals(e.getActionCommand())) - { - if (e.getSource() instanceof AbstractButton) - { - boolean selected = ((AbstractButton) e.getSource()).isSelected(); - this.setEnableEdit(selected); + if (null != e.getActionCommand()) { + switch (e.getActionCommand()) { + case NEW_AIRSPACE: + this.createNewEntry(this.getView().getSelectedFactory()); + break; + case CLEAR_SELECTION: + this.selectEntry(null, true); + break; + case SIZE_NEW_SHAPES_TO_VIEWPORT: + if (e.getSource() instanceof AbstractButton) { + boolean selected = ((AbstractButton) e.getSource()).isSelected(); + this.setResizeNewShapesToViewport(selected); + } + break; + case ENABLE_EDIT: + if (e.getSource() instanceof AbstractButton) { + boolean selected = ((AbstractButton) e.getSource()).isSelected(); + this.setEnableEdit(selected); + } + break; + case OPEN: + this.openFromFile(); + break; + case OPEN_URL: + this.openFromURL(); + break; + case OPEN_DEMO_AIRSPACES: + this.openFromPath(DEMO_AIRSPACES_PATH); + this.zoomTo(LatLon.fromDegrees(47.6584074779224, -122.3059199579634), + Angle.fromDegrees(-152), Angle.fromDegrees(75), 750); + break; + case REMOVE_SELECTED: + this.removeEntries(Arrays.asList(this.getSelectedEntries())); + break; + case SAVE: + this.saveToFile(); + break; + case SELECTION_CHANGED: + this.viewSelectionChanged(); + break; + default: + break; } } - else if (OPEN.equals(e.getActionCommand())) - { - this.openFromFile(); - } - else if (OPEN_URL.equals(e.getActionCommand())) - { - this.openFromURL(); - } - else if (OPEN_DEMO_AIRSPACES.equals(e.getActionCommand())) - { - this.openFromPath(DEMO_AIRSPACES_PATH); - this.zoomTo(LatLon.fromDegrees(47.6584074779224, -122.3059199579634), - Angle.fromDegrees(-152), Angle.fromDegrees(75), 750); - } - else if (REMOVE_SELECTED.equals(e.getActionCommand())) - { - this.removeEntries(Arrays.asList(this.getSelectedEntries())); - } - else if (SAVE.equals(e.getActionCommand())) - { - this.saveToFile(); - } - else if (SELECTION_CHANGED.equals(e.getActionCommand())) - { - this.viewSelectionChanged(); - } } - public void mouseClicked(MouseEvent e) - { + @Override + public void mouseClicked(MouseEvent e) { } - public void mousePressed(MouseEvent e) - { - if (e == null || e.isConsumed()) - { + @Override + public void mousePressed(MouseEvent e) { + if (e == null || e.isConsumed()) { return; } - if (!this.isEnabled()) - { + if (!this.isEnabled()) { return; } - if (e.getButton() == MouseEvent.BUTTON1) - { + if (e.getButton() == MouseEvent.BUTTON1) { this.handleSelect(); } } - public void mouseReleased(MouseEvent e) - { + @Override + public void mouseReleased(MouseEvent e) { } - public void mouseEntered(MouseEvent e) - { + @Override + public void mouseEntered(MouseEvent e) { } - public void mouseExited(MouseEvent e) - { + @Override + public void mouseExited(MouseEvent e) { } - public void airspaceMoved(AirspaceEditEvent e) - { + @Override + public void airspaceMoved(AirspaceEditEvent e) { this.updateShapeIntersection(); } - public void airspaceResized(AirspaceEditEvent e) - { + @Override + public void airspaceResized(AirspaceEditEvent e) { this.updateShapeIntersection(); } - public void controlPointAdded(AirspaceEditEvent e) - { + @Override + public void controlPointAdded(AirspaceEditEvent e) { } - public void controlPointRemoved(AirspaceEditEvent e) - { + @Override + public void controlPointRemoved(AirspaceEditEvent e) { } - public void controlPointChanged(AirspaceEditEvent e) - { + @Override + public void controlPointChanged(AirspaceEditEvent e) { } - protected void handleSelect() - { + protected void handleSelect() { // If the picked object is null or something other than an airspace, then ignore the mouse click. If we // deselect the current entry at this point, the user cannot easily navigate without loosing the selection. PickedObjectList pickedObjects = this.getApp().getWwd().getObjectsAtCurrentPosition(); Object topObject = pickedObjects.getTopObject(); - if (!(topObject instanceof Airspace)) + if (!(topObject instanceof Airspace)) { return; + } AirspaceEntry pickedEntry = this.getEntryFor((Airspace) topObject); - if (pickedEntry == null) + if (pickedEntry == null) { return; + } - if (this.getSelectedEntry() != pickedEntry) - { + if (this.getSelectedEntry() != pickedEntry) { this.selectEntry(pickedEntry, true); } } - protected void handleEnableEdit(boolean enable) - { - if (this.getSelectedEntry() == null) + protected void handleEnableEdit(boolean enable) { + if (this.getSelectedEntry() == null) { return; + } - if (this.isSelectionEditing() != enable) + if (this.isSelectionEditing() != enable) { this.setSelectionEditing(enable); + } } - protected void updateShapeIntersection() - { + protected void updateShapeIntersection() { AirspaceEntry selected = this.getSelectedEntry(); - if (selected != null) - { + if (selected != null) { boolean hasIntersection = false; - for (AirspaceEntry entry : this.getModel().getEntries()) - { - if (entry != selected) - { + for (AirspaceEntry entry : this.getModel().getEntries()) { + if (entry != selected) { boolean intersecting = this.areShapesIntersecting(entry.getAirspace(), selected.getAirspace()); - if (intersecting) + if (intersecting) { hasIntersection = true; + } entry.setIntersecting(intersecting); } } selected.setIntersecting(hasIntersection); - } - else - { - for (AirspaceEntry entry : this.getModel().getEntries()) - { + } else { + for (AirspaceEntry entry : this.getModel().getEntries()) { entry.setIntersecting(false); } } } - protected boolean areShapesIntersecting(Airspace a1, Airspace a2) - { - if ((a1 instanceof SphereAirspace) && (a2 instanceof SphereAirspace)) - { + protected boolean areShapesIntersecting(Airspace a1, Airspace a2) { + if ((a1 instanceof SphereAirspace) && (a2 instanceof SphereAirspace)) { SphereAirspace s1 = (SphereAirspace) a1; SphereAirspace s2 = (SphereAirspace) a2; @@ -945,9 +841,9 @@ protected boolean areShapesIntersecting(Airspace a1, Airspace a2) // We have to compute the 3D coordinates of the sphere's center ourselves here. Vec4 p1 = terrainConforming1 ? this.getSurfacePoint(location1, altitude1) - : this.getPoint(location1, altitude1); + : this.getPoint(location1, altitude1); Vec4 p2 = terrainConforming2 ? this.getSurfacePoint(location2, altitude2) - : this.getPoint(location2, altitude2); + : this.getPoint(location2, altitude2); double r1 = s1.getRadius(); double r2 = s2.getRadius(); @@ -959,40 +855,35 @@ protected boolean areShapesIntersecting(Airspace a1, Airspace a2) return false; } - protected Vec4 getSurfacePoint(LatLon latlon, double elevation) - { + protected Vec4 getSurfacePoint(LatLon latlon, double elevation) { Vec4 point = null; SceneController sc = this.getApp().getWwd().getSceneController(); Globe globe = this.getApp().getWwd().getModel().getGlobe(); - if (sc.getTerrain() != null) - { + if (sc.getTerrain() != null) { point = sc.getTerrain().getSurfacePoint( - latlon.getLatitude(), latlon.getLongitude(), elevation * sc.getVerticalExaggeration()); + latlon.getLatitude(), latlon.getLongitude(), elevation * sc.getVerticalExaggeration()); } - if (point == null) - { + if (point == null) { double e = globe.getElevation(latlon.getLatitude(), latlon.getLongitude()); point = globe.computePointFromPosition( - latlon.getLatitude(), latlon.getLongitude(), (e + elevation) * sc.getVerticalExaggeration()); + latlon.getLatitude(), latlon.getLongitude(), (e + elevation) * sc.getVerticalExaggeration()); } return point; } - protected Vec4 getPoint(LatLon latlon, double elevation) - { + protected Vec4 getPoint(LatLon latlon, double elevation) { SceneController sc = this.getApp().getWwd().getSceneController(); Globe globe = this.getApp().getWwd().getModel().getGlobe(); double e = globe.getElevation(latlon.getLatitude(), latlon.getLongitude()); return globe.computePointFromPosition( - latlon.getLatitude(), latlon.getLongitude(), (e + elevation) * sc.getVerticalExaggeration()); + latlon.getLatitude(), latlon.getLongitude(), (e + elevation) * sc.getVerticalExaggeration()); } - public void createNewEntry(AirspaceFactory factory) - { + public void createNewEntry(AirspaceFactory factory) { Airspace airspace = factory.createAirspace(this.getApp().getWwd(), this.isResizeNewShapesToViewport()); AirspaceEditor editor = factory.createEditor(airspace); AirspaceEntry entry = new AirspaceEntry(airspace, editor); @@ -1002,19 +893,15 @@ public void createNewEntry(AirspaceFactory factory) this.selectEntry(entry, true); } - public void removeEntries(Iterable entries) - { - if (entries != null) - { - for (AirspaceEntry entry : entries) - { + public void removeEntries(Iterable entries) { + if (entries != null) { + for (AirspaceEntry entry : entries) { this.removeEntry(entry); } } } - public void addEntry(AirspaceEntry entry) - { + public void addEntry(AirspaceEntry entry) { entry.getEditor().addEditListener(this); this.getModel().addEntry(entry); this.updateShapeIntersection(); @@ -1023,12 +910,10 @@ public void addEntry(AirspaceEntry entry) this.getApp().getWwd().redraw(); } - public void removeEntry(AirspaceEntry entry) - { + public void removeEntry(AirspaceEntry entry) { entry.getEditor().removeEditListener(this); - if (this.getSelectedEntry() == entry) - { + if (this.getSelectedEntry() == entry) { this.selectEntry(null, true); } @@ -1039,32 +924,24 @@ public void removeEntry(AirspaceEntry entry) this.getApp().getWwd().redraw(); } - public AirspaceEntry getSelectedEntry() - { + public AirspaceEntry getSelectedEntry() { return this.selectedEntry; } - public void selectEntry(AirspaceEntry entry, boolean updateView) - { + public void selectEntry(AirspaceEntry entry, boolean updateView) { this.setSelectedEntry(entry); - if (updateView) - { - if (entry != null) - { + if (updateView) { + if (entry != null) { int index = this.getModel().getIndexForEntry(entry); - this.getView().setSelectedIndices(new int[] {index}); - } - else - { + this.getView().setSelectedIndices(new int[]{index}); + } else { this.getView().setSelectedIndices(new int[0]); } } - if (this.isEnableEdit()) - { - if (this.getSelectedEntry() != null && !this.isSelectionEditing()) - { + if (this.isEnableEdit()) { + if (this.getSelectedEntry() != null && !this.isSelectionEditing()) { this.setSelectionEditing(true); } } @@ -1073,12 +950,9 @@ public void selectEntry(AirspaceEntry entry, boolean updateView) this.getApp().getWwd().redraw(); } - protected void setSelectedEntry(AirspaceEntry entry) - { - if (this.selectedEntry != null) - { - if (this.selectedEntry != entry && this.selectedEntry.isEditing()) - { + protected void setSelectedEntry(AirspaceEntry entry) { + if (this.selectedEntry != null) { + if (this.selectedEntry != entry && this.selectedEntry.isEditing()) { this.setSelectionEditing(false); } @@ -1087,26 +961,21 @@ protected void setSelectedEntry(AirspaceEntry entry) this.selectedEntry = entry; - if (this.selectedEntry != null) - { + if (this.selectedEntry != null) { this.selectedEntry.setSelected(true); } } - protected boolean isSelectionEditing() - { + protected boolean isSelectionEditing() { return this.selectedEntry != null && this.selectedEntry.isEditing(); } - protected void setSelectionEditing(boolean editing) - { - if (this.selectedEntry == null) - { + protected void setSelectionEditing(boolean editing) { + if (this.selectedEntry == null) { throw new IllegalStateException(); } - if (this.selectedEntry.isEditing() == editing) - { + if (this.selectedEntry.isEditing() == editing) { throw new IllegalStateException(); } @@ -1115,13 +984,10 @@ protected void setSelectionEditing(boolean editing) AirspaceEditor editor = this.selectedEntry.getEditor(); editor.setArmed(editing); - if (editing) - { + if (editing) { this.editorController.setEditor(editor); insertBeforePlacenames(this.getApp().getWwd(), editor); - } - else - { + } else { this.editorController.setEditor(null); this.getApp().getWwd().getModel().getLayers().remove(editor); } @@ -1130,13 +996,10 @@ protected void setSelectionEditing(boolean editing) this.getModel().fireTableRowsUpdated(index, index); } - protected void viewSelectionChanged() - { + protected void viewSelectionChanged() { int[] indices = this.getView().getSelectedIndices(); - if (indices != null) - { - for (AirspaceEntry entry : this.getEntriesFor(indices)) - { + if (indices != null) { + for (AirspaceEntry entry : this.getEntriesFor(indices)) { this.selectEntry(entry, false); } } @@ -1144,94 +1007,70 @@ protected void viewSelectionChanged() this.getApp().getWwd().redraw(); } - protected AirspaceEntry[] getSelectedEntries() - { + protected AirspaceEntry[] getSelectedEntries() { int[] indices = this.getView().getSelectedIndices(); - if (indices != null) - { + if (indices != null) { return this.getEntriesFor(indices); } return new AirspaceEntry[0]; } - protected AirspaceEntry[] getEntriesFor(int[] indices) - { + protected AirspaceEntry[] getEntriesFor(int[] indices) { AirspaceEntry[] entries = new AirspaceEntry[indices.length]; - for (int i = 0; i < indices.length; i++) - { + for (int i = 0; i < indices.length; i++) { entries[i] = this.getModel().getEntry(indices[i]); } return entries; } - protected AirspaceEntry getEntryFor(Airspace airspace) - { - for (AirspaceEntry entry : this.getModel().getEntries()) - { - if (entry.getAirspace() == airspace) - { + protected AirspaceEntry getEntryFor(Airspace airspace) { + for (AirspaceEntry entry : this.getModel().getEntries()) { + if (entry.getAirspace() == airspace) { return entry; } } return null; } - protected void zoomTo(LatLon latLon, Angle heading, Angle pitch, double zoom) - { + protected void zoomTo(LatLon latLon, Angle heading, Angle pitch, double zoom) { BasicOrbitView view = (BasicOrbitView) this.getApp().getWwd().getView(); view.stopMovement(); view.addPanToAnimator( - new Position(latLon, 0), heading, pitch, zoom, true); + new Position(latLon, 0), heading, pitch, zoom, true); } - protected void openFromURL() - { + protected void openFromURL() { Object input = JOptionPane.showInputDialog(this.getApp(), "Enter a URL: ", "Open Shapes from URL", - JOptionPane.QUESTION_MESSAGE, null, null, null); - if (input == null) + JOptionPane.QUESTION_MESSAGE, null, null, null); + if (input == null) { return; + } URL url = null; - try - { + try { url = new URL(input.toString()); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } - if (url != null) - { + if (url != null) { this.openFromPath(url.toExternalForm()); } } - protected void openFromPath(final String path) - { - Thread t = new Thread(new Runnable() - { - public void run() - { - final ArrayList airspaces = new ArrayList(); - try - { - loadAirspacesFromPath(path, airspaces); - } - finally - { - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - setAirspaces(airspaces); - setEnabled(true); - getApp().setCursor(null); - getApp().getWwd().redraw(); - } - }); - } + protected void openFromPath(final String path) { + Thread t = new Thread(() -> { + final ArrayList airspaces = new ArrayList<>(); + try { + loadAirspacesFromPath(path, airspaces); + } finally { + SwingUtilities.invokeLater(() -> { + setAirspaces(airspaces); + setEnabled(true); + getApp().setCursor(null); + getApp().getWwd().redraw(); + }); } }); @@ -1240,32 +1079,31 @@ public void run() t.start(); } - protected void loadAirspacesFromPath(String path, Collection airspaces) - { + protected void loadAirspacesFromPath(String path, Collection airspaces) { File file = ExampleUtil.saveResourceToTempFile(path, ".zip"); - if (file == null) + if (file == null) { return; + } - try - { + try { ZipFile zipFile = new ZipFile(file); ZipEntry entry = null; for (Enumeration e = zipFile.entries(); e.hasMoreElements(); - entry = e.nextElement()) - { - if (entry == null) + entry = e.nextElement()) { + if (entry == null) { continue; + } String name = WWIO.getFilename(entry.getName()); - if (!(name.startsWith("gov.nasa.worldwind.render.airspaces") && name.endsWith(".xml"))) + if (!(name.startsWith("gov.nasa.worldwind.render.airspaces") && name.endsWith(".xml"))) { continue; + } String[] tokens = name.split("-"); - try - { + try { Class c = Class.forName(tokens[0]); Airspace airspace = (Airspace) c.getConstructor().newInstance(); BufferedReader input = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry))); @@ -1273,27 +1111,20 @@ protected void loadAirspacesFromPath(String path, Collection airspaces airspace.restoreState(s); airspaces.add(airspace); - if (tokens.length >= 2) - { + if (tokens.length >= 2) { airspace.setValue(AVKey.DISPLAY_NAME, tokens[1]); } - } - catch (Exception ex) - { + } catch (Exception ex) { ex.printStackTrace(); } } - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } } - protected void openFromFile() - { - if (this.fileChooser == null) - { + protected void openFromFile() { + if (this.fileChooser == null) { this.fileChooser = new JFileChooser(); this.fileChooser.setCurrentDirectory(new File(Configuration.getUserHomeDirectory())); } @@ -1302,64 +1133,44 @@ protected void openFromFile() this.fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); this.fileChooser.setMultiSelectionEnabled(false); int status = this.fileChooser.showOpenDialog(null); - if (status != JFileChooser.APPROVE_OPTION) + if (status != JFileChooser.APPROVE_OPTION) { return; + } final File dir = this.fileChooser.getSelectedFile(); - if (dir == null) + if (dir == null) { return; + } - Thread t = new Thread(new Runnable() - { - public void run() - { - final ArrayList airspaces = new ArrayList(); - try - { - File[] files = dir.listFiles(new FilenameFilter() - { - public boolean accept(File dir, String name) - { - return name.startsWith("gov.nasa.worldwind.render.airspaces") && name.endsWith(".xml"); - } - }); - - for (File file : files) - { - String[] name = file.getName().split("-"); - try - { - Class c = Class.forName(name[0]); - Airspace airspace = (Airspace) c.getConstructor().newInstance(); - BufferedReader input = new BufferedReader(new FileReader(file)); - String s = input.readLine(); - airspace.restoreState(s); - airspaces.add(airspace); - - if (name.length >= 2) - { - airspace.setValue(AVKey.DISPLAY_NAME, name[1]); - } - } - catch (Exception e) - { - e.printStackTrace(); + Thread t = new Thread(() -> { + final ArrayList airspaces = new ArrayList<>(); + try { + File[] files = dir.listFiles((File dir1, String name) -> name.startsWith("gov.nasa.worldwind.render.airspaces") && name.endsWith(".xml")); + + for (File file : files) { + String[] name = file.getName().split("-"); + try { + Class c = Class.forName(name[0]); + Airspace airspace = (Airspace) c.getConstructor().newInstance(); + BufferedReader input = new BufferedReader(new FileReader(file)); + String s = input.readLine(); + airspace.restoreState(s); + airspaces.add(airspace); + + if (name.length >= 2) { + airspace.setValue(AVKey.DISPLAY_NAME, name[1]); } + } catch (Exception e) { + e.printStackTrace(); } } - finally - { - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - setAirspaces(airspaces); - setEnabled(true); - getApp().setCursor(null); - getApp().getWwd().redraw(); - } - }); - } + } finally { + SwingUtilities.invokeLater(() -> { + setAirspaces(airspaces); + setEnabled(true); + getApp().setCursor(null); + getApp().getWwd().redraw(); + }); } }); this.setEnabled(false); @@ -1367,10 +1178,8 @@ public void run() t.start(); } - protected void saveToFile() - { - if (this.fileChooser == null) - { + protected void saveToFile() { + if (this.fileChooser == null) { this.fileChooser = new JFileChooser(); this.fileChooser.setCurrentDirectory(new File(Configuration.getUserHomeDirectory())); } @@ -1379,70 +1188,55 @@ protected void saveToFile() this.fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); this.fileChooser.setMultiSelectionEnabled(false); int status = this.fileChooser.showSaveDialog(null); - if (status != JFileChooser.APPROVE_OPTION) + if (status != JFileChooser.APPROVE_OPTION) { return; + } final File dir = this.fileChooser.getSelectedFile(); - if (dir == null) + if (dir == null) { return; + } - if (!dir.exists()) - { + if (!dir.exists()) { //noinspection ResultOfMethodCallIgnored dir.mkdirs(); } final Iterable entries = this.getModel().getEntries(); - Thread t = new Thread(new Runnable() - { - public void run() - { - try - { - java.text.DecimalFormat f = new java.text.DecimalFormat("####"); - f.setMinimumIntegerDigits(4); - int counter = 0; - - for (AirspaceEntry entry : entries) - { - Airspace a = entry.getAirspace(); - AirspaceAttributes currentAttribs = a.getAttributes(); - a.setAttributes(entry.getAttributes()); - - String xmlString = a.getRestorableState(); - if (xmlString != null) - { - try - { - PrintWriter of = new PrintWriter(new File(dir, + Thread t = new Thread(() -> { + try { + java.text.DecimalFormat f = new java.text.DecimalFormat("####"); + f.setMinimumIntegerDigits(4); + int counter = 0; + + for (AirspaceEntry entry : entries) { + Airspace a = entry.getAirspace(); + AirspaceAttributes currentAttribs = a.getAttributes(); + a.setAttributes(entry.getAttributes()); + + String xmlString = a.getRestorableState(); + if (xmlString != null) { + try { + try (PrintWriter of = new PrintWriter(new File(dir, a.getClass().getName() + "-" + entry.getName() + "-" + f.format(counter++) - + ".xml")); + + ".xml"))) { of.write(xmlString); of.flush(); - of.close(); - } - catch (Exception e) - { - e.printStackTrace(); } + } catch (Exception e) { + e.printStackTrace(); } - - a.setAttributes(currentAttribs); } + + a.setAttributes(currentAttribs); } - finally - { - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - setEnabled(true); - getApp().setCursor(null); - getApp().getWwd().redraw(); - } - }); - } + } finally { + SwingUtilities.invokeLater(() -> { + setEnabled(true); + getApp().setCursor(null); + getApp().getWwd().redraw(); + }); } }); this.setEnabled(false); @@ -1450,13 +1244,11 @@ public void run() t.start(); } - protected void setAirspaces(Iterable airspaces) - { - ArrayList entryList = new ArrayList(this.getModel().getEntries()); + protected void setAirspaces(Iterable airspaces) { + ArrayList entryList = new ArrayList<>(this.getModel().getEntries()); this.removeEntries(entryList); - for (Airspace airspace : airspaces) - { + for (Airspace airspace : airspaces) { airspace.setAttributes(getDefaultAttributes()); AirspaceEntry entry = new AirspaceEntry(airspace, getEditorFor(airspace)); this.addEntry(entry); @@ -1467,17 +1259,15 @@ protected void setAirspaces(Iterable airspaces) //**************************************************************// //******************** Main **********************************// //**************************************************************// + protected static class AppFrame extends ApplicationTemplate.AppFrame { - protected static class AppFrame extends ApplicationTemplate.AppFrame - { // Airspace layer and editor UI components. protected RenderableLayer airspaceLayer; protected AirspaceBuilderModel builderModel; protected AirspaceBuilderPanel builderView; protected AirspaceBuilderController builderController; - public AppFrame() - { + public AppFrame() { this.airspaceLayer = new RenderableLayer(); this.airspaceLayer.setName(AIRSPACE_LAYER_NAME); insertBeforePlacenames(this.getWwd(), this.airspaceLayer); @@ -1494,18 +1284,15 @@ public AppFrame() makeMenuBar(this, this.builderController); } - public AirspaceBuilderPanel getAirspaceBuilderPanel() - { + public AirspaceBuilderPanel getAirspaceBuilderPanel() { return this.builderView; } - public RenderableLayer getAirspaceLayer() - { + public RenderableLayer getAirspaceLayer() { return this.airspaceLayer; } - public static void makeMenuBar(JFrame frame, final AirspaceBuilderController controller) - { + public static void makeMenuBar(JFrame frame, final AirspaceBuilderController controller) { JMenuBar menuBar = new JMenuBar(); final JCheckBoxMenuItem resizeNewShapesItem; final JCheckBoxMenuItem enableEditItem; @@ -1514,7 +1301,7 @@ public static void makeMenuBar(JFrame frame, final AirspaceBuilderController con { JMenuItem item = new JMenuItem("Open..."); item.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); + KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.setActionCommand(OPEN); item.addActionListener(controller); menu.add(item); @@ -1526,7 +1313,7 @@ public static void makeMenuBar(JFrame frame, final AirspaceBuilderController con item = new JMenuItem("Save..."); item.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); + KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.setActionCommand(SAVE); item.addActionListener(controller); menu.add(item); @@ -1543,15 +1330,10 @@ public static void makeMenuBar(JFrame frame, final AirspaceBuilderController con menu = new JMenu("Shape"); { JMenu subMenu = new JMenu("New"); - for (final AirspaceFactory factory : defaultAirspaceFactories) - { + for (final AirspaceFactory factory : defaultAirspaceFactories) { JMenuItem item = new JMenuItem(factory.toString()); - item.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { - controller.createNewEntry(factory); - } + item.addActionListener((ActionEvent e) -> { + controller.createNewEntry(factory); }); subMenu.add(item); } @@ -1575,7 +1357,7 @@ public void actionPerformed(ActionEvent e) { JMenuItem item = new JMenuItem("Deselect"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); + Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); item.setActionCommand(CLEAR_SELECTION); item.addActionListener(controller); menu.add(item); @@ -1590,25 +1372,17 @@ public void actionPerformed(ActionEvent e) frame.setJMenuBar(menuBar); - controller.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent e) - { - if (SIZE_NEW_SHAPES_TO_VIEWPORT.equals((e.getPropertyName()))) - { - resizeNewShapesItem.setSelected(controller.isResizeNewShapesToViewport()); - } - else if (ENABLE_EDIT.equals(e.getPropertyName())) - { - enableEditItem.setSelected(controller.isEnableEdit()); - } + controller.addPropertyChangeListener((PropertyChangeEvent e) -> { + if (SIZE_NEW_SHAPES_TO_VIEWPORT.equals((e.getPropertyName()))) { + resizeNewShapesItem.setSelected(controller.isResizeNewShapesToViewport()); + } else if (ENABLE_EDIT.equals(e.getPropertyName())) { + enableEditItem.setSelected(controller.isEnableEdit()); } }); } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind Airspace Builder", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/Balloons.java b/src/gov/nasa/worldwindx/examples/Balloons.java index 11bf8ceac9..83fb990a3e 100644 --- a/src/gov/nasa/worldwindx/examples/Balloons.java +++ b/src/gov/nasa/worldwindx/examples/Balloons.java @@ -44,19 +44,18 @@ * @author pabercrombie * @version $Id: Balloons.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class Balloons extends ApplicationTemplate -{ +public class Balloons extends ApplicationTemplate { + protected static final String BROWSER_BALLOON_CONTENT_PATH - = "gov/nasa/worldwindx/examples/data/BrowserBalloonExample.html"; + = "gov/nasa/worldwindx/examples/data/BrowserBalloonExample.html"; + + public static class AppFrame extends ApplicationTemplate.AppFrame { - public static class AppFrame extends ApplicationTemplate.AppFrame - { protected HotSpotController hotSpotController; protected BalloonController balloonController; protected RenderableLayer layer; - public AppFrame() - { + public AppFrame() { super(true, true, false); // Add a controller to send input events to BrowserBalloons. @@ -81,10 +80,9 @@ public AppFrame() WWUtil.alignComponent(null, this, AVKey.CENTER); } - protected void makeAnnotationBalloon() - { + protected void makeAnnotationBalloon() { Balloon balloon = new ScreenAnnotationBalloon("AnnotationBalloon attached to the screen", - new Point(50, 300)); + new Point(50, 300)); BalloonAttributes attrs = new BasicBalloonAttributes(); // Size the balloon to fit its text, place its lower-left corner at the point, put event padding between the @@ -103,28 +101,23 @@ protected void makeAnnotationBalloon() this.layer.addRenderable(balloon); } - protected void makeBrowserBalloon() - { + protected void makeBrowserBalloon() { String htmlString = null; InputStream contentStream = null; - try - { + try { // Read the URL content into a String using the default encoding (UTF-8). contentStream = WWIO.openFileOrResourceStream(BROWSER_BALLOON_CONTENT_PATH, this.getClass()); htmlString = WWIO.readStreamToString(contentStream, null); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); - } - finally - { + } finally { WWIO.closeStream(contentStream, BROWSER_BALLOON_CONTENT_PATH); } - if (htmlString == null) + if (htmlString == null) { htmlString = Logging.getMessage("generic.ExceptionAttemptingToReadFile", BROWSER_BALLOON_CONTENT_PATH); + } Position balloonPosition = Position.fromDegrees(38.883056, -77.016389); @@ -148,8 +141,7 @@ protected void makeBrowserBalloon() } } - public static void main(String[] args) - { + public static void main(String[] args) { // Configure the initial view parameters so that the browser balloon is centered in the viewport. Configuration.setValue(AVKey.INITIAL_LATITUDE, 60); Configuration.setValue(AVKey.INITIAL_LONGITUDE, -85); diff --git a/src/gov/nasa/worldwindx/examples/ContextMenusOnShapes.java b/src/gov/nasa/worldwindx/examples/ContextMenusOnShapes.java index 03ea947495..e525836714 100644 --- a/src/gov/nasa/worldwindx/examples/ContextMenusOnShapes.java +++ b/src/gov/nasa/worldwindx/examples/ContextMenusOnShapes.java @@ -27,66 +27,65 @@ * @author tag * @version $Id: ContextMenusOnShapes.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class ContextMenusOnShapes extends ApplicationTemplate -{ - /** The Controller listens for selection events and either highlights a selected item or shows its context menu. */ - protected static class ContextMenuController implements SelectListener - { +public class ContextMenusOnShapes extends ApplicationTemplate { + + /** + * The Controller listens for selection events and either highlights a selected item or shows its context menu. + */ + protected static class ContextMenuController implements SelectListener { + protected PointPlacemark lastPickedPlacemark = null; - public void selected(SelectEvent event) - { - try - { - if (event.getEventAction().equals(SelectEvent.ROLLOVER)) + @Override + public void selected(SelectEvent event) { + try { + if (event.getEventAction().equals(SelectEvent.ROLLOVER)) { highlight(event, event.getTopObject()); - else if (event.getEventAction().equals(SelectEvent.RIGHT_PRESS)) // Could do RIGHT_CLICK instead + } else if (event.getEventAction().equals(SelectEvent.RIGHT_PRESS)) // Could do RIGHT_CLICK instead + { showContextMenu(event); - } - catch (Exception e) - { + } + } catch (Exception e) { Util.getLogger().warning(e.getMessage() != null ? e.getMessage() : e.toString()); } } - @SuppressWarnings( {"UnusedDeclaration"}) - protected void highlight(SelectEvent event, Object o) - { - if (this.lastPickedPlacemark == o) + @SuppressWarnings({"UnusedDeclaration"}) + protected void highlight(SelectEvent event, Object o) { + if (this.lastPickedPlacemark == o) { return; // same thing selected - + } // Turn off highlight if on. - if (this.lastPickedPlacemark != null) - { + if (this.lastPickedPlacemark != null) { this.lastPickedPlacemark.setHighlighted(false); this.lastPickedPlacemark = null; } // Turn on highlight if object selected. - if (o != null && o instanceof PointPlacemark) - { + if (o != null && o instanceof PointPlacemark) { this.lastPickedPlacemark = (PointPlacemark) o; this.lastPickedPlacemark.setHighlighted(true); } } - protected void showContextMenu(SelectEvent event) - { - if (!(event.getTopObject() instanceof PointPlacemark)) + protected void showContextMenu(SelectEvent event) { + if (!(event.getTopObject() instanceof PointPlacemark)) { return; + } // See if the top picked object has context-menu info defined. Show the menu if it does. - Object o = event.getTopObject(); if (o instanceof AVList) // Uses an AVList in order to be applicable to all shapes. { AVList params = (AVList) o; ContextMenuInfo menuInfo = (ContextMenuInfo) params.getValue(ContextMenu.CONTEXT_MENU_INFO); - if (menuInfo == null) + if (menuInfo == null) { return; + } - if (!(event.getSource() instanceof Component)) + if (!(event.getSource() instanceof Component)) { return; + } ContextMenu menu = new ContextMenu((Component) event.getSource(), menuInfo); menu.show(event.getMouseEvent()); @@ -94,18 +93,19 @@ protected void showContextMenu(SelectEvent event) } } - /** The ContextMenu class implements the context menu. */ - protected static class ContextMenu - { + /** + * The ContextMenu class implements the context menu. + */ + protected static class ContextMenu { + public static final String CONTEXT_MENU_INFO = "ContextMenuInfo"; protected ContextMenuInfo ctxMenuInfo; protected Component sourceComponent; protected JMenuItem menuTitleItem; - protected ArrayList menuItems = new ArrayList(); + protected ArrayList menuItems = new ArrayList<>(); - public ContextMenu(Component sourceComponent, ContextMenuInfo contextMenuInfo) - { + public ContextMenu(Component sourceComponent, ContextMenuInfo contextMenuInfo) { this.sourceComponent = sourceComponent; this.ctxMenuInfo = contextMenuInfo; @@ -113,29 +113,24 @@ public ContextMenu(Component sourceComponent, ContextMenuInfo contextMenuInfo) this.makeMenuItems(); } - protected void makeMenuTitle() - { + protected void makeMenuTitle() { this.menuTitleItem = new JMenuItem(this.ctxMenuInfo.menuTitle); } - protected void makeMenuItems() - { - for (ContextMenuItemInfo itemInfo : this.ctxMenuInfo.menuItems) - { + protected void makeMenuItems() { + for (ContextMenuItemInfo itemInfo : this.ctxMenuInfo.menuItems) { this.menuItems.add(new JMenuItem(new ContextMenuItemAction(itemInfo))); } } - public void show(final MouseEvent event) - { + public void show(final MouseEvent event) { JPopupMenu popup = new JPopupMenu(); popup.add(this.menuTitleItem); popup.addSeparator(); - for (JMenuItem subMenu : this.menuItems) - { + for (JMenuItem subMenu : this.menuItems) { popup.add(subMenu); } @@ -143,54 +138,55 @@ public void show(final MouseEvent event) } } - /** The ContextMenuInfo class specifies the contents of the context menu. */ - protected static class ContextMenuInfo - { + /** + * The ContextMenuInfo class specifies the contents of the context menu. + */ + protected static class ContextMenuInfo { + protected String menuTitle; protected ContextMenuItemInfo[] menuItems; - public ContextMenuInfo(String title, ContextMenuItemInfo[] menuItems) - { + public ContextMenuInfo(String title, ContextMenuItemInfo[] menuItems) { this.menuTitle = title; this.menuItems = menuItems; } } - /** The ContextMenuItemInfo class specifies the contents of one entry in the context menu. */ - protected static class ContextMenuItemInfo - { + /** + * The ContextMenuItemInfo class specifies the contents of one entry in the context menu. + */ + protected static class ContextMenuItemInfo { + protected String displayString; - public ContextMenuItemInfo(String displayString) - { + public ContextMenuItemInfo(String displayString) { this.displayString = displayString; } } - /** The ContextMenuItemAction responds to user selection of a context menu item. */ - public static class ContextMenuItemAction extends AbstractAction - { + /** + * The ContextMenuItemAction responds to user selection of a context menu item. + */ + public static class ContextMenuItemAction extends AbstractAction { + protected ContextMenuItemInfo itemInfo; - public ContextMenuItemAction(ContextMenuItemInfo itemInfo) - { + public ContextMenuItemAction(ContextMenuItemInfo itemInfo) { super(itemInfo.displayString); this.itemInfo = itemInfo; } - public void actionPerformed(ActionEvent event) - { + @Override + public void actionPerformed(ActionEvent event) { System.out.println(this.itemInfo.displayString); // Replace with application's menu-item response. } } // The code below makes and displays some placemarks. The context menu info for each placemark is also specified. + public static class AppFrame extends ApplicationTemplate.AppFrame { - public static class AppFrame extends ApplicationTemplate.AppFrame - { - public AppFrame() - { + public AppFrame() { RenderableLayer layer = new RenderableLayer(); // Create and set an attribute bundle. @@ -205,12 +201,10 @@ public AppFrame() PointPlacemarkAttributes highlightAttrs = new PointPlacemarkAttributes(attrs); highlightAttrs.setScale(0.7); - ContextMenuItemInfo[] itemActionNames = new ContextMenuItemInfo[] - { - new ContextMenuItemInfo("Do This"), - new ContextMenuItemInfo("Do That"), - new ContextMenuItemInfo("Do the Other Thing"), - }; + ContextMenuItemInfo[] itemActionNames = new ContextMenuItemInfo[]{ + new ContextMenuItemInfo("Do This"), + new ContextMenuItemInfo("Do That"), + new ContextMenuItemInfo("Do the Other Thing"),}; PointPlacemark pp = new PointPlacemark(Position.fromDegrees(28, -102, 1e4)); pp.setAttributes(attrs); @@ -254,8 +248,7 @@ public AppFrame() } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind Context Menus on Shapes", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/ContourBuilderExample.java b/src/gov/nasa/worldwindx/examples/ContourBuilderExample.java index e506f3f183..5bdd60eca8 100644 --- a/src/gov/nasa/worldwindx/examples/ContourBuilderExample.java +++ b/src/gov/nasa/worldwindx/examples/ContourBuilderExample.java @@ -95,8 +95,7 @@ protected void addContourShapes(List> contourList, double value, { Path path = new Path(positions); path.setAttributes(attrs); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setValue(AVKey.DISPLAY_NAME, text); layer.addRenderable(path); } diff --git a/src/gov/nasa/worldwindx/examples/ContourLines.java b/src/gov/nasa/worldwindx/examples/ContourLines.java index fc49cbacb2..f7e338c44e 100644 --- a/src/gov/nasa/worldwindx/examples/ContourLines.java +++ b/src/gov/nasa/worldwindx/examples/ContourLines.java @@ -24,14 +24,13 @@ * @author Patrick Murris * @version $Id: ContourLines.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class ContourLines extends ApplicationTemplate -{ - public static class AppFrame extends ApplicationTemplate.AppFrame - { +public class ContourLines extends ApplicationTemplate { + + public static class AppFrame extends ApplicationTemplate.AppFrame { + protected ContourLine contourLine; - public AppFrame() - { + public AppFrame() { // Create a layer to display the contour lines. RenderableLayer layer = new RenderableLayer(); layer.setName("Contour Lines"); @@ -46,25 +45,23 @@ public AppFrame() layer.addRenderable(this.contourLine); // Add a local contour line to the layer. - ArrayList positions = new ArrayList(); + ArrayList positions = new ArrayList<>(); positions.add(LatLon.fromDegrees(44.16, 6.82)); positions.add(LatLon.fromDegrees(44.16, 7.09)); positions.add(LatLon.fromDegrees(44.30, 6.95)); positions.add(LatLon.fromDegrees(44.16, 6.82)); - for (int elevation = 0; elevation <= 3000; elevation += 250) - { + for (int elevation = 0; elevation <= 3000; elevation += 250) { ContourLinePolygon cl = new ContourLinePolygon(elevation, positions); cl.setColor(new Color(0.2f, 0.2f, 0.8f)); - if (elevation % 1000 == 0) - { - cl.setLineWidth(2); + if (elevation % 1000 == 0) { cl.setColor(new Color(0.0f, 0.1f, 0.6f)); } - if (elevation % 500 == 0) + if (elevation % 500 == 0) { cl.setLineWidth(2); + } layer.addRenderable(cl); } @@ -73,29 +70,24 @@ public AppFrame() this.getControlPanel().add(this.makeContourLineControlPanel(), BorderLayout.SOUTH); } - protected JPanel makeContourLineControlPanel() - { + protected JPanel makeContourLineControlPanel() { JPanel controlPanel = new JPanel(); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS)); controlPanel.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), - new TitledBorder("Contour Line Elevation"))); + new TitledBorder("Contour Line Elevation"))); final JSlider slider = new JSlider(0, 3000, (int) this.contourLine.getElevation()); slider.setMajorTickSpacing(1000); slider.setMinorTickSpacing(250); slider.setPaintTicks(true); slider.setPaintLabels(true); - slider.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent event) - { - contourLine.setElevation(slider.getValue()); - getWwd().redraw(); - } + slider.addChangeListener((ChangeEvent event) -> { + contourLine.setElevation(slider.getValue()); + getWwd().redraw(); }); controlPanel.add(slider); - Hashtable labels = new Hashtable(); + Hashtable labels = new Hashtable<>(); labels.put(0, new JLabel("0km")); labels.put(1000, new JLabel("1km")); labels.put(2000, new JLabel("2km")); @@ -106,8 +98,7 @@ public void stateChanged(ChangeEvent event) } } - public static void main(String[] args) - { + public static void main(String[] args) { Configuration.setValue(AVKey.INITIAL_LATITUDE, 44.23); Configuration.setValue(AVKey.INITIAL_LONGITUDE, 6.92); Configuration.setValue(AVKey.INITIAL_ALTITUDE, 30000); diff --git a/src/gov/nasa/worldwindx/examples/DebuggingGLErrors.java b/src/gov/nasa/worldwindx/examples/DebuggingGLErrors.java index f3a8377a70..652c45613f 100644 --- a/src/gov/nasa/worldwindx/examples/DebuggingGLErrors.java +++ b/src/gov/nasa/worldwindx/examples/DebuggingGLErrors.java @@ -19,10 +19,9 @@ * @author dcollins * @version $Id: DebuggingGLErrors.java 3433 2015-10-01 19:40:46Z dcollins $ */ -public class DebuggingGLErrors extends ApplicationTemplate -{ - static - { +public class DebuggingGLErrors extends ApplicationTemplate { + + static { // Modify the configuration to specify our custom WorldWindowGLDrawable. Normally, an application would specify // this in a configuration file. For example, via the standard WorldWind XML configuration file: // @@ -47,11 +46,12 @@ public class DebuggingGLErrors extends ApplicationTemplate * gov.nasa.worldwind.WorldWindowGLAutoDrawable#init(com.jogamp.opengl.GLAutoDrawable)} to configure the OpenGL * error logger. */ - public static class MyGLAutoDrawable extends WorldWindowGLAutoDrawable - { - /** Constructs a new MyGLAutoDrawable, but otherwise does nothing. */ - public MyGLAutoDrawable() - { + public static class MyGLAutoDrawable extends WorldWindowGLAutoDrawable { + + /** + * Constructs a new MyGLAutoDrawable, but otherwise does nothing. + */ + public MyGLAutoDrawable() { } /** @@ -60,8 +60,8 @@ public MyGLAutoDrawable() * * @param glAutoDrawable the drawable */ - public void init(GLAutoDrawable glAutoDrawable) - { + @Override + public void init(GLAutoDrawable glAutoDrawable) { // Invoked when the GL context changes. The host machine capabilities may have changed, so re-configure the // OpenGL features used by the WorldWind SDK. super.init(glAutoDrawable); @@ -74,8 +74,7 @@ public void init(GLAutoDrawable glAutoDrawable) } } - public static void main(String[] args) - { + public static void main(String[] args) { start("WorldWind Debugging GL Errors", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/ExtrudedShapes.java b/src/gov/nasa/worldwindx/examples/ExtrudedShapes.java index f869bede3e..7b18beed7f 100644 --- a/src/gov/nasa/worldwindx/examples/ExtrudedShapes.java +++ b/src/gov/nasa/worldwindx/examples/ExtrudedShapes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.examples; import gov.nasa.worldwind.View; @@ -28,27 +27,25 @@ * @author tag * @version $Id: ExtrudedShapes.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class ExtrudedShapes extends ApplicationTemplate -{ +public class ExtrudedShapes extends ApplicationTemplate { + protected static final String DEMO_AIRSPACES_PATH - = "gov/nasa/worldwindx/examples/data/AirspaceBuilder-DemoShapes.zip"; + = "gov/nasa/worldwindx/examples/data/AirspaceBuilder-DemoShapes.zip"; protected static String DEFAULT_IMAGE_URL = "gov/nasa/worldwindx/examples/images/build123sm.jpg"; - public static class AppFrame extends ApplicationTemplate.AppFrame - { - public AppFrame() - { + public static class AppFrame extends ApplicationTemplate.AppFrame { + + public AppFrame() { super(true, true, false); - try - { + try { // Create a layer for the shapes. RenderableLayer layer = new RenderableLayer(); layer.setName("Extruded Shapes"); layer.setPickEnabled(true); // Retrieve the geometry from the WorldWind demo site. - List airspaces = new ArrayList(); + List airspaces = new ArrayList<>(); loadAirspacesFromPath(DEMO_AIRSPACES_PATH, airspaces); // Define attributes for the shapes. @@ -61,16 +58,14 @@ public AppFrame() // Construct the extruded polygons from the demo data. int n = 0, m = 0; - for (Airspace airspace : airspaces) - { + for (Airspace airspace : airspaces) { if (airspace instanceof Polygon) // only polygons in the demo data are used { Polygon pgonAirspace = (Polygon) airspace; // Collect the images to be applied to the shape's sides. - ArrayList textures = new ArrayList(); - for (int i = 0; i < pgonAirspace.getLocations().size(); i++) - { + ArrayList textures = new ArrayList<>(); + for (int i = 0; i < pgonAirspace.getLocations().size(); i++) { textures.add(DEFAULT_IMAGE_URL); } @@ -83,9 +78,8 @@ public AppFrame() quad.setCapAttributes(capAttributes); // Specify a cap for the extruded polygon, specifying its texture coordinates and image. - if (pgonAirspace.getLocations().size() == 4) - { - float[] texCoords = new float[] {0, 0, 1, 0, 1, 1, 0, 1}; + if (pgonAirspace.getLocations().size() == 4) { + float[] texCoords = new float[]{0, 0, 1, 0, 1, 1, 0, 1}; quad.setCapImageSource("images/32x32-icon-nasa.png", texCoords, 4); } @@ -107,47 +101,41 @@ public AppFrame() view.setEyePosition(Position.fromDegrees(47.656, -122.306, 1e3)); // This is how a select listener would notice that one of the shapes was picked. - getWwd().addSelectListener(new SelectListener() - { - public void selected(SelectEvent event) - { - if (event.getTopObject() instanceof ExtrudedPolygon) - System.out.println("EXTRUDED POLYGON"); + getWwd().addSelectListener((SelectEvent event) -> { + if (event.getTopObject() instanceof ExtrudedPolygon) { + System.out.println("EXTRUDED POLYGON"); } }); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } } - protected static void loadAirspacesFromPath(String path, Collection airspaces) - { + protected static void loadAirspacesFromPath(String path, Collection airspaces) { File file = ExampleUtil.saveResourceToTempFile(path, ".zip"); - if (file == null) + if (file == null) { return; + } - try - { + try { ZipFile zipFile = new ZipFile(file); ZipEntry entry = null; - for (Enumeration e = zipFile.entries(); e.hasMoreElements(); entry = e.nextElement()) - { - if (entry == null) + for (Enumeration e = zipFile.entries(); e.hasMoreElements(); entry = e.nextElement()) { + if (entry == null) { continue; + } String name = WWIO.getFilename(entry.getName()); - if (!(name.startsWith("gov.nasa.worldwind.render.airspaces") && name.endsWith(".xml"))) + if (!(name.startsWith("gov.nasa.worldwind.render.airspaces") && name.endsWith(".xml"))) { continue; + } String[] tokens = name.split("-"); - try - { + try { Class c = Class.forName(tokens[0]); Airspace airspace = (Airspace) c.getConstructor().newInstance(); BufferedReader input = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry))); @@ -155,25 +143,19 @@ protected static void loadAirspacesFromPath(String path, Collection ai airspace.restoreState(s); airspaces.add(airspace); - if (tokens.length >= 2) - { + if (tokens.length >= 2) { airspace.setValue(AVKey.DISPLAY_NAME, tokens[1]); } - } - catch (Exception ex) - { + } catch (Exception ex) { ex.printStackTrace(); } } - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind Extruded Polygons on Ground", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/GetBestElevations.java b/src/gov/nasa/worldwindx/examples/GetBestElevations.java index 32fa1b824f..f73eb1d29a 100644 --- a/src/gov/nasa/worldwindx/examples/GetBestElevations.java +++ b/src/gov/nasa/worldwindx/examples/GetBestElevations.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.examples; import gov.nasa.worldwind.geom.*; @@ -28,10 +27,10 @@ * @version $Id: GetBestElevations.java 1171 2013-02-11 21:45:02Z dcollins $ * @see gov.nasa.worldwind.terrain.HighResolutionTerrain */ -public class GetBestElevations extends ApplicationTemplate -{ - public static class AppFrame extends ApplicationTemplate.AppFrame - { +public class GetBestElevations extends ApplicationTemplate { + + public static class AppFrame extends ApplicationTemplate.AppFrame { + /** * Retrieve elevations for a specified list of locations. The elevations returned are the best currently * available for the dataset and the area bounding the locations. Since the necessary elevation data might not @@ -48,8 +47,7 @@ public static class AppFrame extends ApplicationTemplate.AppFrame * * @return the resolution actually achieved. */ - public double[] getBestElevations(List locations) - { + public double[] getBestElevations(List locations) { Globe globe = this.getWwd().getModel().getGlobe(); Sector sector = Sector.boundingSector(locations); double[] elevations = new double[locations.size()]; @@ -57,18 +55,14 @@ public double[] getBestElevations(List locations) // Iterate until the best resolution is achieved. Use the elevation model to determine the best elevation. double targetResolution = globe.getElevationModel().getBestResolution(sector); double actualResolution = Double.MAX_VALUE; - while (actualResolution > targetResolution) - { + while (actualResolution > targetResolution) { actualResolution = globe.getElevations(sector, locations, targetResolution, elevations); // Uncomment the two lines below if you want to watch the resolution converge // System.out.printf("Target resolution = %s, Actual resolution = %s\n", // Double.toString(targetResolution), Double.toString(actualResolution)); - try - { + try { Thread.sleep(200); // give the system a chance to retrieve data from the disk cache or the server - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { e.printStackTrace(); } } @@ -76,75 +70,66 @@ public double[] getBestElevations(List locations) return elevations; } - public AppFrame() - { + public AppFrame() { super(true, true, false); final ScreenAnnotation annotation = new ScreenAnnotation("Shift-click to select a location", - new Point(100, 50)); + new Point(100, 50)); AnnotationLayer layer = new AnnotationLayer(); layer.addAnnotation(annotation); insertBeforeCompass(this.getWwd(), layer); - this.getWwd().getInputHandler().addMouseListener(new MouseListener() - { - public void mouseClicked(MouseEvent mouseEvent) - { - if ((mouseEvent.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) == 0) + this.getWwd().getInputHandler().addMouseListener(new MouseListener() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { + if ((mouseEvent.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) == 0) { return; + } mouseEvent.consume(); final Position pos = getWwd().getCurrentPosition(); - if (pos == null) + if (pos == null) { return; + } annotation.setText(String.format("Elevation = ")); getWwd().redraw(); // Run the elevation query in a separate thread to avoid locking up the user interface - Thread t = new Thread(new Runnable() - { - public void run() - { - // We want elevation for only one location, so add a second location that's very near the - // desired one. This causes fewer requests to the disk or server, and causes faster - // convergence. - List locations = Arrays.asList(pos, pos.add(LatLon.fromDegrees(0.00001, 0.00001))); - final double[] elevations = getBestElevations(locations); - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - annotation.setText(String.format("Elevation = %d m", (int) elevations[0])); - getWwd().redraw(); - } - }); - } + Thread t = new Thread(() -> { + // We want elevation for only one location, so add a second location that's very near the + // desired one. This causes fewer requests to the disk or server, and causes faster + // convergence. + List locations = Arrays.asList(pos, pos.add(LatLon.fromDegrees(0.00001, 0.00001))); + final double[] elevations = getBestElevations(locations); + SwingUtilities.invokeLater(() -> { + annotation.setText(String.format("Elevation = %d m", (int) elevations[0])); + getWwd().redraw(); + }); }); t.start(); } - public void mouseEntered(MouseEvent mouseEvent) - { + @Override + public void mouseEntered(MouseEvent mouseEvent) { } - public void mouseExited(MouseEvent mouseEvent) - { + @Override + public void mouseExited(MouseEvent mouseEvent) { } - public void mousePressed(MouseEvent mouseEvent) - { + @Override + public void mousePressed(MouseEvent mouseEvent) { } - public void mouseReleased(MouseEvent mouseEvent) - { + @Override + public void mouseReleased(MouseEvent mouseEvent) { } }); } } - public static void main(String[] args) - { + public static void main(String[] args) { // Adjust configuration values before instantiation ApplicationTemplate.start("WorldWind Get Best Elevations", AppFrame.class); } diff --git a/src/gov/nasa/worldwindx/examples/KeepingObjectsInView.java b/src/gov/nasa/worldwindx/examples/KeepingObjectsInView.java index 9e158b6f0d..adb955fa04 100644 --- a/src/gov/nasa/worldwindx/examples/KeepingObjectsInView.java +++ b/src/gov/nasa/worldwindx/examples/KeepingObjectsInView.java @@ -147,7 +147,7 @@ protected void initSwingComponents() { } public static Iterable createObjectsToTrack() { - ArrayList objects = new ArrayList(); + ArrayList objects = new ArrayList<>(); Sector sector = Sector.fromDegrees(35, 45, -110, -100); for (int i = 0; i < 3; i++) { @@ -173,7 +173,7 @@ public static Iterable createObjectsToTrack() { randLocation1 = randomLocation(sector); randLocation2 = randomLocation(sector); Path path = new Path(Arrays.asList(randLocation1, randLocation2), 0d); - path.setFollowTerrain(true); + path.setSurfacePath(true); var attrs = new BasicShapeAttributes(); attrs.setOutlineWidth(3); attrs.setOutlineMaterial(new Material(Color.RED)); @@ -321,9 +321,9 @@ protected void addExtents(ExtentVisibilitySupport vs) { return; } - ArrayList extentHolders = new ArrayList(); + ArrayList extentHolders = new ArrayList<>(); ArrayList screenExtents - = new ArrayList(); + = new ArrayList<>(); for (Object o : iterable) { if (o == null) { diff --git a/src/gov/nasa/worldwindx/examples/LineBackground.java b/src/gov/nasa/worldwindx/examples/LineBackground.java index 810fc5a27d..61a7192b0e 100644 --- a/src/gov/nasa/worldwindx/examples/LineBackground.java +++ b/src/gov/nasa/worldwindx/examples/LineBackground.java @@ -63,17 +63,19 @@ public AppFrame() { plPoints.add(ll.add(LatLon.fromDegrees(2, 0))); // add 2 degrees of latitude to separate the lines } Path path1 = new Path(plPoints, 0); // the primary Path - path1.setFollowTerrain(true); + path1.setSurfacePath(true); path1.setPathType(AVKey.RHUMB_LINE); path1.setAttributes(foregroundAttrs); + path1.makeClosed(); Path path2 = new Path(plPoints, 0); // the background Path - path2.setFollowTerrain(true); + path2.setSurfacePath(true); path2.setPathType(AVKey.RHUMB_LINE); float[] c = backgroundAttrs.getOutlineMaterial().getDiffuse().getColorComponents(new float[3]); var attrs = new BasicShapeAttributes(backgroundAttrs); attrs.setOutlineMaterial(new Material(new Color(c[0], c[1], c[2], (float) backgroundAttrs.getOutlineOpacity()))); path2.setAttributes(attrs); + path2.makeClosed(); // Add all the lines to the scene. RenderableLayer layer = new RenderableLayer(); diff --git a/src/gov/nasa/worldwindx/examples/LineBuilder.java b/src/gov/nasa/worldwindx/examples/LineBuilder.java index aa861f97fa..7ed6d0e611 100644 --- a/src/gov/nasa/worldwindx/examples/LineBuilder.java +++ b/src/gov/nasa/worldwindx/examples/LineBuilder.java @@ -71,7 +71,7 @@ public LineBuilder(final WorldWindow wwd, RenderableLayer lineLayer, Path path) line = path; } else { this.line = new Path(); - this.line.setFollowTerrain(true); + this.line.setSurfacePath(true); } this.layer = lineLayer != null ? lineLayer : new RenderableLayer(); this.layer.addRenderable(this.line); diff --git a/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java b/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java index 5f7c053695..52cb7ed970 100644 --- a/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java +++ b/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java @@ -20,15 +20,14 @@ import java.util.ArrayList; /** -* Control panel for the MeasureTool. -* -* @author Patrick Murris -* @version $Id: MeasureToolPanel.java 2226 2014-08-14 15:56:45Z tgaskins $ -* @see gov.nasa.worldwind.util.measure.MeasureTool -*/ -@SuppressWarnings("unchecked") -public class MeasureToolPanel extends JPanel -{ + * Control panel for the MeasureTool. + * + * @author Patrick Murris + * @version $Id: MeasureToolPanel.java 2226 2014-08-14 15:56:45Z tgaskins $ + * @see gov.nasa.worldwind.util.measure.MeasureTool + */ +public class MeasureToolPanel extends JPanel { + private final WorldWindow wwd; private final MeasureTool measureTool; @@ -55,11 +54,11 @@ public class MeasureToolPanel extends JPanel private JLabel headingLabel; private JLabel centerLabel; - private static ArrayList LINE = new ArrayList(); - private static ArrayList PATH = new ArrayList(); - private static ArrayList POLYGON = new ArrayList(); - static - { + private static final ArrayList LINE = new ArrayList<>(); + private static final ArrayList PATH = new ArrayList<>(); + private static final ArrayList POLYGON = new ArrayList<>(); + + static { LINE.add(Position.fromDegrees(44, 7, 0)); LINE.add(Position.fromDegrees(45, 8, 0)); @@ -72,89 +71,78 @@ public class MeasureToolPanel extends JPanel POLYGON.add(Position.fromDegrees(44, 7, 0)); } - public MeasureToolPanel(WorldWindow wwdObject, MeasureTool measureToolObject) - { + public MeasureToolPanel(WorldWindow wwdObject, MeasureTool measureToolObject) { super(new BorderLayout()); this.wwd = wwdObject; this.measureTool = measureToolObject; this.makePanel(new Dimension(200, 300)); // Handle measure tool events - measureTool.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent event) - { - // Add, remove or change positions - if (event.getPropertyName().equals(MeasureTool.EVENT_POSITION_ADD) - || event.getPropertyName().equals(MeasureTool.EVENT_POSITION_REMOVE) - || event.getPropertyName().equals(MeasureTool.EVENT_POSITION_REPLACE)) - fillPointsPanel(); // Update position list when changed - - // The tool was armed / disarmed - else if(event.getPropertyName().equals(MeasureTool.EVENT_ARMED)) - { - if (measureTool.isArmed()) - { - newButton.setEnabled(false); - pauseButton.setText("Pause"); - pauseButton.setEnabled(true); - endButton.setEnabled(true); - ((Component) wwd).setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - } - else - { - newButton.setEnabled(true); - pauseButton.setText("Pause"); - pauseButton.setEnabled(false); - endButton.setEnabled(false); - ((Component) wwd).setCursor(Cursor.getDefaultCursor()); - } - - } - - // Metric changed - sent after each render frame - else if(event.getPropertyName().equals(MeasureTool.EVENT_METRIC_CHANGED)) - { - updateMetric(); + measureTool.addPropertyChangeListener((PropertyChangeEvent event) -> { + // Add, remove or change positions + if (event.getPropertyName().equals(MeasureTool.EVENT_POSITION_ADD) + || event.getPropertyName().equals(MeasureTool.EVENT_POSITION_REMOVE) + || event.getPropertyName().equals(MeasureTool.EVENT_POSITION_REPLACE)) { + fillPointsPanel(); // Update position list when changed + } // The tool was armed / disarmed + else if (event.getPropertyName().equals(MeasureTool.EVENT_ARMED)) { + if (measureTool.isArmed()) { + newButton.setEnabled(false); + pauseButton.setText("Pause"); + pauseButton.setEnabled(true); + endButton.setEnabled(true); + ((Component) wwd).setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); + } else { + newButton.setEnabled(true); + pauseButton.setText("Pause"); + pauseButton.setEnabled(false); + endButton.setEnabled(false); + ((Component) wwd).setCursor(Cursor.getDefaultCursor()); } + } // Metric changed - sent after each render frame + else if (event.getPropertyName().equals(MeasureTool.EVENT_METRIC_CHANGED)) { + updateMetric(); } }); } - public MeasureTool getMeasureTool() - { + public MeasureTool getMeasureTool() { return this.measureTool; } - private void makePanel(Dimension size) - { + private void makePanel(Dimension size) { // Shape combo JPanel shapePanel = new JPanel(new GridLayout(1, 2, 5, 5)); shapePanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); shapePanel.add(new JLabel("Shape:")); - shapeCombo = new JComboBox(new String[] - {"Line", "Path", "Polygon", "Circle", "Ellipse", "Square", "Rectangle"}); - shapeCombo.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - String item = (String)((JComboBox)event.getSource()).getSelectedItem(); - if (item.equals("Line") ) + shapeCombo = new JComboBox(new String[]{"Line", "Path", "Polygon", "Circle", "Ellipse", "Square", "Rectangle"}); + shapeCombo.addActionListener((ActionEvent event) -> { + String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); + switch (item) { + case "Line": measureTool.setMeasureShapeType(MeasureTool.SHAPE_LINE); - else if (item.equals("Path")) + break; + case "Path": measureTool.setMeasureShapeType(MeasureTool.SHAPE_PATH); - else if (item.equals("Polygon")) + break; + case "Polygon": measureTool.setMeasureShapeType(MeasureTool.SHAPE_POLYGON); - else if (item.equals("Circle")) + break; + case "Circle": measureTool.setMeasureShapeType(MeasureTool.SHAPE_CIRCLE); - else if (item.equals("Ellipse")) + break; + case "Ellipse": measureTool.setMeasureShapeType(MeasureTool.SHAPE_ELLIPSE); - else if (item.equals("Square")) + break; + case "Square": measureTool.setMeasureShapeType(MeasureTool.SHAPE_SQUARE); - else if (item.equals("Rectangle")) + break; + case "Rectangle": measureTool.setMeasureShapeType(MeasureTool.SHAPE_QUAD); - + break; + default: + break; } }); shapePanel.add(shapeCombo); @@ -163,19 +151,22 @@ else if (item.equals("Rectangle")) JPanel pathTypePanel = new JPanel(new GridLayout(1, 2, 5, 5)); pathTypePanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); pathTypePanel.add(new JLabel("Path type:")); - pathTypeCombo = new JComboBox(new String[] {"Linear", "Rhumb", "Great circle"}); + pathTypeCombo = new JComboBox(new String[]{"Linear", "Rhumb", "Great circle"}); pathTypeCombo.setSelectedIndex(2); - pathTypeCombo.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - String item = (String)((JComboBox)event.getSource()).getSelectedItem(); - if (item.equals("Linear") ) + pathTypeCombo.addActionListener((ActionEvent event) -> { + String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); + switch (item) { + case "Linear": measureTool.setPathType(AVKey.LINEAR); - else if (item.equals("Rhumb")) + break; + case "Rhumb": measureTool.setPathType(AVKey.RHUMB_LINE); - else if (item.equals("Great circle")) + break; + case "Great circle": measureTool.setPathType(AVKey.GREAT_CIRCLE); + break; + default: + break; } }); pathTypePanel.add(pathTypeCombo); @@ -184,49 +175,42 @@ else if (item.equals("Great circle")) JPanel unitsPanel = new JPanel(new GridLayout(1, 2, 5, 5)); unitsPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); unitsPanel.add(new JLabel("Units:")); - unitsCombo = new JComboBox(new String[] {"M/M\u00b2", "KM/KM\u00b2", "KM/Hectare", "Feet/Feet\u00b2", + unitsCombo = new JComboBox(new String[]{"M/M\u00b2", "KM/KM\u00b2", "KM/Hectare", "Feet/Feet\u00b2", "Miles/Miles\u00b2", "Nm/Miles\u00b2", "Yards/Acres"}); unitsCombo.setSelectedItem("KM/KM\u00b2"); - unitsCombo.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - String item = (String)((JComboBox)event.getSource()).getSelectedItem(); - if (item.equals("M/M\u00b2")) - { + unitsCombo.addActionListener((ActionEvent event) -> { + String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); + switch (item) { + case "M/M\u00b2": measureTool.getUnitsFormat().setLengthUnits(UnitsFormat.METERS); measureTool.getUnitsFormat().setAreaUnits(UnitsFormat.SQUARE_METERS); - } - else if (item.equals("KM/KM\u00b2")) - { + break; + case "KM/KM\u00b2": measureTool.getUnitsFormat().setLengthUnits(UnitsFormat.KILOMETERS); measureTool.getUnitsFormat().setAreaUnits(UnitsFormat.SQUARE_KILOMETERS); - } - else if (item.equals("KM/Hectare")) - { + break; + case "KM/Hectare": measureTool.getUnitsFormat().setLengthUnits(UnitsFormat.KILOMETERS); measureTool.getUnitsFormat().setAreaUnits(UnitsFormat.HECTARE); - } - else if (item.equals("Feet/Feet\u00b2")) - { + break; + case "Feet/Feet\u00b2": measureTool.getUnitsFormat().setLengthUnits(UnitsFormat.FEET); measureTool.getUnitsFormat().setAreaUnits(UnitsFormat.SQUARE_FEET); - } - else if (item.equals("Miles/Miles\u00b2")) - { + break; + case "Miles/Miles\u00b2": measureTool.getUnitsFormat().setLengthUnits(UnitsFormat.MILES); measureTool.getUnitsFormat().setAreaUnits(UnitsFormat.SQUARE_MILES); - } - else if (item.equals("Nm/Miles\u00b2")) - { + break; + case "Nm/Miles\u00b2": measureTool.getUnitsFormat().setLengthUnits(UnitsFormat.NAUTICAL_MILES); measureTool.getUnitsFormat().setAreaUnits(UnitsFormat.SQUARE_MILES); - } - else if (item.equals("Yards/Acres")) - { + break; + case "Yards/Acres": measureTool.getUnitsFormat().setLengthUnits(UnitsFormat.YARDS); measureTool.getUnitsFormat().setAreaUnits(UnitsFormat.ACRE); - } + break; + default: + break; } }); unitsPanel.add(unitsCombo); @@ -235,15 +219,11 @@ else if (item.equals("Yards/Acres")) JPanel anglesPanel = new JPanel(new GridLayout(1, 2, 5, 5)); anglesPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); anglesPanel.add(new JLabel("Angle Format:")); - anglesCombo = new JComboBox(new String[] {"DD", "DMS"}); + anglesCombo = new JComboBox(new String[]{"DD", "DMS"}); anglesCombo.setSelectedItem("DD"); - anglesCombo.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - String item = (String)((JComboBox)event.getSource()).getSelectedItem(); - measureTool.getUnitsFormat().setShowDMS(item.equals("DMS")); - } + anglesCombo.addActionListener((ActionEvent event) -> { + String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); + measureTool.getUnitsFormat().setShowDMS(item.equals("DMS")); }); anglesPanel.add(anglesCombo); @@ -253,67 +233,47 @@ public void actionPerformed(ActionEvent event) followCheck = new JCheckBox("Follow terrain"); followCheck.setSelected(measureTool.isFollowTerrain()); - followCheck.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - JCheckBox cb = (JCheckBox)event.getSource(); - measureTool.setFollowTerrain(cb.isSelected()); - wwd.redraw(); - } + followCheck.addActionListener((ActionEvent event) -> { + JCheckBox cb = (JCheckBox) event.getSource(); + measureTool.setFollowTerrain(cb.isSelected()); + wwd.redraw(); }); checkPanel.add(followCheck); showControlsCheck = new JCheckBox("Control points"); showControlsCheck.setSelected(measureTool.isShowControlPoints()); - showControlsCheck.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - JCheckBox cb = (JCheckBox)event.getSource(); - measureTool.setShowControlPoints(cb.isSelected()); - wwd.redraw(); - } + showControlsCheck.addActionListener((ActionEvent event) -> { + JCheckBox cb = (JCheckBox) event.getSource(); + measureTool.setShowControlPoints(cb.isSelected()); + wwd.redraw(); }); checkPanel.add(showControlsCheck); rubberBandCheck = new JCheckBox("Rubber band"); rubberBandCheck.setSelected(measureTool.getController().isUseRubberBand()); - rubberBandCheck.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - JCheckBox cb = (JCheckBox)event.getSource(); - measureTool.getController().setUseRubberBand(cb.isSelected()); - freeHandCheck.setEnabled(cb.isSelected()); - wwd.redraw(); - } + rubberBandCheck.addActionListener((ActionEvent event) -> { + JCheckBox cb = (JCheckBox) event.getSource(); + measureTool.getController().setUseRubberBand(cb.isSelected()); + freeHandCheck.setEnabled(cb.isSelected()); + wwd.redraw(); }); checkPanel.add(rubberBandCheck); freeHandCheck = new JCheckBox("Free Hand"); freeHandCheck.setSelected(measureTool.getController().isFreeHand()); - freeHandCheck.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - JCheckBox cb = (JCheckBox)event.getSource(); - measureTool.getController().setFreeHand(cb.isSelected()); - wwd.redraw(); - } + freeHandCheck.addActionListener((ActionEvent event) -> { + JCheckBox cb = (JCheckBox) event.getSource(); + measureTool.getController().setFreeHand(cb.isSelected()); + wwd.redraw(); }); checkPanel.add(freeHandCheck); showAnnotationCheck = new JCheckBox("Tooltip"); showAnnotationCheck.setSelected(measureTool.isShowAnnotation()); - showAnnotationCheck.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - JCheckBox cb = (JCheckBox)event.getSource(); - measureTool.setShowAnnotation(cb.isSelected()); - wwd.redraw(); - } + showAnnotationCheck.addActionListener((ActionEvent event) -> { + JCheckBox cb = (JCheckBox) event.getSource(); + measureTool.setShowAnnotation(cb.isSelected()); + wwd.redraw(); }); checkPanel.add(showAnnotationCheck); @@ -321,54 +281,39 @@ public void actionPerformed(ActionEvent event) final JPanel colorPanel = new JPanel(new GridLayout(1, 2, 5, 5)); colorPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); lineColorButton = new JButton("Line"); - lineColorButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - Color c = JColorChooser.showDialog(colorPanel, - "Choose a color...", ((JButton)event.getSource()).getBackground()); - if (c != null) - { - ((JButton)event.getSource()).setBackground(c); - measureTool.setLineColor(c); - Color fill = new Color(c.getRed() / 255f * .5f, - c.getGreen() / 255f * .5f, c.getBlue() / 255f * .5f, .5f); - measureTool.setFillColor(fill); - } + lineColorButton.addActionListener((ActionEvent event) -> { + Color c = JColorChooser.showDialog(colorPanel, + "Choose a color...", ((JButton) event.getSource()).getBackground()); + if (c != null) { + ((JButton) event.getSource()).setBackground(c); + measureTool.setLineColor(c); + Color fill = new Color(c.getRed() / 255f * .5f, + c.getGreen() / 255f * .5f, c.getBlue() / 255f * .5f, .5f); + measureTool.setFillColor(fill); } }); colorPanel.add(lineColorButton); lineColorButton.setBackground(measureTool.getLineColor()); pointColorButton = new JButton("Points"); - pointColorButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - Color c = JColorChooser.showDialog(colorPanel, - "Choose a color...", ((JButton)event.getSource()).getBackground()); - if (c != null) - { - ((JButton)event.getSource()).setBackground(c); - measureTool.getControlPointsAttributes().setBackgroundColor(c); - } + pointColorButton.addActionListener((ActionEvent event) -> { + Color c = JColorChooser.showDialog(colorPanel, + "Choose a color...", ((JButton) event.getSource()).getBackground()); + if (c != null) { + ((JButton) event.getSource()).setBackground(c); + measureTool.getControlPointsAttributes().setBackgroundColor(c); } }); colorPanel.add(pointColorButton); pointColorButton.setBackground(measureTool.getControlPointsAttributes().getBackgroundColor()); annotationColorButton = new JButton("Tooltip"); - annotationColorButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - Color c = JColorChooser.showDialog(colorPanel, - "Choose a color...", ((JButton)event.getSource()).getBackground()); - if (c != null) - { - ((JButton)event.getSource()).setBackground(c); - measureTool.getAnnotationAttributes().setTextColor(c); - } + annotationColorButton.addActionListener((ActionEvent event) -> { + Color c = JColorChooser.showDialog(colorPanel, + "Choose a color...", ((JButton) event.getSource()).getBackground()); + if (c != null) { + ((JButton) event.getSource()).setBackground(c); + measureTool.getAnnotationAttributes().setTextColor(c); } }); annotationColorButton.setBackground(measureTool.getAnnotationAttributes().getTextColor()); @@ -378,39 +323,27 @@ public void actionPerformed(ActionEvent event) JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 5)); buttonPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); newButton = new JButton("New"); - newButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - measureTool.clear(); - measureTool.setArmed(true); - } + newButton.addActionListener((ActionEvent actionEvent) -> { + measureTool.clear(); + measureTool.setArmed(true); }); buttonPanel.add(newButton); newButton.setEnabled(true); pauseButton = new JButton("Pause"); - pauseButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - measureTool.setArmed(!measureTool.isArmed()); - pauseButton.setText(!measureTool.isArmed() ? "Resume" : "Pause"); - pauseButton.setEnabled(true); - ((Component) wwd).setCursor(!measureTool.isArmed() ? Cursor.getDefaultCursor() - : Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - } + pauseButton.addActionListener((ActionEvent actionEvent) -> { + measureTool.setArmed(!measureTool.isArmed()); + pauseButton.setText(!measureTool.isArmed() ? "Resume" : "Pause"); + pauseButton.setEnabled(true); + ((Component) wwd).setCursor(!measureTool.isArmed() ? Cursor.getDefaultCursor() + : Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); }); buttonPanel.add(pauseButton); pauseButton.setEnabled(false); endButton = new JButton("End"); - endButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - measureTool.setArmed(false); - } + endButton.addActionListener((ActionEvent actionEvent) -> { + measureTool.setArmed(false); }); buttonPanel.add(endButton); endButton.setEnabled(false); @@ -419,44 +352,30 @@ public void actionPerformed(ActionEvent actionEvent) JPanel presetPanel = new JPanel(new GridLayout(1, 2, 5, 5)); presetPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); JButton bt = new JButton("Polyline"); - bt.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - shapeCombo.setSelectedIndex(1); - measureTool.setMeasureShape(new Path(PATH)); - } + bt.addActionListener((ActionEvent actionEvent) -> { + shapeCombo.setSelectedIndex(1); + measureTool.setMeasureShape(new Path(PATH)); }); presetPanel.add(bt); bt = new JButton("Surf. Quad"); - bt.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - shapeCombo.setSelectedIndex(6); - measureTool.setMeasureShape(new SurfaceQuad(Position.fromDegrees(44, 7, 0), 100e3, 50e3, Angle.fromDegrees(30))); - } + bt.addActionListener((ActionEvent actionEvent) -> { + shapeCombo.setSelectedIndex(6); + measureTool.setMeasureShape(new SurfaceQuad(Position.fromDegrees(44, 7, 0), 100e3, 50e3, Angle.fromDegrees(30))); }); presetPanel.add(bt); bt = new JButton("Polygon"); - bt.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - shapeCombo.setSelectedIndex(2); - measureTool.setMeasureShape(new SurfacePolygon(POLYGON)); - } + bt.addActionListener((ActionEvent actionEvent) -> { + shapeCombo.setSelectedIndex(2); + measureTool.setMeasureShape(new SurfacePolygon(POLYGON)); }); presetPanel.add(bt); - // Point list JPanel pointPanel = new JPanel(new GridLayout(0, 1, 0, 4)); pointPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); this.pointLabels = new JLabel[100]; - for (int i = 0; i < this.pointLabels.length; i++) - { + for (int i = 0; i < this.pointLabels.length; i++) { this.pointLabels[i] = new JLabel(""); pointPanel.add(this.pointLabels[i]); } @@ -468,12 +387,13 @@ public void actionPerformed(ActionEvent actionEvent) // Put the point panel in a scroll bar. JScrollPane scrollPane = new JScrollPane(dummyPanel); scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); - if (size != null) + if (size != null) { scrollPane.setPreferredSize(size); + } // Metric JPanel metricPanel = new JPanel(new GridLayout(0, 2, 0, 4)); - metricPanel.setBorder( new CompoundBorder( + metricPanel.setBorder(new CompoundBorder( new TitledBorder("Metric"), BorderFactory.createEmptyBorder(5, 5, 5, 5))); metricPanel.add(new JLabel("Length:")); lengthLabel = new JLabel(); @@ -494,12 +414,11 @@ public void actionPerformed(ActionEvent actionEvent) centerLabel = new JLabel(); metricPanel.add(centerLabel); - // Add all the panels to a titled panel JPanel outerPanel = new JPanel(); outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS)); outerPanel.setBorder( - new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Measure"))); + new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Measure"))); outerPanel.setToolTipText("Measure tool control and info"); outerPanel.add(colorPanel); outerPanel.add(shapePanel); @@ -515,15 +434,13 @@ public void actionPerformed(ActionEvent actionEvent) this.add(outerPanel, BorderLayout.NORTH); } - private void fillPointsPanel() - { + private void fillPointsPanel() { int i = 0; - if (measureTool.getPositions() != null) - { - for (LatLon pos : measureTool.getPositions()) - { - if (i == this.pointLabels.length) + if (measureTool.getPositions() != null) { + for (LatLon pos : measureTool.getPositions()) { + if (i == this.pointLabels.length) { break; + } String las = String.format("Lat %7.4f\u00B0", pos.getLatitude().getDegrees()); String los = String.format("Lon %7.4f\u00B0", pos.getLongitude().getDegrees()); @@ -531,68 +448,74 @@ private void fillPointsPanel() } } // Clear remaining labels - for (; i < this.pointLabels.length; i++) + for (; i < this.pointLabels.length; i++) { pointLabels[i].setText(""); + } } - private void updateMetric() - { + private void updateMetric() { // Update length label double value = measureTool.getLength(); String s; - if (value <= 0) + if (value <= 0) { s = "na"; - else if(value < 1000) + } else if (value < 1000) { s = String.format("%,7.1f m", value); - else + } else { s = String.format("%,7.3f km", value / 1000); + } lengthLabel.setText(s); // Update area label value = measureTool.getArea(); - if (value < 0) + if (value < 0) { s = "na"; - else if(value < 1e6) + } else if (value < 1e6) { s = String.format("%,7.1f m2", value); - else + } else { s = String.format("%,7.3f km2", value / 1e6); + } areaLabel.setText(s); // Update width label value = measureTool.getWidth(); - if (value < 0) + if (value < 0) { s = "na"; - else if(value < 1000) + } else if (value < 1000) { s = String.format("%,7.1f m", value); - else + } else { s = String.format("%,7.3f km", value / 1000); + } widthLabel.setText(s); // Update height label value = measureTool.getHeight(); - if (value < 0) + if (value < 0) { s = "na"; - else if(value < 1000) + } else if (value < 1000) { s = String.format("%,7.1f m", value); - else + } else { s = String.format("%,7.3f km", value / 1000); + } heightLabel.setText(s); // Update heading label Angle angle = measureTool.getOrientation(); - if(angle != null) + if (angle != null) { s = String.format("%,6.2f\u00B0", angle.degrees); - else + } else { s = "na"; + } headingLabel.setText(s); // Update center label Position center = measureTool.getCenterPosition(); - if(center != null) + if (center != null) { s = String.format("%,7.4f\u00B0 %,7.4f\u00B0", center.getLatitude().degrees, center.getLongitude().degrees); - else + } else { s = "na"; + } centerLabel.setText(s); } } diff --git a/src/gov/nasa/worldwindx/examples/MeasureToolUsage.java b/src/gov/nasa/worldwindx/examples/MeasureToolUsage.java index d004b93971..704cec4e8a 100644 --- a/src/gov/nasa/worldwindx/examples/MeasureToolUsage.java +++ b/src/gov/nasa/worldwindx/examples/MeasureToolUsage.java @@ -25,17 +25,16 @@ * @see gov.nasa.worldwind.util.measure.MeasureToolController * @see MeasureToolPanel */ -public class MeasureToolUsage extends ApplicationTemplate -{ - public static class AppFrame extends ApplicationTemplate.AppFrame - { +public class MeasureToolUsage extends ApplicationTemplate { + + public static class AppFrame extends ApplicationTemplate.AppFrame { + private int lastTabIndex = -1; private final JTabbedPane tabbedPane = new JTabbedPane(); - private TerrainProfileLayer profile = new TerrainProfileLayer(); - private PropertyChangeListener measureToolListener = new MeasureToolListener(); + private final TerrainProfileLayer profile = new TerrainProfileLayer(); + private final PropertyChangeListener measureToolListener = new MeasureToolListener(); - public AppFrame() - { + public AppFrame() { super(true, true, false); // no layer or statistics panel // Add terrain profile layer @@ -47,24 +46,17 @@ public AppFrame() // Add + tab tabbedPane.add(new JPanel()); tabbedPane.setTitleAt(0, "+"); - tabbedPane.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { - if (tabbedPane.getSelectedIndex() == 0) - { - // Add new measure tool in a tab when '+' selected - MeasureTool measureTool = new MeasureTool(getWwd()); - measureTool.setController(new MeasureToolController()); - tabbedPane.add(new MeasureToolPanel(getWwd(), measureTool)); - tabbedPane.setTitleAt(tabbedPane.getTabCount() - 1, "" + (tabbedPane.getTabCount() - 1)); - tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1); - switchMeasureTool(); - } - else - { - switchMeasureTool(); - } + tabbedPane.addChangeListener((ChangeEvent changeEvent) -> { + if (tabbedPane.getSelectedIndex() == 0) { + // Add new measure tool in a tab when '+' selected + MeasureTool measureTool = new MeasureTool(getWwd()); + measureTool.setController(new MeasureToolController()); + tabbedPane.add(new MeasureToolPanel(getWwd(), measureTool)); + tabbedPane.setTitleAt(tabbedPane.getTabCount() - 1, "" + (tabbedPane.getTabCount() - 1)); + tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1); + switchMeasureTool(); + } else { + switchMeasureTool(); } }); @@ -80,53 +72,47 @@ public void stateChanged(ChangeEvent changeEvent) this.pack(); } - private class MeasureToolListener implements PropertyChangeListener - { - public void propertyChange(PropertyChangeEvent event) - { + private class MeasureToolListener implements PropertyChangeListener { + + @Override + public void propertyChange(PropertyChangeEvent event) { // Measure shape position list changed - update terrain profile if (event.getPropertyName().equals(MeasureTool.EVENT_POSITION_ADD) || event.getPropertyName().equals(MeasureTool.EVENT_POSITION_REMOVE) - || event.getPropertyName().equals(MeasureTool.EVENT_POSITION_REPLACE)) - { - updateProfile(((MeasureTool)event.getSource())); + || event.getPropertyName().equals(MeasureTool.EVENT_POSITION_REPLACE)) { + updateProfile(((MeasureTool) event.getSource())); } } } - private void switchMeasureTool() - { + private void switchMeasureTool() { // Disarm last measure tool when changing tab and switching tool - if (lastTabIndex != -1) - { - MeasureTool mt = ((MeasureToolPanel)tabbedPane.getComponentAt(lastTabIndex)).getMeasureTool(); + if (lastTabIndex != -1) { + MeasureTool mt = ((MeasureToolPanel) tabbedPane.getComponentAt(lastTabIndex)).getMeasureTool(); mt.setArmed(false); mt.removePropertyChangeListener(measureToolListener); } // Update terrain profile from current measure tool lastTabIndex = tabbedPane.getSelectedIndex(); - MeasureTool mt = ((MeasureToolPanel)tabbedPane.getComponentAt(lastTabIndex)).getMeasureTool(); + MeasureTool mt = ((MeasureToolPanel) tabbedPane.getComponentAt(lastTabIndex)).getMeasureTool(); mt.addPropertyChangeListener(measureToolListener); updateProfile(mt); } - private void updateProfile(MeasureTool mt) - { + private void updateProfile(MeasureTool mt) { ArrayList positions = mt.getPositions(); - if (positions != null && positions.size() > 1) - { + if (positions != null && positions.size() > 1) { profile.setPathPositions(positions); profile.setEnabled(true); - } - else + } else { profile.setEnabled(false); - + } + getWwd().redraw(); } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind Measure Tool", MeasureToolUsage.AppFrame.class); } diff --git a/src/gov/nasa/worldwindx/examples/MultiResPath.java b/src/gov/nasa/worldwindx/examples/MultiResPath.java index f59c642609..2bf50f3d55 100644 --- a/src/gov/nasa/worldwindx/examples/MultiResPath.java +++ b/src/gov/nasa/worldwindx/examples/MultiResPath.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.examples; import gov.nasa.worldwind.WorldWind; @@ -15,47 +14,41 @@ import java.util.*; /** - * Illustrates use of the {@link MultiResolutionPath} shape, which adapts its complexity as the path's distance frome - * the eye point changes. + * Illustrates use of the {@link MultiResolutionPath} shape, which adapts its complexity as the path's distance from the + * eye point changes. *

* Also illustrates the use of the "show positions" feature of {@link Path}. * * @author tag * @version $Id: MultiResPath.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class MultiResPath extends ApplicationTemplate -{ +public class MultiResPath extends ApplicationTemplate { + // Specify several Paths, each with large numbers of positions. protected static final int NUM_POSITIONS = 108000; protected static final double SPEED = 90 / Earth.WGS84_EQUATORIAL_RADIUS; // meters per second to radians - protected static final Position[] ORIGIN = new Position[] - { - Position.fromDegrees(40.2377, -105.6480, 200), - Position.fromDegrees(41.2625, -105.6503, 200), - Position.fromDegrees(42.2285, -105.6169, 200), - Position.fromDegrees(43.2019, -105.6467, 200), - Position.fromDegrees(44.2414, -105.6911, 200), - }; - - public static class AppFrame extends ApplicationTemplate.AppFrame - { - public AppFrame() - { + protected static final Position[] ORIGIN = new Position[]{ + Position.fromDegrees(40.2377, -105.6480, 200), + Position.fromDegrees(41.2625, -105.6503, 200), + Position.fromDegrees(42.2285, -105.6169, 200), + Position.fromDegrees(43.2019, -105.6467, 200), + Position.fromDegrees(44.2414, -105.6911, 200),}; + + public static class AppFrame extends ApplicationTemplate.AppFrame { + + public AppFrame() { super(true, true, false); makeMany(); } - protected void makeMany() - { - for (Position pos : ORIGIN) - { + protected void makeMany() { + for (Position pos : ORIGIN) { this.addShape(pos); } } - protected void addShape(Position origin) - { + protected void addShape(Position origin) { int altitudeMode = WorldWind.RELATIVE_TO_GROUND; LatLon location = new LatLon(origin); @@ -64,9 +57,8 @@ protected void addShape(Position origin) double distance = 60 * SPEED / 20; // seconds x radians per second // Create the Path positions. - List positions = new ArrayList(NUM_POSITIONS); - for (int i = 0; i < NUM_POSITIONS; i++) - { + List positions = new ArrayList<>(NUM_POSITIONS); + for (int i = 0; i < NUM_POSITIONS; i++) { Position position = new Position(location, altitude); positions.add(position); @@ -100,8 +92,7 @@ protected void addShape(Position origin) } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind UAVPath Test", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/PathPositionColors.java b/src/gov/nasa/worldwindx/examples/PathPositionColors.java index 5887ff6dd7..6ef2d4d932 100644 --- a/src/gov/nasa/worldwindx/examples/PathPositionColors.java +++ b/src/gov/nasa/worldwindx/examples/PathPositionColors.java @@ -54,8 +54,7 @@ public AppFrame() // Create a path with the specified positions that follows the terrain and draws a point at each position. Path path = new Path(pathPositions); - path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); - path.setFollowTerrain(true); + path.setSurfacePath(true); path.setShowPositions(true); path.setShowPositionsScale(3); diff --git a/src/gov/nasa/worldwindx/examples/Paths.java b/src/gov/nasa/worldwindx/examples/Paths.java index 29554f701a..d6165a34c4 100644 --- a/src/gov/nasa/worldwindx/examples/Paths.java +++ b/src/gov/nasa/worldwindx/examples/Paths.java @@ -12,6 +12,7 @@ import gov.nasa.worldwind.render.*; import gov.nasa.worldwind.render.markers.*; import gov.nasa.worldwind.util.*; +import java.awt.Color; import java.util.*; @@ -36,7 +37,7 @@ public AppFrame() { // Create and set an attribute bundle. ShapeAttributes attrs = new BasicShapeAttributes(); - attrs.setOutlineMaterial(new Material(WWUtil.makeRandomColor(null))); + attrs.setOutlineMaterial(new Material(Color.YELLOW)); attrs.setOutlineWidth(2d); // Create a path, set some of its properties and set its attributes. @@ -50,6 +51,13 @@ public AppFrame() { path.setPathType(AVKey.GREAT_CIRCLE); layer.addRenderable(path); + // Create a path that follows the terrain + path = new Path(pathPositions); + path.setAttributes(attrs); + path.setVisible(true); + path.setSurfacePath(true); + layer.addRenderable(path); + // Create a path that uses all default values. pathPositions = new ArrayList<>(); pathPositions.add(Position.fromDegrees(28, -104, 1e4)); @@ -69,8 +77,8 @@ public AppFrame() { path.setPathType(AVKey.LINEAR); attrs = new BasicShapeAttributes(); - attrs.setOutlineMaterial(new Material(WWUtil.makeRandomColor(null))); - attrs.setInteriorMaterial(new Material(WWUtil.makeRandomColor(null))); + attrs.setOutlineMaterial(new Material(Color.BLUE)); + attrs.setInteriorMaterial(new Material(Color.RED)); attrs.setOutlineWidth(2); path.setAttributes(attrs); @@ -79,7 +87,7 @@ public AppFrame() { // Add the layer to the model. insertBeforeCompass(getWwd(), layer); - List markers = new ArrayList(1); + List markers = new ArrayList<>(1); markers.add(new BasicMarker(Position.fromDegrees(90, 0), new BasicMarkerAttributes())); MarkerLayer markerLayer = new MarkerLayer(); markerLayer.setMarkers(markers); diff --git a/src/gov/nasa/worldwindx/examples/ShapeEditing.java b/src/gov/nasa/worldwindx/examples/ShapeEditing.java index b339e2fe06..4a1b26e6aa 100644 --- a/src/gov/nasa/worldwindx/examples/ShapeEditing.java +++ b/src/gov/nasa/worldwindx/examples/ShapeEditing.java @@ -214,8 +214,7 @@ public AppFrame() positions.add(Position.fromDegrees(-90, 180)); positions.add(Position.fromDegrees(90, 180)); Path antiMeridian = new Path(positions); - antiMeridian.setFollowTerrain(true); - antiMeridian.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); + antiMeridian.setSurfacePath(true); ShapeAttributes antiMeridianAttributes = new BasicShapeAttributes(); shapeAttributes.setOutlineMaterial(Material.WHITE); antiMeridian.setAttributes(antiMeridianAttributes); diff --git a/src/gov/nasa/worldwindx/examples/Shapes.java b/src/gov/nasa/worldwindx/examples/Shapes.java index b43a6526ce..31f673d3cf 100644 --- a/src/gov/nasa/worldwindx/examples/Shapes.java +++ b/src/gov/nasa/worldwindx/examples/Shapes.java @@ -32,36 +32,36 @@ * @version $Id: Shapes.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class Shapes { - + private static class Info { - + private final Object object; private final String name; - + public Info(String name, Object object) { this.object = object; this.name = name; } } - + @SuppressWarnings("unchecked") protected static class AppFrame extends JFrame { - + private Dimension canvasSize = new Dimension(800, 600); private ApplicationTemplate.AppPanel wwjPanel; private RenderableLayer layer = new RenderableLayer(); private TextRenderer textRenderer = new TextRenderer(java.awt.Font.decode("Arial-Plain-13"), true, false); - + public AppFrame() { // Create the WorldWindow. this.wwjPanel = new ApplicationTemplate.AppPanel(this.canvasSize, true); this.wwjPanel.setPreferredSize(canvasSize); - + ApplicationTemplate.insertBeforePlacenames(this.wwjPanel.getWwd(), layer); - + JPanel shapesPanel = makeShapeSelectionPanel(); shapesPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - + JPanel attrsPanel = makeAttributesPanel(); attrsPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); @@ -71,7 +71,7 @@ public AppFrame() { JPanel p = new JPanel(new BorderLayout(6, 6)); p.add(attrsPanel, BorderLayout.CENTER); controlPanel.add(p, BorderLayout.SOUTH); - + this.getContentPane().add(wwjPanel, BorderLayout.CENTER); this.getContentPane().add(controlPanel, BorderLayout.WEST); this.pack(); @@ -85,7 +85,7 @@ public AppFrame() { int y = parentLocation.y + (parentSize.height - prefSize.height) / 2; this.setLocation(x, y); this.setResizable(true); - + wwjPanel.getWwd().addRenderingListener((RenderingEvent event) -> { if (!event.getStage().equals(RenderingEvent.BEFORE_BUFFER_SWAP)) { return; @@ -102,9 +102,9 @@ public AppFrame() { // Enable dragging and other selection responses this.setupSelection(); } - + private Renderable currentShape; - + private String currentPathColor = "Yellow"; private int currentPathOpacity = 10; private double currentPathWidth = 1; @@ -114,36 +114,36 @@ public AppFrame() { private float currentOffset = 0; private int currentTerrainConformance = 10; private int currentNumSubsegments = 10; - + private String currentBorderColor = "Yellow"; private double currentBorderWidth = 1; private int currentBorderOpacity = 10; private String currentBorderStyle = "Solid"; - + private String currentInteriorColor = "Yellow"; private int currentInteriorOpacity = 10; private String currentInteriorStyle = "Solid"; - + private ArrayList onTerrainOnlyItems = new ArrayList<>(); private ArrayList offTerrainOnlyItems = new ArrayList<>(); - + private void update() { onTerrainOnlyItems.forEach((c) -> { c.setEnabled(currentFollowTerrain); }); - + offTerrainOnlyItems.forEach((c) -> { c.setEnabled(!currentFollowTerrain); }); - + if (this.currentShape instanceof SurfaceShape) { SurfaceShape shape = (SurfaceShape) currentShape; ShapeAttributes attr = shape.getAttributes(); - + if (attr == null) { attr = new BasicShapeAttributes(); } - + if (!currentBorderStyle.equals("None")) { float alpha = currentBorderOpacity >= 10 ? 1f : currentBorderOpacity <= 0 ? 0f : currentBorderOpacity / 10f; @@ -164,7 +164,7 @@ private void update() { default: break; } - + attr.setDrawOutline(true); attr.setOutlineMaterial(new Material(color)); attr.setOutlineOpacity(alpha); @@ -172,7 +172,7 @@ private void update() { } else { attr.setDrawOutline(false); } - + if (!currentInteriorStyle.equals("None")) { float alpha = currentInteriorOpacity >= 10 ? 1f : currentInteriorOpacity <= 0 ? 0f : currentInteriorOpacity / 10f; @@ -193,14 +193,14 @@ private void update() { default: break; } - + attr.setInteriorMaterial(new Material(color)); attr.setInteriorOpacity(alpha); attr.setDrawInterior(true); } else { attr.setDrawInterior(false); } - + shape.setAttributes(attr); } else { float alpha = currentPathOpacity >= 10 ? 1f : currentPathOpacity <= 0 ? 0f @@ -222,7 +222,7 @@ private void update() { default: break; } - + if (currentShape instanceof Path) { Path path = (Path) currentShape; path.setFollowTerrain(currentFollowTerrain); @@ -233,7 +233,7 @@ private void update() { } path.setTerrainConformance(currentTerrainConformance); path.setNumSubsegments(currentNumSubsegments); - + if (currentPathType.equalsIgnoreCase("linear")) { path.setPathType(AVKey.LINEAR); } else if (currentPathType.equalsIgnoreCase("rhumb line")) { @@ -241,13 +241,14 @@ private void update() { } else { path.setPathType(AVKey.GREAT_CIRCLE); } - + path.setOffset(currentOffset); - + BasicShapeAttributes attrs = new BasicShapeAttributes(); attrs.setOutlineMaterial(new Material(color)); attrs.setInteriorMaterial(new Material(color)); attrs.setOutlineWidth(currentPathWidth); + attrs.setOutlineOpacity(alpha); if (currentPathStyle.equals("Dash")) { attrs.setOutlineStippleFactor(5); attrs.setOutlineStipplePattern((short) 0xAAAA); @@ -263,16 +264,16 @@ private void update() { } this.wwjPanel.getWwd().redraw(); } - + private Info[] buildSurfaceShapes() { LatLon position = new LatLon(Angle.fromDegrees(38), Angle.fromDegrees(-105)); - + ArrayList surfaceLinePositions = new ArrayList<>(); surfaceLinePositions.add(position); surfaceLinePositions.add(LatLon.fromDegrees(39, -104)); surfaceLinePositions.add(LatLon.fromDegrees(39, -105)); surfaceLinePositions.add(position); - + return new Info[]{ new Info("Circle", new SurfaceCircle(position, 100e3)), new Info("Ellipse", new SurfaceEllipse(position, 100e3, 90e3, Angle.ZERO)), @@ -281,33 +282,33 @@ private Info[] buildSurfaceShapes() { new Info("Sector", new SurfaceSector(Sector.fromDegrees(38, 40, -105, -103))), new Info("Polygon", new SurfacePolygon(surfaceLinePositions)),}; } - + private Info[] buildFreeShapes() { double elevation = 10e3; ArrayList positions = new ArrayList<>(); positions.add(new Position(Angle.fromDegrees(37.8484), Angle.fromDegrees(-119.9754), elevation)); positions.add(new Position(Angle.fromDegrees(39.3540), Angle.fromDegrees(-110.1526), elevation)); positions.add(new Position(Angle.fromDegrees(38.3540), Angle.fromDegrees(-100.1526), elevation)); - + ArrayList positions2 = new ArrayList<>(); positions2.add(new Position(Angle.fromDegrees(0), Angle.fromDegrees(-150), elevation)); positions2.add(new Position(Angle.fromDegrees(25), Angle.fromDegrees(-75), elevation)); positions2.add(new Position(Angle.fromDegrees(50), Angle.fromDegrees(0), elevation)); - + ArrayList positions3 = new ArrayList<>(); for (double lat = 42, lon = -100; lat <= 45; lat += .1, lon += .1) { positions3.add(new Position(Angle.fromDegrees(lat), Angle.fromDegrees(lon), elevation)); } - + ArrayList positions4 = new ArrayList<>(); positions4.add(new Position(Angle.fromDegrees(90), Angle.fromDegrees(-110), elevation)); positions4.add(new Position(Angle.fromDegrees(-90), Angle.fromDegrees(-110), elevation)); - + ArrayList positions5 = new ArrayList<>(); for (int i = 0; i < 100; i++) { positions5.add(Position.fromDegrees(38.0 + i * 0.0001, 30.0 + i * 0.0001, 1000.0 + i * 5.0)); } - + Info[] infos = new Info[]{ new Info("Short Path", new Path(positions)), new Info("Long Path", new Path(positions2)), @@ -317,10 +318,10 @@ private Info[] buildFreeShapes() { new Info("Quad", new Quadrilateral(Sector.fromDegrees(38, 40, -104, -105), elevation)), new Info("None", null) }; - + return infos; } - + private JPanel makeShapeSelectionPanel() { final Info[] surfaceShapeInfos = this.buildSurfaceShapes(); GridLayout layout = new GridLayout(surfaceShapeInfos.length, 1); @@ -339,7 +340,7 @@ private JPanel makeShapeSelectionPanel() { } } ssPanel.setBorder(this.createTitleBorder("Surface Shapes")); - + final Info[] freeShapeInfos = this.buildFreeShapes(); layout = new GridLayout(freeShapeInfos.length, 1); JPanel fsPanel = new JPanel(layout); @@ -356,37 +357,37 @@ private JPanel makeShapeSelectionPanel() { } } fsPanel.setBorder(this.createTitleBorder("Path Shapes")); - + JPanel shapesPanel = new JPanel(new GridLayout(1, 2, 8, 1)); shapesPanel.add(fsPanel); shapesPanel.add(ssPanel); - + return shapesPanel; } - + private Border createTitleBorder(String title) { TitledBorder b = BorderFactory.createTitledBorder(title); return new CompoundBorder(b, BorderFactory.createEmptyBorder(10, 10, 10, 10)); } - + private JPanel makeAttributesPanel() { JPanel panel = new JPanel(new GridLayout(1, 2, 8, 8)); panel.add(this.makePathAttributesPanel()); panel.add(this.makeInteriorAttributesPanel()); - + return panel; } - + private JPanel makePathAttributesPanel() { JPanel outerPanel = new JPanel(new BorderLayout(6, 6)); outerPanel.setBorder(this.createTitleBorder("Path Attributes")); - + GridLayout nameLayout = new GridLayout(0, 1, 6, 6); JPanel namePanel = new JPanel(nameLayout); - + GridLayout valueLayout = new GridLayout(0, 1, 6, 6); JPanel valuePanel = new JPanel(valueLayout); - + namePanel.add(new JLabel("Follow Terrain")); JCheckBox ckb = new JCheckBox(); ckb.setSelected(currentFollowTerrain); @@ -395,9 +396,9 @@ private JPanel makePathAttributesPanel() { update(); }); valuePanel.add(ckb); - + JLabel label; - + namePanel.add(label = new JLabel("Conformance")); int[] values = new int[]{1, 2, 4, 8, 10, 15, 20, 30, 40, 50}; String[] strings = new String[values.length]; @@ -415,7 +416,7 @@ private JPanel makePathAttributesPanel() { }); sp.setValue(Integer.toString(currentTerrainConformance) + " pixels"); valuePanel.add(sp); - + namePanel.add(label = new JLabel("Subsegments")); sp = new JSpinner(new SpinnerListModel(new String[]{"1", "2", "5", "10", "20", "40", "50"})); offTerrainOnlyItems.add(label); @@ -427,7 +428,7 @@ private JPanel makePathAttributesPanel() { }); sp.setValue(Integer.toString(currentNumSubsegments)); valuePanel.add(sp); - + namePanel.add(new JLabel("Type")); final JComboBox cb = new JComboBox(new String[]{"Great Circle", "Linear", "Rhumb Line"}); cb.addActionListener((ActionEvent actionEvent) -> { @@ -436,7 +437,7 @@ private JPanel makePathAttributesPanel() { }); cb.setSelectedItem("Great Circle"); valuePanel.add(cb); - + namePanel.add(new JLabel("Style")); final JComboBox cb1 = new JComboBox(new String[]{"None", "Solid", "Dash"}); cb1.addActionListener((ActionEvent actionEvent) -> { @@ -445,7 +446,7 @@ private JPanel makePathAttributesPanel() { }); cb1.setSelectedItem("Solid"); valuePanel.add(cb1); - + namePanel.add(new JLabel("Width")); sp = new JSpinner(new SpinnerNumberModel(this.currentPathWidth, 1d, 10d, 1d)); sp.addChangeListener((ChangeEvent changeEvent) -> { @@ -454,7 +455,7 @@ private JPanel makePathAttributesPanel() { }); sp.setValue(currentPathWidth); valuePanel.add(sp); - + namePanel.add(new JLabel("Color")); JComboBox cb2 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb2.setSelectedItem(currentPathColor); @@ -463,7 +464,7 @@ private JPanel makePathAttributesPanel() { update(); }); valuePanel.add(cb2); - + namePanel.add(new JLabel("Opacity")); sp = new JSpinner(new SpinnerNumberModel(this.currentPathOpacity, 0, 10, 1)); sp.addChangeListener((ChangeEvent changeEvent) -> { @@ -471,7 +472,7 @@ private JPanel makePathAttributesPanel() { update(); }); valuePanel.add(sp); - + namePanel.add(new JLabel("Offset")); sp = new JSpinner( new SpinnerListModel(new String[]{"0", "10", "100", "1000", "10000", "100000", "1000000"})); @@ -481,23 +482,23 @@ private JPanel makePathAttributesPanel() { }); sp.setValue("0"); valuePanel.add(sp); - + outerPanel.add(namePanel, BorderLayout.WEST); outerPanel.add(valuePanel, BorderLayout.CENTER); - + return outerPanel; } - + private JPanel makeInteriorAttributesPanel() { JPanel outerPanel = new JPanel(new BorderLayout(6, 6)); outerPanel.setBorder(this.createTitleBorder("Surface Attributes")); - + GridLayout nameLayout = new GridLayout(0, 1, 6, 6); JPanel namePanel = new JPanel(nameLayout); - + GridLayout valueLayout = new GridLayout(0, 1, 6, 6); JPanel valuePanel = new JPanel(valueLayout); - + namePanel.add(new JLabel("Style")); final JComboBox cb1 = new JComboBox(new String[]{"None", "Solid"}); cb1.addActionListener((ActionEvent actionEvent) -> { @@ -506,7 +507,7 @@ private JPanel makeInteriorAttributesPanel() { }); cb1.setSelectedItem("Solid"); valuePanel.add(cb1); - + namePanel.add(new JLabel("Opacity")); JSpinner sp = new JSpinner(new SpinnerNumberModel(this.currentBorderOpacity, 0, 10, 1)); sp.addChangeListener((ChangeEvent changeEvent) -> { @@ -514,7 +515,7 @@ private JPanel makeInteriorAttributesPanel() { update(); }); valuePanel.add(sp); - + namePanel.add(new JLabel("Color")); final JComboBox cb2 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb2.setSelectedItem(currentInteriorColor); @@ -523,7 +524,7 @@ private JPanel makeInteriorAttributesPanel() { update(); }); valuePanel.add(cb2); - + namePanel.add(new JLabel("Border")); final JComboBox cb5 = new JComboBox(new String[]{"None", "Solid"}); cb5.addActionListener((ActionEvent actionEvent) -> { @@ -532,7 +533,7 @@ private JPanel makeInteriorAttributesPanel() { }); cb5.setSelectedItem("Solid"); valuePanel.add(cb5); - + namePanel.add(new JLabel("Border Width")); sp = new JSpinner(new SpinnerNumberModel(this.currentBorderWidth, 1d, 10d, 1d)); sp.addChangeListener((ChangeEvent changeEvent) -> { @@ -541,7 +542,7 @@ private JPanel makeInteriorAttributesPanel() { }); sp.setValue(currentBorderWidth); valuePanel.add(sp); - + namePanel.add(new JLabel("Border Color")); JComboBox cb4 = new JComboBox(new String[]{"Red", "Green", "Blue", "Yellow"}); cb4.setSelectedItem(currentBorderColor); @@ -550,7 +551,7 @@ private JPanel makeInteriorAttributesPanel() { update(); }); valuePanel.add(cb4); - + namePanel.add(new JLabel("Border Opacity")); sp = new JSpinner(new SpinnerNumberModel(this.currentBorderOpacity, 0, 10, 1)); sp.addChangeListener((ChangeEvent changeEvent) -> { @@ -558,18 +559,18 @@ private JPanel makeInteriorAttributesPanel() { update(); }); valuePanel.add(sp); - + outerPanel.add(namePanel, BorderLayout.WEST); outerPanel.add(valuePanel, BorderLayout.CENTER); - + return outerPanel; } - + private void setupSelection() { this.wwjPanel.getWwd().addSelectListener(new SelectListener() { private WWIcon lastToolTipIcon = null; private final BasicDragger dragger = new BasicDragger(AppFrame.this.wwjPanel.getWwd()); - + @Override public void selected(SelectEvent event) { // Have hover selections show a picked icon's tool tip. @@ -612,9 +613,9 @@ else if (event.getEventAction().equals(SelectEvent.DRAG_END) }); } } - + private static final String APP_NAME = "WorldWind Shapes"; - + static { if (Configuration.isMacOS()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); @@ -622,7 +623,7 @@ else if (event.getEventAction().equals(SelectEvent.DRAG_END) System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); } } - + public static void main(String[] args) { try { AppFrame frame = new AppFrame(); diff --git a/src/gov/nasa/worldwindx/examples/SurfaceImages.java b/src/gov/nasa/worldwindx/examples/SurfaceImages.java index 8e6fcc3855..1a05c12a67 100644 --- a/src/gov/nasa/worldwindx/examples/SurfaceImages.java +++ b/src/gov/nasa/worldwindx/examples/SurfaceImages.java @@ -51,18 +51,20 @@ public AppFrame() { LatLon.fromDegrees(38.1321, -105.1674) ))); Path boundary = new Path(si1.getCorners(), 0); - boundary.setFollowTerrain(true); + boundary.setSurfacePath(true); boundary.setPathType(AVKey.RHUMB_LINE); var attrs = new BasicShapeAttributes(); attrs.setOutlineMaterial(new Material(new Color(0, 255, 0))); boundary.setAttributes(attrs); + boundary.makeClosed(); Path boundary2 = new Path(si2.getCorners(), 0); - boundary2.setFollowTerrain(true); + boundary2.setSurfacePath(true); boundary2.setPathType(AVKey.RHUMB_LINE); attrs = new BasicShapeAttributes(); attrs.setOutlineMaterial(new Material(new Color(0, 255, 0))); boundary2.setAttributes(attrs); + boundary2.makeClosed(); RenderableLayer layer = new RenderableLayer(); layer.setName("Surface Images"); diff --git a/src/gov/nasa/worldwindx/examples/TerrainIntersections.java b/src/gov/nasa/worldwindx/examples/TerrainIntersections.java index bc4c0fe813..7e574fab9b 100644 --- a/src/gov/nasa/worldwindx/examples/TerrainIntersections.java +++ b/src/gov/nasa/worldwindx/examples/TerrainIntersections.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.examples; import gov.nasa.worldwind.*; @@ -41,21 +40,27 @@ * @author tag * @version $Id: TerrainIntersections.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class TerrainIntersections extends ApplicationTemplate -{ - /** The width and height in degrees of the grid used to calculate intersections. */ +public class TerrainIntersections extends ApplicationTemplate { + + /** + * The width and height in degrees of the grid used to calculate intersections. + */ protected static final Angle GRID_RADIUS = Angle.fromDegrees(0.05); - /** The number of cells along each edge of the grid. */ + /** + * The number of cells along each edge of the grid. + */ protected static final int GRID_DIMENSION = 10; // cells per side - /** The desired terrain resolution to use in the intersection calculations. */ + /** + * The desired terrain resolution to use in the intersection calculations. + */ protected static final Double TARGET_RESOLUTION = 10d; // meters, or null for globe's highest resolution protected static final int NUM_THREADS = 4; // set to 1 to run synchronously - public static class AppFrame extends ApplicationTemplate.AppFrame - { + public static class AppFrame extends ApplicationTemplate.AppFrame { + private static final Cursor WaitCursor = new Cursor(Cursor.WAIT_CURSOR); protected HighResolutionTerrain terrain; @@ -71,13 +76,12 @@ public static class AppFrame extends ApplicationTemplate.AppFrame protected long startTime, endTime; // for reporting calculation duration protected Position previousCurrentPosition; - public AppFrame() - { + public AppFrame() { super(true, true, false); // Create a thread pool. this.threadPool = new ThreadPoolExecutor(NUM_THREADS, NUM_THREADS, 200, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue()); + new LinkedBlockingQueue<>()); // Display a progress bar. this.progressBar = new JProgressBar(0, 100); @@ -102,23 +106,22 @@ public AppFrame() this.getWwd().getModel().getLayers().add(this.sightLinesLayer); // Set up a mouse handler to generate a grid and start intersection calculations when the user shift-clicks. - this.getWwd().getInputHandler().addMouseListener(new MouseAdapter() - { - public void mouseClicked(MouseEvent mouseEvent) - { + this.getWwd().getInputHandler().addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent mouseEvent) { // Control-Click cancels any currently running operation. - if ((mouseEvent.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) != 0) - { - if (calculationDispatchThread != null && calculationDispatchThread.isAlive()) + if ((mouseEvent.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) != 0) { + if (calculationDispatchThread != null && calculationDispatchThread.isAlive()) { calculationDispatchThread.interrupt(); + } return; } // Alt-Click repeats the most recent calculations. - if ((mouseEvent.getModifiersEx() & InputEvent.ALT_DOWN_MASK) != 0) - { - if (previousCurrentPosition == null) + if ((mouseEvent.getModifiersEx() & InputEvent.ALT_DOWN_MASK) != 0) { + if (previousCurrentPosition == null) { return; + } mouseEvent.consume(); // tell the rest of WW that this event has been processed @@ -127,45 +130,35 @@ public void mouseClicked(MouseEvent mouseEvent) } // Perform the intersection tests in response to Shift-Click. - if ((mouseEvent.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) == 0) + if ((mouseEvent.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) == 0) { return; + } mouseEvent.consume(); // tell the rest of WW that this event has been processed final Position pos = getWwd().getCurrentPosition(); - if (pos == null) + if (pos == null) { return; + } computeAndShowIntersections(pos); } }); } - protected void computeAndShowIntersections(final Position curPos) - { + protected void computeAndShowIntersections(final Position curPos) { this.previousCurrentPosition = curPos; - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - setCursor(WaitCursor); - } + SwingUtilities.invokeLater(() -> { + setCursor(WaitCursor); }); // Dispatch the calculation threads in a separate thread to avoid locking up the user interface. - this.calculationDispatchThread = new Thread(new Runnable() - { - public void run() - { - try - { - performIntersectionTests(curPos); - } - catch (InterruptedException e) - { - System.out.println("Operation was interrupted"); - } + this.calculationDispatchThread = new Thread(() -> { + try { + performIntersectionTests(curPos); + } catch (InterruptedException e) { + System.out.println("Operation was interrupted"); } }); @@ -173,72 +166,65 @@ public void run() } // Create containers to hold the intersection points and the lines emanating from the center. - protected List firstIntersectionPositions = new ArrayList(); - protected List sightLines = new ArrayList(GRID_DIMENSION * GRID_DIMENSION); + protected List firstIntersectionPositions = new ArrayList<>(); + protected List sightLines = new ArrayList<>(GRID_DIMENSION * GRID_DIMENSION); // Make the picked location's position and model-coordinate point available to all methods. protected Position referencePosition; protected Vec4 referencePoint; // This is a collection of synchronized accessors to the list updated during the calculations. - - protected synchronized void addIntersectionPosition(Position position) - { + protected synchronized void addIntersectionPosition(Position position) { this.firstIntersectionPositions.add(position); } - protected synchronized void addSightLine(Position positionA, Position positionB) - { - this.sightLines.add(new Position[] {positionA, positionB}); + protected synchronized void addSightLine(Position positionA, Position positionB) { + this.sightLines.add(new Position[]{positionA, positionB}); } - protected synchronized int getSightlinesSize() - { + protected synchronized int getSightlinesSize() { return this.sightLines.size(); } private long lastTime = System.currentTimeMillis(); - /** Keeps the progress meter current. When calculations are complete, displays the results. */ - protected synchronized void updateProgress() - { + /** + * Keeps the progress meter current. When calculations are complete, displays the results. + */ + protected synchronized void updateProgress() { // Update the progress bar only once every 250 milliseconds to avoid stealing time from calculations. - if (this.sightLines.size() >= this.numGridPoints) + if (this.sightLines.size() >= this.numGridPoints) { endTime = System.currentTimeMillis(); - else if (System.currentTimeMillis() < this.lastTime + 250) + } else if (System.currentTimeMillis() < this.lastTime + 250) { return; + } this.lastTime = System.currentTimeMillis(); // On the EDT, update the progress bar and if calculations are complete, update the WorldWindow. - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - int progress = (int) (100d * getSightlinesSize() / (double) numGridPoints); - progressBar.setValue(progress); - - if (progress >= 100) - { - setCursor(Cursor.getDefaultCursor()); - progressBar.setString((endTime - startTime) + " ms"); - showResults(); - System.out.printf("Calculation time %d milliseconds\n", endTime - startTime); - } + SwingUtilities.invokeLater(() -> { + int progress = (int) (100d * getSightlinesSize() / (double) numGridPoints); + progressBar.setValue(progress); + + if (progress >= 100) { + setCursor(Cursor.getDefaultCursor()); + progressBar.setString((endTime - startTime) + " ms"); + showResults(); + System.out.printf("Calculation time %d milliseconds\n", endTime - startTime); } }); } - /** Updates the WorldWind model with the new intersection locations and sight lines. */ - protected void showResults() - { + /** + * Updates the WorldWind model with the new intersection locations and sight lines. + */ + protected void showResults() { this.showIntersections(firstIntersectionPositions); this.showSightLines(sightLines); // this.showIntersectingTiles(this.grid, this.referencePosition); this.getWwd().redraw(); } - protected void performIntersectionTests(final Position curPos) throws InterruptedException - { + protected void performIntersectionTests(final Position curPos) throws InterruptedException { // Clear the results lists when the user selects a new location. this.firstIntersectionPositions.clear(); this.sightLines.clear(); @@ -249,8 +235,8 @@ protected void performIntersectionTests(final Position curPos) throws Interrupte // Form the grid. double gridRadius = GRID_RADIUS.degrees; Sector sector = Sector.fromDegrees( - curPos.getLatitude().degrees - gridRadius, curPos.getLatitude().degrees + gridRadius, - curPos.getLongitude().degrees - gridRadius, curPos.getLongitude().degrees + gridRadius); + curPos.getLatitude().degrees - gridRadius, curPos.getLatitude().degrees + gridRadius, + curPos.getLongitude().degrees - gridRadius, curPos.getLongitude().degrees + gridRadius); this.grid = buildGrid(sector, height, GRID_DIMENSION, GRID_DIMENSION); this.numGridPoints = grid.size(); @@ -263,18 +249,13 @@ protected void performIntersectionTests(final Position curPos) throws Interrupte // // calculations. It will incur extra overhead otherwise. The normal intersection calculations // // cause the same caching, making subsequent calculations on the same area faster. // this.preCache(grid, this.referencePosition); - // On the EDT, show the grid. - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - progressBar.setValue(0); - progressBar.setString(null); - clearLayers(); - showGrid(grid, referencePosition); - getWwd().redraw(); - } + SwingUtilities.invokeLater(() -> { + progressBar.setValue(0); + progressBar.setString(null); + clearLayers(); + showGrid(grid, referencePosition); + getWwd().redraw(); }); // Perform the intersection calculations. @@ -282,10 +263,11 @@ public void run() for (Position gridPos : this.grid) // for each grid point. { //noinspection ConstantConditions - if (NUM_THREADS > 0) + if (NUM_THREADS > 0) { this.threadPool.execute(new Intersector(gridPos)); - else + } else { performIntersection(gridPos); + } } } @@ -296,25 +278,22 @@ public void run() * * @throws InterruptedException if the operation is interrupted. */ - protected void performIntersection(Position gridPosition) throws InterruptedException - { + protected void performIntersection(Position gridPosition) throws InterruptedException { // Intersect the line between this grid point and the selected position. Intersection[] intersections = this.terrain.intersect(this.referencePosition, gridPosition); - if (intersections == null || intersections.length == 0) - { + if (intersections == null || intersections.length == 0) { // No intersection, so the line goes from the center to the grid point. - this.sightLines.add(new Position[] {this.referencePosition, gridPosition}); + this.sightLines.add(new Position[]{this.referencePosition, gridPosition}); return; } // Only the first intersection is shown. Vec4 iPoint = intersections[0].getIntersectionPoint(); Vec4 gPoint = terrain.getSurfacePoint(gridPosition.getLatitude(), gridPosition.getLongitude(), - gridPosition.getAltitude()); + gridPosition.getAltitude()); // Check to see whether the intersection is beyond the grid point. - if (iPoint.distanceTo3(this.referencePoint) >= gPoint.distanceTo3(this.referencePoint)) - { + if (iPoint.distanceTo3(this.referencePoint) >= gPoint.distanceTo3(this.referencePoint)) { // Intersection is beyond the grid point; the line goes from the center to the grid point. this.addSightLine(this.referencePosition, gridPosition); return; @@ -332,45 +311,40 @@ protected void performIntersection(Position gridPosition) throws InterruptedExce this.updateProgress(); } - /** Inner {@link Runnable} to perform a single line/terrain intersection calculation. */ - protected class Intersector implements Runnable - { + /** + * Inner {@link Runnable} to perform a single line/terrain intersection calculation. + */ + protected class Intersector implements Runnable { + protected final Position gridPosition; - public Intersector(Position gridPosition) - { + public Intersector(Position gridPosition) { this.gridPosition = gridPosition; } - public void run() - { - try - { + @Override + public void run() { + try { performIntersection(this.gridPosition); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { e.printStackTrace(); } } } - protected List buildGrid(Sector sector, double height, int nLatCells, int nLonCells) - { - List grid = new ArrayList((nLatCells + 1) * (nLonCells + 1)); + protected List buildGrid(Sector sector, double height, int nLatCells, int nLonCells) { + List grid = new ArrayList<>((nLatCells + 1) * (nLonCells + 1)); double dLat = sector.getDeltaLatDegrees() / nLatCells; double dLon = sector.getDeltaLonDegrees() / nLonCells; - for (int j = 0; j <= nLatCells; j++) - { - double lat = j == nLatCells ? - sector.getMaxLatitude().degrees : sector.getMinLatitude().degrees + j * dLat; + for (int j = 0; j <= nLatCells; j++) { + double lat = j == nLatCells + ? sector.getMaxLatitude().degrees : sector.getMinLatitude().degrees + j * dLat; - for (int i = 0; i <= nLonCells; i++) - { - double lon = i == nLonCells ? - sector.getMaxLongitude().degrees : sector.getMinLongitude().degrees + i * dLon; + for (int i = 0; i <= nLonCells; i++) { + double lon = i == nLonCells + ? sector.getMaxLongitude().degrees : sector.getMinLongitude().degrees + i * dLon; grid.add(Position.fromDegrees(lat, lon, height)); } @@ -379,8 +353,7 @@ protected List buildGrid(Sector sector, double height, int nLatCells, return grid; } - protected void preCache(List grid, Position centerPosition) throws InterruptedException - { + protected void preCache(List grid, Position centerPosition) throws InterruptedException { // Pre-cache the tiles that will be needed for the intersection calculations. double n = 0; final long start = System.currentTimeMillis(); @@ -389,38 +362,28 @@ protected void preCache(List grid, Position centerPosition) throws Int final double progress = 100 * (n++ / grid.size()); terrain.cacheIntersectingTiles(centerPosition, gridPos); - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - progressBar.setValue((int) progress); - progressBar.setString(null); - } + SwingUtilities.invokeLater(() -> { + progressBar.setValue((int) progress); + progressBar.setString(null); }); } - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - progressBar.setValue(100); - } + SwingUtilities.invokeLater(() -> { + progressBar.setValue(100); }); long end = System.currentTimeMillis(); System.out.printf("Pre-caching time %d milliseconds, cache usage %f, tiles %d\n", end - start, - terrain.getCacheUsage(), terrain.getNumCacheEntries()); + terrain.getCacheUsage(), terrain.getNumCacheEntries()); } - protected void clearLayers() - { + protected void clearLayers() { this.intersectionsLayer.removeAllRenderables(); this.sightLinesLayer.removeAllRenderables(); this.gridLayer.removeAllRenderables(); } - protected void showIntersections(List intersections) - { + protected void showIntersections(List intersections) { this.intersectionsLayer.removeAllRenderables(); // Display the intersections as CYAN points. @@ -430,8 +393,7 @@ protected void showIntersections(List intersections) intersectionPointAttributes.setScale(6d); intersectionPointAttributes.setUsePointAsDefaultImage(true); - for (Position p : intersections) - { + for (Position p : intersections) { PointPlacemark pm = new PointPlacemark(p); pm.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); pm.setAttributes(intersectionPointAttributes); @@ -440,8 +402,7 @@ protected void showIntersections(List intersections) } } - protected void showSightLines(List sightLines) - { + protected void showSightLines(List sightLines) { this.sightLinesLayer.removeAllRenderables(); // Display the sight lines as green lines. @@ -452,9 +413,8 @@ protected void showSightLines(List sightLines) lineAttributes.setOutlineMaterial(Material.GREEN); lineAttributes.setOutlineOpacity(0.6); - for (Position[] pp : sightLines) - { - List endPoints = new ArrayList(); + for (Position[] pp : sightLines) { + List endPoints = new ArrayList<>(); endPoints.add(pp[0]); endPoints.add(pp[1]); @@ -465,8 +425,7 @@ protected void showSightLines(List sightLines) } } - protected void showGridSightLines(List grid, Position cPos) - { + protected void showGridSightLines(List grid, Position cPos) { this.sightLinesLayer.removeAllRenderables(); // Display lines from the center to each grid point. @@ -477,9 +436,8 @@ protected void showGridSightLines(List grid, Position cPos) lineAttributes.setOutlineMaterial(Material.GREEN); lineAttributes.setOutlineOpacity(0.6); - for (Position p : grid) - { - List endPoints = new ArrayList(); + for (Position p : grid) { + List endPoints = new ArrayList<>(); endPoints.add(cPos); endPoints.add(new Position(p.getLatitude(), p.getLongitude(), 0)); @@ -490,8 +448,7 @@ protected void showGridSightLines(List grid, Position cPos) } } - protected void showGrid(List grid, Position cPos) - { + protected void showGrid(List grid, Position cPos) { this.gridLayer.removeAllRenderables(); // Display the grid points in yellow. @@ -501,8 +458,7 @@ protected void showGrid(List grid, Position cPos) gridPointAttributes.setScale(6d); gridPointAttributes.setUsePointAsDefaultImage(true); - for (Position p : grid) - { + for (Position p : grid) { PointPlacemark pm = new PointPlacemark(p); pm.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); pm.setAttributes(gridPointAttributes); @@ -514,8 +470,7 @@ protected void showGrid(List grid, Position cPos) showCenterPoint(cPos); } - protected void showCenterPoint(Position cPos) - { + protected void showCenterPoint(Position cPos) { // Display the center point in red. PointPlacemarkAttributes selectedLocationAttributes; selectedLocationAttributes = new PointPlacemarkAttributes(); @@ -532,8 +487,7 @@ protected void showCenterPoint(Position cPos) } } - public static void main(String[] args) - { + public static void main(String[] args) { // zoom to San Francisco downtown Configuration.setValue(AVKey.INITIAL_ALTITUDE, 34e3); Configuration.setValue(AVKey.INITIAL_LATITUDE, 37.9521d); diff --git a/src/gov/nasa/worldwindx/examples/TerrainProfiler.java b/src/gov/nasa/worldwindx/examples/TerrainProfiler.java index 82da365698..eda4e673f3 100644 --- a/src/gov/nasa/worldwindx/examples/TerrainProfiler.java +++ b/src/gov/nasa/worldwindx/examples/TerrainProfiler.java @@ -26,11 +26,11 @@ * @author tag * @version $Id: TerrainProfiler.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class TerrainProfiler extends ApplicationTemplate -{ +public class TerrainProfiler extends ApplicationTemplate { + @SuppressWarnings("unchecked") - public static class AppFrame extends ApplicationTemplate.AppFrame - { + public static class AppFrame extends ApplicationTemplate.AppFrame { + private String follow; private boolean showEyePosition; private boolean keepProportions; @@ -43,12 +43,10 @@ public static class AppFrame extends ApplicationTemplate.AppFrame private JCheckBox showEyeCheck; private TerrainProfileLayer tpl; - public AppFrame() - { + public AppFrame() { super(true, true, false); - try - { + try { // Add TerrainProfileLayer this.tpl = new TerrainProfileLayer(); this.tpl.setEventSource(this.getWwd()); @@ -66,40 +64,29 @@ public AppFrame() // Add control panel this.getControlPanel().add(makeControlPanel(), BorderLayout.SOUTH); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } - private JPanel makeControlPanel() - { + private JPanel makeControlPanel() { JPanel controlPanel = new JPanel(new GridLayout(0, 1, 0, 4)); // Show eye position check box JPanel buttonsPanel = new JPanel(new GridLayout(0, 2, 0, 0)); this.showEyeCheck = new JCheckBox("Show eye"); - this.showEyeCheck.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - showEyePosition = ((JCheckBox) actionEvent.getSource()).isSelected(); - update(); - } + this.showEyeCheck.addActionListener((ActionEvent actionEvent) -> { + showEyePosition = ((JCheckBox) actionEvent.getSource()).isSelected(); + update(); }); this.showEyeCheck.setSelected(this.showEyePosition); this.showEyeCheck.setEnabled(this.follow.equals(TerrainProfileLayer.FOLLOW_EYE)); buttonsPanel.add(this.showEyeCheck); // Keep proportions check box JCheckBox cbKeepProportions = new JCheckBox("Keep proportions"); - cbKeepProportions.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - keepProportions = ((JCheckBox) actionEvent.getSource()).isSelected(); - update(); - } + cbKeepProportions.addActionListener((ActionEvent actionEvent) -> { + keepProportions = ((JCheckBox) actionEvent.getSource()).isSelected(); + update(); }); cbKeepProportions.setSelected(this.keepProportions); buttonsPanel.add(cbKeepProportions); @@ -107,13 +94,9 @@ public void actionPerformed(ActionEvent actionEvent) // Zero based graph check box JPanel buttonsPanel2 = new JPanel(new GridLayout(0, 2, 0, 0)); JCheckBox cb = new JCheckBox("Zero based"); - cb.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - zeroBased = ((JCheckBox) actionEvent.getSource()).isSelected(); - update(); - } + cb.addActionListener((ActionEvent actionEvent) -> { + zeroBased = ((JCheckBox) actionEvent.getSource()).isSelected(); + update(); }); cb.setSelected(this.zeroBased); buttonsPanel2.add(new JLabel("")); // Dummy @@ -122,26 +105,23 @@ public void actionPerformed(ActionEvent actionEvent) // Dimension combo JPanel dimensionPanel = new JPanel(new GridLayout(0, 2, 0, 0)); dimensionPanel.add(new JLabel(" Dimension:")); - final JComboBox cbDimension = new JComboBox(new String[] {"Small", "Medium", "Large"}); - cbDimension.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - String size = (String) cbDimension.getSelectedItem(); - if (size.equals("Small")) - { + final JComboBox cbDimension = new JComboBox(new String[]{"Small", "Medium", "Large"}); + cbDimension.addActionListener((ActionEvent actionEvent) -> { + String size = (String) cbDimension.getSelectedItem(); + switch (size) { + case "Small": graphDimension = new Dimension(250, 100); - } - else if (size.equals("Medium")) - { + break; + case "Medium": graphDimension = new Dimension(450, 140); - } - else if (size.equals("Large")) - { + break; + case "Large": graphDimension = new Dimension(655, 240); - } - update(); + break; + default: + break; } + update(); }); cbDimension.setSelectedItem("Small"); dimensionPanel.add(cbDimension); @@ -149,22 +129,17 @@ else if (size.equals("Large")) // Profile length factor slider JPanel sliderPanel = new JPanel(new GridLayout(0, 1, 0, 0)); JSlider s = new JSlider(JSlider.HORIZONTAL, 0, 30, - (int) (this.profileLengthFactor * 10)); // -5 - 5 in tenth + (int) (this.profileLengthFactor * 10)); // -5 - 5 in tenth s.setMajorTickSpacing(10); s.setMinorTickSpacing(1); //s.setPaintTicks(true); //s.setPaintLabels(true); s.setToolTipText("Profile length"); - s.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent event) - { - JSlider s = (JSlider) event.getSource(); - if (!s.getValueIsAdjusting()) - { - profileLengthFactor = (double) s.getValue() / 10; - update(); - } + s.addChangeListener((ChangeEvent event) -> { + JSlider s1 = (JSlider) event.getSource(); + if (!s1.getValueIsAdjusting()) { + profileLengthFactor = (double) s1.getValue() / 10; + update(); } }); sliderPanel.add(s); @@ -179,42 +154,35 @@ public void stateChanged(ChangeEvent event) // Follow behavior combo JPanel followPanel = new JPanel(new GridLayout(0, 2, 0, 0)); followPanel.add(new JLabel(" Follow:")); - final JComboBox cbFollow = new JComboBox(new String[] {"View", "Cursor", "Eye", "None", "Object"}); - cbFollow.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - String size = (String) cbFollow.getSelectedItem(); - if (size.equals("View")) - { + final JComboBox cbFollow = new JComboBox(new String[]{"View", "Cursor", "Eye", "None", "Object"}); + cbFollow.addActionListener((ActionEvent actionEvent) -> { + String size = (String) cbFollow.getSelectedItem(); + switch (size) { + case "View": follow = TerrainProfileLayer.FOLLOW_VIEW; helpLabel.setEnabled(true); showEyeCheck.setEnabled(false); lengthSlider.setEnabled(true); - } - else if (size.equals("Cursor")) - { + break; + case "Cursor": follow = TerrainProfileLayer.FOLLOW_CURSOR; helpLabel.setEnabled(false); showEyeCheck.setEnabled(false); lengthSlider.setEnabled(true); - } - else if (size.equals("Eye")) - { + break; + case "Eye": follow = TerrainProfileLayer.FOLLOW_EYE; helpLabel.setEnabled(true); showEyeCheck.setEnabled(true); lengthSlider.setEnabled(true); - } - else if (size.equals("None")) - { + break; + case "None": follow = TerrainProfileLayer.FOLLOW_NONE; helpLabel.setEnabled(true); showEyeCheck.setEnabled(false); lengthSlider.setEnabled(false); - } - else if (size.equals("Object")) - { + break; + case "Object": follow = TerrainProfileLayer.FOLLOW_OBJECT; helpLabel.setEnabled(true); showEyeCheck.setEnabled(true); @@ -222,9 +190,11 @@ else if (size.equals("Object")) OrbitView view = (OrbitView) getWwd().getView(); tpl.setObjectPosition(getWwd().getView().getEyePosition()); tpl.setObjectHeading(view.getHeading()); - } - update(); + break; + default: + break; } + update(); }); cbFollow.setSelectedItem("View"); followPanel.add(cbFollow); @@ -237,14 +207,13 @@ else if (size.equals("Object")) controlPanel.add(sliderPanel); controlPanel.add(textPanel); controlPanel.setBorder( - new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Terrain profile"))); + new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Terrain profile"))); controlPanel.setToolTipText("Terrain profile controls"); return controlPanel; } // Update worldwind - private void update() - { + private void update() { this.tpl.setFollow(this.follow); this.tpl.setKeepProportions(this.keepProportions); this.tpl.setZeroBased(this.zeroBased); @@ -255,8 +224,7 @@ private void update() } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind Terrain Profiler", AppFrame.class); } } diff --git a/src/gov/nasa/worldwindx/examples/ViewLookAround.java b/src/gov/nasa/worldwindx/examples/ViewLookAround.java index 4ae1cf5c6a..e3d85c3bdb 100644 --- a/src/gov/nasa/worldwindx/examples/ViewLookAround.java +++ b/src/gov/nasa/worldwindx/examples/ViewLookAround.java @@ -25,27 +25,31 @@ * @author Patrick Murris * @version $Id: ViewLookAround.java 2109 2014-06-30 16:52:38Z tgaskins $ */ -public class ViewLookAround extends ApplicationTemplate -{ - public static class AppFrame extends ApplicationTemplate.AppFrame - { - private ViewControlPanel vcp; - - public AppFrame() - { +public class ViewLookAround extends ApplicationTemplate { + + public static class AppFrame extends ApplicationTemplate.AppFrame { + + private final ViewControlPanel vcp; + + public AppFrame() { super(true, true, false); // Add view control panel to the layer panel this.vcp = new ViewControlPanel(getWwd()); - getWwd().setView(new BasicFlyView()); + BasicFlyView flyView = new BasicFlyView(); + getWwd().setView(flyView); this.getControlPanel().add(this.vcp, BorderLayout.SOUTH); Position pos = new Position(new LatLon(Angle.fromDegrees(45), Angle.fromDegrees(-120)), 2000); - getWwd().getView().setEyePosition(pos); + flyView.setEyePosition(pos); + flyView.setHeading(Angle.fromDegrees(0)); + flyView.setPitch(Angle.fromDegrees(90)); + flyView.setFieldOfView(Angle.fromDegrees(45)); + flyView.setRoll(Angle.fromDegrees(0)); } - private class ViewControlPanel extends JPanel - { - private WorldWindow wwd; + private class ViewControlPanel extends JPanel { + + private final WorldWindow wwd; private JSlider pitchSlider; private JSlider headingSlider; private JSlider rollSlider; @@ -53,16 +57,11 @@ private class ViewControlPanel extends JPanel private boolean suspendEvents = false; - public ViewControlPanel(WorldWindow wwd) - { + public ViewControlPanel(WorldWindow wwd) { this.wwd = wwd; // Add view property listener - this.wwd.getView().addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { - update(); - } + this.wwd.getView().addPropertyChangeListener((PropertyChangeEvent propertyChangeEvent) -> { + update(); }); // Compose panel @@ -75,12 +74,8 @@ public void propertyChange(PropertyChangeEvent propertyChangeEvent) pitchPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); pitchPanel.add(new JLabel("Pitch:")); pitchSlider = new JSlider(0, 180, 90); - pitchSlider.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { - updateView(); - } + pitchSlider.addChangeListener((ChangeEvent changeEvent) -> { + updateView(); }); pitchPanel.add(pitchSlider); @@ -89,12 +84,8 @@ public void stateChanged(ChangeEvent changeEvent) headingPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); headingPanel.add(new JLabel("Heading:")); headingSlider = new JSlider(-180, 180, 0); - headingSlider.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { - updateView(); - } + headingSlider.addChangeListener((ChangeEvent changeEvent) -> { + updateView(); }); headingPanel.add(headingSlider); @@ -103,12 +94,8 @@ public void stateChanged(ChangeEvent changeEvent) rollPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); rollPanel.add(new JLabel("Roll:")); rollSlider = new JSlider(-180, 180, 0); - rollSlider.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { - updateView(); - } + rollSlider.addChangeListener((ChangeEvent changeEvent) -> { + updateView(); }); rollPanel.add(rollSlider); @@ -117,12 +104,8 @@ public void stateChanged(ChangeEvent changeEvent) fovPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); fovPanel.add(new JLabel("Field of view:")); fovSlider = new JSlider(10, 120, 45); - fovSlider.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent changeEvent) - { - updateView(); - } + fovSlider.addChangeListener((ChangeEvent changeEvent) -> { + updateView(); }); fovPanel.add(fovSlider); @@ -133,30 +116,23 @@ public void stateChanged(ChangeEvent changeEvent) this.add(fovPanel); JButton resetBut = new JButton("Reset"); - resetBut.addActionListener(new ActionListener() - { - - public void actionPerformed(ActionEvent e) - { - pitchSlider.setValue(90); - rollSlider.setValue(0); - headingSlider.setValue(0); - fovSlider.setValue(45); - updateView(); - } + resetBut.addActionListener((ActionEvent e) -> { + pitchSlider.setValue(90); + rollSlider.setValue(0); + headingSlider.setValue(0); + fovSlider.setValue(45); + updateView(); }); this.add(resetBut); this.setBorder( - new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("View"))); + new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("View"))); this.setToolTipText("View controls"); } // Update view settings from control panel in a 'first person' perspective - private void updateView() - { - if (!suspendEvents) - { + private void updateView() { + if (!suspendEvents) { BasicFlyView view = (BasicFlyView) this.wwd.getView(); // Stop iterators first @@ -170,12 +146,9 @@ private void updateView() view.setPitch(Angle.fromDegrees(this.pitchSlider.getValue())); view.setFieldOfView(Angle.fromDegrees(this.fovSlider.getValue())); view.setRoll(Angle.fromDegrees(this.rollSlider.getValue())); - //view.setZoom(0); // Restore eye position view.setEyePosition(pos); -// System.out.println("Eye Position: " + pos.latitude.toString() + " , " + pos.longitude.toString() + ", " + pos.getElevation()); -// System.out.println("Orient: " + view.getHeading() + ", " + view.getPitch() + ", " + view.getRoll() ); // Redraw this.wwd.redraw(); @@ -183,8 +156,7 @@ private void updateView() } // Update control panel from view - public void update() - { + public void update() { this.suspendEvents = true; { OrbitView view = (OrbitView) wwd.getView(); @@ -197,8 +169,7 @@ public void update() } } - public static void main(String[] args) - { + public static void main(String[] args) { ApplicationTemplate.start("WorldWind View Look Around", AppFrame.class); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwindx/examples/WorldWindDiagnostics.java b/src/gov/nasa/worldwindx/examples/WorldWindDiagnostics.java index d07a298d4e..fef8c9546b 100644 --- a/src/gov/nasa/worldwindx/examples/WorldWindDiagnostics.java +++ b/src/gov/nasa/worldwindx/examples/WorldWindDiagnostics.java @@ -18,14 +18,13 @@ * @author tag * @version $Id: WorldWindDiagnostics.java 2319 2014-09-17 19:22:58Z dcollins $ */ -public class WorldWindDiagnostics -{ - private static class GLFrame extends JFrame implements GLEventListener - { - private JTextArea outputArea; - - GLFrame(JTextArea outputArea) - { +public class WorldWindDiagnostics { + + private static class GLFrame extends JFrame implements GLEventListener { + + private final JTextArea outputArea; + + GLFrame(JTextArea outputArea) { this.outputArea = outputArea; GLCapabilities caps = new GLCapabilities(Configuration.getMaxCompatibleGLProfile()); caps.setAlphaBits(8); @@ -38,34 +37,32 @@ private static class GLFrame extends JFrame implements GLEventListener this.setSize(200, 200); } - private static class Attr - { - private Attr(Object attr, String name) - { + private static class Attr { + + private Attr(Object attr, String name) { this.attr = attr; this.name = name; } - private Object attr; - private String name; + private final Object attr; + private final String name; } - private static Attr[] attrs = new Attr[] - { - new Attr(GL.GL_STENCIL_BITS, "stencil bits"), - new Attr(GL.GL_DEPTH_BITS, "depth bits"), - new Attr(GL2.GL_MAX_TEXTURE_UNITS, "max texture units"), - new Attr(GL2.GL_MAX_TEXTURE_IMAGE_UNITS_ARB, "max texture image units"), - new Attr(GL2.GL_MAX_TEXTURE_COORDS_ARB, "max texture coords"), - new Attr(GL.GL_MAX_TEXTURE_SIZE, "max texture size"), - new Attr(GL2.GL_MAX_ELEMENTS_INDICES, "max elements indices"), - new Attr(GL2.GL_MAX_ELEMENTS_VERTICES, "max elements vertices"), - new Attr(GL2.GL_MAX_LIGHTS, "max lights"), - new Attr(GL2.GL_LINE_WIDTH_RANGE, "line width range") - }; - - public void init(GLAutoDrawable glAutoDrawable) - { + private static Attr[] attrs = new Attr[]{ + new Attr(GL.GL_STENCIL_BITS, "stencil bits"), + new Attr(GL.GL_DEPTH_BITS, "depth bits"), + new Attr(GL2.GL_MAX_TEXTURE_UNITS, "max texture units"), + new Attr(GL2.GL_MAX_TEXTURE_IMAGE_UNITS_ARB, "max texture image units"), + new Attr(GL2.GL_MAX_TEXTURE_COORDS_ARB, "max texture coords"), + new Attr(GL.GL_MAX_TEXTURE_SIZE, "max texture size"), + new Attr(GL2.GL_MAX_ELEMENTS_INDICES, "max elements indices"), + new Attr(GL2.GL_MAX_ELEMENTS_VERTICES, "max elements vertices"), + new Attr(GL2.GL_MAX_LIGHTS, "max lights"), + new Attr(GL2.GL_LINE_WIDTH_RANGE, "line width range") + }; + + @Override + public void init(GLAutoDrawable glAutoDrawable) { StringBuilder sb = new StringBuilder(); sb.append(gov.nasa.worldwind.Version.getVersion() + "\n"); @@ -76,8 +73,7 @@ public void init(GLAutoDrawable glAutoDrawable) sb.append("Max memory: " + Runtime.getRuntime().maxMemory() + " bytes\n"); sb.append("Total memory: " + Runtime.getRuntime().totalMemory() + " bytes\n"); - for (Map.Entry prop : System.getProperties().entrySet()) - { + for (Map.Entry prop : System.getProperties().entrySet()) { sb.append(prop.getKey() + " = " + prop.getValue() + "\n"); } @@ -95,12 +91,10 @@ public void init(GLAutoDrawable glAutoDrawable) sb.append("OpenGL renderer: " + oglRenderer + "\n"); int[] intVals = new int[2]; - for (Attr attr : attrs) - { + for (Attr attr : attrs) { sb.append(attr.name).append(": "); - if (attr.attr instanceof Integer) - { + if (attr.attr instanceof Integer) { gl.glGetIntegerv((Integer) attr.attr, intVals, 0); sb.append(intVals[0]).append(intVals[1] > 0 ? ", " + intVals[1] : ""); } @@ -111,24 +105,19 @@ public void init(GLAutoDrawable glAutoDrawable) String extensionString = gl.glGetString(GL.GL_EXTENSIONS); String[] extensions = extensionString.split(" "); sb.append("Extensions\n"); - for (String ext : extensions) - { + for (String ext : extensions) { sb.append(" " + ext + "\n"); } sb.append("\nJOGL Values\n"); String pkgName = "com.jogamp.opengl"; - try - { + try { getClass().getClassLoader().loadClass(pkgName + ".GL"); Package p = getClass().getClassLoader().getDefinedPackage(pkgName); - if (p == null) - { + if (p == null) { sb.append("WARNING: Package.getPackage(" + pkgName + ") is null\n"); - } - else - { + } else { sb.append(p + "\n"); sb.append("Specification Title = " + p.getSpecificationTitle() + "\n"); sb.append("Specification Vendor = " + p.getSpecificationVendor() + "\n"); @@ -136,49 +125,45 @@ public void init(GLAutoDrawable glAutoDrawable) sb.append("Implementation Vendor = " + p.getImplementationVendor() + "\n"); sb.append("Implementation Version = " + p.getImplementationVersion() + "\n"); } - } - catch (ClassNotFoundException e) - { + } catch (ClassNotFoundException e) { sb.append("Unable to load " + pkgName + "\n"); } this.outputArea.setText(sb.toString()); } - public void dispose(GLAutoDrawable glAutoDrawable) - { + @Override + public void dispose(GLAutoDrawable glAutoDrawable) { } - public void display(GLAutoDrawable glAutoDrawable) - { + public void display(GLAutoDrawable glAutoDrawable) { glAutoDrawable.getGL().glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); } - public void reshape(GLAutoDrawable glAutoDrawable, int x, int y, int width, int height) - { + @Override + public void reshape(GLAutoDrawable glAutoDrawable, int x, int y, int width, int height) { } } - private static class MainFrame extends JFrame - { - private static JTextArea outputArea = new JTextArea(20, 80); + private static class MainFrame extends JFrame { - private static class RunAction extends AbstractAction - { - public RunAction() - { + private static final JTextArea outputArea = new JTextArea(20, 80); + + private static class RunAction extends AbstractAction { + + public RunAction() { super("Re-run Test"); } - public void actionPerformed(ActionEvent actionEvent) - { + @Override + public void actionPerformed(ActionEvent actionEvent) { outputArea.setText(""); GLFrame glFrame = new GLFrame(outputArea); glFrame.setVisible(true); } } - private static Action[] operations = new Action[] { + private static final Action[] operations = new Action[]{ new RunAction() }; @@ -186,10 +171,8 @@ public void actionPerformed(ActionEvent actionEvent) private JPanel controlContainer = new JPanel(new BorderLayout()); private JPanel outputContainer = new JPanel(); - public MainFrame() - { - try - { + public MainFrame() { + try { mainPanel.setLayout(new BorderLayout()); mainPanel.setBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9)); mainPanel.add(outputContainer, java.awt.BorderLayout.CENTER); @@ -199,15 +182,14 @@ public MainFrame() this.getContentPane().add(mainPanel, java.awt.BorderLayout.CENTER); - java.util.ArrayList btns = new java.util.ArrayList(); + java.util.ArrayList btns = new java.util.ArrayList<>(); { JPanel westPanel = new JPanel(new GridLayout(0, 1, 0, 10)); westPanel.setBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9)); JPanel opsPanel = new JPanel(new GridLayout(6, 1)); opsPanel.setBorder(new javax.swing.border.TitledBorder("Operations")); - for (Action action : operations) - { + for (Action action : operations) { JPanel p = new JPanel(new BorderLayout()); JButton jb = new JButton(action); btns.add(jb); @@ -223,8 +205,7 @@ public MainFrame() this.pack(); Dimension dim = btns.get(0).getSize(); - for (JButton btn : btns) - { + for (JButton btn : btns) { btn.setPreferredSize(dim); } @@ -239,37 +220,33 @@ public MainFrame() int y = parentLocation.y + (parentSize.height - prefSize.height) / 2; this.setLocation(x, y); this.setResizable(true); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } - protected void processWindowEvent(java.awt.event.WindowEvent e) - { + @Override + protected void processWindowEvent(java.awt.event.WindowEvent e) { super.processWindowEvent(e); - if (e.getID() != java.awt.event.WindowEvent.WINDOW_OPENED) - //noinspection UnnecessaryReturnStatement + if (e.getID() != java.awt.event.WindowEvent.WINDOW_OPENED) //noinspection UnnecessaryReturnStatement + { return; + } GLFrame glFrame = new GLFrame(outputArea); glFrame.setVisible(true); } } - static - { - if (Configuration.isMacOS()) - { + static { + if (Configuration.isMacOS()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "WorldWind Diagnostic Program"); System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); } } - public static void main(String[] arg) - { + public static void main(String[] arg) { final MainFrame frame = new MainFrame(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); From 347001b4f08514cc3b49eeb88ee626d71d877053 Mon Sep 17 00:00:00 2001 From: markpet49 Date: Wed, 16 Oct 2019 16:18:52 -0500 Subject: [PATCH 10/11] Build fixes --- build.macros.xml => release-build.macros.xml | 0 build.properties => release-build.properties | 8 +------- release-build.xml | 4 ++-- src/gov/nasa/worldwindx/examples/MeasureToolPanel.java | 8 ++++---- 4 files changed, 7 insertions(+), 13 deletions(-) rename build.macros.xml => release-build.macros.xml (100%) rename build.properties => release-build.properties (78%) diff --git a/build.macros.xml b/release-build.macros.xml similarity index 100% rename from build.macros.xml rename to release-build.macros.xml diff --git a/build.properties b/release-build.properties similarity index 78% rename from build.properties rename to release-build.properties index a29f5b35a0..b54d6c43ac 100644 --- a/build.properties +++ b/release-build.properties @@ -16,7 +16,7 @@ worldwind.classes.dir=${worldwind.build.dir}/classes worldwind.doc.dir=${worldwind.build.dir}/doc worldwind.jar.dir=${worldwind.build.dir}/jar worldwind.test.results.dir=${worldwind.build.dir}/test-results -worldwind.jdk=1.8 +worldwind.jdk=11 #worldwind.exclude.jackson=true # MIL-STD-2525 package build properties @@ -26,9 +26,3 @@ milstd2525.png.dir=${milstd2525.out.dir}/png milstd2525.png.width=128 milstd2525.png.height=128 -# WebStart package build properties -webstart.src.dir=${basedir}/webstart -webstart.out.dir=${worldwind.build.dir}/webstart -webstart.unsigned.dir=${webstart.out.dir}/jar-unsigned -webstart.jar.dir=${webstart.out.dir}/jar -webstart.jnlp.dir=${webstart.out.dir}/jnlp diff --git a/release-build.xml b/release-build.xml index a94f6d1e5f..46e0fb8ba7 100644 --- a/release-build.xml +++ b/release-build.xml @@ -13,8 +13,8 @@ - - + + diff --git a/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java b/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java index 52cb7ed970..33304cb652 100644 --- a/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java +++ b/src/gov/nasa/worldwindx/examples/MeasureToolPanel.java @@ -116,7 +116,7 @@ private void makePanel(Dimension size) { JPanel shapePanel = new JPanel(new GridLayout(1, 2, 5, 5)); shapePanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); shapePanel.add(new JLabel("Shape:")); - shapeCombo = new JComboBox(new String[]{"Line", "Path", "Polygon", "Circle", "Ellipse", "Square", "Rectangle"}); + shapeCombo = new JComboBox<>(new String[]{"Line", "Path", "Polygon", "Circle", "Ellipse", "Square", "Rectangle"}); shapeCombo.addActionListener((ActionEvent event) -> { String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); switch (item) { @@ -151,7 +151,7 @@ private void makePanel(Dimension size) { JPanel pathTypePanel = new JPanel(new GridLayout(1, 2, 5, 5)); pathTypePanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); pathTypePanel.add(new JLabel("Path type:")); - pathTypeCombo = new JComboBox(new String[]{"Linear", "Rhumb", "Great circle"}); + pathTypeCombo = new JComboBox<>(new String[]{"Linear", "Rhumb", "Great circle"}); pathTypeCombo.setSelectedIndex(2); pathTypeCombo.addActionListener((ActionEvent event) -> { String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); @@ -175,7 +175,7 @@ private void makePanel(Dimension size) { JPanel unitsPanel = new JPanel(new GridLayout(1, 2, 5, 5)); unitsPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); unitsPanel.add(new JLabel("Units:")); - unitsCombo = new JComboBox(new String[]{"M/M\u00b2", "KM/KM\u00b2", "KM/Hectare", "Feet/Feet\u00b2", + unitsCombo = new JComboBox<>(new String[]{"M/M\u00b2", "KM/KM\u00b2", "KM/Hectare", "Feet/Feet\u00b2", "Miles/Miles\u00b2", "Nm/Miles\u00b2", "Yards/Acres"}); unitsCombo.setSelectedItem("KM/KM\u00b2"); unitsCombo.addActionListener((ActionEvent event) -> { @@ -219,7 +219,7 @@ private void makePanel(Dimension size) { JPanel anglesPanel = new JPanel(new GridLayout(1, 2, 5, 5)); anglesPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); anglesPanel.add(new JLabel("Angle Format:")); - anglesCombo = new JComboBox(new String[]{"DD", "DMS"}); + anglesCombo = new JComboBox<>(new String[]{"DD", "DMS"}); anglesCombo.setSelectedItem("DD"); anglesCombo.addActionListener((ActionEvent event) -> { String item = (String) ((JComboBox) event.getSource()).getSelectedItem(); From dfd8e0b00849a2719d95fbd23a8cfef069733e1b Mon Sep 17 00:00:00 2001 From: markpet49 Date: Fri, 18 Oct 2019 15:53:53 -0500 Subject: [PATCH 11/11] Logging run config --- nbproject/configs/LoggingControl.properties | 1 + 1 file changed, 1 insertion(+) create mode 100644 nbproject/configs/LoggingControl.properties diff --git a/nbproject/configs/LoggingControl.properties b/nbproject/configs/LoggingControl.properties new file mode 100644 index 0000000000..66b2b5fb71 --- /dev/null +++ b/nbproject/configs/LoggingControl.properties @@ -0,0 +1 @@ +main.class=gov.nasa.worldwindx.examples.LoggingControl