private void makePartialCylinderTerrainConformant( DrawContext dc, int slices, int stacks, float[] verts, double[] altitudes, boolean[] terrainConformant, Vec4 referenceCenter) { Globe globe = dc.getGlobe(); Matrix transform = this.computeTransform(dc.getGlobe(), dc.getVerticalExaggeration()); for (int i = 0; i <= slices; i++) { int index = i * (stacks + 1); index = 3 * index; Vec4 vec = new Vec4(verts[index], verts[index + 1], verts[index + 2]); vec = vec.transformBy4(transform); Position p = globe.computePositionFromPoint(vec); for (int j = 0; j <= stacks; j++) { double elevation = altitudes[j]; if (terrainConformant[j]) elevation += this.computeElevationAt(dc, p.getLatitude(), p.getLongitude()); vec = globe.computePointFromPosition(p.getLatitude(), p.getLongitude(), elevation); index = j + i * (stacks + 1); index = 3 * index; verts[index] = (float) (vec.x - referenceCenter.x); verts[index + 1] = (float) (vec.y - referenceCenter.y); verts[index + 2] = (float) (vec.z - referenceCenter.z); } } }
private void makeRadialWallTerrainConformant( DrawContext dc, int pillars, int stacks, float[] verts, double[] altitudes, boolean[] terrainConformant, Vec4 referenceCenter) { Globe globe = dc.getGlobe(); Matrix transform = this.computeTransform(dc.getGlobe(), dc.getVerticalExaggeration()); for (int p = 0; p <= pillars; p++) { int index = p; index = 3 * index; Vec4 vec = new Vec4(verts[index], verts[index + 1], verts[index + 2]); vec = vec.transformBy4(transform); Position pos = globe.computePositionFromPoint(vec); for (int s = 0; s <= stacks; s++) { double elevation = altitudes[s]; if (terrainConformant[s]) elevation += this.computeElevationAt(dc, pos.getLatitude(), pos.getLongitude()); vec = globe.computePointFromPosition(pos.getLatitude(), pos.getLongitude(), elevation); index = p + s * (pillars + 1); index = 3 * index; verts[index] = (float) (vec.x - referenceCenter.x); verts[index + 1] = (float) (vec.y - referenceCenter.y); verts[index + 2] = (float) (vec.z - referenceCenter.z); } } }
private void drawTileIDs(DrawContext dc, ArrayList<MercatorTextureTile> tiles) { java.awt.Rectangle viewport = dc.getView().getViewport(); if (this.textRenderer == null) { this.textRenderer = new TextRenderer(java.awt.Font.decode("Arial-Plain-13"), true, true); this.textRenderer.setUseVertexArrays(false); } dc.getGL().glDisable(GL.GL_DEPTH_TEST); dc.getGL().glDisable(GL.GL_BLEND); dc.getGL().glDisable(GL.GL_TEXTURE_2D); this.textRenderer.setColor(java.awt.Color.YELLOW); this.textRenderer.beginRendering(viewport.width, viewport.height); for (MercatorTextureTile tile : tiles) { String tileLabel = tile.getLabel(); if (tile.getFallbackTile() != null) tileLabel += "/" + tile.getFallbackTile().getLabel(); LatLon ll = tile.getSector().getCentroid(); Vec4 pt = dc.getGlobe() .computePointFromPosition( ll.getLatitude(), ll.getLongitude(), dc.getGlobe().getElevation(ll.getLatitude(), ll.getLongitude())); pt = dc.getView().project(pt); this.textRenderer.draw(tileLabel, (int) pt.x, (int) pt.y); } this.textRenderer.endRendering(); }
private void makePartialDiskTerrainConformant( DrawContext dc, int numCoords, float[] verts, double altitude, boolean terrainConformant, Vec4 referenceCenter) { Globe globe = dc.getGlobe(); Matrix transform = this.computeTransform(dc.getGlobe(), dc.getVerticalExaggeration()); for (int i = 0; i < numCoords; i += 3) { Vec4 vec = new Vec4(verts[i], verts[i + 1], verts[i + 2]); vec = vec.transformBy4(transform); Position p = globe.computePositionFromPoint(vec); double elevation = altitude; if (terrainConformant) elevation += this.computeElevationAt(dc, p.getLatitude(), p.getLongitude()); vec = globe.computePointFromPosition(p.getLatitude(), p.getLongitude(), elevation); verts[i] = (float) (vec.x - referenceCenter.x); verts[i + 1] = (float) (vec.y - referenceCenter.y); verts[i + 2] = (float) (vec.z - referenceCenter.z); } }
private Vec4 computeReferencePoint(DrawContext dc) { if (dc.getViewportCenterPosition() != null) return dc.getGlobe().computePointFromPosition(dc.getViewportCenterPosition()); java.awt.geom.Rectangle2D viewport = dc.getView().getViewport(); int x = (int) viewport.getWidth() / 2; for (int y = (int) (0.5 * viewport.getHeight()); y >= 0; y--) { Position pos = dc.getView().computePositionFromScreenPoint(x, y); if (pos == null) continue; return dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), 0d); } return null; }
protected static boolean isTileVisible( DrawContext dc, Tile tile, double minDistanceSquared, double maxDistanceSquared) { if (!tile.getSector().intersects(dc.getVisibleSector())) return false; View view = dc.getView(); Position eyePos = view.getEyePosition(); if (eyePos == null) return false; Angle lat = clampAngle( eyePos.getLatitude(), tile.getSector().getMinLatitude(), tile.getSector().getMaxLatitude()); Angle lon = clampAngle( eyePos.getLongitude(), tile.getSector().getMinLongitude(), tile.getSector().getMaxLongitude()); Vec4 p = dc.getGlobe().computePointFromPosition(lat, lon, 0d); double distSquared = dc.getView().getEyePoint().distanceToSquared3(p); //noinspection RedundantIfStatement if (minDistanceSquared > distSquared || maxDistanceSquared < distSquared) return false; return true; }
public void pick(DrawContext dc, java.awt.Point point) { if (!this.enabled) return; // Don't check for arg errors if we're disabled if (null == dc) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } if (null == dc.getGlobe()) { String message = Logging.getMessage("layers.AbstractLayer.NoGlobeSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } if (null == dc.getView()) { String message = Logging.getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } if (!this.isLayerActive(dc)) return; if (!this.isLayerInView(dc)) return; this.doPick(dc, point); }
/** * Compute the positions of the arrow head of the graphic's legs. * * @param dc Current draw context * @param base Position of the arrow's starting point. * @param tip Position of the arrow head tip. * @param arrowLength Length of the arrowhead as a fraction of the total line length. * @param arrowAngle Angle of the arrow head. * @return Positions required to draw the arrow head. */ protected List<Position> computeArrowheadPositions( DrawContext dc, Position base, Position tip, double arrowLength, Angle arrowAngle) { // Build a triangle to represent the arrowhead. The triangle is built from two vectors, one // parallel to the // segment, and one perpendicular to it. Globe globe = dc.getGlobe(); Vec4 ptA = globe.computePointFromPosition(base); Vec4 ptB = globe.computePointFromPosition(tip); // Compute parallel component Vec4 parallel = ptA.subtract3(ptB); Vec4 surfaceNormal = globe.computeSurfaceNormalAtPoint(ptB); // Compute perpendicular component Vec4 perpendicular = surfaceNormal.cross3(parallel); double finalArrowLength = arrowLength * parallel.getLength3(); double arrowHalfWidth = finalArrowLength * arrowAngle.tanHalfAngle(); perpendicular = perpendicular.normalize3().multiply3(arrowHalfWidth); parallel = parallel.normalize3().multiply3(finalArrowLength); // Compute geometry of direction arrow Vec4 vertex1 = ptB.add3(parallel).add3(perpendicular); Vec4 vertex2 = ptB.add3(parallel).subtract3(perpendicular); return TacticalGraphicUtil.asPositionList(globe, vertex1, vertex2, ptB); }
/** * Generate the positions required to draw the line. * * @param dc Current draw context. * @param positions Positions that define the polygon boundary. */ @Override protected void generateIntermediatePositions( DrawContext dc, Iterable<? extends Position> positions) { Globe globe = dc.getGlobe(); boolean useDefaultWaveLength = false; double waveLength = this.getWaveLength(); if (waveLength == 0) { waveLength = this.computeDefaultWavelength(positions, globe); useDefaultWaveLength = true; } // Generate lines that parallel the control line. List<Position> leftPositions = new ArrayList<Position>(); List<Position> rightPositions = new ArrayList<Position>(); this.generateParallelLines( positions.iterator(), leftPositions, rightPositions, waveLength / 2.0, globe); if (useDefaultWaveLength) waveLength = this.computeDefaultWavelength(leftPositions, globe); double radius = (waveLength) / 2.0; // Generate wavy line to the left of the control line. PositionIterator iterator = new PositionIterator(leftPositions, waveLength, globe); this.computedPositions = this.generateWavePositions(iterator, radius / globe.getRadius(), false); this.path.setPositions(this.computedPositions); if (useDefaultWaveLength) waveLength = this.computeDefaultWavelength(rightPositions, globe); radius = (waveLength) / 2.0; // Generate wavy line to the right of the control line. iterator = new PositionIterator(rightPositions, waveLength, globe); this.path2.setPositions(this.generateWavePositions(iterator, radius / globe.getRadius(), true)); }
/** * Select the visible grid elements * * @param dc the current <code>DrawContext</code>. */ protected void selectRenderables(DrawContext dc) { if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Sector vs = dc.getVisibleSector(); OrbitView view = (OrbitView) dc.getView(); // Compute labels offset from view center Position centerPos = view.getCenterPosition(); Double pixelSizeDegrees = Angle.fromRadians( view.computePixelSizeAtDistance(view.getZoom()) / dc.getGlobe().getEquatorialRadius()) .degrees; Double labelOffsetDegrees = pixelSizeDegrees * view.getViewport().getWidth() / 4; Position labelPos = Position.fromDegrees( centerPos.getLatitude().degrees - labelOffsetDegrees, centerPos.getLongitude().degrees - labelOffsetDegrees, 0); Double labelLatDegrees = labelPos.getLatitude().normalizedLatitude().degrees; labelLatDegrees = Math.min(Math.max(labelLatDegrees, -76), 78); labelPos = new Position( Angle.fromDegrees(labelLatDegrees), labelPos.getLongitude().normalizedLongitude(), 0); if (vs != null) { for (GridElement ge : this.gridElements) { if (ge.isInView(dc)) { if (ge.renderable instanceof GeographicText) { GeographicText gt = (GeographicText) ge.renderable; if (labelPos.getLatitude().degrees < 72 || "*32*34*36*".indexOf("*" + gt.getText() + "*") == -1) { // Adjust label position according to eye position Position pos = gt.getPosition(); if (ge.type.equals(GridElement.TYPE_LATITUDE_LABEL)) pos = Position.fromDegrees( pos.getLatitude().degrees, labelPos.getLongitude().degrees, pos.getElevation()); else if (ge.type.equals(GridElement.TYPE_LONGITUDE_LABEL)) pos = Position.fromDegrees( labelPos.getLatitude().degrees, pos.getLongitude().degrees, pos.getElevation()); gt.setPosition(pos); } } this.graticuleSupport.addRenderable(ge.renderable, GRATICULE_UTM); } } // System.out.println("Total elements: " + count + " visible sector: " + vs); } }
protected void requestTile(DrawContext dc, Tile tile) { Vec4 centroid = dc.getGlobe().computePointFromPosition(tile.getSector().getCentroid(), 0); if (this.getReferencePoint() != null) tile.setPriority(centroid.distanceTo3(this.getReferencePoint())); RequestTask task = new RequestTask(tile, this); this.getRequestQ().add(task); }
@Override protected void doRender(DrawContext dc) { if (!loaded) { loaded = true; loadAttempts++; downloadData(); } if (lastVerticalExaggeration != dc.getVerticalExaggeration() || lastGlobe != dc.getGlobe()) { lastVerticalExaggeration = dc.getVerticalExaggeration(); lastGlobe = dc.getGlobe(); recalculateVertices(lastGlobe, lastVerticalExaggeration); recalculateColors(); } GL2 gl = dc.getGL().getGL2(); int push = GL2.GL_CLIENT_VERTEX_ARRAY_BIT; if (colors != null) { push |= GL2.GL_COLOR_BUFFER_BIT; } if (getOpacity() < 1.0) { push |= GL2.GL_CURRENT_BIT; } gl.glPushClientAttrib(push); if (colors != null) { gl.glEnableClientState(GL2.GL_COLOR_ARRAY); gl.glColorPointer(4, GL2.GL_DOUBLE, 0, colors.rewind()); } if (getOpacity() < 1.0) { setBlendingFunction(dc); } gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL2.GL_DOUBLE, 0, vertices.rewind()); gl.glDrawElements( GL2.GL_TRIANGLE_STRIP, indices.limit(), GL2.GL_UNSIGNED_INT, indices.rewind()); gl.glColor4d(1, 1, 1, 1); gl.glPopClientAttrib(); }
@SuppressWarnings({"RedundantIfStatement"}) public boolean isInView(DrawContext dc) { if (!viewFrustum.intersects(this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) return false; // Check apparent size if (getSizeInPixels(dc) <= MIN_CELL_SIZE_PIXELS) return false; return true; }
protected static boolean isNameVisible( DrawContext dc, PlaceNameService service, Position namePosition) { double elevation = dc.getVerticalExaggeration() * namePosition.getElevation(); Vec4 namePoint = dc.getGlobe() .computePointFromPosition( namePosition.getLatitude(), namePosition.getLongitude(), elevation); Vec4 eyeVec = dc.getView().getEyePoint(); double dist = eyeVec.distanceTo3(namePoint); return dist >= service.getMinDisplayDistance() && dist <= service.getMaxDisplayDistance(); }
private boolean needToSplit(DrawContext dc, Sector sector) { Vec4[] corners = sector.computeCornerPoints(dc.getGlobe(), dc.getVerticalExaggeration()); Vec4 centerPoint = sector.computeCenterPoint(dc.getGlobe(), dc.getVerticalExaggeration()); View view = dc.getView(); double d1 = view.getEyePoint().distanceTo3(corners[0]); double d2 = view.getEyePoint().distanceTo3(corners[1]); double d3 = view.getEyePoint().distanceTo3(corners[2]); double d4 = view.getEyePoint().distanceTo3(corners[3]); double d5 = view.getEyePoint().distanceTo3(centerPoint); double minDistance = d1; if (d2 < minDistance) minDistance = d2; if (d3 < minDistance) minDistance = d3; if (d4 < minDistance) minDistance = d4; if (d5 < minDistance) minDistance = d5; double cellSize = (Math.PI * sector.getDeltaLatRadians() * dc.getGlobe().getRadius()) / 20; // TODO return !(Math.log10(cellSize) <= (Math.log10(minDistance) - this.splitScale)); }
protected void computeQuadSize(DrawContext dc) { if (this.positions == null) return; Iterator<? extends Position> iterator = this.positions.iterator(); Position pos1 = iterator.next(); Position pos2 = iterator.next(); Angle angularDistance = LatLon.greatCircleDistance(pos1, pos2); double length = angularDistance.radians * dc.getGlobe().getRadius(); this.quad.setWidth(length); }
/** * Compute the lat/lon position of the view center * * @param dc the current DrawContext * @param view the current View * @return the ground position of the view center or null */ protected Position computeGroundPosition(DrawContext dc, View view) { if (view == null) return null; Position groundPos = view.computePositionFromScreenPoint( view.getViewport().getWidth() / 2, view.getViewport().getHeight() / 2); if (groundPos == null) return null; double elevation = dc.getGlobe().getElevation(groundPos.getLatitude(), groundPos.getLongitude()); return new Position( groundPos.getLatitude(), groundPos.getLongitude(), elevation * dc.getVerticalExaggeration()); }
private void makeCap( DrawContext dc, GeometryBuilder.IndexedTriangleArray ita, double altitude, boolean terrainConformant, int orientation, Matrix locationTransform, Vec4 referenceCenter, int indexPos, int[] indices, int vertexPos, float[] vertices, float[] normals) { GeometryBuilder gb = this.getGeometryBuilder(); Globe globe = dc.getGlobe(); int indexCount = ita.getIndexCount(); int vertexCount = ita.getVertexCount(); int[] locationIndices = ita.getIndices(); float[] locationVerts = ita.getVertices(); this.copyIndexArray( indexCount, (orientation == GeometryBuilder.INSIDE), locationIndices, vertexPos, indexPos, indices); for (int i = 0; i < vertexCount; i++) { int index = 3 * i; Vec4 vec = new Vec4(locationVerts[index], locationVerts[index + 1], locationVerts[index + 2]); vec = vec.transformBy4(locationTransform); Position pos = globe.computePositionFromPoint(vec); vec = this.computePointFromPosition( dc, pos.getLatitude(), pos.getLongitude(), altitude, terrainConformant); index = 3 * (vertexPos + i); vertices[index] = (float) (vec.x - referenceCenter.x); vertices[index + 1] = (float) (vec.y - referenceCenter.y); vertices[index + 2] = (float) (vec.z - referenceCenter.z); } gb.makeIndexedTriangleArrayNormals( indexPos, indexCount, indices, vertexPos, vertexCount, vertices, normals); }
private void makeSectionVertices( DrawContext dc, int locationPos, float[] locations, double[] altitude, boolean[] terrainConformant, int subdivisions, Matrix locationTransform, Vec4 referenceCenter, int vertexPos, float[] vertices) { GeometryBuilder gb = this.getGeometryBuilder(); int numPoints = gb.getSubdivisionPointsVertexCount(subdivisions); Globe globe = dc.getGlobe(); int index1 = 3 * locationPos; int index2 = 3 * (locationPos + 1); float[] locationVerts = new float[3 * numPoints]; gb.makeSubdivisionPoints( locations[index1], locations[index1 + 1], locations[index1 + 2], locations[index2], locations[index2 + 1], locations[index2 + 2], subdivisions, locationVerts); for (int i = 0; i < numPoints; i++) { int index = 3 * i; Vec4 vec = new Vec4(locationVerts[index], locationVerts[index + 1], locationVerts[index + 2]); vec = vec.transformBy4(locationTransform); Position pos = globe.computePositionFromPoint(vec); for (int j = 0; j < 2; j++) { vec = this.computePointFromPosition( dc, pos.getLatitude(), pos.getLongitude(), altitude[j], terrainConformant[j]); index = 2 * i + j; index = 3 * (vertexPos + index); vertices[index] = (float) (vec.x - referenceCenter.x); vertices[index + 1] = (float) (vec.y - referenceCenter.y); vertices[index + 2] = (float) (vec.z - referenceCenter.z); } } }
public void computeZone(DrawContext dc) { try { Position centerPos = ((OrbitView) dc.getView()).getCenterPosition(); if (centerPos != null) { if (centerPos.latitude.degrees <= UTM_MAX_LATITUDE && centerPos.latitude.degrees >= UTM_MIN_LATITUDE) { UTMCoord UTM = UTMCoord.fromLatLon( centerPos.getLatitude(), centerPos.getLongitude(), dc.getGlobe()); this.zone = UTM.getZone(); } else this.zone = 0; } } catch (Exception ex) { this.zone = 0; } }
private void drawBoundingVolumes(DrawContext dc, ArrayList<MercatorTextureTile> tiles) { float[] previousColor = new float[4]; dc.getGL().glGetFloatv(GL.GL_CURRENT_COLOR, previousColor, 0); dc.getGL().glColor3d(0, 1, 0); for (MercatorTextureTile tile : tiles) { ((Cylinder) tile.getExtent(dc)).render(dc); } Cylinder c = dc.getGlobe() .computeBoundingCylinder(dc.getVerticalExaggeration(), this.levels.getSector()); dc.getGL().glColor3d(1, 1, 0); c.render(dc); dc.getGL().glColor4fv(previousColor, 0); }
/** * Compute the view range footprint on the globe. * * @param dc the current <code>DrawContext</code> * @param steps the number of steps. * @return an array list of <code>LatLon</code> forming a closed shape. */ protected ArrayList<LatLon> computeViewFootPrint(DrawContext dc, int steps) { ArrayList<LatLon> positions = new ArrayList<LatLon>(); Position eyePos = dc.getView().getEyePosition(); Angle distance = Angle.fromRadians( Math.asin( dc.getView().getFarClipDistance() / (dc.getGlobe().getRadius() + eyePos.getElevation()))); if (distance.degrees > 10) { double headStep = 360d / steps; Angle heading = Angle.ZERO; for (int i = 0; i <= steps; i++) { LatLon p = LatLon.greatCircleEndPosition(eyePos, heading, distance); positions.add(p); heading = heading.addDegrees(headStep); } return positions; } else return null; }
/** * Determine the positions that make up the arrowhead. * * @param dc Current draw context. * @param startPosition Position of the arrow's base. * @param endPosition Position of the arrow head tip. * @return Positions that define the arrowhead. */ protected List<Position> computeArrowheadPositions( DrawContext dc, Position startPosition, Position endPosition) { Globe globe = dc.getGlobe(); // Arrowhead looks like this: // _ // A\ | 1/2 width // ________B\ _| // Pt. 1 / // C/ // | | // Length Vec4 p1 = globe.computePointFromPosition(startPosition); Vec4 pB = globe.computePointFromPosition(endPosition); // Find vector in the direction of the arrow Vec4 vB1 = p1.subtract3(pB); double arrowLengthFraction = this.getArrowLength(); // Find the point at the base of the arrowhead Vec4 arrowBase = pB.add3(vB1.multiply3(arrowLengthFraction)); Vec4 normal = globe.computeSurfaceNormalAtPoint(arrowBase); // Compute the length of the arrowhead double arrowLength = vB1.getLength3() * arrowLengthFraction; double arrowHalfWidth = arrowLength * this.getArrowAngle().tanHalfAngle(); // Compute a vector perpendicular to the segment and the normal vector Vec4 perpendicular = vB1.cross3(normal); perpendicular = perpendicular.normalize3().multiply3(arrowHalfWidth); // Find points A and C Vec4 pA = arrowBase.add3(perpendicular); Vec4 pC = arrowBase.subtract3(perpendicular); return TacticalGraphicUtil.asPositionList(globe, pA, pB, pC); }
/** {@inheritDoc} */ @Override protected void determineLabelPositions(DrawContext dc) { Position center = this.getReferencePosition(); if (center == null) return; // Position the labels along a line radiating out from the center of the circle. The angle (60 // degrees) is // chosen to match the graphic template defined by MIL-STD-2525C, pg. 613. double globeRadius = dc.getGlobe().getRadius(); Angle labelAngle = this.getLabelAngle(); int i = 0; for (SurfaceCircle ring : this.rings) { double radius = ring.getRadius(); LatLon ll = LatLon.greatCircleEndPosition(center, labelAngle.radians, radius / globeRadius); this.labels.get(i).setPosition(new Position(ll, 0)); i += 1; } }
/** * Create the circles used to draw this graphic. * * @param dc Current draw context. */ protected void createShapes(DrawContext dc) { if (this.positions == null) return; this.rings = new ArrayList<SurfaceCircle>(); Iterator<? extends Position> iterator = this.positions.iterator(); Position center = iterator.next(); double globeRadius = dc.getGlobe().getRadius(); while (iterator.hasNext()) { SurfaceCircle ring = this.createCircle(); ring.setCenter(center); Position pos = iterator.next(); Angle radius = LatLon.greatCircleDistance(center, pos); double radiusMeters = radius.radians * globeRadius; ring.setRadius(radiusMeters); this.rings.add(ring); } }
protected boolean isNavSectorVisible( DrawContext dc, double minDistanceSquared, double maxDistanceSquared) { if (!navSector.intersects(dc.getVisibleSector())) return false; View view = dc.getView(); Position eyePos = view.getEyePosition(); if (eyePos == null) return false; // check for eyePos over globe if (Double.isNaN(eyePos.getLatitude().getDegrees()) || Double.isNaN(eyePos.getLongitude().getDegrees())) return false; Angle lat = clampAngle(eyePos.getLatitude(), navSector.getMinLatitude(), navSector.getMaxLatitude()); Angle lon = clampAngle( eyePos.getLongitude(), navSector.getMinLongitude(), navSector.getMaxLongitude()); Vec4 p = dc.getGlobe().computePointFromPosition(lat, lon, 0d); double distSquared = dc.getView().getEyePoint().distanceToSquared3(p); //noinspection RedundantIfStatement if (minDistanceSquared > distSquared || maxDistanceSquared < distSquared) return false; return true; }
// Rendering public void draw(DrawContext dc) { GL gl = dc.getGL(); boolean attribsPushed = false; boolean modelviewPushed = false; boolean projectionPushed = false; try { gl.glPushAttrib( GL.GL_DEPTH_BUFFER_BIT | GL.GL_COLOR_BUFFER_BIT | GL.GL_ENABLE_BIT | GL.GL_TEXTURE_BIT | GL.GL_TRANSFORM_BIT | GL.GL_VIEWPORT_BIT | GL.GL_CURRENT_BIT); attribsPushed = true; gl.glDisable(GL.GL_TEXTURE_2D); // no textures gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glDisable(GL.GL_DEPTH_TEST); double width = this.size.width; double height = this.size.height; // Load a parallel projection with xy dimensions (viewportWidth, viewportHeight) // into the GL projection matrix. java.awt.Rectangle viewport = dc.getView().getViewport(); gl.glMatrixMode(javax.media.opengl.GL.GL_PROJECTION); gl.glPushMatrix(); projectionPushed = true; gl.glLoadIdentity(); double maxwh = width > height ? width : height; gl.glOrtho(0d, viewport.width, 0d, viewport.height, -0.6 * maxwh, 0.6 * maxwh); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPushMatrix(); modelviewPushed = true; gl.glLoadIdentity(); // Scale to a width x height space // located at the proper position on screen double scale = this.computeScale(viewport); Vec4 locationSW = this.computeLocation(viewport, scale); gl.glTranslated(locationSW.x(), locationSW.y(), locationSW.z()); gl.glScaled(scale, scale, 1); // Compute scale size in real world Position referencePosition = dc.getViewportCenterPosition(); if (referencePosition != null) { Vec4 groundTarget = dc.getGlobe().computePointFromPosition(referencePosition); Double distance = dc.getView().getEyePoint().distanceTo3(groundTarget); this.pixelSize = dc.getView().computePixelSizeAtDistance(distance); Double scaleSize = this.pixelSize * width * scale; // meter String unitLabel = "m"; if (this.unit.equals(UNIT_METRIC)) { if (scaleSize > 10000) { scaleSize /= 1000; unitLabel = "Km"; } } else if (this.unit.equals(UNIT_IMPERIAL)) { scaleSize *= 3.280839895; // feet unitLabel = "ft"; if (scaleSize > 5280) { scaleSize /= 5280; unitLabel = "mile(s)"; } } // Rounded division size int pot = (int) Math.floor(Math.log10(scaleSize)); if (!Double.isNaN(pot)) { int digit = Integer.parseInt(String.format("%.0f", scaleSize).substring(0, 1)); double divSize = digit * Math.pow(10, pot); if (digit >= 5) divSize = 5 * Math.pow(10, pot); else if (digit >= 2) divSize = 2 * Math.pow(10, pot); double divWidth = width * divSize / scaleSize; // Draw scale if (!dc.isPickingMode()) { // Set color using current layer opacity Color backColor = this.getBackgroundColor(this.color); float[] colorRGB = backColor.getRGBColorComponents(null); gl.glColor4d( colorRGB[0], colorRGB[1], colorRGB[2], (double) backColor.getAlpha() / 255d * this.getOpacity()); gl.glTranslated((width - divWidth) / 2, 0d, 0d); this.drawScale(dc, divWidth, height); colorRGB = this.color.getRGBColorComponents(null); gl.glColor4d(colorRGB[0], colorRGB[1], colorRGB[2], this.getOpacity()); gl.glTranslated(-1d / scale, 1d / scale, 0d); this.drawScale(dc, divWidth, height); // Draw label String label = String.format("%.0f ", divSize) + unitLabel; gl.glLoadIdentity(); gl.glDisable(GL.GL_CULL_FACE); drawLabel( dc, label, locationSW.add3( new Vec4(divWidth * scale / 2 + (width - divWidth) / 2, height * scale, 0))); } else { // Picking this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); // Draw unique color across the map Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); // Add our object(s) to the pickable list this.pickSupport.addPickableObject(colorCode, this, referencePosition, false); gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); gl.glTranslated((width - divWidth) / 2, 0d, 0d); this.drawRectangle(dc, divWidth, height); // Done picking this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, dc.getPickPoint(), this); } } } } finally { if (projectionPushed) { gl.glMatrixMode(GL.GL_PROJECTION); gl.glPopMatrix(); } if (modelviewPushed) { gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPopMatrix(); } if (attribsPushed) gl.glPopAttrib(); } }
public void selectRenderables(DrawContext dc) { try { OrbitView view = (OrbitView) dc.getView(); // Compute easting and northing label offsets Double pixelSize = view.computePixelSizeAtDistance(view.getZoom()); Double eastingOffset = view.getViewport().width * pixelSize * offsetFactorX / 2; Double northingOffset = view.getViewport().height * pixelSize * offsetFactorY / 2; // Derive labels center pos from the view center Position centerPos = view.getCenterPosition(); double labelEasting; double labelNorthing; String labelHemisphere; if (this.zone > 0) { UTMCoord UTM = UTMCoord.fromLatLon(centerPos.getLatitude(), centerPos.getLongitude(), dc.getGlobe()); labelEasting = UTM.getEasting() + eastingOffset; labelNorthing = UTM.getNorthing() + northingOffset; labelHemisphere = UTM.getHemisphere(); if (labelNorthing < 0) { labelNorthing = 10e6 + labelNorthing; labelHemisphere = AVKey.SOUTH; } } else { UPSCoord UPS = UPSCoord.fromLatLon(centerPos.getLatitude(), centerPos.getLongitude(), dc.getGlobe()); labelEasting = UPS.getEasting() + eastingOffset; labelNorthing = UPS.getNorthing() + northingOffset; labelHemisphere = UPS.getHemisphere(); } Position labelPos; for (int i = 0; i < this.extremes.length; i++) { UTMExtremes levelExtremes = this.extremes[i]; double gridStep = Math.pow(10, i); double gridStepTimesTen = gridStep * 10; String graticuleType = getTypeFor((int) gridStep); if (levelExtremes.minX <= levelExtremes.maxX) { // Process easting scale labels for this level for (double easting = levelExtremes.minX; easting <= levelExtremes.maxX; easting += gridStep) { // Skip multiples of ten grid steps except for last (higher) level if (i == this.extremes.length - 1 || easting % gridStepTimesTen != 0) { try { labelPos = computePosition(this.zone, labelHemisphere, easting, labelNorthing); if (labelPos == null) continue; Angle lat = labelPos.getLatitude(); Angle lon = labelPos.getLongitude(); Vec4 surfacePoint = getSurfacePoint(dc, lat, lon); if (viewFrustum.contains(surfacePoint) && isPointInRange(dc, surfacePoint)) { String text = String.valueOf((int) (easting % this.scaleModulo)); GeographicText gt = new UserFacingText(text, new Position(lat, lon, 0)); gt.setPriority(gridStepTimesTen); addRenderable(gt, graticuleType); } } catch (IllegalArgumentException ignore) { } } } } if (!(levelExtremes.maxYHemisphere.equals(AVKey.SOUTH) && levelExtremes.maxY == 0)) { // Process northing scale labels for this level String currentHemisphere = levelExtremes.minYHemisphere; for (double northing = levelExtremes.minY; (northing <= levelExtremes.maxY) || !currentHemisphere.equals(levelExtremes.maxYHemisphere); northing += gridStep) { // Skip multiples of ten grid steps except for last (higher) level if (i == this.extremes.length - 1 || northing % gridStepTimesTen != 0) { try { labelPos = computePosition(this.zone, currentHemisphere, labelEasting, northing); if (labelPos == null) continue; Angle lat = labelPos.getLatitude(); Angle lon = labelPos.getLongitude(); Vec4 surfacePoint = getSurfacePoint(dc, lat, lon); if (viewFrustum.contains(surfacePoint) && isPointInRange(dc, surfacePoint)) { String text = String.valueOf((int) (northing % this.scaleModulo)); GeographicText gt = new UserFacingText(text, new Position(lat, lon, 0)); gt.setPriority(gridStepTimesTen); addRenderable(gt, graticuleType); } } catch (IllegalArgumentException ignore) { } if (!currentHemisphere.equals(levelExtremes.maxYHemisphere) && northing >= 10e6 - gridStep) { // Switch hemisphere currentHemisphere = levelExtremes.maxYHemisphere; northing = -gridStep; } } } } // end northing } // for levels } catch (IllegalArgumentException ignore) { } }
private PolygonGeometry getPolygonGeometry( DrawContext dc, List<LatLon> locations, List<Boolean> edgeFlags, double[] altitudes, boolean[] terrainConformant, boolean enableCaps, int subdivisions, Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey( dc.getGlobe(), this.getClass(), "Polygon", locations, edgeFlags, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], enableCaps, subdivisions, referenceCenter); // Wrap geometry creation in a try/catch block. We do this to catch and handle OutOfMemoryErrors // caused during // tessellation of the polygon vertices. If the polygon cannot be tessellated, we replace the // polygon's // locations with an empty list to prevent subsequent tessellation attempts, and to avoid // rendering a misleading // representation by omitting any part of the geometry. try { PolygonGeometry geom = (PolygonGeometry) this.getGeometryCache().getObject(cacheKey); if (geom == null || this.isExpired(dc, geom.getVertexGeometry())) { if (geom == null) geom = new PolygonGeometry(); this.makePolygon( dc, locations, edgeFlags, altitudes, terrainConformant, enableCaps, subdivisions, referenceCenter, geom); this.updateExpiryCriteria(dc, geom.getVertexGeometry()); this.getGeometryCache().add(cacheKey, geom); } return geom; } catch (OutOfMemoryError e) { String message = Logging.getMessage("generic.ExceptionWhileTessellating", this); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); //noinspection ThrowableInstanceNeverThrown dc.addRenderingException(new WWRuntimeException(message, e)); this.handleUnsuccessfulGeometryCreation(); return null; } }
private void makePolygon( DrawContext dc, List<LatLon> locations, List<Boolean> edgeFlags, double[] altitudes, boolean[] terrainConformant, boolean enableCaps, int subdivisions, Vec4 referenceCenter, PolygonGeometry dest) { if (locations.size() == 0) return; GeometryBuilder gb = this.getGeometryBuilder(); Vec4[] polyPoints = new Vec4[locations.size() + 1]; Boolean[] polyEdgeFlags = new Boolean[locations.size() + 1]; Matrix[] polyTransform = new Matrix[1]; int polyCount = this.computeCartesianPolygon( dc.getGlobe(), locations, edgeFlags, polyPoints, polyEdgeFlags, polyTransform); // Compute the winding order of the planar cartesian points. If the order is not // counter-clockwise, then // reverse the locations and points ordering. int winding = gb.computePolygonWindingOrder2(0, polyCount, polyPoints); if (winding != GeometryBuilder.COUNTER_CLOCKWISE) { gb.reversePoints(0, polyCount, polyPoints); gb.reversePoints(0, polyCount, polyEdgeFlags); } float[] polyVertices = new float[3 * polyCount]; this.makePolygonVertices(polyCount, polyPoints, polyVertices); int fillDrawMode = GL.GL_TRIANGLES; int outlineDrawMode = GL.GL_LINES; int fillIndexCount = 0; int outlineIndexCount = 0; int vertexCount = 0; GeometryBuilder.IndexedTriangleArray ita = null; fillIndexCount += this.getEdgeFillIndexCount(polyCount, subdivisions); outlineIndexCount += this.getEdgeOutlineIndexCount(polyCount, subdivisions, polyEdgeFlags); vertexCount += this.getEdgeVertexCount(polyCount, subdivisions); if (enableCaps) { ita = gb.tessellatePolygon2(0, polyCount, polyVertices); for (int i = 0; i < subdivisions; i++) { gb.subdivideIndexedTriangleArray(ita); } fillIndexCount += ita.getIndexCount(); vertexCount += ita.getVertexCount(); // Bottom cap isn't drawn if airspace is collapsed. if (!this.isAirspaceCollapsed()) { fillIndexCount += ita.getIndexCount(); vertexCount += ita.getVertexCount(); } } int[] fillIndices = new int[fillIndexCount]; int[] outlineIndices = new int[outlineIndexCount]; float[] vertices = new float[3 * vertexCount]; float[] normals = new float[3 * vertexCount]; int fillIndexPos = 0; int outlineIndexPos = 0; int vertexPos = 0; this.makeEdge( dc, polyCount, polyVertices, polyEdgeFlags, altitudes, terrainConformant, subdivisions, GeometryBuilder.OUTSIDE, polyTransform[0], referenceCenter, fillIndexPos, fillIndices, outlineIndexPos, outlineIndices, vertexPos, vertices, normals); fillIndexPos += this.getEdgeFillIndexCount(polyCount, subdivisions); outlineIndexPos += this.getEdgeOutlineIndexCount(polyCount, subdivisions, polyEdgeFlags); vertexPos += this.getEdgeVertexCount(polyCount, subdivisions); if (enableCaps) { this.makeCap( dc, ita, altitudes[1], terrainConformant[1], GeometryBuilder.OUTSIDE, polyTransform[0], referenceCenter, fillIndexPos, fillIndices, vertexPos, vertices, normals); fillIndexPos += ita.getIndexCount(); vertexPos += ita.getVertexCount(); // Bottom cap isn't drawn if airspace is collapsed. if (!this.isAirspaceCollapsed()) { this.makeCap( dc, ita, altitudes[0], terrainConformant[0], GeometryBuilder.INSIDE, polyTransform[0], referenceCenter, fillIndexPos, fillIndices, vertexPos, vertices, normals); fillIndexPos += ita.getIndexCount(); vertexPos += ita.getVertexCount(); } } dest.getFillIndexGeometry().setElementData(fillDrawMode, fillIndexCount, fillIndices); dest.getOutlineIndexGeometry() .setElementData(outlineDrawMode, outlineIndexCount, outlineIndices); dest.getVertexGeometry().setVertexData(vertexCount, vertices); dest.getVertexGeometry().setNormalData(vertexCount, normals); }