Repository navigation
SpeedChartIndicator
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 SpeedChartIndicator.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.sdk.FrameContext;
import com.velitask.sdk.Indicator;
import com.velitask.sdk.IndicatorContext;
import com.velitask.sdk.IndicatorSkin;
import com.velitask.sdk.data.DistanceSensorAtom;
import com.velitask.sdk.db.DataCacheRule;
import com.velitask.sdk.db.DataCacheStorage;
import com.velitask.sdk.db.DataParams;
import com.velitask.sdk.db.SensorData;
import com.velitask.sdk.properties.ColorProperty;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.DisplayHint;
import com.velitask.sdk.properties.DistanceSensorProperty;
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 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 "Speed Chart" indicator: a speed chart around the current position with a gradient fill, the average speed and a marker. */
public class SpeedChartIndicator extends Indicator {
/* Stable indicator name in the layer JSON. It must not be changed without a migration. */
public static final String NAME = "speedChart";
/* Prefix of the localization keys: Plugin.Indicator.speedChart. */
private static final String KEY = _KEY + "." + NAME;
/* Distance sensor (JSON "Distance"): the distance and the speed are taken from its atoms. */
private final DistanceSensorProperty mDistance = new DistanceSensorProperty();
{
/*
* Query "speedRange": atoms that intersect the distance range [minDistance, maxDistance),
* in time order. No cache.
*/
mDistance.query("speedRange")
.where("(distance + distanceDelta) >= {minDistance} "
+ "AND distance < {maxDistance}")
.orderBy("timeRaw")
.cache(DataCacheRule.none())
.cacheSize(2)
.buildList();
/*
* Aggregate "avgSpeed": the average nonzero speed over the whole sensor,
* weighted by the duration of the atoms. The result is cached separately for each sensor.
*/
mDistance.aggregate("avgSpeed")
.select("SUM(speed * duration) * 1.0 / SUM(duration) AS avgSpeed")
.where("speed > 0 AND duration > 0")
.cache(ONCE_CACHE_RULE)
.cacheSize(1)
.build();
}
/* Horizontal scale (JSON "geoZoom"): map level 8..19, 14 by default. */
private final GeoZoomProperty mGeoZoom = new GeoZoomProperty();
/*
* Vertical speed scale (JSON "SpeedScale"): 1..20, 1 by default.
* Not part of the skins.
*/
private final IntegerProperty mSpeedScale = new IntegerProperty() {
{
setRange(1, 20);
setSkinnable(false);
}
@Override
public String getName() {
return "SpeedScale";
}
@Override
public Integer getDefault() {
return 1;
}
@Override
public String getTitle() {
return localized(KEY + ".speedScale.title");
}
};
/* Chart line (JSON "line"): the color and the thickness are used; the line style and the dash pattern do not take part in drawing. */
private final LineProperty mLine = new LineProperty();
/* JSON name of the "Fill (min)" property. */
private static final String FILL_COLOR_LOW = "fillColorLow";
/* Fill color at low speed (green by default, alpha 60). */
private final ColorProperty mFillColorLow = new ColorProperty(
new Color(0, 200, 0, 60),
FILL_COLOR_LOW,
localized(KEY + "." + FILL_COLOR_LOW + ".title")
);
/* JSON name of the "Fill (max)" property. */
private static final String FILL_COLOR_HIGH = "fillColorHigh";
/* Fill color at the maximum speed of the window (red by default, alpha 60). */
private final ColorProperty mFillColorHigh = new ColorProperty(
new Color(200, 0, 0, 60),
FILL_COLOR_HIGH,
localized(KEY + "." + FILL_COLOR_HIGH + ".title")
);
/* JSON name of the "Average speed color" property. */
private static final String AVG_COLOR = "avgColor";
/* Color of the dashed line of the average speed (yellow by default, alpha 180). */
private final ColorProperty mAvgColor = new ColorProperty(
new Color(255, 255, 0, 180),
AVG_COLOR,
localized(KEY + "." + AVG_COLOR + ".title")
);
@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 600x300 at the bottom left corner, margins 100 on the left and 100 at the bottom. */
public void defineMaket(Maket maket) {
maket.setVertical(VerticalAlign.BOTTOM);
maket.setHorizontal(HorizontalAlign.LEFT);
maket.setLayerMargin(100D, null, null, 100d);
maket.setLayerSize(600d, 300d);
}
@Override
/* The order of properties matches the order in the settings panel and in JSON. */
public IProperty[] defineProperties() {
return new IProperty[]{
mDistance,
mGeoZoom, mSpeedScale,
mLine,
mFillColorLow, mFillColorHigh, mAvgColor
};
}
@Override
/* All appearance settings are in the "Appearance" group; the speed scale is a slider. */
public void configureDisplay(DisplayConfig config) {
config.set(mGeoZoom, PropertyGroup.APPEARANCE);
config.set(mSpeedScale, PropertyGroup.APPEARANCE, DisplayHint.SLIDER);
config.set(mLine, PropertyGroup.APPEARANCE);
config.set(mFillColorLow, PropertyGroup.APPEARANCE);
config.set(mFillColorHigh, PropertyGroup.APPEARANCE);
config.set(mAvgColor, PropertyGroup.APPEARANCE);
}
@Override
/* The "neon" skin ("Neon green"): a green line with thickness 4 and green fills. */
public IndicatorSkin[] defineSkins() {
return new IndicatorSkin[]{
IndicatorSkin.builder("neon", localized(KEY + ".skin.neon"))
.set(mLine.getColor().skin(0, 255, 100))
.set(mLine.getThickness().skin(4))
.set(mFillColorLow.skin(0, 100, 0, 40))
.set(mFillColorHigh.skin(0, 255, 0, 80))
.set(mAvgColor.skin(0, 200, 200, 150))
.build()
};
}
/*
* Cache rule "once per sensor": the aggregate result is stored under the key
* "avg:<sensorId>" and is returned for any other query parameters.
*/
private static final DataCacheRule ONCE_CACHE_RULE = new DataCacheRule() {
@Override
public boolean isCached(DataParams params, DataCacheStorage cache) {
return cache.has(avgKey(params));
}
@Override
public Object getFromCache(DataParams params, DataCacheStorage cache) {
return cache.get(avgKey(params));
}
@Override
public void store(DataParams params, Object data, DataCacheStorage cache) {
cache.put(avgKey(params), data);
}
/* The cache key includes the sensor identifier. */
private String avgKey(DataParams params) {
return "avg:" + ((Number) params.get("sensorId")).longValue();
}
};
@Override
/* Drawing of one frame: the chart window, the vertical scale, the fill, the line, the average speed, the marker. */
public void render(IndicatorContext indicatorContext) {
SpeedChartContext ctx = (SpeedChartContext) indicatorContext;
Graphics2D g = ctx.graphics;
/* The distance atom for the current moment; in a recording pause, the last atom before the pause. No data: nothing is drawn. */
DistanceSensorAtom currAtom = ctx.distance.queryAtomOrBefore();
if (currAtom == null) {
return;
}
/*
* Chart window horizontally: the center is the distance of the current point, the X scale is by geoZoom.
* The vertical scale is calculated separately (yScale), so the center and the Y scale are not used here.
*/
MillimetersChart chart = new MillimetersChart(
ctx.width, ctx.height,
ctx.geoZoom.value, GeoUtils.LAT_EQUATOR,
currAtom.distance, 0,
1, 1
);
/* A margin of 50 pixels on each side of the window. */
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.distance.sensorId)
.set("minDistance", minDist)
.set("maxDistance", maxDist);
/* Distance atoms in the window. */
List<DistanceSensorAtom> atoms = ctx.distance.queryList("speedRange", rangeParams);
if (atoms == null || atoms.isEmpty()) {
return;
}
/* The maximum speed among the atoms of the window (the start or the end of an atom). Zero: nothing to draw. */
int maxSpeed = 0;
for (DistanceSensorAtom atom : atoms) {
int s = Math.max(atom.speed, atom.speed + atom.speedDelta);
if (s > maxSpeed) {
maxSpeed = s;
}
}
if (maxSpeed == 0) {
return;
}
/*
* Pixels per speed unit: the window maximum takes the layer height / 1.1 (a 10% margin),
* multiplied by the "Speed scale".
*/
double yScale = (double) ctx.height * ctx.speedScale.value / (maxSpeed * 1.1);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
/* The fill under the chart. */
renderFill(g, chart, atoms, maxSpeed, yScale, ctx);
/* The speed line. */
renderLine(g, chart, atoms, yScale, ctx);
/* The dashed line of the average speed. */
renderAvgLine(g, chart, yScale, ctx);
/* The marker of the current speed in the center of the layer. */
renderMarker(g, chart, currAtom, yScale, ctx);
}
/* Speed to the Y coordinate: zero is the bottom of the layer, the higher the speed, the higher the point. */
private int speedToPixelY(int speed, double yScale, int height) {
return height - (int) (speed * yScale);
}
/*
* Fill with trapezoids between points; the color is a linear blend of "min" and "max"
* by the ratio of the average speed of the section to the window maximum.
*/
private void renderFill(Graphics2D g, MillimetersChart chart,
List<DistanceSensorAtom> atoms, int maxSpeed,
double yScale, SpeedChartContext ctx) {
int height = ctx.height;
Color cLow = ctx.fillColorLow.value;
Color cHigh = ctx.fillColorHigh.value;
for (int i = 0; i < atoms.size(); i++) {
DistanceSensorAtom atom = atoms.get(i);
int x1 = chart.convertMmToPxX(atom.distance);
int y1 = speedToPixelY(atom.speed, yScale, height);
int x2, y2;
int speedSum = atom.speed;
int speedCount = 1;
boolean found = false;
for (int j = i + 1; j < atoms.size(); j++) {
DistanceSensorAtom next = atoms.get(j);
/* The fill does not cross a recording pause. */
if (!atoms.get(j - 1).continuesWith(next)) {
break;
}
x2 = chart.convertMmToPxX(next.getNextDistance());
if ((x2 - x1) >= MIN_PX_BETWEEN_POINTS) {
y2 = speedToPixelY(next.getNextSpeed(), yScale, height);
speedSum += next.getNextSpeed();
speedCount++;
i = j;
found = true;
double ratio = (double) speedSum / speedCount / maxSpeed;
ratio = Math.max(0, Math.min(1, ratio));
Polygon polygon = new Polygon();
polygon.addPoint(x1, height);
polygon.addPoint(x1, y1);
polygon.addPoint(x2, y2);
polygon.addPoint(x2, height);
g.setColor(lerpColor(cLow, cHigh, ratio));
g.fillPolygon(polygon);
break;
}
speedSum += next.speed;
speedCount++;
}
if (!found) {
x2 = chart.convertMmToPxX(atom.getNextDistance());
y2 = speedToPixelY(atom.getNextSpeed(), yScale, height);
if (x2 - x1 < 1) {
continue;
}
double ratio = (double) (atom.speed + atom.getNextSpeed()) / 2.0 / maxSpeed;
ratio = Math.max(0, Math.min(1, ratio));
Polygon polygon = new Polygon();
polygon.addPoint(x1, height);
polygon.addPoint(x1, y1);
polygon.addPoint(x2, y2);
polygon.addPoint(x2, height);
g.setColor(lerpColor(cLow, cHigh, ratio));
g.fillPolygon(polygon);
}
}
}
/* Minimal step along X (in pixels) for merging close points. */
private static final int MIN_PX_BETWEEN_POINTS = 2;
/* Line: atoms close along X are merged into one segment. */
private void renderLine(Graphics2D g, MillimetersChart chart,
List<DistanceSensorAtom> atoms,
double yScale, SpeedChartContext ctx) {
int height = ctx.height;
float depth = (float) (ctx.line.thickness * ctx.scale);
g.setStroke(new BasicStroke(depth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.setColor(ctx.line.color);
int x1, y1, x2, y2;
for (int i = 0; i < atoms.size(); i++) {
DistanceSensorAtom atom = atoms.get(i);
x1 = chart.convertMmToPxX(atom.distance);
y1 = speedToPixelY(atom.speed, yScale, height);
boolean hasNext = false;
/* Index of the recording pause at which the merging of atoms broke off; -1 means there was no pause. */
int gapAt = -1;
for (int j = i + 1; j < atoms.size(); j++) {
DistanceSensorAtom next = atoms.get(j);
/* The line does not cross a recording pause. */
if (!atoms.get(j - 1).continuesWith(next)) {
gapAt = j;
break;
}
x2 = chart.convertMmToPxX(next.getNextDistance());
y2 = speedToPixelY(next.getNextSpeed(), yScale, height);
if ((x2 - x1) >= MIN_PX_BETWEEN_POINTS) {
hasNext = true;
i = j;
g.drawLine(x1, y1, x2, y2);
break;
}
}
if (!hasNext) {
x2 = chart.convertMmToPxX(atom.getNextDistance());
y2 = speedToPixelY(atom.getNextSpeed(), yScale, height);
g.drawLine(x1, y1, x2, y2);
/* Continue from the atom after the pause or finish the walk. */
i = gapAt < 0 ? atoms.size() : gapAt - 1;
}
}
}
/*
* Average speed over the whole sensor (aggregate "avgSpeed"); zero or missing is not drawn.
* A line of fixed thickness 2 with the dash 10/8.
*/
private void renderAvgLine(Graphics2D g, MillimetersChart chart,
double yScale, SpeedChartContext ctx) {
DataParams avgParams = DataParams.of("sensorId", ctx.distance.sensorId);
SensorData avgData = ctx.distance.queryItem("avgSpeed", avgParams);
if (avgData == null || !avgData.has("avgSpeed")) {
return;
}
Object avgValue = avgData.get("avgSpeed");
if (avgValue == null) {
return;
}
int avgSpeed = ((Number) avgValue).intValue();
if (avgSpeed <= 0) {
return;
}
int y = speedToPixelY(avgSpeed, yScale, ctx.height);
float[] dash = {10f, 8f};
g.setStroke(new BasicStroke(
2f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND,
10f, dash, 0f
));
g.setColor(ctx.avgColor.value);
g.drawLine(0, y, ctx.width, y);
}
/* Marker is a ring: at the center of the layer along X, at the current speed along Y; the inner circle is cut out to transparency. */
private void renderMarker(Graphics2D g, MillimetersChart chart,
DistanceSensorAtom currAtom,
double yScale, SpeedChartContext ctx) {
float depth = (float) (ctx.line.thickness * ctx.scale);
int rOut = (int) (depth * 6);
int rIn = (int) (depth * 4);
int x = ctx.width / 2;
int y = speedToPixelY(currAtom.speed, yScale, ctx.height);
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);
}
/* Component-wise linear blend of two colors (including the alpha channel). */
private static Color lerpColor(Color a, Color b, double t) {
return new Color(
(int) (a.getRed() + (b.getRed() - a.getRed()) * t),
(int) (a.getGreen() + (b.getGreen() - a.getGreen()) * t),
(int) (a.getBlue() + (b.getBlue() - a.getBlue()) * t),
(int) (a.getAlpha() + (b.getAlpha() - a.getAlpha()) * t)
);
}
/* Property values for the current frame. Created in createContext(frame). */
public class SpeedChartContext extends IndicatorContext {
public final DistanceSensorProperty.SensorContext distance;
public final IntegerProperty.IntegerContext geoZoom;
public final IntegerProperty.IntegerContext speedScale;
public final LineProperty.LineContext line;
public final ColorProperty.ColorContext fillColorLow;
public final ColorProperty.ColorContext fillColorHigh;
public final ColorProperty.ColorContext avgColor;
public SpeedChartContext(FrameContext frame) {
super(frame);
distance = mDistance.createContext(frame);
geoZoom = mGeoZoom.createContext(frame);
speedScale = mSpeedScale.createContext(frame);
line = mLine.createContext(frame);
fillColorLow = mFillColorLow.createContext(frame);
fillColorHigh = mFillColorHigh.createContext(frame);
avgColor = mAvgColor.createContext(frame);
}
}
@Override
/* Frame context factory. */
public IndicatorContext createContext(FrameContext frame) {
return new SpeedChartContext(frame);
}
}The save format of the indicator is described on the page SpeedChartIndicator JSON. The user guide: Speed Chart.
SpeedChartIndicator (the JSON name is speedChart, the interface title is "Speed Chart") draws a speed chart along the track around the current position: a speed line, a fill under it with a smooth color transition from "min" to "max", a dashed line of the average speed and a ring marker of the current speed in the center of the layer.
- The only sensor is
DistanceSensorProperty(JSON keyDistance, "Distance" in the interface). TheDistanceSensorAtomatom carries the accumulated distancedistancein millimeters and the speedspeedin mm/h with the incrementsspeedDeltaanddistanceDelta. - The current atom is taken without arguments:
ctx.distance.queryAtomOrBefore(): the atom for the frame time, and in a recording pause (a stop, a device auto-pause) the last atom before the pause, so the chart and the marker do not disappear. The sensor isctx.distance.sensorId. - The
speedRangemanager returns the atoms that intersect the distance range[minDistance, maxDistance), intimeRaworder, without a cache. - The
avgSpeedaggregate is the average speed over the whole sensor, weighted by duration:SUM(speed * duration) / SUM(duration)over the atoms withspeed > 0andduration > 0(the simple averageAVG(speed)is no longer used). The cache ruleONCE_CACHE_RULEstores the result under the keyavg:<sensor identifier>, that is, it computes once for each sensor. - Absolute speed units are not shown on the chart: only the ratios of the values matter.
| JSON key | SDK type | Default | Range | Role |
|---|---|---|---|---|
Distance |
DistanceSensorProperty |
not selected | n/a | The source and the sensor of distance and speed. |
geoZoom |
GeoZoomProperty |
14 | 8..19 | The horizontal scale: how many millimeters of distance fall on a pixel. |
SpeedScale |
IntegerProperty |
1 | 1..20 | The vertical stretching of the chart. |
line |
LineProperty |
white, thickness 1, solid | thickness 0..50 | The speed line and the marker; only the color and the thickness are used. |
fillColorLow |
ColorProperty |
0, 200, 0, 60 | 0..255 per channel | The fill color at low speed. |
fillColorHigh |
ColorProperty |
200, 0, 0, 60 | 0..255 per channel | The fill color at the maximum speed of the window. |
avgColor |
ColorProperty |
255, 255, 0, 180 | 0..255 per channel | The color of the average speed line. |
geoZoom and SpeedScale are declared non-skinnable. The neon skin ("Neon green") sets the line (0, 255, 100) with thickness 4, fillColorLow (0, 100, 0, 40), fillColorHigh (0, 255, 0, 80) and avgColor (0, 200, 200, 150).
- The atom of the current moment is not found (outside the recording): the frame stays empty; in a recording pause the last atom before the pause is taken.
- A
MillimetersChartis built with the center along X at the distance of the current atom and scale multipliers 1 and 1. This object is not used along Y: the vertical scale is calculated separately. - The atoms of the window plus a margin of
50 * mmPerPixelon each side are requested. No atoms: exit. -
maxSpeedis the maximum ofmax(speed, speed + speedDelta)over the atoms of the window. A zero maximum: exit. - The vertical scale:
yScale = layer_height * SpeedScale / (maxSpeed * 1.1). Zero speed lies on the bottom edge of the layer; atSpeedScale = 1the window maximum takes about 91% of the height. - The fill: trapezoids from the bottom edge of the layer to the speed line between neighboring points (points close along X are merged when the step is less than 2 pixels; the merging stops at a recording pause: no fill is built between atoms that do not continue each other). The color is a linear blend of
fillColorLowandfillColorHighby the ratio of the average speed of the section tomaxSpeed(from 0 to 1), including the alpha channel. - The speed line: a
BasicStrokewith the thicknessthickness * scale, with rounded end and join. Atoms are merged only within one recording segment (continuesWith): at a pause the merging breaks off, and the next segment of the line starts from the atom after the pause. - The average speed: a horizontal line at the height of the
avgSpeedaggregate; not drawn when the value is missing or zero. The pen is fixed: thickness 2, dash 10/8 pixels, coloravgColor. - The marker: at the center of the layer along X, at the current speed along Y; the outer circle with the diameter
6 * thickness, the inner one with the diameter4 * thicknessis cut out with theAlphaComposite.Clearmode.
-
Autoscale by the window. The vertical scale is recalculated every frame by the maximum speed in the visible window, so the height of the chart "breathes" when fast and slow sections pass.
SpeedScaleonly amplifies this scale. - The average speed is global. The line is calculated over the whole sensor (weighted by the duration of the atoms; zero speed is not counted), while the scale is calculated only over the window, so the average can end up above the top edge of the layer.
-
The average speed cache. The result is cached once for each sensor under the key
avg:<sensor identifier>, so changing the sensor gives a new value, not the old one. -
The latitude is not taken into account.
MillimetersChartreceivesGeoUtils.LAT_EQUATORand does not use the latitude in the calculation (see MillimetersChart). - The line style and the pattern do not work. The pen is created without a dash, the line is always solid.
- Zero thickness. At thickness 0 the diameters of the marker become zero and it is not visible.
- The marker in the center. The X position of the marker is the middle of the layer, not a recalculation of the distance.
- The minimal step along X here is 2 pixels (in SlopeChartIndicator it is 5).