Repository navigation
GeoMapIndicator
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 kept in the working file GeoMapIndicator.java: the production code stays clean, and the explanations live in the wiki.
package com.velitask.plugin.official;
import com.velitask.plugin.official.geo.GeoPlaceBoundaryFigure;
import com.velitask.plugin.official.geo.GeoPlaceLabelsFigure;
import com.velitask.plugin.official.geo.GeoPositionFigure;
import com.velitask.plugin.official.geo.GeoTrackFigure;
import com.velitask.sdk.FrameContext;
import com.velitask.sdk.Indicator;
import com.velitask.sdk.IndicatorContext;
import com.velitask.sdk.IndicatorSkin;
import com.velitask.sdk.MissingData;
import com.velitask.sdk.data.GeoSensorAtom;
import com.velitask.sdk.data.LandBounds;
import com.velitask.sdk.db.DataCacheRule;
import com.velitask.sdk.db.DataParams;
import com.velitask.sdk.figures.IFigure;
import com.velitask.sdk.properties.ArrayProperty;
import com.velitask.sdk.properties.BorderProperty;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.DisplayHint;
import com.velitask.sdk.properties.EnumArrayProperty;
import com.velitask.sdk.properties.FitTrackProperty;
import com.velitask.sdk.properties.GeoSensorProperty;
import com.velitask.sdk.properties.GeoZoomProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.IntegerProperty;
import com.velitask.sdk.properties.MapTilesProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.TransparencyProperty;
import com.velitask.sdk.properties.VisibleProperty;
import com.velitask.units.angle.TrackBearing;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.util.List;
import org.abricos.core.state.maket.HorizontalAlign;
import org.abricos.core.state.maket.Maket;
import org.abricos.core.state.maket.VerticalAlign;
import org.abricos.geo.GeoUtils;
import org.abricos.geo.MapZoom;
import org.abricos.geo.tile.Tile;
import org.abricos.geo.tile.TilePixel;
import org.json.JSONObject;
public class GeoMapIndicator extends Indicator {
/* Indicator name; it is part of the layer identifier and of JSON. */
public static final String NAME = "geoMap";
/* Prefix of the localization keys of the indicator and its figures. */
public static final String KEY = _KEY + "." + NAME;
/* Rotation mode: north up, heading up, manual. JSON stores the index. */
public enum RotationMode {
NORTH_UP, HEADING_UP, MANUAL
}
/* Where on the map the current position stands: at the center or in the bottom third. JSON stores the index. */
public enum VehicleAnchor {
CENTER, BOTTOM_THIRD
}
/* Geo sensor choice. The track query returns the track points for the current zoom, by time. */
private final GeoSensorProperty mGeoSensor = new GeoSensorProperty();
{
mGeoSensor.query("track")
/* The track is read from simplified copies at the selected scale, not from exact atoms. */
.anyLevel()
.where("zoom = {zoom}")
.orderBy("timeRaw")
.cache(DataCacheRule.byParams())
.cacheSize(2)
.buildList();
}
/* Access to the OSM raster tiles; not saved in JSON. */
private final MapTilesProperty mTiles = new MapTilesProperty();
/* Map zoom (8..19, 14 by default); blocked with "Fit track". */
private final GeoZoomProperty mGeoZoom = new GeoZoomProperty();
/* Transparency of the map tiles in percent (0..100). */
private final TransparencyProperty mMapTransparency = new TransparencyProperty();
/* Visibility of the map tiles. The track and the other figures do not depend on it. */
private final VisibleProperty mShowMap = new VisibleProperty();
/* Border around the map: color, thickness, line style and corner radius. */
private final BorderProperty mBorder = new BorderProperty();
/* Tilt angle 0..85, 50 by default; active only when the 3D view is on. */
private final IntegerProperty mTilt = new IntegerProperty() {
{
setRange(0, 85);
}
@Override
public String getName() {
return "tilt";
}
@Override
public Integer getDefault() {
return 50;
}
@Override
public String getTitle() {
return localized(KEY + ".tilt.title");
}
};
/* 3D view switch (off by default); it enables and disables the tilt field. */
private final VisibleProperty mView3D = new VisibleProperty() {
{
setDefault(false);
set(false);
}
@Override
public String getName() {
return "view3D";
}
@Override
public String getTitle() {
return localized(KEY + ".view3D.title");
}
@Override
public IProperty[] dependents() {
return new IProperty[]{mTilt};
}
@Override
protected void onChanged(Object oldVal, Object newVal) {
mTilt.setEnabled(Boolean.TRUE.equals(newVal));
}
@Override
public void fromJSON(JSONObject json) {
super.fromJSON(json);
mTilt.setEnabled(get());
}
};
/* Bearing for the "Manual" mode, 0..359, 0 by default. */
private final IntegerProperty mManualBearing = new IntegerProperty() {
{
setRange(0, 359);
}
@Override
public String getName() {
return "manualBearing";
}
@Override
public Integer getDefault() {
return 0;
}
@Override
public String getTitle() {
return localized(KEY + ".manualBearing.title");
}
};
/* Minimum speed (km/h, 0..50, 2 by default) from which the bearing is updated in the "Heading up" mode. */
private final IntegerProperty mMinSpeedKmh = new IntegerProperty() {
{
setRange(0, 50);
}
@Override
public String getName() {
return "minSpeedKmh";
}
@Override
public Integer getDefault() {
return 2;
}
@Override
public String getTitle() {
return localized(KEY + ".minSpeedKmh.title");
}
};
/* Vehicle anchor: center (default) or bottom third. */
private final EnumArrayProperty<VehicleAnchor> mVehicleAnchor
= new EnumArrayProperty<>(VehicleAnchor.class) {
@Override
public String getName() {
return "vehicleAnchor";
}
@Override
public String getTitle() {
return localized(KEY + ".vehicleAnchor.title");
}
@Override
protected String[] defineTitles() {
return new String[]{
localized(KEY + ".vehicleAnchor.center"),
localized(KEY + ".vehicleAnchor.bottomThird")
};
}
};
/* Rotation mode; it enables the manual bearing or the minimum speed depending on the mode. */
private final EnumArrayProperty<RotationMode> mRotation
= new EnumArrayProperty<>(RotationMode.class) {
@Override
public String getName() {
return "rotation";
}
@Override
public String getTitle() {
return localized(KEY + ".rotation.title");
}
@Override
protected String[] defineTitles() {
return new String[]{
localized(KEY + ".rotation.northUp"),
localized(KEY + ".rotation.headingUp"),
localized(KEY + ".rotation.manual")
};
}
@Override
public IProperty[] dependents() {
return new IProperty[]{mManualBearing, mMinSpeedKmh};
}
@Override
protected void onChanged(Object oldVal, Object newVal) {
applyRotationDependents();
}
@Override
public void fromJSON(JSONObject json) {
super.fromJSON(json);
applyRotationDependents();
}
};
/* "Fit track": show the whole track instead of following the position; it blocks the zoom. */
private final FitTrackProperty mFitTrack = new FitTrackProperty() {
@Override
public IProperty[] dependents() {
return new IProperty[]{mGeoZoom};
}
@Override
protected void onChanged(Object oldVal, Object newVal) {
mGeoZoom.setEnabled(!Boolean.TRUE.equals(newVal));
}
@Override
public void fromJSON(JSONObject json) {
super.fromJSON(json);
mGeoZoom.setEnabled(!get());
}
};
/* The last reliable bearing of movement: held while the speed is below the threshold. */
private double mLastValidBearingDeg = 0;
/* Enables the manual bearing only for the "Manual" mode, the speed threshold only for "Heading up". */
private void applyRotationDependents() {
RotationMode m = mRotation.get();
mManualBearing.setEnabled(m == RotationMode.MANUAL);
mMinSpeedKmh.setEnabled(m == RotationMode.HEADING_UP);
}
/* Access to the geo property for code outside the indicator. */
public GeoSensorProperty getGeo() {
return mGeoSensor;
}
public FitTrackProperty getFitTrack() {
return mFitTrack;
}
@Override
public String getName() {
return NAME;
}
@Override
public String getTitle() {
return localized(KEY + ".title");
}
@Override
public String getDescription() {
return localized(KEY + ".description");
}
@Override
public String getTags() {
return localized(KEY + ".tags");
}
@Override
/* Default maket: layer 700×400, pinned to the bottom left corner, margin 50. */
public void defineMaket(Maket maket) {
maket.setVertical(VerticalAlign.BOTTOM);
maket.setHorizontal(HorizontalAlign.LEFT);
maket.setLayerMargin(50d, null, null, 50d);
maket.setLayerSize(700d, 400d);
}
@Override
/* Order of properties; they are saved by name, except mTiles (not a Property). */
public IProperty[] defineProperties() {
return new IProperty[]{
mGeoSensor, mTiles, mShowMap, mFitTrack, mGeoZoom, mMapTransparency, mBorder,
mView3D, mTilt, mRotation, mManualBearing, mMinSpeedKmh, mVehicleAnchor
};
}
@Override
/* All settings are in the appearance group; the tilt and the manual bearing are sliders. */
public void configureDisplay(DisplayConfig config) {
config.set(mShowMap, PropertyGroup.APPEARANCE);
config.set(mFitTrack, PropertyGroup.APPEARANCE);
config.set(mGeoZoom, PropertyGroup.APPEARANCE);
config.set(mMapTransparency, PropertyGroup.APPEARANCE);
config.set(mBorder, PropertyGroup.APPEARANCE);
config.set(mView3D, PropertyGroup.APPEARANCE);
config.set(mTilt, PropertyGroup.APPEARANCE, DisplayHint.SLIDER);
config.set(mRotation, PropertyGroup.APPEARANCE);
config.set(mManualBearing, PropertyGroup.APPEARANCE, DisplayHint.SLIDER);
config.set(mMinSpeedKmh, PropertyGroup.APPEARANCE);
config.set(mVehicleAnchor, PropertyGroup.APPEARANCE);
}
@Override
@SuppressWarnings("unchecked")
/* Figures that the user can add to the map. */
public Class<? extends IFigure>[] supportedFigures() {
return (Class<? extends IFigure>[]) new Class<?>[]{
GeoPlaceBoundaryFigure.class,
GeoTrackFigure.class,
GeoPositionFigure.class,
GeoPlaceLabelsFigure.class
};
}
@Override
@SuppressWarnings("unchecked")
/* Figures added automatically: the track and the position. */
public Class<? extends IFigure>[] defaultFigures() {
return (Class<? extends IFigure>[]) new Class<?>[]{
GeoTrackFigure.class,
GeoPositionFigure.class
};
}
@Override
/* Two skins: "Faded" (the map is visible, transparency 60) and "No map". */
public IndicatorSkin[] defineSkins() {
return new IndicatorSkin[]{
IndicatorSkin.builder("faded", localized(KEY + ".skin.faded"))
.set(mShowMap.skin(true))
.set(mMapTransparency.skin(60))
.build(),
IndicatorSkin.builder("hidden", localized(KEY + ".skin.hidden"))
.set(mShowMap.skin(false))
.build()
};
}
@Override
/* Draws only the tiles and the border; the track, the position and the labels are drawn by figures. */
public void render(IndicatorContext indicatorContext) {
GeoMapContext ctx = (GeoMapContext) indicatorContext;
Graphics2D g = ctx.graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
if (!ctx.showMap.value) {
return;
}
renderMap(ctx);
}
/* Drawing the tiles: a clip by the rounding, the map through mapTransform, then the border. */
private void renderMap(GeoMapContext ctx) {
Graphics2D g = ctx.graphics;
int w = ctx.width, h = ctx.height;
MapZoom zoom = ctx.zoom;
if (zoom == null) {
return;
}
Shape oldClip = g.getClip();
int radius = (int) (ctx.border.radius * ctx.scale);
if (radius > 0) {
g.setClip(new RoundRectangle2D.Double(0, 0, w, h, radius * 2.0, radius * 2.0));
}
AffineTransform oldTransform = g.getTransform();
g.transform(ctx.mapTransform);
/* Halves of the visible area in map pixels taking the "fit track" scale and the tilt into account. */
double invExtra = 1.0 / Math.max(0.0001, ctx.extraScale);
double halfW = w / 2.0 * invExtra;
double halfH;
if (ctx.tiltRad > 0) {
double cosTilt = Math.cos(ctx.tiltRad);
halfH = (h / 2.0 + ctx.anchorOffsetY) / Math.max(0.05, cosTilt) * invExtra;
} else {
halfH = h / 2.0 * invExtra;
}
double centerX = ctx.centerPx;
double centerY = ctx.centerPy;
int xIndexMin, yIndexMin, xIndexMax, yIndexMax;
if (ctx.bearingRad == 0 && ctx.tiltRad == 0) {
xIndexMin = Math.max(
(int) Math.floor((centerX - halfW) / GeoUtils.TILE_SIZE) - 1, 0);
yIndexMin = Math.max(
(int) Math.floor((centerY - halfH) / GeoUtils.TILE_SIZE) - 1, 0);
xIndexMax = (int) Math.floor((centerX + halfW) / GeoUtils.TILE_SIZE) + 1;
yIndexMax = (int) Math.floor((centerY + halfH) / GeoUtils.TILE_SIZE) + 1;
} else {
double radiusPx = Math.hypot(halfW, halfH) + GeoUtils.TILE_SIZE;
xIndexMin = Math.max(
(int) Math.floor((centerX - radiusPx) / GeoUtils.TILE_SIZE) - 1, 0);
yIndexMin = Math.max(
(int) Math.floor((centerY - radiusPx) / GeoUtils.TILE_SIZE) - 1, 0);
xIndexMax = (int) Math.floor((centerX + radiusPx) / GeoUtils.TILE_SIZE) + 1;
yIndexMax = (int) Math.floor((centerY + radiusPx) / GeoUtils.TILE_SIZE) + 1;
}
/* Tiles above this line (beyond the "horizon" in 3D) are skipped. */
double horizonCullY = -halfH * 1.5;
Composite oldComp = g.getComposite();
float alpha = Math.max(0, Math.min(1, 1f - ctx.mapTransparency.value / 100f));
if (alpha < 1f) {
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
}
/* Loop over the tiles: in the preview from the cache without waiting, on export with a wait of up to 5 s. */
int zoomValue = zoom.getLevel();
for (int tx = xIndexMin; tx <= xIndexMax; tx++) {
for (int ty = yIndexMin; ty <= yIndexMax; ty++) {
double localY = ty * GeoUtils.TILE_SIZE - centerY;
if (localY + GeoUtils.TILE_SIZE < horizonCullY) {
continue;
}
Tile tile = ctx.player.isPreview
? mTiles.getTile(zoomValue, tx, ty)
: mTiles.getTileBlocking(zoomValue, tx, ty, 5_000);
if (tile == null || tile.getImage() == null) {
/* The frame is drawn without part of the background: the source preview will be redrawn when the tiles are loaded. */
ctx.reportMissing(MissingData.MAP_TILES);
continue;
}
g.drawImage(tile.getImage(),
tx * GeoUtils.TILE_SIZE, ty * GeoUtils.TILE_SIZE, null);
}
}
g.setComposite(oldComp);
g.setTransform(oldTransform);
if (radius > 0) {
g.setClip(oldClip);
}
drawBorder(g, ctx, w, h, radius);
}
/* The border is drawn over the map in screen coordinates, without rotation. */
private static void drawBorder(Graphics2D g, GeoMapContext ctx, int w, int h, int radius) {
int bw = (int) (ctx.border.thickness * ctx.scale);
if (bw <= 0) {
return;
}
g.setColor(ctx.border.color);
g.setStroke(new BasicStroke(bw));
int bx = bw / 2, by = bw / 2;
int bw2 = Math.max(1, w - bw);
int bh2 = Math.max(1, h - bw);
if (radius > 0) {
g.drawRoundRect(bx, by, bw2, bh2, radius * 2, radius * 2);
} else {
g.drawRect(bx, by, bw2, bh2);
}
}
/* The result of the selection: the integer zoom and the additional scale. */
private record FitZoom(int intZoom, double extraScale) {
}
/* The threshold √2: the zoom is raised until the track goes beyond the area by more than √2 times. */
private static final double FIT_THRESHOLD = Math.sqrt(2.0);
/* Selects the zoom and the fractional scale so that the track fits with 5% margins (4..40 px). */
private static FitZoom computeFitZoom(int baseWidth, int baseHeight, LandBounds b) {
int padding = Math.max(4, Math.min(40,
(int) Math.round(Math.min(baseWidth, baseHeight) * 0.05)));
int innerW = Math.max(1, baseWidth - 2 * padding);
int innerH = Math.max(1, baseHeight - 2 * padding);
int intZoom = GeoUtils.ZOOM_MIN;
double fitW = 0, fitH = 0;
for (int i = GeoUtils.ZOOM_MIN; i <= GeoUtils.ZOOM_MAX; i++) {
TilePixel px1 = GeoUtils.getTileX(b.lonMin(), i);
TilePixel py1 = GeoUtils.getTileY(b.latMin(), i);
TilePixel px2 = GeoUtils.getTileX(b.lonMax(), i);
TilePixel py2 = GeoUtils.getTileY(b.latMax(), i);
double figureWidth = Math.abs(px2.getPixelGlobal() - px1.getPixelGlobal());
double figureHeight = Math.abs(py2.getPixelGlobal() - py1.getPixelGlobal());
if (figureWidth > innerW * FIT_THRESHOLD
|| figureHeight > innerH * FIT_THRESHOLD) {
if (i == GeoUtils.ZOOM_MIN) {
double extra = Math.min(innerW / figureWidth, innerH / figureHeight);
return new FitZoom(GeoUtils.ZOOM_MIN, extra);
}
break;
}
intZoom = i;
fitW = figureWidth;
fitH = figureHeight;
}
if (fitW <= 0 || fitH <= 0) {
return new FitZoom(intZoom, 1.0);
}
double extra = Math.min(innerW / fitW, innerH / fitH);
return new FitZoom(intZoom, extra);
}
/* The window of track points for calculating the bearing of movement. */
private static final int BEARING_WINDOW = 16;
/* The bearing from the next 16 track points from the current time; NaN if there are few points. */
private double computeHeadingBearing(MapZoom zm, GeoSensorProperty.GeoSensorContext position) {
int actualZoom = position.approximateZoom(zm.getLevel());
DataParams params = DataParams.of("sensorId", position.sensorId)
.set("zoom", actualZoom);
List<GeoSensorAtom> points = position.queryList("track", params);
if (points == null || points.size() < 2) {
return Double.NaN;
}
int from = lowerBoundByTimeRaw(points, position.rawTime);
if (from >= points.size() - 1) {
from = points.size() - 2;
}
int to = Math.min(from + BEARING_WINDOW, points.size());
/* The bearing window breaks off at a recording pause: points after it are not included in the calculation. */
for (int i = from + 1; i < to; i++) {
if (!points.get(i - 1).continuesWith(points.get(i))) {
to = i;
break;
}
}
if (to - from < 2) {
return Double.NaN;
}
double[] lats = new double[to - from];
double[] lons = new double[to - from];
for (int i = from; i < to; i++) {
GeoSensorAtom p = points.get(i);
lats[i - from] = p.lat;
lons[i - from] = p.lon;
}
return TrackBearing.fromPoints(lats, lons);
}
/* Binary search for the last point with a time less than t. */
private static int lowerBoundByTimeRaw(List<GeoSensorAtom> points, long t) {
int lo = 0;
int hi = points.size();
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (points.get(mid).timeRaw < t) {
lo = mid + 1;
} else {
hi = mid;
}
}
return Math.max(0, lo - 1);
}
/* Speed estimate from the coordinate increment of the atom and its duration. */
private static double estimateSpeedKmh(GeoSensorAtom atom) {
if (atom.duration <= 0) {
return 0.0;
}
double latRad = Math.toRadians(atom.lat);
double dyM = atom.latDelta * 111_320.0;
double dxM = atom.lonDelta * 111_320.0 * Math.cos(latRad);
double distM = Math.hypot(dxM, dyM);
double seconds = atom.duration / 1000.0;
return distM / seconds * 3.6;
}
/* Frame context: the property values and the calculated map geometry shared by the indicator and the figures. */
public class GeoMapContext extends IndicatorContext {
/* Property values on the current frame. */
public final GeoSensorProperty.GeoSensorContext position;
public final IntegerProperty.IntegerContext mapTransparency;
public final BorderProperty.BorderContext border;
public final VisibleProperty.BooleanContext showMap;
public final FitTrackProperty.BooleanContext fitTrack;
public final VisibleProperty.BooleanContext view3D;
public final IntegerProperty.IntegerContext tilt;
public final IntegerProperty.IntegerContext manualBearing;
public final IntegerProperty.IntegerContext minSpeedKmh;
public final ArrayProperty<RotationMode>.ArrayContext rotation;
public final ArrayProperty<VehicleAnchor>.ArrayContext vehicleAnchor;
/* Calculated geometry: zoom, center in map pixels, bearing, tilt, vehicle offset, extra scale, position and matrix. */
public final MapZoom zoom;
public final double centerPx;
public final double centerPy;
public final double bearingDeg;
public final double bearingRad;
public final double tiltRad;
public final double anchorOffsetY;
public final double extraScale;
public final double posLat;
public final double posLon;
public final AffineTransform mapTransform;
/* The constructor reads the frame properties and builds the map matrix. */
public GeoMapContext(FrameContext frame) {
super(frame);
position = mGeoSensor.createContext(frame);
fitTrack = mFitTrack.createContext(frame);
mapTransparency = mMapTransparency.createContext(frame);
border = mBorder.createContext(frame);
showMap = mShowMap.createContext(frame);
view3D = mView3D.createContext(frame);
tilt = mTilt.createContext(frame);
manualBearing = mManualBearing.createContext(frame);
minSpeedKmh = mMinSpeedKmh.createContext(frame);
rotation = mRotation.createContext(frame);
vehicleAnchor = mVehicleAnchor.createContext(frame);
MapZoom zm = null;
double cPx = 0;
double cPy = 0;
double br = 0;
double extra = 1.0;
/* Without a selected sensor the zoom stays null and nothing is drawn. */
if (position.sensorId > 0) {
/* The "Fit track" mode: the center is the middle of the track bounds, the zoom is selected. */
if (fitTrack.value) {
LandBounds b = position.queryLandBounds();
if (b != null) {
FitZoom fz = computeFitZoom(width, height, b);
zm = new MapZoom(fz.intZoom());
extra = fz.extraScale();
double centerLat = (b.latMin() + b.latMax()) / 2.0;
double centerLon = (b.lonMin() + b.lonMax()) / 2.0;
cPx = zm.pixelX(centerLon);
cPy = zm.pixelY(centerLat);
}
} else {
/* Follow mode: the center is the interpolated position at the current moment (in a recording pause, at the last point before the pause). */
GeoSensorAtom atom = position.queryAtomOrBefore();
if (atom != null) {
zm = new MapZoom(mGeoZoom.get(frame));
double lat = atom.calcLat(position.rawTime);
double lon = atom.calcLon(position.rawTime);
cPx = zm.pixelX(lon);
cPy = zm.pixelY(lat);
/* The bearing of movement is updated only at a speed not lower than the threshold. */
if (rotation.value == RotationMode.HEADING_UP) {
double speedKmh = estimateSpeedKmh(atom);
if (speedKmh >= minSpeedKmh.value) {
double deg = computeHeadingBearing(zm, position);
if (!Double.isNaN(deg)) {
mLastValidBearingDeg = deg;
}
}
br = mLastValidBearingDeg;
}
}
}
}
/* Position for figures (place boundaries); NaN if there is no data. */
double pLat = Double.NaN;
double pLon = Double.NaN;
if (position.sensorId > 0) {
GeoSensorAtom posAtom = position.queryAtomOrBefore();
if (posAtom != null) {
pLat = posAtom.calcLat(position.rawTime);
pLon = posAtom.calcLon(position.rawTime);
}
}
posLat = pLat;
posLon = pLon;
/* Assignment of the calculated values. */
zoom = zm;
centerPx = cPx;
centerPy = cPy;
bearingDeg = br;
/* In the "Fit track" mode the rotation, the tilt and the vehicle offset are disabled. */
boolean fit = fitTrack.value;
boolean is3D = !fit && view3D.value;
double bRad;
if (fit) {
bRad = 0;
} else {
bRad = switch (rotation.value) {
case NORTH_UP ->
0.0;
case MANUAL ->
Math.toRadians(manualBearing.value);
case HEADING_UP ->
Math.toRadians(br);
};
}
bearingRad = bRad;
tiltRad = is3D ? Math.toRadians(tilt.value) : 0.0;
anchorOffsetY = (!fit && vehicleAnchor.value == VehicleAnchor.BOTTOM_THIRD)
? height / 6.0 : 0.0;
extraScale = extra;
/* Map matrix: shift to the center, scale, vertical squeeze for the tilt, rotation, shift of the map center to the origin. */
AffineTransform t = new AffineTransform();
t.translate(width / 2.0, height / 2.0 + anchorOffsetY);
if (extraScale != 1.0) {
t.scale(extraScale, extraScale);
}
if (tiltRad > 0) {
t.scale(1.0, Math.cos(tiltRad));
}
if (bearingRad != 0) {
t.rotate(-bearingRad);
}
t.translate(-centerPx, -centerPy);
mapTransform = t;
}
}
@Override
/* Creation of the frame context. */
public GeoMapContext createContext(FrameContext frame) {
return new GeoMapContext(frame);
}
}GeoMapIndicator is a map on OpenStreetMap tiles that follows the current position from the geo sensor of the project (or shows the whole track at once). Figures are drawn on top of the tiles: by default the track and the position marker, and additionally the boundaries and labels of places. Map rotation (north up, heading up, manual), a 3D tilt and shifting the position into the bottom third are supported.
Related pages: indicator JSON, user description, user JSON template. Figures: GeoFigureContext, GeoTrackFigure, GeoPositionFigure, GeoPlaceBoundaryFigure, GeoPlaceLabelsFigure.
Data. GeoSensorProperty provides a GeoSensorAtom with the coordinates lat / lon and the increments. The current point is taken through position.queryAtomOrBefore() (the atom for the frame time, and in a recording pause the last atom before the pause, so the map center and the position of the figures stay at the last point before the pause) and is interpolated to the frame moment by the methods calcLat(rawTime) / calcLon(rawTime). For the "Fit track" mode position.queryLandBounds() is used: the rectangle of the bounds of the whole track (LandBounds). The track query is declared with anyLevel(): the track is read from simplified copies at the zoom level, not only from exact atoms (the position atom is taken exact, so the position does not leave the track in turns). For the bearing of movement, the list of track points is requested for the zoom nearest to the available one (approximateZoom), and 16 points starting from the current time are taken, but not beyond the recording pause (by continuesWith); the bearing is calculated by TrackBearing.fromPoints. The speed for the threshold is estimated from latDelta / lonDelta and the duration of the atom. The tiles come through MapTilesProperty (getTile in the preview, getTileBlocking with a wait of 5 s on export). If the tile of the frame is not loaded yet (no image), the indicator calls ctx.reportMissing(MissingData.MAP_TILES): the source preview with such a frame is not saved and is redrawn later, when the tiles are loaded. The player and the export ignore these reports.
Settings. Thirteen properties in defineProperties(): Geo, mapTiles (not saved), visible, fitTrack, geoZoom, transparency, border, view3D, tilt, rotation, manualBearing, minSpeedKmh, vehicleAnchor. Dependencies between them: "Fit track" blocks the zoom; the 3D view opens the tilt angle; the "Manual" mode opens the manual bearing, the "Heading up" mode opens the minimum speed. Skins: "Faded" (visible = true, transparency = 60) and "No map" (visible = false). The figures are set through supportedFigures() (four classes) and defaultFigures() (the track and the position).
Drawing. The GeoMapContext constructor calculates the zoom, the map center in pixels (centerPx, centerPy), the bearing, the tilt and the mapTransform matrix: a shift to the vehicle point, the scale extraScale, a vertical squeeze by cos(tilt), a rotation by -bearing, a shift to the map center. render() turns on antialiasing, then, if visibility is on, renderMap() restricts the area with a rounded rectangle, applies mapTransform, walks over the tiles around the center (with rotation or tilt, a square with a radius by the diagonal), draws them taking the transparency into account and at the end draws the border in screen coordinates. The figures are drawn by the runtime after the indicator, each gets a GeoFigureContext with the same matrix.
- Tiles that are not loaded are skipped (the place is empty) and are declared as missing data
MissingData.MAP_TILES. - In a recording pause the map and the marker stay at the last point before the pause; the "heading up" bearing is calculated from the points before the pause.
- While the geo sensor is not selected (
sensorId == 0) or it has no points, the zoom isnull: the tiles and the figures are not drawn. - The "Fit track" mode ignores the rotation, the tilt and the vehicle offset; the map zoom is not used then. The integer zoom is selected from 8 to 19, the remainder is covered by the fractional
extraScale. - In the "Heading up" mode the bearing is updated only at a speed not lower than the threshold, otherwise it stays at the last reliable one. It is stored in a field of the indicator (
mLastValidBearingDeg), not in the frame, so on rewinding and repeated rendering the result depends on the order of the frames. - The 3D tilt is an affine vertical squeeze of the map, not a perspective. Tiles above
horizonCullYare skipped. - The tiles are requested at an integer zoom, the maximum zoom is 19 (
GeoUtils.ZOOM_MAX), the minimum is 8 (GeoUtils.ZOOM_MIN). - The border is drawn before the figures; the figures themselves are not clipped by the rounding of the border.
- The transparency is applied only to the tiles; the border and the figures are drawn opaque.