-
Notifications
You must be signed in to change notification settings - Fork 220
/
Copy patheffectmanager.cpp
404 lines (316 loc) · 12.9 KB
/
effectmanager.cpp
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//+--------------------------------------------------------------------------
//
// File: effectmanager.cpp
//
// NightDriverStrip - (c) 2018 Plummer's Software LLC. All Rights Reserved.
//
// This file is part of the NightDriver software project.
//
// NightDriver is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// NightDriver is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Nightdriver. It is normally found in copying.txt
// If not, see <https://www.gnu.org/licenses/>.
//
// Description:
//
// Various functions related to EffectManager and its initialization
//
// History: Sep-26-2023 Rbergen Extracted from effects.cpp
//---------------------------------------------------------------------------
#include <FS.h>
#include <SPIFFS.h>
#include "globals.h"
#include "systemcontainer.h"
#include "effects/strip/misceffects.h"
// Variables we need further down
extern DRAM_ATTR std::unique_ptr<EffectFactories> g_ptrEffectFactories;
extern std::map<int, JSONEffectFactory> g_JsonStarryNightEffectFactories;
DRAM_ATTR size_t g_EffectsManagerJSONBufferSize = 0;
static DRAM_ATTR size_t l_EffectsManagerJSONWriterIndex = SIZE_MAX;
static DRAM_ATTR size_t l_CurrentEffectWriterIndex = SIZE_MAX;
//
// EffectManager initialization functions
//
#if USE_HUB75
void InitSplashEffectManager()
{
debugW("InitSplashEffectManager");
g_ptrSystem->SetupEffectManager(make_shared_psram<SplashLogoEffect>(), g_ptrSystem->Devices());
}
#endif
// Declare these here just so InitEffectsManager can refer to them. They're defined elsewhere or further down.
void LoadEffectFactories();
std::optional<JsonObjectConst> LoadEffectsJSONFile(std::unique_ptr<AllocatedJsonDocument>& pJsonDoc);
void WriteCurrentEffectIndexFile();
// InitEffectsManager
//
// Initializes the effect manager. Reboots on failure, since it's not optional
void InitEffectsManager()
{
debugW("InitEffectsManager...");
LoadEffectFactories();
l_EffectsManagerJSONWriterIndex = g_ptrSystem->JSONWriter().RegisterWriter([]()
{
if (!SaveToJSONFile(EFFECTS_CONFIG_FILE, g_EffectsManagerJSONBufferSize, g_ptrSystem->EffectManager()) && EFFECT_PERSISTENCE_CRITICAL)
throw std::runtime_error("Effects serialization failed");
});
l_CurrentEffectWriterIndex = g_ptrSystem->JSONWriter().RegisterWriter(WriteCurrentEffectIndexFile);
std::unique_ptr<AllocatedJsonDocument> pJsonDoc;
auto jsonObject = LoadEffectsJSONFile(pJsonDoc);
if (jsonObject)
{
debugI("Creating EffectManager from JSON config");
if (g_ptrSystem->HasEffectManager())
g_ptrSystem->EffectManager().DeserializeFromJSON(jsonObject.value());
else
g_ptrSystem->SetupEffectManager(jsonObject.value(), g_ptrSystem->Devices());
pJsonDoc->clear();
}
else
{
debugI("Creating EffectManager using default effects");
if (g_ptrSystem->HasEffectManager())
g_ptrSystem->EffectManager().LoadDefaultEffects();
else
g_ptrSystem->SetupEffectManager(g_ptrSystem->Devices());
}
if (false == g_ptrSystem->EffectManager().Init())
throw std::runtime_error("Could not initialize effect manager");
// We won't need the default factories anymore, so swipe them from memory
g_ptrEffectFactories->ClearDefaultFactories();
}
//
// EffectManager member function definitions
//
void EffectManager::SaveCurrentEffectIndex()
{
if (g_ptrSystem->DeviceConfig().RememberCurrentEffect())
// Default value for writer index is max value for size_t, so nothing will happen if writer has not yet been registered
g_ptrSystem->JSONWriter().FlagWriter(l_CurrentEffectWriterIndex);
}
bool EffectManager::ReadCurrentEffectIndex(size_t& index)
{
File file = SPIFFS.open(CURRENT_EFFECT_CONFIG_FILE);
bool readIndex = false;
if (file)
{
if (file.size() > 0)
{
debugI("Attempting to read file %s", CURRENT_EFFECT_CONFIG_FILE);
auto valueString = file.readString();
if (!valueString.isEmpty())
{
index = strtoul(valueString.c_str(), nullptr, 10);
readIndex = true;
}
}
file.close();
}
return readIndex;
}
void EffectManager::LoadJSONAndMissingEffects(const JsonArrayConst& effectsArray)
{
std::set<int> loadedEffectNumbers;
// Create effects from JSON objects, using the respective factories in g_EffectFactories
auto& jsonFactories = g_ptrEffectFactories->GetJSONFactories();
for (auto effectObject : effectsArray)
{
int effectNumber = effectObject[PTY_EFFECTNR];
auto factoryEntry = jsonFactories.find(effectNumber);
if (factoryEntry == jsonFactories.end())
continue;
auto pEffect = factoryEntry->second(effectObject);
if (pEffect)
{
if (effectObject[PTY_COREEFFECT].as<int>())
pEffect->MarkAsCoreEffect();
_vEffects.push_back(pEffect);
loadedEffectNumbers.insert(effectNumber);
}
}
// Now add missing effects from the default factory list
auto &defaultFactories = g_ptrEffectFactories->GetDefaultFactories();
// We iterate manually, so we can use where we are as the starting point for a later inner loop
for (auto iter = defaultFactories.begin(); iter != defaultFactories.end(); iter++)
{
int effectNumber = iter->EffectNumber();
// If we've already loaded this effect (number) from JSON, we can move on to check the next one
if (loadedEffectNumbers.count(effectNumber))
continue;
// We found an effect (number) in the default list that we have not yet loaded from JSON.
// So, we go through the rest of the default factory list to create and add to our effects
// list all instances of this effect.
std::for_each(iter, defaultFactories.end(), [&](const EffectFactories::NumberedFactory& numberedFactory)
{
if (numberedFactory.EffectNumber() == effectNumber)
ProduceAndLoadDefaultEffect(numberedFactory);
}
);
// Register that we added this effect number, so we don't add the respective effects more than once
loadedEffectNumbers.insert(effectNumber);
}
}
std::shared_ptr<LEDStripEffect> EffectManager::CopyEffect(size_t index)
{
if (index >= _vEffects.size())
{
debugW("Invalid index for CopyEffect");
return nullptr;
}
static size_t jsonBufferSize = JSON_BUFFER_BASE_SIZE;
auto& sourceEffect = _vEffects[index];
auto jsonEffectFactories = g_ptrEffectFactories->GetJSONFactories();
auto factoryEntry = jsonEffectFactories.find(sourceEffect->EffectNumber());
if (factoryEntry == jsonEffectFactories.end())
return nullptr;
std::unique_ptr<AllocatedJsonDocument> ptrJsonDoc = nullptr;
assert(SerializeWithBufferSize(ptrJsonDoc, jsonBufferSize,
[&sourceEffect](JsonObject &jsonObject) { return sourceEffect->SerializeToJSON(jsonObject); }));
auto copiedEffect = factoryEntry->second(ptrJsonDoc->as<JsonObjectConst>());
ptrJsonDoc->clear();
if (!copiedEffect)
return nullptr;
copiedEffect->SetEnabled(false);
return copiedEffect;
}
//
// Helper functions related to JSON persistence
//
void SaveEffectManagerConfig()
{
debugV("Saving effect manager config...");
// Default value for writer index is max value for size_t, so nothing will happen if writer has not yet been registered
g_ptrSystem->JSONWriter().FlagWriter(l_EffectsManagerJSONWriterIndex);
}
void RemoveEffectManagerConfig()
{
RemoveJSONFile(EFFECTS_CONFIG_FILE);
// We take the liberty of also removing the file with the current effect config index
SPIFFS.remove(CURRENT_EFFECT_CONFIG_FILE);
}
void WriteCurrentEffectIndexFile()
{
SPIFFS.remove(CURRENT_EFFECT_CONFIG_FILE);
File file = SPIFFS.open(CURRENT_EFFECT_CONFIG_FILE, FILE_WRITE);
if (!file)
{
debugE("Unable to open file %s for writing!", CURRENT_EFFECT_CONFIG_FILE);
return;
}
auto bytesWritten = file.print(g_ptrSystem->EffectManager().GetCurrentEffectIndex());
debugI("Number of bytes written to file %s: %zu", CURRENT_EFFECT_CONFIG_FILE, bytesWritten);
file.flush();
file.close();
if (bytesWritten == 0)
{
debugE("Unable to write to file %s!", CURRENT_EFFECT_CONFIG_FILE);
SPIFFS.remove(CURRENT_EFFECT_CONFIG_FILE);
}
}
// Helper function to create a StarryNightEffect from JSON.
// It picks the actual effect factory from g_JsonStarryNightEffectFactories based on the star type number in the JSON blob.
std::shared_ptr<LEDStripEffect> CreateStarryNightEffectFromJSON(const JsonObjectConst& jsonObject)
{
auto entry = g_JsonStarryNightEffectFactories.find(jsonObject[PTY_STARTYPENR]);
return entry != g_JsonStarryNightEffectFactories.end()
? entry->second(jsonObject)
: nullptr;
}
//
// Other helper functions
//
#if ENABLE_AUDIO
#include "effects/matrix/spectrumeffects.h"
// GetSpectrumAnalyzer
//
// A little factory that makes colored spectrum analyzers
std::shared_ptr<LEDStripEffect> GetSpectrumAnalyzer(CRGB color)
{
CHSV hueColor = rgb2hsv_approximate(color);
CRGB color2 = CRGB(CHSV(hueColor.hue + 64, 255, 255));
auto object = make_shared_psram<SpectrumAnalyzerEffect>("Spectrum Clr", 24, CRGBPalette16(color, color2), true);
if (object->Init(g_ptrSystem->Devices()))
return object;
throw std::runtime_error("Could not initialize new spectrum analyzer, one color version!");
}
#endif
#include "effects/strip/fireeffect.h"
bool EffectManager::Init()
{
for (const auto & _vEffect : _vEffects)
{
debugV("About to init effect %s", _vEffect->FriendlyName().c_str());
if (false == _vEffect->Init(_gfx))
{
debugW("Could not initialize effect: %s\n", _vEffect->FriendlyName().c_str());
return false;
}
debugV("Loaded Effect: %s", _vEffect->FriendlyName().c_str());
}
debugV("First Effect: %s", GetCurrentEffectName().c_str());
if (g_ptrSystem->DeviceConfig().ApplyGlobalColors())
ApplyGlobalPaletteColors();
return true;
}
bool EffectManager::ShowVU(bool bShow)
{
auto& deviceConfig = g_ptrSystem->DeviceConfig();
bool bResult = deviceConfig.ShowVUMeter();
debugI("Setting ShowVU to %d\n", bShow);
deviceConfig.SetShowVUMeter(bShow);
// Erase any exising pixels since effects don't all clear each frame
if (!bShow)
_gfx[0]->setPixelsF(0, MATRIX_WIDTH, CRGB::Black);
return bResult;
}
bool EffectManager::IsVUVisible() const
{
return g_ptrSystem->DeviceConfig().ShowVUMeter() && GetCurrentEffect().CanDisplayVUMeter();
}
void EffectManager::ClearRemoteColor(bool retainRemoteEffect)
{
if (!retainRemoteEffect)
_tempEffect = nullptr;
#if (USE_HUB75)
g()->PausePalette(false);
#endif
g_ptrSystem->DeviceConfig().ClearApplyGlobalColors();
}
void EffectManager::ApplyGlobalColor(CRGB color) const
{
debugI("Setting Global Color: %08X\n", (uint32_t) color);
auto& deviceConfig = g_ptrSystem->DeviceConfig();
deviceConfig.SetColorSettings(color, deviceConfig.GlobalColor());
ApplyGlobalPaletteColors();
}
void EffectManager::ApplyGlobalPaletteColors() const
{
#if (USE_HUB75)
auto pMatrix = g();
auto& deviceConfig = g_ptrSystem->DeviceConfig();
auto& globalColor = deviceConfig.GlobalColor();
auto& secondColor = deviceConfig.SecondColor();
// If the two colors are the same, we just shift the palette by 64 degrees to create a palette
// based from where those colors sit on the spectrum
if (secondColor == globalColor)
{
CHSV hsv = rgb2hsv_approximate(globalColor);
pMatrix->setPalette(CRGBPalette16(globalColor, CRGB(CHSV(hsv.hue + 64, 255, 255))));
}
else
{
// But if we have two different colors, we create a palette spread between them
pMatrix->setPalette(CRGBPalette16(secondColor, globalColor));
}
pMatrix->PausePalette(true);
#endif
}