Skip to content

GForceIndicator

roosit edited this page Nov 15, 2026 · 1 revision

GForceIndicator

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 stored in the working file GForceIndicator.java: the production code stays clean and the explanations live in the wiki.

package com.velitask.plugin.official;

import com.velitask.sdk.FrameContext;
import com.velitask.sdk.Indicator;
import com.velitask.sdk.IndicatorContext;
import com.velitask.sdk.data.CurrentAtom;
import com.velitask.sdk.data.GForceSensorAtom;
import com.velitask.sdk.db.DataCacheRule;
import com.velitask.sdk.db.DataParams;
import com.velitask.sdk.properties.BooleanProperty;
import com.velitask.sdk.properties.ColorProperty;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.DisplayHint;
import com.velitask.sdk.properties.EnumArrayProperty;
import com.velitask.sdk.properties.FontColorProperty;
import com.velitask.sdk.properties.GForceAtomProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.IntegerProperty;
import com.velitask.sdk.properties.IntegerSliderProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.TransparentColorProperty;
import com.velitask.sdk.properties.measurement.MeasurementProperty;
import com.velitask.units.UnitKind;
import com.velitask.units.acceleration.Acceleration;
import com.velitask.units.acceleration.AccelerationSystem;
import com.velitask.units.format.UnitValue;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
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;

/* Circular G-force chart: the point, the trail, an optional peak marker and value captions. */
public class GForceIndicator extends Indicator {

    /* Circle limit in g. JSON stores the index (ordinal), value is the limit. */
    public static enum Scale {
        G1(1.0),
        G1_5(1.5),
        G2(2.0),
        G3(3.0);

        public final double value;

        Scale(double value) {
            this.value = value;
        }
    }

    /* Where the point moves: by the felt force (FELT) or by the direction of acceleration (ACCELERATION). */
    public static enum Direction {
        FELT,
        ACCELERATION
    }

    /* Stable indicator name in the layer JSON. It must not be changed without a migration. */
    public static final String NAME = "gforce";

    /* Localization key prefix: Plugin.Indicator.gforce. */
    private static final String KEY = _KEY + "." + NAME;

    private static final String KEY_PAUSE = KEY + ".pause";

    /* The drawing is built in a 360 x 420 base grid; with another layer size it is scaled as a whole. */
    private static final double BASE_WIDTH = 360d;
    private static final double BASE_HEIGHT = 420d;
    /* The circle center, the radius and the number of rings; then the sizes and positions of the captions in the base grid. */
    private static final double CENTER_X = 180d;
    private static final double CENTER_Y = 190d;
    private static final double RADIUS = 130d;
    private static final int RING_COUNT = 3;
    private static final double RING_LABEL_OFFSET = 4.6;
    private static final double POINT_RADIUS = 9.8;
    private static final double PEAK_SIDE = 12d;
    private static final double TRAIL_WIDTH = 3d;
    private static final double LABEL_SIZE = 12d;
    private static final double COMPONENT_SIZE_RATIO = 13d / 30d;
    private static final double AXIS_TOP_Y = 52d;
    private static final double AXIS_BOTTOM_Y = 338d;
    private static final double AXIS_SIDE_Y = 194d;
    private static final double AXIS_LEFT_X = 42d;
    private static final double AXIS_RIGHT_X = 318d;
    private static final double TOTAL_Y = 384d;
    private static final double COMPONENT_LEFT_X = 24d;
    private static final double COMPONENT_RIGHT_X = 336d;
    private static final double COMPONENT_Y = 406d;
    /* Fixed colors: the circle and point outlines; the text color also serves as the default font value. */
    private static final Color BACKGROUND_STROKE = new Color(0x3A3D44);
    private static final Color POINT_STROKE = new Color(0xE6E7EA);
    private static final Color TEXT_COLOR = new Color(0xE6E7EA);

    /* The G-force sensor (JSON key "GForce"). The longitudinal, lateral and vertical components are taken from its records. */
    private final GForceAtomProperty mGForce = new GForceAtomProperty();

    {
        /* Peak query: the record with the largest sum of squares of the longitudinal and lateral components up to the current time. */
        mGForce.query("peak")
                .where("timeRaw <= {to}")
                .orderBy("(longitudinal * longitudinal + lateral * lateral) DESC")
                .limit(1)
                .cache(DataCacheRule.none())
                .buildAtom();

        /* Trail query: the records whose windows intersect the last trailSec seconds. */
        mGForce.query("trail")
                .where("timeRaw < {to} AND (timeRaw + duration) > {from}")
                .orderBy("timeRaw")
                .cache(DataCacheRule.none())
                .cacheSize(2)
                .buildList();
    }

    /* Measurement system and acceleration unit (JSON key "measurement"). */
    private final MeasurementProperty mUnits = new MeasurementProperty(UnitKind.ACCELERATION);

    /* Circle limit; 1.5 g by default (index 1). */
    private final EnumArrayProperty<Scale> mScale
            = new EnumArrayProperty<>(Scale.class) {
        {
            set(Scale.G1_5);
        }

        @Override
        public Scale getDefault() {
            return Scale.G1_5;
        }

        @Override
        public String getName() {
            return "scale";
        }

        @Override
        public String getTitle() {
            return localized(KEY + ".scale.title");
        }

        @Override
        protected String[] defineTitles() {
            Scale[] vs = Scale.values();
            String[] t = new String[vs.length];
            for (int i = 0; i < vs.length; i++) {
                t[i] = localized(KEY + ".scale." + vs[i].name().toLowerCase());
            }
            return t;
        }
    };

    /* Point direction; by default the felt force (index 0). */
    private final EnumArrayProperty<Direction> mDirection
            = new EnumArrayProperty<>(Direction.class) {
        @Override
        public String getName() {
            return "direction";
        }

        @Override
        public String getTitle() {
            return localized(KEY + ".direction.title");
        }

        @Override
        protected String[] defineTitles() {
            Direction[] vs = Direction.values();
            String[] t = new String[vs.length];
            for (int i = 0; i < vs.length; i++) {
                t[i] = localized(KEY + ".direction." + vs[i].name().toLowerCase());
            }
            return t;
        }
    };

    /* Trail length in seconds, range 0..10, 2 by default; 0 disables the trail. */
    private final IntegerSliderProperty mTrailSec
            = new IntegerSliderProperty(2, "trailSec", localized(KEY + ".trailSec.title")) {
        {
            setRange(0, 10);
        }
    };

    /* Behavior in a recording pause; the options are described on the GForcePause page. The default is center and dash. */
    private final EnumArrayProperty<GForcePause> mPause
            = new EnumArrayProperty<>(GForcePause.class) {
        @Override
        public String getName() {
            return "pause";
        }

        @Override
        public String getTitle() {
            return localized(KEY_PAUSE + ".title");
        }

        @Override
        protected String[] defineTitles() {
            GForcePause[] vs = GForcePause.values();
            String[] t = new String[vs.length];
            for (int i = 0; i < vs.length; i++) {
                t[i] = localized(KEY_PAUSE + "." + vs[i].name().toLowerCase());
            }
            return t;
        }
    };

    /* Peak marker; off by default. */
    private final BooleanProperty mShowPeak
            = new BooleanProperty(false, "showPeak", localized(KEY + ".showPeak.title"));

    /* Digits after the decimal point in the captions, range 0..3, 2 by default. */
    private final IntegerSliderProperty mFractionDigits
            = new IntegerSliderProperty(2, "fractionDigits", localized(KEY + ".fractionDigits.title")) {
        {
            setRange(0, 3);
        }
    };

    /* Circle background: black color, transparency 65. */
    private final TransparentColorProperty mBackground = new TransparentColorProperty(
            "background",
            localized(KEY + ".background.title"),
            new Color(0x000000), 65
    );

    /* Rings, axes and captions: color (167, 171, 179), transparency 55. */
    private final TransparentColorProperty mRings = new TransparentColorProperty(
            "rings",
            localized(KEY + ".rings.title"),
            new Color(0xA7ABB3), 55
    );

    /* Point and trail colors are (74, 144, 226), the peak marker color is (245, 194, 66). */
    private final ColorProperty mPoint = new ColorProperty(new Color(0x4A90E2)) {
        @Override
        public String getName() {
            return "point";
        }

        @Override
        public String getTitle() {
            return localized(KEY + ".point.title");
        }
    };

    private final ColorProperty mTrail = new ColorProperty(new Color(0x4A90E2)) {
        @Override
        public String getName() {
            return "trail";
        }

        @Override
        public String getTitle() {
            return localized(KEY + ".trail.title");
        }
    };

    private final ColorProperty mPeak = new ColorProperty(new Color(0xF5C242)) {
        @Override
        public String getName() {
            return "peak";
        }

        @Override
        public String getTitle() {
            return localized(KEY + ".peak.title");
        }
    };

    /* Font and color of the captions; default size 30. */
    private final FontColorProperty mText = new FontColorProperty(30);

    /* The default text color (230, 231, 234) is set in the constructor. */
    public GForceIndicator() {
        mText.getColor().setDefault(TEXT_COLOR);
        mText.getColor().set(TEXT_COLOR);
    }

    @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");
    }

    /* Default maket: layer 360 x 420, bottom/left alignment, margins (left, top, right, bottom) = null, 100, 100, null. */
    @Override
    public void defineMaket(Maket maket) {
        maket.setVertical(VerticalAlign.BOTTOM);
        maket.setHorizontal(HorizontalAlign.LEFT);
        maket.setLayerMargin(null, 100d, 100d, null);
        maket.setLayerSize(BASE_WIDTH, BASE_HEIGHT);
    }

    /* The property order = the order in the settings panel and in JSON. */
    @Override
    public IProperty[] defineProperties() {
        return new IProperty[]{
            mGForce,
            mUnits,
            mScale,
            mDirection,
            mTrailSec,
            mPause,
            mShowPeak,
            mFractionDigits,
            mBackground,
            mRings,
            mPoint,
            mTrail,
            mPeak,
            mText
        };
    }

    /* All properties except the sensor and the font are moved to the "Appearance" group. */
    @Override
    public void configureDisplay(DisplayConfig config) {
        config.set(mUnits, PropertyGroup.APPEARANCE);
        config.set(mScale, PropertyGroup.APPEARANCE);
        config.set(mDirection, PropertyGroup.APPEARANCE);
        config.set(mTrailSec, PropertyGroup.APPEARANCE, DisplayHint.SLIDER);
        config.set(mPause, PropertyGroup.APPEARANCE);
        config.set(mShowPeak, PropertyGroup.APPEARANCE);
        config.set(mFractionDigits, PropertyGroup.APPEARANCE, DisplayHint.SLIDER);
        config.set(mBackground, PropertyGroup.APPEARANCE);
        config.set(mRings, PropertyGroup.APPEARANCE);
        config.set(mPoint, PropertyGroup.APPEARANCE);
        config.set(mTrail, PropertyGroup.APPEARANCE);
        config.set(mPeak, PropertyGroup.APPEARANCE);
    }

    /* Drawing: background, rings, axes, trail, peak, point, texts. */
    @Override
    public void render(IndicatorContext indicatorContext) {
        GForceContext ctx = (GForceContext) indicatorContext;
        Graphics2D g = ctx.graphics;

        CurrentAtom<GForceSensorAtom> current = ctx.gforce.queryCurrent();
        GForceSensorAtom atom = current.atom();
        boolean fromGap = current.inPause();
        /* Outside the recording, and in a pause without a preceding recording, the layer stays empty. */
        if (atom == null) {
            return;
        }

        /* In a pause with the CENTER option the point stays in the center and the values are replaced with dashes. */
        boolean centered = fromGap && ctx.pause.value == GForcePause.CENTER;
        long time = ctx.gforce.rawTime;
        int longitudinal = 0;
        int lateral = 0;
        Integer vertical = null;
        if (!centered) {
            longitudinal = fromGap ? atom.getNextLongitudinal() : atom.calcLongitudinal(time);
            lateral = fromGap ? atom.getNextLateral() : atom.calcLateral(time);
            vertical = fromGap ? atom.getNextVertical() : atom.calcVertical(time);
        }

        /* Circle limit in mm/s². */
        int limit = Acceleration.fromUnit(ctx.limit.value.value, AccelerationSystem.G);
        /* A single scale: the drawing fits into the layer by the smaller side and is centered. */
        double u = Math.min(ctx.width / BASE_WIDTH, ctx.height / BASE_HEIGHT);

        AffineTransform saved = g.getTransform();
        g.translate((ctx.width - BASE_WIDTH * u) / 2d, (ctx.height - BASE_HEIGHT * u) / 2d);
        g.scale(u, u);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        Font base = ctx.text.toFont();
        renderBackground(g, ctx);
        renderRings(g, ctx, base, limit);
        renderAxes(g, ctx, base);
        /* The trail is drawn only inside a recording, not in a pause. */
        if (!fromGap && ctx.trailSec.value > 0) {
            renderTrail(g, ctx, atom, longitudinal, lateral, limit);
        }
        if (ctx.showPeak.value) {
            renderPeak(g, ctx, limit);
        }
        renderPoint(g, ctx, centered, longitudinal, lateral, limit);
        renderTexts(g, ctx, base, centered, longitudinal, lateral, vertical);

        g.setTransform(saved);
    }

    /* Multiplies the color transparency by a coefficient 0..1. */
    private static Color withAlpha(Color color, double alpha) {
        int a = (int) Math.round(color.getAlpha() * Math.max(0d, Math.min(1d, alpha)));
        return new Color(color.getRed(), color.getGreen(), color.getBlue(), a);
    }

    /* Point offset from the center in base grid pixels; beyond the circle the point is pressed to the border. */
    private static double[] offset(Direction direction, int longitudinal, int lateral, int limit) {
        double a = longitudinal / (double) limit;
        double b = lateral / (double) limit;
        double x = direction == Direction.ACCELERATION ? -b : b;
        double yUp = direction == Direction.ACCELERATION ? a : -a;
        double length = Math.hypot(x, yUp);
        if (length > 1d) {
            x /= length;
            yUp /= length;
        }
        return new double[]{RADIUS * x, -RADIUS * yUp};
    }

    /* A signed number: always "+" or "-". */
    private static String signed(UnitValue value, int fractionDigits) {
        String number = new UnitValue(Math.abs(value.value()), value.unit()).number(fractionDigits);
        return (value.value() < 0d ? "-" : "+") + number;
    }

    /* Outputs a string with an anchor: 0 - from the left edge, 0.5 - centered, 1 - at the right edge. */
    private static void drawString(Graphics2D g, String text, double x, double y, double anchor) {
        FontMetrics metrics = g.getFontMetrics();
        double width = metrics.stringWidth(text);
        g.drawString(text, (float) (x - width * anchor), (float) y);
    }

    private void renderBackground(Graphics2D g, GForceContext ctx) {
        Ellipse2D circle = new Ellipse2D.Double(
                CENTER_X - RADIUS, CENTER_Y - RADIUS, RADIUS * 2d, RADIUS * 2d);
        g.setColor(withAlpha(ctx.background.color, ctx.background.alpha));
        g.fill(circle);
        g.setColor(BACKGROUND_STROKE);
        g.setStroke(new BasicStroke(2f));
        g.draw(circle);
    }

    /* Three dashed rings at 1/3, 2/3 and the full limit; the ring captions are in the chosen units. */
    private void renderRings(Graphics2D g, GForceContext ctx, Font base, int limit) {
        Color ringColor = withAlpha(ctx.rings.color, ctx.rings.alpha);
        float[] dash = {4f, 4f};
        double diagonal = Math.sqrt(0.5);
        g.setFont(base.deriveFont(Font.PLAIN, (float) LABEL_SIZE));
        for (int k = 1; k <= RING_COUNT; k++) {
            double r = RADIUS * k / RING_COUNT;
            g.setColor(ringColor);
            g.setStroke(new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, dash, 0f));
            g.draw(new Ellipse2D.Double(CENTER_X - r, CENTER_Y - r, r * 2d, r * 2d));

            UnitValue parts = ctx.units.accelerationParts((int) Math.round((double) limit * k / RING_COUNT));
            g.setColor(ctx.rings.color);
            drawString(g, parts.number() + " " + parts.unit(),
                    CENTER_X + r * diagonal + RING_LABEL_OFFSET,
                    CENTER_Y - r * diagonal - RING_LABEL_OFFSET, 0d);
        }
    }

    /* The axes cross and four captions; when the direction changes the captions swap places. */
    private void renderAxes(Graphics2D g, GForceContext ctx, Font base) {
        g.setColor(withAlpha(ctx.rings.color, ctx.rings.alpha));
        g.setStroke(new BasicStroke(1f));
        g.draw(new Line2D.Double(CENTER_X - RADIUS, CENTER_Y, CENTER_X + RADIUS, CENTER_Y));
        g.draw(new Line2D.Double(CENTER_X, CENTER_Y - RADIUS, CENTER_X, CENTER_Y + RADIUS));

        boolean felt = ctx.direction.value == Direction.FELT;
        g.setFont(base.deriveFont(Font.PLAIN, (float) LABEL_SIZE));
        g.setColor(ctx.rings.color);
        String accel = localized(KEY + ".axis.accel");
        String brake = localized(KEY + ".axis.brake");
        String left = localized(KEY + ".axis.left");
        String right = localized(KEY + ".axis.right");
        drawString(g, felt ? brake : accel, CENTER_X, AXIS_TOP_Y, 0.5);
        drawString(g, felt ? accel : brake, CENTER_X, AXIS_BOTTOM_Y, 0.5);
        drawString(g, felt ? right : left, AXIS_LEFT_X, AXIS_SIDE_Y, 1d);
        drawString(g, felt ? left : right, AXIS_RIGHT_X, AXIS_SIDE_Y, 0d);
    }

    /* Trail: segments between neighboring records inside one segment; the older the segment, the more transparent it is. */
    private void renderTrail(Graphics2D g, GForceContext ctx, GForceSensorAtom atom,
            int longitudinal, int lateral, int limit) {
        long time = ctx.gforce.rawTime;
        long from = time - ctx.trailSec.value * 1000L;
        List<GForceSensorAtom> window = ctx.gforce.queryList("trail",
                DataParams.of("sensorId", ctx.gforce.sensorId).set("from", from).set("to", time));
        if (window == null || window.isEmpty()) {
            return;
        }

        g.setStroke(new BasicStroke((float) TRAIL_WIDTH, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        double span = Math.max(1d, time - from);

        GForceSensorAtom previous = null;
        double[] previousOffset = null;
        for (GForceSensorAtom item : window) {
            double[] current = offset(ctx.direction.value, item.longitudinal, item.lateral, limit);
            if (previous != null && previous.continuesWith(item)) {
                drawTrailSegment(g, ctx, previousOffset, current, (item.timeRaw - from) / span);
            }
            previous = item;
            previousOffset = current;
        }

        if (previous.segmentStart == atom.segmentStart) {
            double[] current = offset(ctx.direction.value, longitudinal, lateral, limit);
            drawTrailSegment(g, ctx, previousOffset, current, 1d);
        }
    }

    private void drawTrailSegment(Graphics2D g, GForceContext ctx, double[] from, double[] to, double alpha) {
        g.setColor(withAlpha(ctx.trailColor.value, alpha));
        g.draw(new Line2D.Double(
                CENTER_X + from[0], CENTER_Y + from[1],
                CENTER_X + to[0], CENTER_Y + to[1]));
    }

    /* The peak marker is a diamond at the record point with the maximum magnitude up to the current time. */
    private void renderPeak(Graphics2D g, GForceContext ctx, int limit) {
        GForceSensorAtom peak = ctx.gforce.queryAtom("peak",
                DataParams.of("sensorId", ctx.gforce.sensorId).set("to", ctx.gforce.rawTime));
        if (peak == null) {
            return;
        }
        double[] position = offset(ctx.direction.value, peak.longitudinal, peak.lateral, limit);
        double x = CENTER_X + position[0];
        double y = CENTER_Y + position[1];
        double half = PEAK_SIDE * Math.sqrt(0.5);
        Path2D diamond = new Path2D.Double();
        diamond.moveTo(x, y - half);
        diamond.lineTo(x + half, y);
        diamond.lineTo(x, y + half);
        diamond.lineTo(x - half, y);
        diamond.closePath();
        g.setColor(ctx.peakColor.value);
        g.fill(diamond);
    }

    /* The point: the circle center for a pause with a dash, otherwise the position by the current values. */
    private void renderPoint(Graphics2D g, GForceContext ctx, boolean centered,
            int longitudinal, int lateral, int limit) {
        double[] position = centered
                ? new double[]{0d, 0d}
                : offset(ctx.direction.value, longitudinal, lateral, limit);
        Ellipse2D point = new Ellipse2D.Double(
                CENTER_X + position[0] - POINT_RADIUS, CENTER_Y + position[1] - POINT_RADIUS,
                POINT_RADIUS * 2d, POINT_RADIUS * 2d);
        g.setColor(ctx.pointColor.value);
        g.fill(point);
        g.setColor(POINT_STROKE);
        g.setStroke(new BasicStroke(2f));
        g.draw(point);
    }

    /* The total value at the bottom center, the longitudinal and lateral components with a sign at the edges. */
    private void renderTexts(Graphics2D g, GForceContext ctx, Font base, boolean centered,
            int longitudinal, int lateral, Integer vertical) {
        int digits = ctx.fractionDigits.value;
        String dash = localized(KEY + ".dash");
        String totalText = dash;
        String longitudinalText = dash;
        String lateralText = dash;
        if (!centered) {
            double total = Acceleration.magnitude(longitudinal, lateral, vertical);
            UnitValue totalParts = ctx.units.accelerationParts((int) Math.round(total));
            totalText = totalParts.number(digits) + " " + totalParts.unit();
            longitudinalText = signed(ctx.units.accelerationParts(longitudinal), digits);
            lateralText = signed(ctx.units.accelerationParts(lateral), digits);
        }

        g.setColor(ctx.text.color.value);
        g.setFont(base.deriveFont(Font.BOLD));
        drawString(g, totalText, CENTER_X, TOTAL_Y, 0.5);

        g.setColor(ctx.rings.color);
        g.setFont(base.deriveFont(Font.PLAIN, (float) (base.getSize2D() * COMPONENT_SIZE_RATIO)));
        drawString(g, localized(KEY + ".longitudinal") + " " + longitudinalText,
                COMPONENT_LEFT_X, COMPONENT_Y, 0d);
        drawString(g, localized(KEY + ".lateral") + " " + lateralText,
                COMPONENT_RIGHT_X, COMPONENT_Y, 1d);
    }

    /* Frame context: the values of all properties at the moment of the frame being drawn. */
    public class GForceContext extends IndicatorContext {

        public final GForceAtomProperty.SensorContext gforce;
        public final MeasurementProperty.Context units;
        public final EnumArrayProperty<Scale>.ArrayContext limit;
        public final EnumArrayProperty<Direction>.ArrayContext direction;
        public final IntegerProperty.IntegerContext trailSec;
        public final EnumArrayProperty<GForcePause>.ArrayContext pause;
        public final BooleanProperty.BooleanContext showPeak;
        public final IntegerProperty.IntegerContext fractionDigits;
        public final TransparentColorProperty.TransparentColorContext background;
        public final TransparentColorProperty.TransparentColorContext rings;
        public final ColorProperty.ColorContext pointColor;
        public final ColorProperty.ColorContext trailColor;
        public final ColorProperty.ColorContext peakColor;
        public final FontColorProperty.FontColorContext text;

        public GForceContext(FrameContext frame) {
            super(frame);
            gforce = mGForce.createContext(frame);
            units = mUnits.createContext(frame);
            limit = mScale.createContext(frame);
            direction = mDirection.createContext(frame);
            trailSec = mTrailSec.createContext(frame);
            pause = mPause.createContext(frame);
            showPeak = mShowPeak.createContext(frame);
            fractionDigits = mFractionDigits.createContext(frame);
            background = mBackground.createContext(frame);
            rings = mRings.createContext(frame);
            pointColor = mPoint.createContext(frame);
            trailColor = mTrail.createContext(frame);
            peakColor = mPeak.createContext(frame);
            text = mText.createContext(frame);
        }
    }

    /* Context factory, called for every frame. */
    @Override
    public IndicatorContext createContext(FrameContext frame) {
        return new GForceContext(frame);
    }
}

Purpose

GForceIndicator draws a circle with the point of the current G-force: the larger the longitudinal and lateral components, the farther the point is from the center. Around the center there are three dashed rings with captions in the chosen units and four axis captions (acceleration, braking, left, right); a trail of the last seconds follows the point, and optionally the peak is marked on the circle. Under the circle the total value and both components with a sign are output. The indicator has no skins.

How it works

Data. GForceAtomProperty (JSON key GForce, table sensors_gforce_data) creates ctx.gforce. queryCurrent() returns a pair "record, pause flag": inside a recording it is the record for the frame time, in a pause the last record before the pause, outside a recording there is no record (then render draws nothing). The components are stored as integers in mm/s² relative to the direction of movement. Inside a recording the values are refined linearly through calcLongitudinal(rawTime), calcLateral(rawTime), calcVertical(rawTime); in a pause the values at the end of the window of the last record are taken (getNext...). The vertical component can be null, in which case it is not included in the magnitude.

Two additional queries are declared in the initialization block. peak returns one record with the largest longitudinal² + lateral² among the records with timeRaw <= {to}, that is, the peak from the start of the recording to the current frame. trail returns the records whose windows intersect the interval from "to minus the trail length" to to. Both queries are declared without a cache (DataCacheRule.none()); for trail, cacheSize(2) is additionally set.

Settings. defineProperties() has fourteen properties in this order: GForce, measurement, scale, direction, trailSec, pause, showPeak, fractionDigits, background, rings, point, trail, peak, font.

  • measurement — MeasurementProperty(UnitKind.ACCELERATION): the measurement system, the unit caption format and the acceleration unit; it applies to all captions, including the rings.
  • scale — the circle limit: 1, 1.5, 2 or 3 g (index 0..3), 1.5 g by default. The rings stand at a third, two thirds and the full value of the limit.
  • direction — FELT (felt force, the default) or ACCELERATION (acceleration). It changes the sign of the offset along both axes and the axis captions.
  • trailSec — the trail length, an IntegerSliderProperty with the range 0..10 seconds, 2 by default.
  • pause — EnumArrayProperty<GForcePause>: CENTER (the default) or LAST, see GForcePause.
  • showPeak — BooleanProperty, false by default.
  • fractionDigits — digits after the decimal point in the captions, range 0..3, 2 by default.
  • background, rings — TransparentColorProperty: color and transparency. The background is black, transparency 65; the rings, axes and captions have the color 167, 171, 179, transparency 55.
  • point, trail — ColorProperty, both 74, 144, 226; peak — ColorProperty 245, 194, 66.
  • font — FontColorProperty with size 30; the class constructor sets the default color 230, 231, 234.

In configureDisplay() all properties except the sensor and the font are moved to the "Appearance" group; the trail length and the number of digits are shown as sliders (DisplayHint.SLIDER).

Drawing. The drawing is built in a 360 x 420 base grid (the circle center 180, 190, radius 130). The scale is u = min(width / 360, height / 420), the drawing is centered in the layer; the font is taken through ctx.text.toFont() without ctx.scale, since the canvas does the scaling itself. The order:

  1. the background: a circle filled by the color and transparency of background with a gray outline #3A3D44;
  2. the rings (dashed) with captions of the form "number unit" at the upper right edge of each ring; then the cross of axes and four side captions;
  3. the trail — only if a recording is playing (not a pause) and trailSec > 0;
  4. the peak marker — if showPeak is on: a filled diamond of the peak color;
  5. the point: a circle of radius 9.8 filled with point and a light outline #E6E7EA;
  6. the texts: the total value in bold at the bottom center, under the circle on the left "longitudinal ±number", on the right "lateral ±number" in a small font (13/30 of the font size).

The point offset is calculated in offset(...): the components are divided by the circle limit; in the FELT mode a positive longitudinal component shifts the point down and a positive lateral one to the right, in the ACCELERATION mode the longitudinal one shifts it up and the lateral one to the left. If the vector length is greater than one, it is normalized and the point stays on the circle border. The side captions swap places together with the mode.

The trail is built from segments between neighboring records that lie in one recording segment (continuesWith); the transparency of a segment grows linearly from 0 at the old end of the window to 1 at the current time. The last segment leads from the last record of the window to the current point if they are from one segment.

The total value is Acceleration.magnitude(longitudinal, lateral, vertical), rounded to a whole mm/s² and converted to the chosen unit; the vertical component is taken into account in it. The components are shown with a sign (+ or -) and the same number of digits.

Features and limitations

  • The peak marker is calculated only from the longitudinal and lateral components and from the record values without interpolation, while the total value in the caption also takes the vertical component and interpolation into account; therefore the "total" can exceed the value corresponding to the peak marker.
  • In a pause with CENTER the point stays in the center, and the total value and the components are replaced with the dash —; with LAST the last value before the pause is shown. The peak marker (if enabled) is drawn in a pause too, the trail is not.
  • Outside the recording, and in a pause without a preceding recording, the indicator draws nothing.
  • Only the position of the point is normalized beyond the circle; the values in the captions stay real.
  • The default layer size is 360 x 420, aligned bottom left; the proportions of the drawing are fixed, with another layer proportion it is fitted by the smaller side.
  • The scale, direction, pause properties store the option index, not the name: reordering the options in the enum breaks saved projects.
  • Renaming properties (scale, trailSec, etc.) breaks loading of saved projects: loading goes by names.

Clone this wiki locally