AUI Framework  master
Cross-platform base for C++ UI apps
Loading...
Searching...
No Matches
AValueSmoother.h
    1/*
    2 * AUI Framework - Declarative UI toolkit for modern C++20
    3 * Copyright (C) 2020-2025 Alex2772 and Contributors
    4 *
    5 * SPDX-License-Identifier: MPL-2.0
    6 *
    7 * This Source Code Form is subject to the terms of the Mozilla Public
    8 * License, v. 2.0. If a copy of the MPL was not distributed with this
    9 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
   10 */
   11
   12#pragma once
   13
   14template<typename T = float>
   15class AValueSmoother {
   16public:
   17    AValueSmoother(const T& current, const T& smoothK = 0.5) noexcept
   18            : mCurrent(current),
   19              mSmoothK(smoothK),
   20              mStart(current)
   21    {
   22    }
   23
   24    AValueSmoother() noexcept
   25            : mCurrent(0),
   26              mSmoothK(0.5),
   27              mStart(0)
   28    {
   29    }
   30
   31    T nextValue(T value) noexcept
   32    {
   33        auto delta = glm::abs(mCurrent - value);
   34        auto toAdd = (value - mCurrent) * mSmoothK;
   35        if (delta < glm::abs(toAdd)) { // avoid chatter
   36            mCurrent = value;
   37        } else {
   38            mCurrent += toAdd;
   39        }
   40        return mCurrent;
   41    }
   42
   43
   44    void setCurrent(T value) noexcept
   45    {
   46        mCurrent = value;
   47    }
   48
   49    T getCurrent() noexcept
   50    {
   51        return mCurrent;
   52    }
   53
   54    void setK(T k) noexcept
   55    {
   56        mSmoothK = k;
   57    }
   58    T getK() noexcept
   59    {
   60        return mSmoothK;
   61    }
   62
   63    void reset() noexcept
   64    {
   65        mCurrent = mStart;
   66    }
   67
   68private:
   69    T mCurrent;
   70    T mSmoothK;
   71    T mStart;
   72};