-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy patheffectsmanager.h
More file actions
366 lines (297 loc) · 10.8 KB
/
effectsmanager.h
File metadata and controls
366 lines (297 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#pragma once
using namespace std;
using namespace chrono;
#include "effects/colorwaveeffect.h"
#include "effects/fireworkseffect.h"
#include "effects/misceffects.h"
#include "effects/paletteeffect.h"
#include "effects/starfield.h"
#include "effects/videoeffect.h"
#include "effects/bouncingballeffect.h"
// EffectsManager
//
// Manages a collection of ILEDEffect objects. The EffectsManager is responsible for
// starting and stopping the effects, and for switching between them. The EffectsManager
// can also be used to clear all effects.
#include "interfaces.h"
#include <vector>
#include <mutex>
class EffectsManager : public IEffectsManager
{
uint16_t _fps;
int _currentEffectIndex; // Index of the current effect
atomic<bool> _running;
bool _wantsToRun;
mutable mutex _effectsMutex; // Add mutex as member
vector<shared_ptr<ILEDEffect>> _effects;
thread _workerThread;
public:
EffectsManager(uint16_t fps) : _fps(fps), _currentEffectIndex(-1), _wantsToRun(true), _running(false) // No effect selected initially
{
}
~EffectsManager()
{
Stop(); // Ensure the worker thread is stopped when the manager is destroyed
}
void SetFPS(uint16_t fps) override
{
_fps = fps;
}
uint16_t GetFPS() const override
{
return _fps;
}
size_t GetCurrentEffect() const override
{
return _currentEffectIndex;
}
size_t EffectCount() const override
{
return _effects.size();
}
vector<shared_ptr<ILEDEffect>> Effects() const override
{
lock_guard lock(_effectsMutex);
return _effects;
}
// Add an effect to the manager
void AddEffect(shared_ptr<ILEDEffect> effect) override
{
lock_guard lock(_effectsMutex);
if (!effect)
throw invalid_argument("Cannot add a null effect.");
_effects.push_back(effect);
// Automatically set the first effect as current if none is selected
if (_currentEffectIndex == -1)
_currentEffectIndex = 0;
}
// Remove an effect from the manager
void RemoveEffect(shared_ptr<ILEDEffect> &effect) override
{
lock_guard lock(_effectsMutex);
if (!effect)
throw invalid_argument("Cannot remove a null effect.");
auto it = remove(_effects.begin(), _effects.end(), effect);
if (it != _effects.end())
{
auto index = distance(_effects.begin(), it);
_effects.erase(it);
// Adjust the current effect index
if (index <= _currentEffectIndex)
_currentEffectIndex = (_currentEffectIndex > 0) ? _currentEffectIndex - 1 : -1;
// If no effects remain, reset the current index
if (_effects.empty())
_currentEffectIndex = -1;
}
}
// Start the current effect
void StartCurrentEffect(ICanvas &canvas) override
{
if (_running && IsEffectSelected())
_effects[_currentEffectIndex]->Start(canvas);
}
void SetCurrentEffect(size_t index, ICanvas &canvas) override
{
if (index >= _effects.size())
throw out_of_range("Effect index out of range.");
_currentEffectIndex = index;
StartCurrentEffect(canvas);
}
// Update the current effect and render it to the canvas
void UpdateCurrentEffect(ICanvas &canvas, milliseconds millisDelta) override
{
if (_running && IsEffectSelected())
_effects[_currentEffectIndex]->Update(canvas, millisDelta);
}
// Switch to the next effect
void NextEffect() override
{
if (!_effects.empty())
_currentEffectIndex = (_currentEffectIndex + 1) % _effects.size();
}
// Switch to the previous effect
void PreviousEffect() override
{
if (!_effects.empty())
_currentEffectIndex = (_currentEffectIndex == 0) ? _effects.size() - 1 : _currentEffectIndex - 1;
}
// Get the name of the current effect
string CurrentEffectName() const override
{
if (IsEffectSelected())
return _effects[_currentEffectIndex]->Name();
return "No Effect Selected";
}
// Clear all effects
void ClearEffects() override
{
lock_guard lock(_effectsMutex);
_effects.clear();
_currentEffectIndex = -1;
}
bool WantsToRun() const override
{
return _wantsToRun;
}
void WantToRun(bool wantsToRun) override
{
_wantsToRun = wantsToRun;
}
bool IsRunning() const override
{
return _running;
}
// Start the worker thread to update effects
void Start(ICanvas &canvas) override
{
logger->debug("Starting effects manager with {} effects at {} FPS", _effects.size(), _fps);
if (_running.exchange(true))
return; // Already running
_workerThread = thread([this, &canvas]()
{
auto frameDuration = 1000ms / _fps; // Target duration per frame
auto nextFrameTime = steady_clock::now();
constexpr auto bUseCompression = true;
// Starting the canvas should start the effect at least one time, as many effects
// have one-time setup in their Start() method
StartCurrentEffect(canvas);
while (_running)
{
{
lock_guard lock(_effectsMutex);
// Update the effects and enqueue frames
UpdateCurrentEffect(canvas, frameDuration);
for (const auto &feature : canvas.Features())
{
auto frame = feature->GetDataFrame();
if (bUseCompression)
{
auto compressedFrame = feature->Socket()->CompressFrame(frame);
feature->Socket()->EnqueueFrame(std::move(compressedFrame));
}
else
{
feature->Socket()->EnqueueFrame(std::move(frame));
}
}
}
// We wait here while periodically checking _running
auto now = steady_clock::now();
while (now < nextFrameTime && _running) {
this_thread::sleep_for(min(steady_clock::duration(10ms), nextFrameTime - now));
now = steady_clock::now(); // Update 'now' to avoid an infinite loop
}
// Set the next frame target
nextFrameTime += frameDuration;
} });
}
// Stop the worker thread
void Stop() override
{
logger->debug("Stopping effects manager");
if (!_running.exchange(false))
return; // Not running
if (_workerThread.joinable())
_workerThread.join();
}
void SetEffects(vector<shared_ptr<ILEDEffect>> effects) override
{
lock_guard lock(_effectsMutex);
_effects = std::move(effects);
}
void SetCurrentEffectIndex(int index) override
{
_currentEffectIndex = index;
}
private:
bool IsEffectSelected() const
{
return _currentEffectIndex >= 0 && _currentEffectIndex < static_cast<int>(_effects.size());
}
};
// Define type aliases for effect (de)serialization functions for legibility reasons
using EffectSerializer = function<void(nlohmann::json &, const ILEDEffect &)>;
using EffectDeserializer = function<shared_ptr<ILEDEffect>(const nlohmann::json &)>;
// Factory function to create a pair of effect (de)serialization functions for a given type
template <typename T>
pair<string, pair<EffectSerializer, EffectDeserializer>> jsonPair()
{
EffectSerializer serializer = [](nlohmann::json &j, const ILEDEffect &effect)
{
to_json(j, dynamic_cast<const T &>(effect));
};
EffectDeserializer deserializer = [](const nlohmann::json &j)
{
return j.get<shared_ptr<T>>();
};
return make_pair(typeid(T).name(), make_pair(serializer, deserializer));
}
// Map with effect (de)serialization functions
static const map<string, pair<EffectSerializer, EffectDeserializer>> to_from_json_map =
{
jsonPair<BouncingBallEffect>(),
jsonPair<ColorWaveEffect>(),
jsonPair<FireworksEffect>(),
jsonPair<SolidColorFill>(),
jsonPair<PaletteEffect>(),
jsonPair<StarfieldEffect>(),
jsonPair<MP4PlaybackEffect>()
};
// Dynamically serialize an effect to JSON based on its actual type
inline void to_json(nlohmann::json &j, const ILEDEffect &effect)
{
string type = typeid(effect).name();
auto it = to_from_json_map.find(type);
if (it == to_from_json_map.end())
{
logger->error("Unknown effect type for serialization: {}", type);
throw runtime_error("Unknown effect type for serialization: " + type);
}
it->second.first(j, effect);
j["type"] = type;
// Serialize schedule if we have one
if (effect.GetSchedule())
j["schedule"] = *effect.GetSchedule();
}
// Dynamically deserialize an effect from JSON based on its indicated type
// and return it on the unique pointer out reference
// ILEDEffect <-- JSON
inline void from_json(const nlohmann::json &j, shared_ptr<ILEDEffect> & effect)
{
auto it = to_from_json_map.find(j["type"]);
if (it == to_from_json_map.end())
{
logger->error("Unknown effect type for deserialization: {}, replacing with magenta fill", j["type"].get<string>());
effect = make_shared<SolidColorFill>("Unknown Effect Type", CRGB::Magenta);
return;
}
effect = it->second.second(j);
// Deserialize schedule if present
if (j.contains("schedule")) {
auto schedule = j["schedule"].get<shared_ptr<ISchedule>>();
effect->SetSchedule(schedule);
}
}
// IEffectsManager <-- JSON
inline void to_json(nlohmann::json &j, const IEffectsManager &manager)
{
j =
{
{"fps", manager.GetFPS()},
{"currentEffectIndex", manager.GetCurrentEffect()},
{"running", manager.IsRunning()}
};
for (const auto &effect : manager.Effects())
j["effects"].push_back(*effect);
};
// IEffectManager --> JSON
inline void from_json(const nlohmann::json &j, IEffectsManager &manager)
{
manager.SetFPS(j.at("fps").get<uint16_t>());
manager.SetEffects(j.at("effects").get<vector<shared_ptr<ILEDEffect>>>());
manager.SetCurrentEffectIndex(j.at("currentEffectIndex").get<int>());
// We deserialize the running state to a running *preference*. Directly starting the manager after
// deserialization could create problems, and without having the canvas we can't start it anyway.
if (j.contains("running"))
manager.WantToRun(j.at("running").get<bool>());
}