Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.2 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //=============================================================================//
  7. #ifndef LOWPASSSTREAM_H
  8. #define LOWPASSSTREAM_H
  9. #ifdef _WIN32
  10. #pragma once
  11. #endif
  12. // ------------------------------------------------------------------ //
  13. // Default implementations of the operators used for averaging.
  14. // ------------------------------------------------------------------ //
  15. template< class DataType >
  16. inline void SetToZero( DataType &data )
  17. {
  18. data = 0;
  19. }
  20. template< class DataType >
  21. inline void AddSamples( DataType const &d1, DataType const &d2, DataType &out )
  22. {
  23. out = d1 + d2;
  24. }
  25. template< class DataType >
  26. inline DataType DivideSample( DataType const &data, int factor )
  27. {
  28. return data / factor;
  29. }
  30. // This class does a simple low pass filter on data that you pass through it.
  31. // You tell it the number of samples to hang onto and it will average that number
  32. // of samples as you feed it data.
  33. template< class DataType, int nSamples >
  34. class CLowPassStream
  35. {
  36. public:
  37. CLowPassStream();
  38. // Add a sample to the list.
  39. void AddSample( DataType const &data );
  40. // Get the current average.
  41. DataType GetCurrentAverage();
  42. private:
  43. DataType m_Samples[nSamples];
  44. int m_iOutSample;
  45. int m_nSamplesGotten; // incremented until it reaches nSamples.
  46. // helps avoid the startup transient.
  47. };
  48. template< class DataType, int nSamples >
  49. inline CLowPassStream<DataType, nSamples>::CLowPassStream()
  50. {
  51. for( int i=0; i < nSamples; i++ )
  52. SetToZero( m_Samples[i] );
  53. m_iOutSample = 0;
  54. m_nSamplesGotten = 0;
  55. }
  56. template< class DataType, int nSamples >
  57. inline void CLowPassStream<DataType, nSamples>::AddSample( DataType const &data )
  58. {
  59. m_Samples[m_iOutSample] = data;
  60. ++m_nSamplesGotten;
  61. if( m_nSamplesGotten >= nSamples )
  62. m_nSamplesGotten = nSamples;
  63. ++m_iOutSample;
  64. if( m_iOutSample >= nSamples )
  65. m_iOutSample = 0;
  66. }
  67. template< class DataType, int nSamples >
  68. inline DataType CLowPassStream<DataType, nSamples>::GetCurrentAverage()
  69. {
  70. DataType data;
  71. SetToZero( data );
  72. for( int i=0; i < nSamples; i++ )
  73. AddSamples( data, m_Samples[i], data );
  74. return DivideSample( data, m_nSamplesGotten );
  75. }
  76. #endif // LOWPASSSTREAM_H