Skip to content

SlopeChartIndicator

roosit edited this page Nov 15, 2026 · 4 revisions

SlopeChartIndicator

Up | Previous | Next | Русский

Full source with short explanations

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 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.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, the colored fill of sections and a marker. */
public class SlopeChartIndicator extends Indicator {

    /* Stable indicator name 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;

    /* Minimal step along X (in pixels) between line points: atoms closer than that 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 with "Fill transparency". */
    private final ColorProperty mFillPlain = new ColorProperty(
            Color.WHITE, "fillPlain", localized(KEY + ".fillPlain.title"));

    /* Fill color of climbs (JSON "fillUp"), red by default. */
    private final ColorProperty mFillUp = new ColorProperty(
            Color.RED, "fillUp", localized(KEY + ".fillUp.title"));

    /* Fill color of descents (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 chosen in the project. */
    private final SlopeAtomProperty mSlope = new SlopeAtomProperty();

    {
        /*
         * Query "slopeRange": 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. Sets how many millimeters of the track fit 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"): 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();

    @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 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 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; the elevation scale and the 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 thickness 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 of 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; in a recording pause, the last atom before the pause. No data: nothing is drawn. */
        SlopeSensorAtom currAtom = ctx.slope.queryAtomOrBefore();
        if (currAtom == null) {
            return;
        }

        /*
         * Chart window: the center is the distance and the elevation of the current point, the X scale is by geoZoom, the Y scale is 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 database (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 are 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, by ascending distance. Without a database: 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;
            /* A group entirely to the left of the window: skip; to the right: exit (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; skip points with the same X. */
            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());

            g.setColor(groupFill(groupAtom, fillDown, fillUp, fillPlain));
            g.fillPolygon(polygon);
        }
    }

    /* Fill color by group type: descent, climb or flat. */
    private static Color groupFill(SlopeGroupAtom groupAtom,
            Color fillDown, Color fillUp, Color fillPlain) {
        if (groupAtom.slopeType < 0) {
            return fillDown;
        }
        if (groupAtom.slopeType > 0) {
            return fillUp;
        }
        return fillPlain;
    }

    /* Line: consecutive atoms closer than 5 pixels along 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;
            for (int j = i + 1; j < atoms.size(); j++) {
                SlopeSensorAtom item2 = atoms.get(j);
                x2 = chart.convertMmToPxX(item2.getNextDistance());
                y2 = chart.convertMmToPxY(item2.getNextElevation());
                if ((x2 - x1) > MIN_PX_BETWEEN_POINTS) {
                    hasItem2 = true;
                    /* The outer loop continues after the atom where the segment ended. */
                    i = j;
                    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);
                /* Merging to the end of the list: there is nothing left to walk through. */
                i = atoms.size();
            }
        }
    }

    /* 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);
    }

    /* Color with a given alpha channel (limited 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
    /* Frame context factory. */
    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.

Purpose

SlopeChartIndicator (the JSON name is slopeChart, the interface title is "Elevation Chart") draws the elevation profile of the track around the current position: an elevation line, a colored fill under it (a separate color for climbs, descents and flat sections) and a ring marker of the current point. The marker always stands in the center of the layer, and the chart "moves" past it as the video plays.

How it works

Data

  • The only sensor is SlopeAtomProperty (JSON key Slope, "Slope" in the interface). It reads the project table sensors_slope_data, and the atom is SlopeSensorAtom: the accumulated distance and elevation in millimeters and the increments distanceDelta / elevationDelta over the atom window.
  • The current atom is requested with the standard SDK method ctx.slope.queryAtomOrBefore(): the atom that covers the frame time, and in a recording pause (a stop, a device auto-pause) the last atom before the pause, so the marker and the chart do not disappear. The indicator no longer registers its own slope data manager. The sensor identifier is taken from ctx.slope.sensorId.
  • The atoms of the window are requested by the slopeRange manager: all atoms that intersect the distance range [minDistance, maxDistance) (the condition (distance + distanceDelta) >= {minDistance} AND distance < {maxDistance}), in timeRaw order. The cache is disabled (DataCacheRule.none()) because the range changes every frame.
  • The slope groups are read by a direct SQL query through ctx.db from the plugin table slope_groups (see SlopeGroupAtom). The table is filled by VelitaskPlagin.onSourceImported when a source with a slope sensor is imported. If db is null or 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.

Settings

JSON key SDK type Default Range Role
Slope SlopeAtomProperty not selected n/a The slope source and sensor.
geoZoom GeoZoomProperty 14 8..19 The horizontal scale: how many millimeters of distance fall on a pixel.
EleChartScale IntegerProperty 10 1..50 The 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 the color and the thickness are used.
fillPlain ColorProperty white 0..255 per channel The fill of flat sections.
fillUp ColorProperty red 0..255 per channel The fill of climbs.
fillDown ColorProperty green 0..255 per channel The fill of descents.
fillTransparency IntegerProperty 30 0..255 The alpha channel of all three fills.

geoZoom, EleChartScale, fillTransparency are declared non-skinnable. The bold skin ("Bold") changes only the line color (white) and its thickness (10).

Drawing

  1. 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.
  2. A MillimetersChart is built with the width and height of the layer, centered at the point (distance, elevation) of the current atom, with the X scale by geoZoom and the Y scale by EleChartScale.
  3. The query range is the chart window plus a margin of 50 * mmPerPixel on each side.
  4. If there are no atoms in the window, exit.
  5. The fill of groups (if there are any): 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 helper method groupFill by the slopeType of the group: descent is fillDown, climb is fillUp, otherwise fillPlain; the alpha channel of any of the colors is replaced with the value of fillTransparency.
  6. The line: atoms are walked in order; the next point is taken from the first atom whose end is more than 5 pixels along X from the start of the segment, so small atoms merge. The pen is a BasicStroke with the thickness thickness * scale, the end CAP_SQUARE, the join JOIN_ROUND.
  7. The marker: the outer circle with the diameter 6 * thickness in the line color, then the inner circle with the diameter 4 * thickness is cut out with the AlphaComposite.Clear mode, which gives a ring with a transparent middle.

Features and limitations

  • The latitude is not taken into account. GeoUtils.LAT_EQUATOR is passed to MillimetersChart, and the class itself does not use the latitude in the calculation (see MillimetersChart), so the scale does not depend on the place on Earth.
  • The 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.
  • The line style and the pattern do not work. LineProperty shows the line style and the dash pattern in the interface, but the pen is created without a dash: the line is always solid.
  • The fill alpha. The alpha channel set in the colors fillPlain, fillUp, fillDown themselves is ignored: fillTransparency is applied everywhere.
  • Zero thickness. At thickness 0 the diameters of the marker become zero and it is not visible.
  • Pauses. The line, the fill and the marker are drawn solid, and a recording pause does not break them: the slopeRange data window is taken by the distance range without regard to pauses, and during a pause the marker stands at the last point before it.
  • 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.
  • The transparent hole of the marker. The cut-out is made in the layer itself, so the hole is transparent even over the fill.
  • Fixed size. The chart window always equals the size of the layer in pixels; the distance coverage depends on the layer size and geoZoom.

Clone this wiki locally