Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit dfe4c235 authored by Zak Cohen's avatar Zak Cohen Committed by Android (Google) Code Review
Browse files

Merge "Adds lerpInv, saturate, lerpInvSat and constrainedMap to MathUtils."

parents 2b5eef9e c730de91
Loading
Loading
Loading
Loading
+46 −0
Original line number Diff line number Diff line
@@ -165,6 +165,26 @@ public final class MathUtils {
        return start + (stop - start) * amount;
    }

    /**
     * Returns the interpolation scalar (s) that satisfies the equation: {@code value = }{@link
     * #lerp}{@code (a, b, s)}
     *
     * <p>If {@code a == b}, then this function will return 0.
     */
    public static float lerpInv(float a, float b, float value) {
        return a != b ? ((value - a) / (b - a)) : 0.0f;
    }

    /** Returns the single argument constrained between [0.0, 1.0]. */
    public static float saturate(float value) {
        return constrain(value, 0.0f, 1.0f);
    }

    /** Returns the saturated (constrained between [0, 1]) result of {@link #lerpInv}. */
    public static float lerpInvSat(float a, float b, float value) {
        return saturate(lerpInv(a, b, value));
    }

    /**
     * Returns an interpolated angle in degrees between a set of start and end
     * angles.
@@ -194,6 +214,32 @@ public final class MathUtils {
        return maxStart + (maxStop - maxStart) * ((value - minStart) / (minStop - minStart));
    }

    /**
     * Calculates a value in [rangeMin, rangeMax] that maps value in [valueMin, valueMax] to
     * returnVal in [rangeMin, rangeMax].
     * <p>
     * Always returns a constrained value in the range [rangeMin, rangeMax], even if value is
     * outside [valueMin, valueMax].
     * <p>
     * Eg:
     *    constrainedMap(0f, 100f, 0f, 1f, 0.5f) = 50f
     *    constrainedMap(20f, 200f, 10f, 20f, 20f) = 200f
     *    constrainedMap(20f, 200f, 10f, 20f, 50f) = 200f
     *    constrainedMap(10f, 50f, 10f, 20f, 5f) = 10f
     *
     * @param rangeMin minimum of the range that should be returned.
     * @param rangeMax maximum of the range that should be returned.
     * @param valueMin minimum of range to map {@code value} to.
     * @param valueMax maximum of range to map {@code value} to.
     * @param value to map to the range [{@code valueMin}, {@code valueMax}]. Note, can be outside
     *              this range, resulting in a clamped value.
     * @return the mapped value, constrained to [{@code rangeMin}, {@code rangeMax}.
     */
    public static float constrainedMap(
            float rangeMin, float rangeMax, float valueMin, float valueMax, float value) {
        return lerp(rangeMin, rangeMax, lerpInvSat(valueMin, valueMax, value));
    }

    /**
     * Perform Hermite interpolation between two values.
     * Eg: