Repository navigation
SlopeChartIndicator
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 SlopeChartIndicator.java: the production code stays clean, and the explanations live in the wiki.
package com.velitask.plugin.official;
import com.velitask.plugin.official.charts.MillimetersChart;
import com.velitask.plugin.official.slope.SlopeGroupAtom;
import com.velitask.sdk.FrameContext;
import com.velitask.sdk.Indicator;
import com.velitask.sdk.IndicatorContext;
import com.velitask.sdk.IndicatorSkin;
import com.velitask.sdk.data.SlopeSensorAtom;
import com.velitask.sdk.db.DataCacheRule;
import com.velitask.sdk.db.DataParams;
import com.velitask.sdk.db.PluginDatabase;
import com.velitask.sdk.db.SensorDataManager;
import com.velitask.sdk.properties.ColorProperty;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.DisplayHint;
import com.velitask.sdk.properties.GeoZoomProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.IntegerProperty;
import com.velitask.sdk.properties.LineProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.SlopeAtomProperty;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.RenderingHints;
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;
/* The "Elevation Chart" indicator: the elevation profile around the current position, a colored fill of the sections and a marker. */
public class SlopeChartIndicator extends Indicator {
/* Stable name of the indicator in the layer JSON. It must not be changed without a migration. */
public static final String NAME = "slopeChart";
/* Prefix of the localization keys: Plugin.Indicator.slopeChart. */
private static final String KEY = _KEY + "." + NAME;
/* Minimum X step (in pixels) between line points: closer atoms are merged into one segment. */
private static final int MIN_PX_BETWEEN_POINTS = 5;
/* Fill color of flat sections (JSON "fillPlain"), white by default. Its alpha is replaced by "Fill transparency". */
private final ColorProperty mFillPlain = new ColorProperty(
Color.WHITE, "fillPlain", localized(KEY + ".fillPlain.title"));
/* Fill color of uphills (JSON "fillUp"), red by default. */
private final ColorProperty mFillUp = new ColorProperty(
Color.RED, "fillUp", localized(KEY + ".fillUp.title"));
/* Fill color of downhills (JSON "fillDown"), green by default. */
private final ColorProperty mFillDown = new ColorProperty(
Color.GREEN, "fillDown", localized(KEY + ".fillDown.title"));
/*
* Alpha channel of the fill (JSON "fillTransparency"): 0..255, 30 by default.
* Not part of the skins (setSkinnable(false)).
*/
private final IntegerProperty mFillTransparency = new IntegerProperty() {
{
setRange(0, 255);
setSkinnable(false);
}
@Override
public String getName() {
return "fillTransparency";
}
@Override
public Integer getDefault() {
return 30;
}
@Override
public String getTitle() {
return localized(KEY + ".fillTransparency.title");
}
};
/* Slope sensor (JSON "Slope"): the source and the sensor are selected in the project. */
private final SlopeAtomProperty mSlope = new SlopeAtomProperty();
{
/* The "slope" manager: the slope atom whose window contains the given time. */
mSlope.addManager(
new SensorDataManager.Builder<>("slope", mSlope.getAtomClass())
.table(SlopeAtomProperty.TABLE_NAME)
.byTime()
.build()
);
/*
* The "slopeRange" query: atoms that intersect the distance range [minDistance, maxDistance),
* in time order. No cache.
*/
mSlope.query("slopeRange")
.where("(distance + distanceDelta) >= {minDistance} "
+ "AND distance < {maxDistance}")
.orderBy("timeRaw")
.cache(DataCacheRule.none())
.cacheSize(2)
.buildList();
}
/* Horizontal scale (JSON "geoZoom"): map level 8..19, 14 by default. Defines how many millimeters of the track are in a pixel. */
private final GeoZoomProperty mGeoZoom = new GeoZoomProperty();
/*
* Vertical exaggeration of elevations (JSON "EleChartScale"): 1..50, 10 by default.
* Not part of the skins.
*/
private final IntegerProperty mEleChartScale = new IntegerProperty() {
{
setRange(1, 50);
setSkinnable(false);
}
@Override
public String getName() {
return "EleChartScale";
}
@Override
public Integer getDefault() {
return 10;
}
@Override
public String getTitle() {
return localized(KEY + ".eleChartScale.title");
}
};
/* Profile line (JSON "line"): color and thickness are used; the line style and the dash pattern do not take part in drawing. */
private final LineProperty mLine = new LineProperty();
@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: a 600x300 layer at the top left corner, margins 300 at the top and 100 on the right. */
public void defineMaket(Maket maket) {
maket.setVertical(VerticalAlign.TOP);
maket.setHorizontal(HorizontalAlign.LEFT);
maket.setLayerMargin(null, 300d, 100d, null);
maket.setLayerSize(600d, 300d);
}
@Override
/* The order of the properties matches the order in the settings panel and in JSON. */
public IProperty[] defineProperties() {
return new IProperty[]{
mSlope,
mGeoZoom, mEleChartScale,
mLine,
mFillPlain, mFillUp, mFillDown, mFillTransparency
};
}
@Override
/* All appearance settings are in the "Appearance" group; elevation scale and transparency are sliders. */
public void configureDisplay(DisplayConfig config) {
config.set(mGeoZoom, PropertyGroup.APPEARANCE);
config.set(mEleChartScale, PropertyGroup.APPEARANCE, DisplayHint.SLIDER);
config.set(mLine, PropertyGroup.APPEARANCE);
config.set(mFillPlain, PropertyGroup.APPEARANCE);
config.set(mFillUp, PropertyGroup.APPEARANCE);
config.set(mFillDown, PropertyGroup.APPEARANCE);
config.set(mFillTransparency, PropertyGroup.APPEARANCE, DisplayHint.SLIDER);
}
@Override
/* The "bold" skin ("Bold"): a white line with a thickness of 10. */
public IndicatorSkin[] defineSkins() {
return new IndicatorSkin[]{
IndicatorSkin.builder("bold", localized(KEY + ".skin.bold"))
.set(mLine.getColor().skin(Color.WHITE))
.set(mLine.getThickness().skin(10))
.build()
};
}
@Override
/* Drawing one frame: the chart window, the data query, the fill, the line, the marker. */
public void render(IndicatorContext indicatorContext) {
SlopeChartContext ctx = (SlopeChartContext) indicatorContext;
Graphics2D g = ctx.graphics;
/* The slope atom for the current moment. No data - draw nothing. */
SlopeSensorAtom currAtom = ctx.slope.queryAtom("slope", ctx.slope.rawTime);
if (currAtom == null) {
return;
}
/*
* The chart window: the center is the distance and elevation of the current point, the X scale is by geoZoom, Y by EleChartScale.
* The latitude is passed but does not take part in the calculation (see MillimetersChart).
*/
MillimetersChart chart = new MillimetersChart(
ctx.width, ctx.height,
ctx.geoZoom.value, GeoUtils.LAT_EQUATOR,
currAtom.distance, currAtom.elevation,
1, ctx.eleChartScale.value
);
/* A margin of 50 pixels on each side of the window so that the line does not break off at the edges. */
long margin = chart.getMmPerPixel() * 50;
long minDist = chart.getMinMmX() - margin;
long maxDist = chart.getMaxMmX() + margin;
/* Query parameters: the sensor and the bounds of the distance range. */
DataParams rangeParams = DataParams
.of("sensorId", ctx.slope.sensorId)
.set("minDistance", minDist)
.set("maxDistance", maxDist);
/* Slope atoms in the window and slope groups from the plugin DB (the table is computed when the source is imported). */
List<SlopeSensorAtom> atoms = ctx.slope.queryList("slopeRange", rangeParams);
List<SlopeGroupAtom> groups = queryGroups(ctx.db, ctx.slope.sensorId, minDist, maxDist);
/* No atoms in the window - nothing to draw. */
if (atoms == null || atoms.isEmpty()) {
return;
}
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
/* The fill under the profile is drawn only if groups have been computed for the sensor. */
if (groups != null && !groups.isEmpty()) {
renderGroupFills(g, chart, groups, atoms, ctx);
}
/* The elevation profile line. */
renderLine(g, chart, atoms, ctx);
/* The marker of the current position. */
renderMarker(g, chart, currAtom, ctx);
}
/* Slope groups of the sensor that intersect the distance range, in ascending order of distance. Without a DB - an empty list. */
private static List<SlopeGroupAtom> queryGroups(PluginDatabase db,
long sensorId, long minDistance, long maxDistance) {
if (db == null) {
return List.of();
}
return db.queryList(
"SELECT * FROM ${table:slope_groups}"
+ " WHERE sensor_id = ?"
+ " AND (distance + distanceDelta) >= ?"
+ " AND distance < ?"
+ " ORDER BY distance",
SlopeGroupAtom.class,
sensorId, minDistance, maxDistance
);
}
/*
* Fill: for each group a polygon is built from the bottom of the chart along the profile points of the group;
* the color depends on the slope type.
*/
private void renderGroupFills(Graphics2D g, MillimetersChart chart,
List<SlopeGroupAtom> groups,
List<SlopeSensorAtom> atoms,
SlopeChartContext ctx) {
/* One alpha channel for all three fill colors. */
int alpha = ctx.fillTransparency.value;
Color fillDown = setAlpha(ctx.fillDown.value, alpha);
Color fillUp = setAlpha(ctx.fillUp.value, alpha);
Color fillPlain = setAlpha(ctx.fillPlain.value, alpha);
for (SlopeGroupAtom groupAtom : groups) {
long groupEndDistance = groupAtom.distance + groupAtom.distanceDelta;
/* The group is entirely to the left of the window - skip; to the right - stop (the groups are sorted by distance). */
if (groupEndDistance < chart.getMinMmX()) {
continue;
}
if (groupAtom.distance > chart.getMaxMmX()) {
break;
}
/* Start of the polygon: the bottom and top points at the left edge of the group. */
Polygon polygon = new Polygon();
int x1 = chart.convertMmToPxX(groupAtom.distance);
polygon.addPoint(x1, chart.getHeight());
polygon.addPoint(x1, chart.convertMmToPxY(groupAtom.elevation));
/* Add the end of each atom of the group; points with the same X are skipped. */
SlopeSensorAtom item = null;
for (SlopeSensorAtom point : atoms) {
if (point.distance < groupAtom.distance || point.distance >= groupEndDistance) {
continue;
}
int x2 = chart.convertMmToPxX(point.getNextDistance());
if (x2 == x1) {
continue;
}
x1 = x2;
item = point;
polygon.addPoint(x2, chart.convertMmToPxY(point.getNextElevation()));
}
if (item == null) {
continue;
}
polygon.addPoint(x1, chart.getHeight());
/* Downhill, uphill or flat. */
Color fill;
if (groupAtom.slopeType < 0) {
fill = fillDown;
} else if (groupAtom.slopeType > 0) {
fill = fillUp;
} else {
fill = fillPlain;
}
g.setColor(fill);
g.fillPolygon(polygon);
}
}
/* Line: consecutive atoms closer than 5 pixels in X are merged into one segment. */
private void renderLine(Graphics2D g, MillimetersChart chart,
List<SlopeSensorAtom> atoms, SlopeChartContext ctx) {
float depth = (float) (ctx.line.thickness * ctx.scale);
g.setStroke(new BasicStroke(depth, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND));
g.setColor(ctx.line.color);
for (int i = 0; i < atoms.size(); i++) {
SlopeSensorAtom item = atoms.get(i);
int x1 = chart.convertMmToPxX(item.distance);
int y1 = chart.convertMmToPxY(item.elevation);
int x2, y2;
boolean hasItem2 = false;
i++;
for (; i < atoms.size(); i++) {
SlopeSensorAtom item2 = atoms.get(i);
x2 = chart.convertMmToPxX(item2.getNextDistance());
y2 = chart.convertMmToPxY(item2.getNextElevation());
if ((x2 - x1) > MIN_PX_BETWEEN_POINTS) {
hasItem2 = true;
g.drawLine(x1, y1, x2, y2);
break;
}
}
if (!hasItem2) {
x2 = chart.convertMmToPxX(item.getNextDistance());
y2 = chart.convertMmToPxY(item.getNextElevation());
g.drawLine(x1, y1, x2, y2);
}
}
}
/* The marker is a ring: the outer circle in the line color, the inner one is cut out to transparency. The radii depend on the line thickness. */
private void renderMarker(Graphics2D g, MillimetersChart chart,
SlopeSensorAtom atom, SlopeChartContext ctx) {
float depth = (float) (ctx.line.thickness * ctx.scale);
int rOut = (int) (depth * 6);
int rIn = (int) (depth * 4);
int x = chart.convertMmToPxX(atom.distance);
int y = chart.convertMmToPxY(atom.elevation);
g.setColor(ctx.line.color);
g.fillOval(x - rOut / 2, y - rOut / 2, rOut, rOut);
g.setComposite(AlphaComposite.Clear);
g.fillOval(x - rIn / 2, y - rIn / 2, rIn, rIn);
g.setComposite(AlphaComposite.SrcOver);
}
/* A color with the given alpha channel (clamped to 0..255). */
private static Color setAlpha(Color c, int alpha) {
alpha = Math.max(0, Math.min(255, alpha));
return new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha);
}
/* Property values for the current frame. Created in createContext(frame). */
public class SlopeChartContext extends IndicatorContext {
public final SlopeAtomProperty.SensorContext slope;
public final IntegerProperty.IntegerContext geoZoom;
public final IntegerProperty.IntegerContext eleChartScale;
public final LineProperty.LineContext line;
public final ColorProperty.ColorContext fillPlain;
public final ColorProperty.ColorContext fillUp;
public final ColorProperty.ColorContext fillDown;
public final IntegerProperty.IntegerContext fillTransparency;
public SlopeChartContext(FrameContext frame) {
super(frame);
slope = mSlope.createContext(frame);
geoZoom = mGeoZoom.createContext(frame);
eleChartScale = mEleChartScale.createContext(frame);
line = mLine.createContext(frame);
fillPlain = mFillPlain.createContext(frame);
fillUp = mFillUp.createContext(frame);
fillDown = mFillDown.createContext(frame);
fillTransparency = mFillTransparency.createContext(frame);
}
}
@Override
/* Factory of the frame context. */
public IndicatorContext createContext(FrameContext frame) {
return new SlopeChartContext(frame);
}
}The save format of the indicator is described on the page SlopeChartIndicator JSON. The user guide: Elevation Chart.
SlopeChartIndicator (JSON name slopeChart, interface title "Elevation Chart") draws the elevation profile of the track around the current position: the elevation line, a colored fill under it (a separate color for uphills, downhills and flat sections) and a ring marker of the current point. The marker always stays in the center of the layer, and the chart "moves" past it as playback goes on.
- The only sensor is
SlopeAtomProperty(JSON keySlope, "Slope" in the interface). It reads the project tablesensors_slope_data, and the atom isSlopeSensorAtom: the accumulateddistanceandelevationin millimeters and the incrementsdistanceDelta/elevationDeltaper atom window. - The current atom is requested by the
slopemanager (byTime) for the raw time of the frame:ctx.slope.queryAtom("slope", ctx.slope.rawTime). The manager returns an atom interpolated to the moment of the frame. The sensor identifier is taken fromctx.slope.sensorId. - The atoms of the window are requested by the
slopeRangemanager: all atoms that intersect the distance range[minDistance, maxDistance)(the condition(distance + distanceDelta) >= {minDistance} AND distance < {maxDistance}), intimeRaworder. The cache is disabled (DataCacheRule.none()) because the range changes every frame. - The slope groups are read by a direct SQL query through
ctx.dbfrom the plugin tableslope_groups(see SlopeGroupAtom). The table is filled byVelitaskPlagin.onSourceImportedwhen a source with a slope sensor is imported. Ifdbisnullor there are no groups, the fill is skipped, and the line and the marker are drawn. - Units: all distances and elevations are stored in millimeters; there is no unit conversion in this indicator, the scale is set by the settings.
| JSON key | SDK type | Default | Range | Role |
|---|---|---|---|---|
Slope |
SlopeAtomProperty |
not selected | — | Source and slope sensor. |
geoZoom |
GeoZoomProperty |
14 | 8..19 | Horizontal scale: how many millimeters of distance fall on a pixel. |
EleChartScale |
IntegerProperty |
10 | 1..50 | Vertical exaggeration of elevations relative to the horizontal scale. |
line |
LineProperty |
white, thickness 1, solid | thickness 0..50 | The profile line and the marker; only color and thickness are used. |
fillPlain |
ColorProperty |
white | 0..255 per channel | Fill of flat sections. |
fillUp |
ColorProperty |
red | 0..255 per channel | Fill of uphills. |
fillDown |
ColorProperty |
green | 0..255 per channel | Fill of downhills. |
fillTransparency |
IntegerProperty |
30 | 0..255 | Alpha channel of all three fills. |
geoZoom, EleChartScale and fillTransparency are declared as non-skinnable. The bold skin ("Bold") changes only the line color (white) and its thickness (10).
- The atom of the current moment is not found - the frame stays empty.
- A
MillimetersChartis built with the width and height of the layer, centered at the point (distance,elevation) of the current atom, with the X scale bygeoZoomand the Y scale byEleChartScale. - The query range is the chart window plus a margin of
50 * mmPerPixelon each side. - If there are no atoms in the window - exit.
- Group fill (if there are groups): for each group that intersects the window, a polygon is built from the bottom of the layer up to the height of the start of the group, then along the ends of the atoms of the group (points with the same X are skipped) and back down. The color is chosen by the
slopeTypeof the group: downhill isfillDown, uphill isfillUp, otherwisefillPlain; the alpha channel of any of the colors is replaced by the value offillTransparency. - Line: the atoms are traversed in order; the next point is taken from the first atom whose end is more than 5 pixels in X away from the start of the segment, so small atoms are merged. The pen is a
BasicStrokewith the thicknessthickness * scale, the end capCAP_SQUARE, the joinJOIN_ROUND. - Marker: an outer circle with a diameter of
6 * thicknessin the line color, then an inner circle with a diameter of4 * thicknessis cut out with theAlphaComposite.Clearmode - a ring with a transparent middle is obtained.
-
Latitude is not taken into account.
GeoUtils.LAT_EQUATORis passed toMillimetersChart, and the class itself does not use latitude in the calculation (see MillimetersChart), so the scale does not depend on the place on Earth. -
Vertical scale. The size of one pixel in height equals
mmPerPixel / EleChartScale. At level 14 one pixel horizontally is about 9.55 m of distance, and vertically at the value 10 about 0.95 m of elevation. -
Line style and pattern do not work.
LinePropertyshows the line style and the dash pattern in the interface, but the pen is created without a dash: the line is always solid. -
Fill alpha. The alpha channel set in the colors
fillPlain,fillUp,fillDownthemselves is ignored:fillTransparencyis applied everywhere. - Zero thickness. At a thickness of 0 the marker diameters become zero and the marker is not visible.
-
Dependence on groups. Without rows in
slope_groups(for example, the source was imported before the plugin appeared or it has no slope sensor) there is no fill. - Transparent hole of the marker. The cut-out is made in the layer itself, so the hole is transparent even on top of the fill.
-
Fixed size. The chart window always equals the layer size in pixels; the distance coverage depends on the layer size and
geoZoom.