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. Must not be changed without a migration. */
public static final String NAME = "speedChart";
/* Localization key prefix: 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();
{
/*
* The "speedRange" query: 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();
/*
* The "avgSpeed" aggregate: the average non-zero speed over the whole sensor.
* The result is cached once under the "avg" key.
*/
mDistance.aggregate("avgSpeed")
.select("AVG(speed) AS avgSpeed")
.where("speed > 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 thickness are used; the line style and 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 average speed line (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: a 600x300 layer at the bottom left corner, margins 100 from the left and 100 from 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 property order 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 4 thick 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()
};
}
/*
* The "once" cache rule: the aggregate result is stored under the "avg" key
* and returned for any query parameters.
*/
private static final DataCacheRule ONCE_CACHE_RULE = new DataCacheRule() {
@Override
public boolean isCached(DataParams params, DataCacheStorage cache) {
return cache.has("avg");
}
@Override
public Object getFromCache(DataParams params, DataCacheStorage cache) {
return cache.get("avg");
}
@Override
public void store(DataParams params, Object data, DataCacheStorage cache) {
cache.put("avg", data);
}
};
@Override
/* Drawing 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. No data: draw nothing. */
DistanceSensorAtom currAtom = ctx.distance.queryAtom();
if (currAtom == null) {
return;
}
/*
* Horizontal chart window: the center is the distance of the current point, the X scale is by geoZoom.
* The vertical scale is computed 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 reserve 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;
}
/* Maximum speed among the window atoms (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% reserve),
* 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 average speed line. */
renderAvgLine(g, chart, yScale, ctx);
/* The current speed marker at 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 segment's average speed 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);
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);
}
}
}
/* Minimum step along X (in pixels) for merging close points. */
private static final int MIN_PX_BETWEEN_POINTS = 2;
/* The line: atoms that are 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;
i++;
for (; i < atoms.size(); i++) {
DistanceSensorAtom next = atoms.get(i);
x2 = chart.convertMmToPxX(next.getNextDistance());
y2 = speedToPixelY(next.getNextSpeed(), yScale, height);
if ((x2 - x1) >= MIN_PX_BETWEEN_POINTS) {
hasNext = true;
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);
}
}
}
/*
* The average speed over the whole sensor (the "avgSpeed" aggregate); zero or missing: not drawn.
* A line of fixed thickness 2 with a 10/8 dash.
*/
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);
}
/* The marker is a ring: at the layer center 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 indicator's save format is described on the page SpeedChartIndicator JSON. User guide: Speed Chart.
SpeedChartIndicator (name in JSON speedChart, UI title "Speed Chart") draws a speed chart along the track around the current position: the speed line, the fill under it with a smooth color transition from "min" to "max", a dashed average speed line, and a ring marker of the current speed at the center of the layer.
- The only sensor is
DistanceSensorProperty(JSON keyDistance, "Distance" in the UI). TheDistanceSensorAtomatom carries the accumulated distancedistancein millimeters and the speedspeedin mm/h with the incrementsspeedDeltaanddistanceDelta. - The current atom is taken without arguments:
ctx.distance.queryAtom()(by the frame time, interpolated). The sensor isctx.distance.sensorId. - The
speedRangemanager returns atoms that intersect the distance range[minDistance, maxDistance), intimeRaworder, without a cache. - The
avgSpeedaggregate isAVG(speed)over the non-zero speeds of the whole sensor. The cache ruleONCE_CACHE_RULEstores the result under the keyavgand returns it for any query parameters, that is, it is computed once. - 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 | - | Source and sensor of distance and speed. |
geoZoom |
GeoZoomProperty |
14 | 8..19 | Horizontal scale: how many millimeters of distance fall on a pixel. |
SpeedScale |
IntegerProperty |
1 | 1..20 | Vertical stretch of the chart. |
line |
LineProperty |
white, thickness 1, solid | thickness 0..50 | The speed line and the marker; only the color and thickness are used. |
fillColorLow |
ColorProperty |
0, 200, 0, 60 | 0..255 per channel | Fill color at low speed. |
fillColorHigh |
ColorProperty |
200, 0, 0, 60 | 0..255 per channel | Fill color at the maximum speed of the window. |
avgColor |
ColorProperty |
255, 255, 0, 180 | 0..255 per channel | 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).
- If the atom of the current moment is not found, the frame stays empty.
- A
MillimetersChartis built with the X center at the distance of the current atom and scale multipliers 1 and 1. This object is not used along Y: the vertical scale is computed separately. - The window atoms plus a reserve of
50 * mmPerPixelon each side are requested. No atoms: exit. -
maxSpeedis the maximum ofmax(speed, speed + speedDelta)over the window atoms. A zero maximum: exit. - 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. - Fill: trapezoids from the bottom edge of the layer to the speed line between neighboring points (points that are close along X are merged when the step is less than 2 pixels). The color is a linear blend of
fillColorLowandfillColorHighby the ratio of the segment's average speed tomaxSpeed(from 0 to 1), including the alpha channel. - Speed line: a
BasicStrokeof thicknessthickness * scale, with rounded cap and join. - Average speed: a horizontal line at the height of the
avgSpeedaggregate; not drawn if the value is missing or zero. The pen is fixed: thickness 2, dash 10/8 pixels, coloravgColor. - Marker: at the layer center along X, at the current speed along Y; the outer circle has diameter
6 * thickness, and the inner one with diameter4 * thicknessis cut out withAlphaComposite.Clear.
-
Auto-scaling by window. The vertical scale is recomputed every frame from the maximum speed in the visible window, so the chart height "breathes" when passing fast and slow sections.
SpeedScaleonly amplifies this scale. - The average speed is global. The line is computed over the whole sensor, while the scale is only over the window, so the average may end up above the top edge of the layer.
-
Average speed cache. The result is cached once under the fixed key
avgregardless of the sensor. If the sensor is changed within one session, the old value may be used; this behavior was not checked in practice. -
Latitude is not taken into account.
MillimetersChartreceivesGeoUtils.LAT_EQUATORand does not use latitude in its calculation (see MillimetersChart). - Line style and dash pattern do not work. The pen is created without a dash, so the line is always solid.
- Zero thickness. With thickness 0 the marker diameters become zero and it is not visible.
- Marker at the center. The marker's X position is the middle of the layer, not a recalculation of the distance.
- The minimum step along X is 2 pixels here (5 in SlopeChartIndicator).