vkmEngine 1.0.15
A C++ game engine · vkmengine.com
Loading...
Searching...
No Matches
curve.h
1#pragma once
2
3#include <algorithm>
4#include <vector>
5
6#include <glm/glm.hpp>
7
8#include "core/reflect.h"
9#include "core/math/random.h"
10
11namespace Vkm::Engine::Math {
12
16struct FloatRange {
17 float min = 0.0f;
18 float max = 0.0f;
19
26 float draw(Rng& rng) const { return min == max ? min : rng.nextFloat(min, max); }
27};
28
44template <typename Key, typename Value, typename Read>
45Value sampleKeys(const std::vector<Key>& keys, float t, const Value& none, Read&& value) {
46 const Key* below = nullptr;
47 const Key* above = nullptr;
48 for (const Key& key : keys) {
49 if (key.time <= t && (!below || key.time >= below->time)) below = &key;
50 if (key.time >= t && (!above || key.time < above->time)) above = &key;
51 }
52 if (!below && !above) return none;
53 if (!below) return value(*above);
54 if (!above || above->time <= below->time) return value(*below);
55 return glm::mix(value(*below), value(*above), (t - below->time) / (above->time - below->time));
56}
57
61struct CurveKey {
62 float time = 0.0f;
63 float value = 1.0f;
64};
65
72struct Curve {
73 std::vector<CurveKey> keys;
74
81 float at(float t) const {
82 return sampleKeys(keys, t, 1.0f, [](const CurveKey& key) { return key.value; });
83 }
84};
85
90 float time = 0.0f;
91 glm::vec4 color{1.0f};
92};
93
100struct Gradient {
101 std::vector<GradientKey> keys;
102
109 glm::vec4 at(float t) const {
110 return sampleKeys(keys, t, glm::vec4(1.0f), [](const GradientKey& key) { return key.color; });
111 }
112};
113
114} // namespace Vkm::Engine::Math
115
116VKM_REFLECT_BEGIN(::Vkm::Engine::Math::FloatRange)
117 VKM_F(min)
118 VKM_F(max)
119VKM_REFLECT_END()
120
121VKM_REFLECT_BEGIN(::Vkm::Engine::Math::CurveKey)
122 VKM_F(time)
123 VKM_F(value)
124VKM_REFLECT_END()
125
126VKM_REFLECT_BEGIN(::Vkm::Engine::Math::Curve)
127 VKM_F(keys)
128VKM_REFLECT_END()
129
130VKM_REFLECT_BEGIN(::Vkm::Engine::Math::GradientKey)
131 VKM_F(time)
132 VKM_F(color)
133VKM_REFLECT_END()
134
135VKM_REFLECT_BEGIN(::Vkm::Engine::Math::Gradient)
136 VKM_F(keys)
137VKM_REFLECT_END()
PCG32 pseudo-random generator (O'Neill, 2014).
Definition random.h:12
One key of a Curve: its value at a time between 0 and 1.
Definition curve.h:61
A value over a span from 0 to 1 - a particle's life, say - straight between its keys.
Definition curve.h:72
float at(float t) const
The value at t.
Definition curve.h:81
A value drawn once, uniformly between min and max; equal ends are a constant.
Definition curve.h:16
float draw(Rng &rng) const
One draw from the range.
Definition curve.h:26
One key of a Gradient: its colour at a time between 0 and 1.
Definition curve.h:89
A colour over a span from 0 to 1, straight between its keys in linear RGBA.
Definition curve.h:100
glm::vec4 at(float t) const
The colour at t.
Definition curve.h:109