1 /* 2 * CRRCsim - the Charles River Radio Control Club Flight Simulator Project 3 * Copyright (C) 2005, 2008 - Jens Wilhelm Wulf (original author) 4 * Copyright (C) 2010 - Jan Reucker (conversion to template class) 5 * 6 * This program is free software; you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 2 8 * as published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program; if not, write to the Free Software 17 * Foundation, Inc., 59 Temple Place, Suite 330, 18 * Boston, MA 02111-1307, USA. 19 * 20 */ 21 #ifndef RATELIM_H 22 # define RATELIM_H 23 24 namespace CRRCMath 25 { 26 /** 27 * Limits the rate of change of a value. 28 * 29 * @author Jens Wilhelm Wulf 30 */ 31 template <typename T> 32 class RateLimiter 33 { 34 public: 35 /** 36 * @param ival initial value 37 * @param rate rate of change per second 38 */ 39 RateLimiter(T ival = 0, T rate = 1) 40 { 41 init(ival, rate); 42 } 43 44 /** 45 * @param ival initial value 46 * @param rate the value is allowed to change rate per second 47 */ init(T ival,T rate)48 void init(T ival, T rate) 49 { 50 val = ival; 51 ratemax = rate; 52 } 53 54 /** 55 * @param dt timestep [s] 56 * @param nval new input value 57 */ step(double dt,T nval)58 void step(double dt, T nval) 59 { 60 T dmax = ratemax * dt; 61 62 T diff = nval - val; 63 64 if (diff > dmax) 65 { 66 diff = dmax; 67 } 68 else if (diff < -dmax) 69 { 70 diff = -dmax; 71 } 72 73 val += diff; 74 } 75 76 77 /** 78 * limited value 79 */ 80 T val; 81 82 private: 83 T ratemax; 84 }; 85 }; 86 #endif 87