VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
DecayingScore.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cmath>
4
5namespace VoltMod
6{
7
8/**
9 * @brief A score that loses half its weight every half-life - the building block for evidence
10 * that should fade with age rather than expire on a window edge.
11 *
12 * Holds one value and one timestamp, so it costs the same whether it saw one event or a
13 * thousand. Time is caller-supplied (seconds, any monotonic origin) so the class stays
14 * clock-free and testable; pass the same time source to every call.
15 *
16 * A half-life of 0 or less never decays, which is how a score latches.
17 */
19{
20public:
21 DecayingScore() = default;
22 explicit DecayingScore(double halfLifeSec) : _halfLifeSec(halfLifeSec) {}
23
24 /** Takes effect from the next @ref Value; weight already accrued is not re-aged. */
25 void SetHalfLife(double halfLifeSec) { _halfLifeSec = halfLifeSec; }
26 double HalfLife() const { return _halfLifeSec; }
27
28 /** Ages the score to @p now, adds @p weight, and returns the result. */
29 double Add(double now, double weight = 1.0)
30 {
31 _value = Value(now) + weight;
32 _stamp = now;
33 return _value;
34 }
35
36 /** The score at @p now, leaving the stored value and stamp alone. */
37 double Value(double now) const
38 {
39 const double elapsed = now - _stamp;
40 // A clock that went backwards - map restart, skew - reads as no time passed, never as gain.
41 if (_halfLifeSec <= 0.0 || elapsed <= 0.0)
42 {
43 return _value;
44 }
45 return _value * std::exp2(-elapsed / _halfLifeSec);
46 }
47
48 void Clear()
49 {
50 _value = 0.0;
51 _stamp = 0.0;
52 }
53
54private:
55 double _value = 0.0;
56 double _stamp = 0.0;
57 double _halfLifeSec = 0.0;
58};
59
60} // namespace VoltMod
A score that loses half its weight every half-life - the building block for evidence that should fade...
void SetHalfLife(double halfLifeSec)
double Add(double now, double weight=1.0)
double Value(double now) const
DecayingScore(double halfLifeSec)
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56