1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.support.v4.view.animation;
18
19import android.view.animation.Interpolator;
20
21/**
22 * An {@link Interpolator} that uses a lookup table to compute an interpolation based on a
23 * given input.
24 */
25abstract class LookupTableInterpolator implements Interpolator {
26
27    private final float[] mValues;
28    private final float mStepSize;
29
30    public LookupTableInterpolator(float[] values) {
31        mValues = values;
32        mStepSize = 1f / (mValues.length - 1);
33    }
34
35    @Override
36    public float getInterpolation(float input) {
37        if (input >= 1.0f) {
38            return 1.0f;
39        }
40        if (input <= 0f) {
41            return 0f;
42        }
43
44        // Calculate index - We use min with length - 2 to avoid IndexOutOfBoundsException when
45        // we lerp (linearly interpolate) in the return statement
46        int position = Math.min((int) (input * (mValues.length - 1)), mValues.length - 2);
47
48        // Calculate values to account for small offsets as the lookup table has discrete values
49        float quantized = position * mStepSize;
50        float diff = input - quantized;
51        float weight = diff / mStepSize;
52
53        // Linearly interpolate between the table values
54        return mValues[position] + weight * (mValues[position + 1] - mValues[position]);
55    }
56
57}
58