Repository navigation
GeoPlaceLabelsFigure
Up | Previous | Next | Русский
Below is the full source of the class in documentation form. The comments inside the block explain the purpose of the parts of the class, but they are not stored in the working file GeoPlaceLabelsFigure.java: the production code stays clean, and the explanations live in the wiki.
package com.velitask.plugin.official.geo;
import com.velitask.plugin.official.GeoMapIndicator;
import com.velitask.sdk.IndicatorContext;
import com.velitask.sdk.figures.Figure;
import com.velitask.sdk.properties.ColorProperty;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.DisplayHint;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.MapPlacesProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.SizeProperty;
import com.velitask.sdk.properties.VisibleProperty;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.abricos.geo.GeoUtils;
import org.abricos.geo.vector.Feature;
import org.abricos.geo.vector.VectorDataTypes;
import org.abricos.geo.vector.VectorTile;
/* The "Place labels" figure: names of cities, towns, villages and hamlets. */
public class GeoPlaceLabelsFigure extends Figure<GeoFigureContext> {
/* Figure name (the type field in the figure JSON). */
public static final String NAME = "placeLabels";
/* Localization key prefix. */
private static final String KEY = GeoMapIndicator.KEY + "." + NAME;
/* Place data exists up to zoom 12; above that the zoom 12 tile is used. */
private static final int MAX_DATA_ZOOM = 12;
/* Parameters of depth scaling of the labels with a 3D tilt. */
private static final double DEPTH_STRENGTH = 0.88;
private static final double MIN_DEPTH_SCALE = 0.4;
private static final double MAX_DEPTH_SCALE = 1.6;
/* Base font of the labels; the size is set by the properties. */
private static final Font BASE_FONT = new Font("SansSerif", Font.BOLD, 12);
/* Source of the place points; not saved in JSON. */
private final MapPlacesProperty mPlaces = new MapPlacesProperty();
/* Name of the text color property. */
private static final String TEXT_COLOR = "textColor";
/* Label text color, (30, 30, 30) by default. */
private final ColorProperty mTextColor = new ColorProperty(
new Color(30, 30, 30), TEXT_COLOR, localized(KEY + "." + TEXT_COLOR + ".title"));
/* Name of the halo color property. */
private static final String HALO_COLOR = "haloColor";
/* Color of the text outline (halo), white by default. */
private final ColorProperty mHaloColor = new ColorProperty(
Color.WHITE, HALO_COLOR, localized(KEY + "." + HALO_COLOR + ".title"));
/* Base font size: 8..72, 16 by default. */
private final SizeProperty mFontSize = new SizeProperty() {
{
setRange(8, 72);
}
@Override
public Integer getDefault() {
return 16;
}
};
/* Point marker next to the label; off by default. */
private final VisibleProperty mShowMarker = new VisibleProperty() {
{
setDefault(false);
set(false);
}
@Override
public String getName() {
return "showMarker";
}
@Override
public String getTitle() {
return localized(KEY + ".showMarker.title");
}
};
/* Three properties per place type: show, from which zoom, size as a percentage of the base (cities 100%, towns 85%, villages 72%, hamlets 62%). */
private final VisibleProperty mCityShow = showToggle("cityShow", true);
private final SizeProperty mCityZoom = zoomSpinner("cityZoom", 8);
private final SizeProperty mCityDelta = deltaSpinner("cityDelta", 100);
private final VisibleProperty mTownShow = showToggle("townShow", true);
private final SizeProperty mTownZoom = zoomSpinner("townZoom", 10);
private final SizeProperty mTownDelta = deltaSpinner("townDelta", 85);
private final VisibleProperty mVillageShow = showToggle("villageShow", true);
private final SizeProperty mVillageZoom = zoomSpinner("villageZoom", 12);
private final SizeProperty mVillageDelta = deltaSpinner("villageDelta", 72);
private final VisibleProperty mHamletShow = showToggle("hamletShow", true);
private final SizeProperty mHamletZoom = zoomSpinner("hamletZoom", 14);
private final SizeProperty mHamletDelta = deltaSpinner("hamletDelta", 62);
/* Factory of the toggles. */
private VisibleProperty showToggle(String name, boolean def) {
return new VisibleProperty() {
{
setDefault(def);
set(def);
}
@Override
public String getName() {
return name;
}
@Override
public String getTitle() {
return localized(KEY + "." + name + ".title");
}
};
}
/* Factory of the zoom thresholds: range 1..19. */
private SizeProperty zoomSpinner(String name, int def) {
return new SizeProperty() {
{
setRange(1, 19);
}
@Override
public Integer getDefault() {
return def;
}
@Override
public String getName() {
return name;
}
@Override
public String getTitle() {
return localized(KEY + "." + name + ".title");
}
};
}
/* Factory of the size percentages: range 10..300. */
private SizeProperty deltaSpinner(String name, int def) {
return new SizeProperty() {
{
setRange(10, 300);
}
@Override
public Integer getDefault() {
return def;
}
@Override
public String getName() {
return name;
}
@Override
public String getTitle() {
return localized(KEY + "." + name + ".title");
}
};
}
@Override
public String getName() {
return NAME;
}
@Override
public String getTitle() {
return localized(KEY + ".title");
}
@Override
/* Set and order of the saved properties. */
public IProperty[] defineProperties() {
return new IProperty[]{
mTextColor, mHaloColor, mFontSize, mShowMarker,
mCityShow, mCityZoom, mCityDelta,
mTownShow, mTownZoom, mTownDelta,
mVillageShow, mVillageZoom, mVillageDelta,
mHamletShow, mHamletZoom, mHamletDelta
};
}
@Override
/* All settings are in the appearance group; sizes and zooms are spinners. */
public void configureDisplay(DisplayConfig config) {
config.set(mTextColor, PropertyGroup.APPEARANCE);
config.set(mHaloColor, PropertyGroup.APPEARANCE);
config.set(mFontSize, PropertyGroup.APPEARANCE, DisplayHint.SPINNER);
config.set(mShowMarker, PropertyGroup.APPEARANCE);
for (SizeProperty s : new SizeProperty[]{
mCityZoom, mCityDelta, mTownZoom, mTownDelta,
mVillageZoom, mVillageDelta, mHamletZoom, mHamletDelta}) {
config.set(s, PropertyGroup.APPEARANCE, DisplayHint.SPINNER);
}
for (VisibleProperty v : new VisibleProperty[]{
mCityShow, mTownShow, mVillageShow, mHamletShow}) {
config.set(v, PropertyGroup.APPEARANCE);
}
}
@Override
/* Collects the places in the visible area and draws the labels without overlaps. */
public void render(GeoFigureContext baseCtx) {
LabelsContext ctx = (LabelsContext) baseCtx;
if (ctx.zoom == null) {
return;
}
int z = ctx.zoom.getLevel();
/* Place types that are enabled and allowed by the current zoom. */
Set<String> required = new LinkedHashSet<>();
if (ctx.cityShow && z >= ctx.cityZoom) {
required.add(VectorDataTypes.CITY);
}
if (ctx.townShow && z >= ctx.townZoom) {
required.add(VectorDataTypes.TOWN);
}
if (ctx.villageShow && z >= ctx.villageZoom) {
required.add(VectorDataTypes.VILLAGE);
}
if (ctx.hamletShow && z >= ctx.hamletZoom) {
required.add(VectorDataTypes.HAMLET);
}
if (required.isEmpty()) {
return;
}
/* Tile range around the map center by the radius of the frame diagonal. */
double cx = ctx.centerPx;
double cy = ctx.centerPy;
double extra = Math.max(0.05, ctx.indicator.extraScale);
double radiusPx = Math.hypot(ctx.width, ctx.height) / extra + GeoUtils.TILE_SIZE;
int maxIndex = (1 << z) - 1;
int xMin = Math.max((int) Math.floor((cx - radiusPx) / GeoUtils.TILE_SIZE) - 1, 0);
int yMin = Math.max((int) Math.floor((cy - radiusPx) / GeoUtils.TILE_SIZE) - 1, 0);
int xMax = Math.min((int) Math.floor((cx + radiusPx) / GeoUtils.TILE_SIZE) + 1, maxIndex);
int yMax = Math.min((int) Math.floor((cy + radiusPx) / GeoUtils.TILE_SIZE) + 1, maxIndex);
Graphics2D g = ctx.graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
/* The sizes of the marker, the gap and the halo depend on the layer scale. */
int markerR = Math.max(2, (int) Math.round(3 * ctx.scale));
int gap = markerR + Math.max(2, (int) Math.round(3 * ctx.scale));
int haloO = Math.max(1, (int) Math.round(1.5 * ctx.scale));
/* Data tile number with a shift at zooms above 12. */
int dataZoom = Math.min(z, MAX_DATA_ZOOM);
int shift = z - dataZoom;
/* Collecting places from the tiles: duplicates by id and unnamed ones are discarded. */
Set<Long> requested = new HashSet<>();
Set<String> seen = new HashSet<>();
List<Feature> places = new ArrayList<>();
for (int tx = xMin; tx <= xMax; tx++) {
for (int ty = yMin; ty <= yMax; ty++) {
int px = tx >> shift;
int py = ty >> shift;
long pkey = (((long) px) << 32) | (py & 0xffffffffL);
if (!requested.add(pkey)) {
continue;
}
VectorTile tile = ctx.indicator.player.isPreview
? mPlaces.getPlaces(dataZoom, px, py, required)
: mPlaces.getPlacesBlocking(dataZoom, px, py, required, 5_000);
List<Feature> feats = tile.getFeatures();
if (feats == null) {
continue;
}
for (Feature f : feats) {
if (f.getId() != null && !seen.add(f.getId())) {
continue;
}
if (f.getName() == null || f.getName().isBlank()) {
continue;
}
places.add(f);
}
}
}
/* Large places (city → hamlet) are placed first and push out the small ones. */
places.sort(Comparator.comparingInt(f -> rank(f.getSubtype())));
/* Label placement: a label is skipped if its box intersects an already placed one. */
List<Rectangle> placed = new ArrayList<>();
for (Feature f : places) {
int deltaPct = deltaFor(ctx, f.getSubtype());
double fs = Math.max(6, ctx.fontSize * ctx.scale * deltaPct / 100.0);
g.setFont(BASE_FONT.deriveFont((float) fs));
FontMetrics fm = g.getFontMetrics();
Point2D.Double p = ctx.toScreen(f.lat(), f.lon());
int px = (int) p.x;
int py = (int) p.y;
if (px < -200 || py < -200 || px > ctx.width + 200 || py > ctx.height + 200) {
continue;
}
String name = f.getName();
double ds = depthScale(ctx, py);
int w = fm.stringWidth(name);
int sw = (int) Math.round(w * ds);
int sAsc = (int) Math.round(fm.getAscent() * ds);
int sH = (int) Math.round(fm.getHeight() * ds);
int labelY = ctx.showMarker ? py - gap : py + sAsc / 2;
Rectangle box = new Rectangle(px - sw / 2, labelY - sAsc, sw, sH);
boolean overlap = false;
for (Rectangle r : placed) {
if (r.intersects(box)) {
overlap = true;
break;
}
}
if (overlap) {
continue;
}
placed.add(box);
if (ctx.showMarker) {
g.setColor(ctx.textColor);
g.fillOval(px - markerR, py - markerR, markerR * 2, markerR * 2);
g.setColor(ctx.haloColor);
g.drawOval(px - markerR, py - markerR, markerR * 2, markerR * 2);
}
Graphics2D gp = (Graphics2D) g.create();
try {
gp.translate(px, labelY);
gp.scale(ds, ds);
drawHaloText(gp, name, -w / 2, 0, ctx.haloColor, ctx.textColor, haloO);
} finally {
gp.dispose();
}
}
}
/* With a tilt, distant labels shrink and near ones grow (0.4..1.6). */
private static double depthScale(LabelsContext ctx, int py) {
double tilt = ctx.indicator.tiltRad;
if (tilt <= 0.01) {
return 1.0;
}
double anchorY = ctx.height / 2.0 + ctx.indicator.anchorOffsetY;
double rel = (anchorY - py) / Math.max(1.0, ctx.height);
double factor = rel * Math.sin(tilt) * DEPTH_STRENGTH;
double s = 1.0 / (1.0 + factor);
return Math.max(MIN_DEPTH_SCALE, Math.min(MAX_DEPTH_SCALE, s));
}
/* Size percentage by place type. */
private static int deltaFor(LabelsContext ctx, String subtype) {
if (subtype == null) {
return 100;
}
switch (subtype) {
case "city":
return ctx.cityDelta;
case "town":
return ctx.townDelta;
case "village":
return ctx.villageDelta;
case "hamlet":
return ctx.hamletDelta;
default:
return 100;
}
}
/* Order of importance of the types. */
private static int rank(String subtype) {
if (subtype == null) {
return 4;
}
switch (subtype) {
case "city":
return 0;
case "town":
return 1;
case "village":
return 2;
case "hamlet":
return 3;
default:
return 4;
}
}
/* Text with a halo: first in the halo color with offsets, then in the main color. */
private static void drawHaloText(Graphics2D g, String s, int x, int y,
Color halo, Color text, int o) {
g.setColor(halo);
for (int dx = -o; dx <= o; dx++) {
for (int dy = -o; dy <= o; dy++) {
if (dx != 0 || dy != 0) {
g.drawString(s, x + dx, y + dy);
}
}
}
g.setColor(text);
g.drawString(s, x, y);
}
@Override
/* Creating the context from the indicator context. */
public GeoFigureContext createContext(IndicatorContext indCtx) {
return new LabelsContext((GeoMapIndicator.GeoMapContext) indCtx);
}
/* Figure context: property values for the frame. */
public class LabelsContext extends GeoFigureContext {
public final Color textColor;
public final Color haloColor;
public final int fontSize;
public final boolean showMarker;
public final boolean cityShow;
public final int cityZoom;
public final int cityDelta;
public final boolean townShow;
public final int townZoom;
public final int townDelta;
public final boolean villageShow;
public final int villageZoom;
public final int villageDelta;
public final boolean hamletShow;
public final int hamletZoom;
public final int hamletDelta;
public LabelsContext(GeoMapIndicator.GeoMapContext indCtx) {
super(indCtx);
textColor = mTextColor.get(indCtx);
haloColor = mHaloColor.get(indCtx);
fontSize = mFontSize.get(indCtx);
showMarker = mShowMarker.get(indCtx);
cityShow = mCityShow.get(indCtx);
cityZoom = mCityZoom.get(indCtx);
cityDelta = mCityDelta.get(indCtx);
townShow = mTownShow.get(indCtx);
townZoom = mTownZoom.get(indCtx);
townDelta = mTownDelta.get(indCtx);
villageShow = mVillageShow.get(indCtx);
villageZoom = mVillageZoom.get(indCtx);
villageDelta = mVillageDelta.get(indCtx);
hamletShow = mHamletShow.get(indCtx);
hamletZoom = mHamletZoom.get(indCtx);
hamletDelta = mHamletDelta.get(indCtx);
}
}
}GeoPlaceLabelsFigure labels cities, towns, villages and hamlets on the map with names from vector data. The labels do not overlap each other, large places have priority, and at small scales the small types are hidden. It is supported only in GeoMapIndicator and is not added by default.
Data. MapPlacesProperty requests VectorTile tiles with Feature points (the subtypes city, town, village, hamlet; the name comes from getName()). Data exists up to zoom 12; at higher zooms the tile index is shifted. Which tiles are needed is determined by the map center (centerPx, centerPy), the radius of the frame diagonal and the indicator's extraScale. In preview, tiles are taken from the cache without waiting; during export, with a wait of up to 5 seconds.
Settings. 16 properties are saved in the figure JSON: textColor, haloColor, size, showMarker and, for each of the types city, town, village, hamlet, the triple …Show, …Zoom, …Delta. A place takes part if its …Show is on and the map zoom is not lower than …Zoom. The label size equals size × scale × …Delta / 100, but not less than 6 pixels.
Rendering. The places are sorted by importance (city, town, village, hamlet). Each one is converted by the toScreen(lat, lon) method (GeoFigureContext); points more than 200 pixels beyond the frame edge are skipped. The label rectangle is compared with the already placed ones, and if it intersects, the label is not drawn. With a tilt, the label size is scaled by the depthScale function. The text is drawn with a halo about 1.5 × scale thick; with showMarker, a dot in the text color with an outline in the halo color is placed next to it, and the label is shifted up.
- The labels do not rotate with the map: when the map is rotated, the text stays horizontal.
- With a large number of places, some labels disappear because of intersections; this is normal behavior, not a data error.
- Places without a name are not drawn.
- If all types are off or the zoom is below all thresholds, the figure does nothing.
- Without external vector data there will be no labels, and no error is shown.
- Transparency is not configurable: the text and halo colors are drawn with the alpha set in the colors themselves.