GCC Code Coverage Report


Directory: ./
File: overlays/wled/FX_fcn.cpp
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 477 947 50.4%
Functions: 36 70 51.4%
Branches: 387 1156 33.5%

Line Branch Exec Source
1 /*
2 WS2812FX_fcn.cpp contains all utility functions
3 Harm Aldick - 2016
4 www.aldick.org
5
6 Copyright (c) 2016 Harm Aldick
7 Licensed under the EUPL v. 1.2 or later
8 Adapted from code originally licensed under the MIT license
9
10 Modified heavily for WLED
11 */
12 #include "wled.h"
13 #include "FX.h"
14 #include "FXparticleSystem.h" // TODO: better define the required function (mem service) in FX.h?
15 #include "palettes.h"
16
17 #include <climits>
18
19 /*
20 Custom per-LED mapping has moved!
21
22 Create a file "ledmap.json" using the edit page.
23
24 this is just an example (30 LEDs). It will first set all even, then all uneven LEDs.
25 {"map":[
26 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28,
27 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]}
28
29 another example. Switches direction every 5 LEDs.
30 {"map":[
31 0, 1, 2, 3, 4, 9, 8, 7, 6, 5, 10, 11, 12, 13, 14,
32 19, 18, 17, 16, 15, 20, 21, 22, 23, 24, 29, 28, 27, 26, 25]}
33 */
34
35 #ifndef PIXEL_COUNTS
36 #define PIXEL_COUNTS DEFAULT_LED_COUNT
37 #endif
38
39 #ifndef DATA_PINS
40 #define DATA_PINS DEFAULT_LED_PIN
41 #endif
42
43 #ifndef LED_TYPES
44 #define LED_TYPES DEFAULT_LED_TYPE
45 #endif
46
47 #ifndef DEFAULT_LED_COLOR_ORDER
48 #define DEFAULT_LED_COLOR_ORDER COL_ORDER_GRB //default to GRB
49 #endif
50
51
52 #if MAX_NUM_SEGMENTS < WLED_MAX_BUSSES
53 #error "Max segments must be at least max number of busses!"
54 #endif
55
56 static constexpr unsigned sumPinsRequired(const unsigned* current, size_t count) {
57 return (count > 0) ? (Bus::getNumberOfPins(*current) + sumPinsRequired(current+1,count-1)) : 0;
58 }
59
60 #ifndef WLED_DISABLE_FPP
61 static constexpr bool validatePinsAndTypes(const unsigned* types, unsigned numTypes, unsigned numPins ) {
62 // Pins provided < pins required -> always invalid
63 // Pins provided = pins required -> always valid
64 // Pins provided > pins required -> valid if excess pins are a product of last type pins since it will be repeated
65 return (sumPinsRequired(types, numTypes) > numPins) ? false :
66 (numPins - sumPinsRequired(types, numTypes)) % Bus::getNumberOfPins(types[numTypes-1]) == 0;
67 }
68 #else
69 static constexpr bool validatePinsAndTypes(const unsigned* types, unsigned numTypes, unsigned numPins ) {
70 return true;
71 }
72 #endif
73
74 ///////////////////////////////////////////////////////////////////////////////
75 // Segment class implementation
76 ///////////////////////////////////////////////////////////////////////////////
77 unsigned Segment::_usedSegmentData = 0U; // amount of RAM all segments use for their data[]
78 uint16_t Segment::maxWidth = DEFAULT_LED_COUNT;
79 uint16_t Segment::maxHeight = 1;
80 unsigned Segment::_vLength = 0;
81 unsigned Segment::_vWidth = 0;
82 unsigned Segment::_vHeight = 0;
83 uint8_t Segment::_segBri = 0;
84 uint32_t Segment::_currentColors[NUM_COLORS] = {0,0,0};
85 bool Segment::_colorScaled = false;
86 CRGBPalette16 Segment::_currentPalette = CRGBPalette16(CRGB::Black);
87 CRGBPalette16 Segment::_randomPalette = generateRandomPalette(); // was CRGBPalette16(DEFAULT_COLOR);
88 CRGBPalette16 Segment::_newRandomPalette = generateRandomPalette(); // was CRGBPalette16(DEFAULT_COLOR);
89 uint16_t Segment::_lastPaletteChange = 0; // perhaps it should be per segment
90 uint16_t Segment::_lastPaletteBlend = 0; //in millis (lowest 16 bits only)
91 uint16_t Segment::_transitionprogress = 0xFFFF;
92
93 #ifndef WLED_DISABLE_MODE_BLEND
94 bool Segment::_modeBlend = false;
95 uint16_t Segment::_clipStart = 0;
96 uint16_t Segment::_clipStop = 0;
97 uint8_t Segment::_clipStartY = 0;
98 uint8_t Segment::_clipStopY = 1;
99 #endif
100
101 // copy constructor
102 ✗ Segment::Segment(const Segment &orig) {
103 //DEBUG_PRINTF_P(PSTR("-- Copy segment constructor: %p -> %p\n"), &orig, this);
104 ✗ memcpy((void*)this, (void*)&orig, sizeof(Segment));
105 ✗ _t = nullptr; // copied segment cannot be in transition
106 ✗ name = nullptr;
107 ✗ data = nullptr;
108 ✗ _dataLen = 0;
109 ✗ if (orig.name) { name = static_cast<char*>(malloc(strlen(orig.name)+1)); if (name) strcpy(name, orig.name); }
110 ✗ if (orig.data) { if (allocateData(orig._dataLen)) memcpy(data, orig.data, orig._dataLen); }
111 ✗ }
112
113 // move constructor
114 1203 Segment::Segment(Segment &&orig) noexcept {
115 //DEBUG_PRINTF_P(PSTR("-- Move segment constructor: %p -> %p\n"), &orig, this);
116 1203 memcpy((void*)this, (void*)&orig, sizeof(Segment));
117 1203 orig._t = nullptr; // old segment cannot be in transition any more
118 1203 orig.name = nullptr;
119 1203 orig.data = nullptr;
120 1203 orig._dataLen = 0;
121 1203 }
122
123 // copy assignment
124 ✗ Segment& Segment::operator= (const Segment &orig) {
125 //DEBUG_PRINTF_P(PSTR("-- Copying segment: %p -> %p\n"), &orig, this);
126 ✗ if (this != &orig) {
127 // clean destination
128 ✗ if (name) { free(name); name = nullptr; }
129 ✗ stopTransition();
130 ✗ deallocateData();
131 // copy source
132 ✗ memcpy((void*)this, (void*)&orig, sizeof(Segment));
133 // erase pointers to allocated data
134 ✗ data = nullptr;
135 ✗ _dataLen = 0;
136 // copy source data
137 ✗ if (orig.name) { name = static_cast<char*>(malloc(strlen(orig.name)+1)); if (name) strcpy(name, orig.name); }
138 ✗ if (orig.data) { if (allocateData(orig._dataLen)) memcpy(data, orig.data, orig._dataLen); }
139 }
140 ✗ return *this;
141 }
142
143 // move assignment
144 ✗ Segment& Segment::operator= (Segment &&orig) noexcept {
145 //DEBUG_PRINTF_P(PSTR("-- Moving segment: %p -> %p\n"), &orig, this);
146 ✗ if (this != &orig) {
147 ✗ if (name) { free(name); name = nullptr; } // free old name
148 ✗ stopTransition();
149 ✗ deallocateData(); // free old runtime data
150 ✗ memcpy((void*)this, (void*)&orig, sizeof(Segment));
151 ✗ orig.name = nullptr;
152 ✗ orig.data = nullptr;
153 ✗ orig._dataLen = 0;
154 ✗ orig._t = nullptr; // old segment cannot be in transition
155 }
156 ✗ return *this;
157 }
158
159 // allocates effect data buffer on heap and initialises (erases) it
160 1817 bool IRAM_ATTR_YN Segment::allocateData(size_t len) {
161
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1817 times.
1817 if (len == 0) return false; // nothing to do
162
3/4
✓ Branch 0 taken 1426 times.
✓ Branch 1 taken 391 times.
✓ Branch 2 taken 1426 times.
✗ Branch 3 not taken.
1817 if (data && _dataLen >= len) { // already allocated enough (reduce fragmentation)
163
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1426 times.
1426 if (call == 0) memset(data, 0, len); // erase buffer if called during effect initialisation
164 1426 return true;
165 }
166 //DEBUG_PRINTF_P(PSTR("-- Allocating data (%d): %p\n", len, this);
167 391 deallocateData(); // if the old buffer was smaller release it first
168
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 391 times.
391 if (Segment::getUsedSegmentData() + len > MAX_SEGMENT_DATA) {
169 // not enough memory
170 DEBUG_PRINT(F("!!! Effect RAM depleted: "));
171 DEBUG_PRINTF_P(PSTR("%d/%d !!!\n"), len, Segment::getUsedSegmentData());
172 ✗ errorFlag = ERR_NORAM;
173 ✗ return false;
174 }
175 // do not use SPI RAM on ESP32 since it is slow
176 391 data = (byte*)calloc(len, sizeof(byte));
177
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 391 times.
391 if (!data) { DEBUG_PRINTLN(F("!!! Allocation failed. !!!")); return false; } // allocation failed
178 391 Segment::addUsedSegmentData(len);
179 //DEBUG_PRINTF_P(PSTR("--- Allocated data (%p): %d/%d -> %p\n"), this, len, Segment::getUsedSegmentData(), data);
180 391 _dataLen = len;
181 391 return true;
182 }
183
184 2768 void IRAM_ATTR_YN Segment::deallocateData() {
185
2/2
✓ Branch 0 taken 2380 times.
✓ Branch 1 taken 388 times.
2768 if (!data) { _dataLen = 0; return; }
186 //DEBUG_PRINTF_P(PSTR("--- Released data (%p): %d/%d -> %p\n"), this, _dataLen, Segment::getUsedSegmentData(), data);
187
3/6
✓ Branch 0 taken 388 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 388 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 388 times.
✗ Branch 5 not taken.
388 if ((Segment::getUsedSegmentData() > 0) && (_dataLen > 0)) { // check that we don't have a dangling / inconsistent data pointer
188 388 free(data);
189 } else {
190 DEBUG_PRINTF_P(PSTR("---- Released data (%p): inconsistent UsedSegmentData (%d/%d), cowardly refusing to free nothing.\n"), this, _dataLen, Segment::getUsedSegmentData());
191 }
192 388 data = nullptr;
193
1/2
✓ Branch 0 taken 388 times.
✗ Branch 1 not taken.
388 Segment::addUsedSegmentData(_dataLen <= Segment::getUsedSegmentData() ? -_dataLen : -Segment::getUsedSegmentData());
194 388 _dataLen = 0;
195 }
196
197 /**
198 * If reset of this segment was requested, clears runtime
199 * settings of this segment.
200 * Must not be called while an effect mode function is running
201 * because it could access the data buffer and this method
202 * may free that data buffer.
203 */
204 9926 void Segment::resetIfRequired() {
205
2/2
✓ Branch 0 taken 8723 times.
✓ Branch 1 taken 1203 times.
9926 if (!reset) return;
206 //DEBUG_PRINTF_P(PSTR("-- Segment reset: %p\n"), this);
207
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 1203 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
1203 if (data && _dataLen > 0) memset(data, 0, _dataLen); // prevent heap fragmentation (just erase buffer instead of deallocateData())
208 1203 next_time = 0; step = 0; call = 0; aux0 = 0; aux1 = 0;
209 1203 reset = false;
210 #ifdef WLED_ENABLE_GIF
211 endImagePlayback(this);
212 #endif
213 }
214
215 9926 CRGBPalette16 &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) {
216
2/4
✓ Branch 0 taken 9926 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 9926 times.
9926 if (pal < 245 && pal > GRADIENT_PALETTE_COUNT+13) pal = 0;
217
2/8
✗ Branch 0 not taken.
✓ Branch 1 taken 9926 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✓ Branch 7 taken 9926 times.
9926 if (pal > 245 && (strip().customPalettes.size() == 0 || 255U-pal > strip().customPalettes.size()-1)) pal = 0; // TODO remove strip dependency by moving customPalettes out of strip
218 //default palette. Differs depending on effect
219
2/2
✓ Branch 0 taken 7112 times.
✓ Branch 1 taken 2814 times.
9926 if (pal == 0) pal = _default_palette; //load default palette set in FX _data, party colors as default
220
7/7
✓ Branch 0 taken 227 times.
✓ Branch 1 taken 26 times.
✓ Branch 2 taken 1528 times.
✓ Branch 3 taken 26 times.
✓ Branch 4 taken 3 times.
✓ Branch 5 taken 3 times.
✓ Branch 6 taken 8113 times.
9926 switch (pal) {
221 227 case 0: //default palette. Exceptions for specific effects above
222 227 targetPalette = PartyColors_p; break;
223 26 case 1: //randomly generated palette
224 26 targetPalette = _randomPalette; //random palette is generated at intervals in handleRandomPalette()
225 26 break;
226 1528 case 2: {//primary color only
227
1/2
✓ Branch 0 taken 1528 times.
✗ Branch 1 not taken.
1528 CRGB prim = gamma32(colors[0]);
228
1/2
✓ Branch 0 taken 1528 times.
✗ Branch 1 not taken.
1528 targetPalette = CRGBPalette16(prim); break;}
229 26 case 3: {//primary + secondary
230
1/2
✓ Branch 0 taken 26 times.
✗ Branch 1 not taken.
26 CRGB prim = gamma32(colors[0]);
231
1/2
✓ Branch 0 taken 26 times.
✗ Branch 1 not taken.
26 CRGB sec = gamma32(colors[1]);
232
1/2
✓ Branch 0 taken 26 times.
✗ Branch 1 not taken.
26 targetPalette = CRGBPalette16(prim,prim,sec,sec); break;}
233 3 case 4: {//primary + secondary + tertiary
234
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 CRGB prim = gamma32(colors[0]);
235
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 CRGB sec = gamma32(colors[1]);
236
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 CRGB ter = gamma32(colors[2]);
237
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 targetPalette = CRGBPalette16(ter,sec,prim); break;}
238 3 case 5: {//primary + secondary (+tertiary if not off), more distinct
239
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 CRGB prim = gamma32(colors[0]);
240
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 CRGB sec = gamma32(colors[1]);
241
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 3 times.
3 if (colors[2]) {
242 ✗ CRGB ter = gamma32(colors[2]);
243 ✗ targetPalette = CRGBPalette16(prim,prim,prim,prim,prim,sec,sec,sec,sec,sec,ter,ter,ter,ter,ter,prim);
244 } else {
245 3 targetPalette = CRGBPalette16(prim,prim,prim,prim,prim,prim,prim,prim,sec,sec,sec,sec,sec,sec,sec,sec);
246 }
247 3 break;}
248 8113 default: //progmem palettes
249
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 8113 times.
8113 if (pal>245) {
250 ✗ targetPalette = strip().customPalettes[255-pal]; // we checked bounds above
251
2/2
✓ Branch 0 taken 7290 times.
✓ Branch 1 taken 823 times.
8113 } else if (pal < 13) { // palette 6 - 12, fastled palettes
252 7290 targetPalette = *fastledPalettes[pal-6];
253 } else {
254 // Straight from the table: the gradients are ordinary memory here, and
255 // loadDynamicGradientPalette() stops at the entry indexed 255 that ends
256 // each one. WLED copied a fixed 72 bytes out of flash first, which on
257 // an ESP reads harmlessly past a short gradient; here it read past the
258 // end of the array (Fire, Fire 2012's default, among others).
259 823 targetPalette.loadDynamicGradientPalette((const byte*)gGradientPalettes[pal-13]);
260 }
261 8113 break;
262 }
263 9926 return targetPalette;
264 }
265
266 3206 void Segment::startTransition(uint16_t dur) {
267
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 3206 times.
3206 if (dur == 0) {
268 ✗ if (isInTransition()) _t->_dur = dur; // this will stop transition in next handleTransition()
269 ✗ return;
270 }
271
2/2
✓ Branch 0 taken 2003 times.
✓ Branch 1 taken 1203 times.
3206 if (isInTransition()) return; // already in transition no need to store anything
272
273 // starting a transition has to occur before change so we get current values 1st
274
4/12
✓ Branch 0 taken 1203 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1203 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1203 times.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✓ Branch 7 taken 1203 times.
✗ Branch 8 not taken.
✗ Branch 9 not taken.
✗ Branch 10 not taken.
✗ Branch 11 not taken.
1203 _t = new(std::nothrow) Transition(dur); // no previous transition running
275
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1203 times.
1203 if (!_t) return; // failed to allocate data
276
277 //DEBUG_PRINTF_P(PSTR("-- Started transition: %p (%p)\n"), this, _t);
278 1203 loadPalette(_t->_palT, palette);
279 1203 _t->_palTid = palette;
280
1/2
✓ Branch 0 taken 1203 times.
✗ Branch 1 not taken.
1203 _t->_briT = on ? opacity : 0;
281 1203 _t->_cctT = cct;
282 #ifndef WLED_DISABLE_MODE_BLEND
283 swapSegenv(_t->_segT); // copy runtime data to temporary
284 _t->_modeT = mode;
285 _t->_segT._dataLenT = 0;
286 _t->_segT._dataT = nullptr;
287 if (_dataLen > 0 && data) {
288 _t->_segT._dataT = (byte *)malloc(_dataLen);
289 if (_t->_segT._dataT) {
290 //DEBUG_PRINTF_P(PSTR("-- Allocated duplicate data (%d) for %p: %p\n"), _dataLen, this, _t->_segT._dataT);
291 memcpy(_t->_segT._dataT, data, _dataLen);
292 _t->_segT._dataLenT = _dataLen;
293 }
294 }
295 DEBUG_PRINTF_P(PSTR("-- pal: %d, bri: %d, C:[%08X,%08X,%08X], m: %d\n"),
296 (int)_t->_palTid,
297 (int)_t->_briT,
298 _t->_segT._colorT[0],
299 _t->_segT._colorT[1],
300 _t->_segT._colorT[2],
301 (int)_t->_modeT);
302 #else
303
2/2
✓ Branch 0 taken 3609 times.
✓ Branch 1 taken 1203 times.
4812 for (size_t i=0; i<NUM_COLORS; i++) _t->_colorT[i] = colors[i];
304 #endif
305 }
306
307 5127 void Segment::stopTransition() {
308
2/2
✓ Branch 0 taken 1193 times.
✓ Branch 1 taken 3934 times.
5127 if (isInTransition()) {
309 //DEBUG_PRINTF_P(PSTR("-- Stopping transition: %p\n"), this);
310 #ifndef WLED_DISABLE_MODE_BLEND
311 if (_t->_segT._dataT && _t->_segT._dataLenT > 0) {
312 //DEBUG_PRINTF_P(PSTR("-- Released duplicate data (%d) for %p: %p\n"), _t->_segT._dataLenT, this, _t->_segT._dataT);
313 free(_t->_segT._dataT);
314 _t->_segT._dataT = nullptr;
315 _t->_segT._dataLenT = 0;
316 }
317 #endif
318
1/2
✓ Branch 0 taken 1193 times.
✗ Branch 1 not taken.
1193 delete _t;
319 1193 _t = nullptr;
320 }
321 5127 _transitionprogress = 0xFFFFU; // stop means stop - transition has ended
322 5127 }
323
324 // transition progression between 0-65535
325 8723 inline void Segment::updateTransitionProgress() {
326 8723 _transitionprogress = 0xFFFFU;
327
2/2
✓ Branch 0 taken 6029 times.
✓ Branch 1 taken 2694 times.
8723 if (isInTransition()) {
328 6029 unsigned diff = millis() - _t->_start;
329
3/4
✓ Branch 0 taken 6029 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 5973 times.
✓ Branch 3 taken 56 times.
6029 if (_t->_dur > 0 && diff < _t->_dur) _transitionprogress = diff * 0xFFFFU / _t->_dur;
330 }
331 8723 }
332
333 #ifndef WLED_DISABLE_MODE_BLEND
334 void Segment::swapSegenv(tmpsegd_t &tmpSeg) {
335 //DEBUG_PRINTF_P(PSTR("-- Saving temp seg: %p->(%p) [%d->%p]\n"), this, &tmpSeg, _dataLen, data);
336 tmpSeg._optionsT = options;
337 for (size_t i=0; i<NUM_COLORS; i++) tmpSeg._colorT[i] = colors[i];
338 tmpSeg._speedT = speed;
339 tmpSeg._intensityT = intensity;
340 tmpSeg._custom1T = custom1;
341 tmpSeg._custom2T = custom2;
342 tmpSeg._custom3T = custom3;
343 tmpSeg._check1T = check1;
344 tmpSeg._check2T = check2;
345 tmpSeg._check3T = check3;
346 tmpSeg._aux0T = aux0;
347 tmpSeg._aux1T = aux1;
348 tmpSeg._stepT = step;
349 tmpSeg._callT = call;
350 tmpSeg._dataT = data;
351 tmpSeg._dataLenT = _dataLen;
352 if (isInTransition() && &tmpSeg != &(_t->_segT)) {
353 // swap SEGENV with transitional data
354 options = _t->_segT._optionsT;
355 for (size_t i=0; i<NUM_COLORS; i++) colors[i] = _t->_segT._colorT[i];
356 speed = _t->_segT._speedT;
357 intensity = _t->_segT._intensityT;
358 custom1 = _t->_segT._custom1T;
359 custom2 = _t->_segT._custom2T;
360 custom3 = _t->_segT._custom3T;
361 check1 = _t->_segT._check1T;
362 check2 = _t->_segT._check2T;
363 check3 = _t->_segT._check3T;
364 aux0 = _t->_segT._aux0T;
365 aux1 = _t->_segT._aux1T;
366 step = _t->_segT._stepT;
367 call = _t->_segT._callT;
368 data = _t->_segT._dataT;
369 _dataLen = _t->_segT._dataLenT;
370 }
371 }
372
373 void Segment::restoreSegenv(const tmpsegd_t &tmpSeg) {
374 //DEBUG_PRINTF_P(PSTR("-- Restoring temp seg: %p->(%p) [%d->%p]\n"), &tmpSeg, this, _dataLen, data);
375 if (isInTransition() && &(_t->_segT) != &tmpSeg) {
376 // update possibly changed variables to keep old effect running correctly
377 _t->_segT._aux0T = aux0;
378 _t->_segT._aux1T = aux1;
379 _t->_segT._stepT = step;
380 _t->_segT._callT = call;
381 //if (_t->_segT._dataT != data) DEBUG_PRINTF_P(PSTR("--- data re-allocated: (%p) %p -> %p\n"), this, _t->_segT._dataT, data);
382 _t->_segT._dataT = data;
383 _t->_segT._dataLenT = _dataLen;
384 }
385 options = tmpSeg._optionsT;
386 for (size_t i=0; i<NUM_COLORS; i++) colors[i] = tmpSeg._colorT[i];
387 speed = tmpSeg._speedT;
388 intensity = tmpSeg._intensityT;
389 custom1 = tmpSeg._custom1T;
390 custom2 = tmpSeg._custom2T;
391 custom3 = tmpSeg._custom3T;
392 check1 = tmpSeg._check1T;
393 check2 = tmpSeg._check2T;
394 check3 = tmpSeg._check3T;
395 aux0 = tmpSeg._aux0T;
396 aux1 = tmpSeg._aux1T;
397 step = tmpSeg._stepT;
398 call = tmpSeg._callT;
399 data = tmpSeg._dataT;
400 _dataLen = tmpSeg._dataLenT;
401 }
402 #endif
403
404 17410 uint8_t Segment::currentBri(bool useCct) const {
405
2/2
✓ Branch 0 taken 11946 times.
✓ Branch 1 taken 5464 times.
17410 unsigned prog = isInTransition() ? progress() : 0xFFFFU;
406
3/4
✓ Branch 0 taken 8705 times.
✓ Branch 1 taken 8705 times.
✓ Branch 2 taken 8705 times.
✗ Branch 3 not taken.
17410 uint32_t curBri = useCct ? cct : (on ? opacity : 0);
407
2/2
✓ Branch 0 taken 11946 times.
✓ Branch 1 taken 5464 times.
17410 if (prog < 0xFFFFU) {
408 #ifndef WLED_DISABLE_MODE_BLEND
409 uint8_t tmpBri = useCct ? _t->_cctT : (_t->_segT._optionsT & 0x0004 ? _t->_briT : 0);
410 // _modeBlend==true -> old effect
411 if (blendingStyle != BLEND_STYLE_FADE) return _modeBlend ? tmpBri : curBri; // not fade/blend transition, each effect uses its brightness
412 #else
413
2/2
✓ Branch 0 taken 5973 times.
✓ Branch 1 taken 5973 times.
11946 uint8_t tmpBri = useCct ? _t->_cctT : _t->_briT;
414 #endif
415 11946 curBri *= prog;
416 11946 curBri += tmpBri * (0xFFFFU - prog);
417 11946 return curBri / 0xFFFFU;
418 }
419 5464 return curBri;
420 }
421
422 ✗ uint8_t Segment::currentMode() const {
423 #ifndef WLED_DISABLE_MODE_BLEND
424 unsigned prog = isInTransition() ? progress() : 0xFFFFU;
425 if (prog == 0xFFFFU) return mode;
426 if (blendingStyle != BLEND_STYLE_FADE) {
427 // workaround for on/off transition to respect blending style
428 uint8_t modeT = (bri != briT) && bri ? FX_MODE_STATIC : _t->_modeT; // On/Off transition active (bri!=briT) and final bri>0 : old mode is STATIC
429 uint8_t modeS = (bri != briT) && !bri ? FX_MODE_STATIC : mode; // On/Off transition active (bri!=briT) and final bri==0 : new mode is STATIC
430 return _modeBlend ? modeT : modeS; // _modeBlend==true -> old effect
431 }
432 return _modeBlend ? _t->_modeT : mode; // _modeBlend==true -> old effect
433 #else
434 ✗ return mode;
435 #endif
436 }
437
438 ✗ uint32_t Segment::currentColor(uint8_t slot) const {
439 ✗ if (slot >= NUM_COLORS) slot = 0;
440 ✗ unsigned prog = progress();
441 ✗ if (prog == 0xFFFFU) return colors[slot];
442 #ifndef WLED_DISABLE_MODE_BLEND
443 if (blendingStyle != BLEND_STYLE_FADE) {
444 // workaround for on/off transition to respect blending style
445 uint32_t colT = (bri != briT) && bri ? BLACK : _t->_segT._colorT[slot]; // On/Off transition active (bri!=briT) and final bri>0 : old color is BLACK
446 uint32_t colS = (bri != briT) && !bri ? BLACK : colors[slot]; // On/Off transition active (bri!=briT) and final bri==0 : new color is BLACK
447 return _modeBlend ? colT : colS; // _modeBlend==true -> old effect
448 }
449 return color_blend16(_t->_segT._colorT[slot], colors[slot], prog);
450 #else
451 ✗ return color_blend16(_t->_colorT[slot], colors[slot], prog);
452 #endif
453 }
454
455 // pre-calculate drawing parameters for faster access (based on the idea from @softhack007 from MM fork)
456 8705 void Segment::beginDraw() {
457 8705 _vWidth = virtualWidth();
458 8705 _vHeight = virtualHeight();
459 8705 _vLength = virtualLength();
460 8705 _segBri = currentBri();
461
2/2
✓ Branch 0 taken 5973 times.
✓ Branch 1 taken 2732 times.
8705 unsigned prog = isInTransition() ? progress() : 0xFFFFU; // transition progress; 0xFFFFU = no transition active
462 // adjust gamma for effects
463
2/2
✓ Branch 0 taken 26115 times.
✓ Branch 1 taken 8705 times.
34820 for (unsigned i = 0; i < NUM_COLORS; i++) {
464 #ifndef WLED_DISABLE_MODE_BLEND
465 uint32_t col = isInTransition() ? color_blend16(_t->_segT._colorT[i], colors[i], prog) : colors[i];
466 #else
467
2/2
✓ Branch 0 taken 17919 times.
✓ Branch 1 taken 8196 times.
26115 uint32_t col = isInTransition() ? color_blend16(_t->_colorT[i], colors[i], prog) : colors[i];
468 #endif
469 26115 _currentColors[i] = gamma32(col);
470 }
471 // load palette into _currentPalette
472 8705 loadPalette(_currentPalette, palette);
473
2/2
✓ Branch 0 taken 5973 times.
✓ Branch 1 taken 2732 times.
8705 if (prog < 0xFFFFU) {
474 #ifndef WLED_DISABLE_MODE_BLEND
475 if (blendingStyle > BLEND_STYLE_FADE) {
476 //if (_modeBlend) loadPalette(_currentPalette, _t->_palTid); // not fade/blend transition, each effect uses its palette
477 if (_modeBlend) _currentPalette = _t->_palT; // not fade/blend transition, each effect uses its palette
478 } else
479 #endif
480 {
481 // blend palettes
482 // there are about 255 blend passes of 48 "blends" to completely blend two palettes (in _dur time)
483 // minimum blend time is 100ms maximum is 65535ms
484 5973 unsigned noOfBlends = ((255U * prog) / 0xFFFFU) - _t->_prevPaletteBlends;
485
2/2
✓ Branch 0 taken 90737 times.
✓ Branch 1 taken 5973 times.
96710 for (unsigned i = 0; i < noOfBlends; i++, _t->_prevPaletteBlends++) nblendPaletteTowardPalette(_t->_palT, _currentPalette, 48);
486 5973 _currentPalette = _t->_palT; // copy transitioning/temporary palette
487 }
488 }
489 8705 }
490
491 // loads palette of the old FX during transitions (used by particle system)
492 ✗ void Segment::loadOldPalette(void) {
493 ✗ if(isInTransition())
494 ✗ loadPalette(_currentPalette, _t->_palTid);
495 ✗ }
496
497 // relies on WS2812FX::service() to call it for each frame
498 8705 void Segment::handleRandomPalette() {
499 // is it time to generate a new palette?
500
2/2
✓ Branch 0 taken 472 times.
✓ Branch 1 taken 8233 times.
8705 if ((uint16_t)(millis()/1000U) - _lastPaletteChange > randomPaletteChangeTime) {
501
2/6
✓ Branch 0 taken 472 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 472 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
472 _newRandomPalette = useHarmonicRandomPalette ? generateHarmonicRandomPalette(_randomPalette) : generateRandomPalette();
502 472 _lastPaletteChange = (uint16_t)(millis()/1000U);
503 472 _lastPaletteBlend = (uint16_t)(millis())-512; // starts blending immediately
504 }
505
506 // assumes that 128 updates are sufficient to blend a palette, so shift by 7 (can be more, can be less)
507 // in reality there need to be 255 blends to fully blend two entirely different palettes
508
2/2
✓ Branch 0 taken 123 times.
✓ Branch 1 taken 8582 times.
8705 if ((uint16_t)millis() - _lastPaletteBlend < strip().getTransition() >> 7) return; // not yet time to fade, delay the update
509 8582 _lastPaletteBlend = (uint16_t)millis();
510 8582 nblendPaletteTowardPalette(_randomPalette, _newRandomPalette, 48);
511 }
512
513 // sets Segment geometry (length or width/height and grouping, spacing and offset as well as 2D mapping)
514 // strip must be suspended (strip().suspend()) before calling this function
515 // this function may call fill() to clear pixels if spacing or mapping changed (which requires setting _vWidth, _vHeight, _vLength or beginDraw())
516 ✗ void Segment::setGeometry(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t ofs, uint16_t i1Y, uint16_t i2Y, uint8_t m12) {
517 // return if neither bounds nor grouping have changed
518 ✗ bool boundsUnchanged = (start == i1 && stop == i2);
519 #ifndef WLED_DISABLE_2D
520 ✗ if (Segment::maxHeight>1) boundsUnchanged &= (startY == i1Y && stopY == i2Y); // 2D
521 #endif
522
523 ✗ if (stop && (spc > 0 || m12 != map1D2D)) clear();
524 /*
525 if (boundsUnchanged
526 && (!grp || (grouping == grp && spacing == spc))
527 && (ofs == UINT16_MAX || ofs == offset)
528 && (m12 == map1D2D)
529 ) return;
530 */
531 ✗ stateChanged = true; // send UDP/WS broadcast
532
533 ✗ if (grp) { // prevent assignment of 0
534 ✗ grouping = grp;
535 ✗ spacing = spc;
536 } else {
537 ✗ grouping = 1;
538 ✗ spacing = 0;
539 }
540 ✗ if (ofs < UINT16_MAX) offset = ofs;
541 ✗ map1D2D = constrain(m12, 0, 7);
542
543 DEBUG_PRINTF_P(PSTR("Segment geometry: %d,%d -> %d,%d\n"), (int)i1, (int)i2, (int)i1Y, (int)i2Y);
544 ✗ markForReset();
545 ✗ if (boundsUnchanged) return;
546
547 // apply change immediately
548 ✗ if (i2 <= i1) { //disable segment
549 ✗ stop = 0;
550 ✗ return;
551 }
552 ✗ if (i1 < Segment::maxWidth || (i1 >= Segment::maxWidth*Segment::maxHeight && i1 < strip().getLengthTotal())) start = i1; // Segment::maxWidth equals strip().getLengthTotal() for 1D
553 ✗ stop = i2 > Segment::maxWidth*Segment::maxHeight ? MIN(i2,strip().getLengthTotal()) : (i2 > Segment::maxWidth ? Segment::maxWidth : MAX(1,i2));
554 ✗ startY = 0;
555 ✗ stopY = 1;
556 #ifndef WLED_DISABLE_2D
557 ✗ if (Segment::maxHeight>1) { // 2D
558 ✗ if (i1Y < Segment::maxHeight) startY = i1Y;
559 ✗ stopY = i2Y > Segment::maxHeight ? Segment::maxHeight : MAX(1,i2Y);
560 }
561 #endif
562 // safety check
563 ✗ if (start >= stop || startY >= stopY) {
564 ✗ stop = 0;
565 ✗ return;
566 }
567 ✗ refreshLightCapabilities();
568 }
569
570
571 3609 Segment &Segment::setColor(uint8_t slot, uint32_t c) {
572
3/4
✓ Branch 0 taken 3609 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 630 times.
✓ Branch 3 taken 2979 times.
3609 if (slot >= NUM_COLORS || c == colors[slot]) return *this;
573
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 2979 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
2979 if (!_isRGB && !_hasW) {
574 ✗ if (slot == 0 && c == BLACK) return *this; // on/off segment cannot have primary color black
575 ✗ if (slot == 1 && c != BLACK) return *this; // on/off segment cannot have secondary color non black
576 }
577 //DEBUG_PRINTF_P(PSTR("- Starting color transition: %d [0x%X]\n"), slot, c);
578 2979 startTransition(strip().getTransition()); // start transition prior to change
579 2979 colors[slot] = c;
580 2979 stateChanged = true; // send UDP/WS broadcast
581 2979 return *this;
582 }
583
584 ✗ Segment &Segment::setCCT(uint16_t k) {
585 ✗ if (k > 255) { //kelvin value, convert to 0-255
586 ✗ if (k < 1900) k = 1900;
587 ✗ if (k > 10091) k = 10091;
588 ✗ k = (k - 1900) >> 5;
589 }
590 ✗ if (cct != k) {
591 //DEBUG_PRINTF_P(PSTR("- Starting CCT transition: %d\n"), k);
592 ✗ startTransition(strip().getTransition()); // start transition prior to change
593 ✗ cct = k;
594 ✗ stateChanged = true; // send UDP/WS broadcast
595 }
596 ✗ return *this;
597 }
598
599 ✗ Segment &Segment::setOpacity(uint8_t o) {
600 ✗ if (opacity != o) {
601 //DEBUG_PRINTF_P(PSTR("- Starting opacity transition: %d\n"), o);
602 ✗ startTransition(strip().getTransition()); // start transition prior to change
603 ✗ opacity = o;
604 ✗ stateChanged = true; // send UDP/WS broadcast
605 }
606 ✗ return *this;
607 }
608
609 ✗ Segment &Segment::setOption(uint8_t n, bool val) {
610 ✗ bool prevOn = on;
611 ✗ if (n == SEG_OPTION_ON && val != prevOn) startTransition(strip().getTransition()); // start transition prior to change
612 ✗ if (val) options |= 0x01 << n;
613 ✗ else options &= ~(0x01 << n);
614 ✗ if (!(n == SEG_OPTION_SELECTED || n == SEG_OPTION_RESET)) stateChanged = true; // send UDP/WS broadcast
615 ✗ return *this;
616 }
617
618 1203 Segment &Segment::setMode(uint8_t fx, bool loadDefaults) {
619 // skip reserved
620
3/6
✓ Branch 0 taken 1203 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1203 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 1203 times.
1203 while (fx < strip().getModeCount() && strncmp_P("RSVD", strip().getModeData(fx), 4) == 0) fx++;
621
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1203 times.
1203 if (fx >= strip().getModeCount()) fx = 0; // set solid mode
622 // if we have a valid mode & is not reserved
623
1/2
✓ Branch 0 taken 1203 times.
✗ Branch 1 not taken.
1203 if (fx != mode) {
624 #ifndef WLED_DISABLE_MODE_BLEND
625 //DEBUG_PRINTF_P(PSTR("- Starting effect transition: %d\n"), fx);
626 startTransition(strip().getTransition()); // set effect transitions
627 #endif
628 1203 mode = fx;
629 int sOpt;
630 // load default values from effect string
631
1/2
✓ Branch 0 taken 1203 times.
✗ Branch 1 not taken.
1203 if (loadDefaults) {
632
2/2
✓ Branch 0 taken 178 times.
✓ Branch 1 taken 1025 times.
1203 sOpt = extractModeDefaults(fx, "sx"); speed = (sOpt >= 0) ? sOpt : DEFAULT_SPEED;
633
2/2
✓ Branch 0 taken 348 times.
✓ Branch 1 taken 855 times.
1203 sOpt = extractModeDefaults(fx, "ix"); intensity = (sOpt >= 0) ? sOpt : DEFAULT_INTENSITY;
634
2/2
✓ Branch 0 taken 264 times.
✓ Branch 1 taken 939 times.
1203 sOpt = extractModeDefaults(fx, "c1"); custom1 = (sOpt >= 0) ? sOpt : DEFAULT_C1;
635
2/2
✓ Branch 0 taken 194 times.
✓ Branch 1 taken 1009 times.
1203 sOpt = extractModeDefaults(fx, "c2"); custom2 = (sOpt >= 0) ? sOpt : DEFAULT_C2;
636
2/2
✓ Branch 0 taken 166 times.
✓ Branch 1 taken 1037 times.
1203 sOpt = extractModeDefaults(fx, "c3"); custom3 = (sOpt >= 0) ? sOpt : DEFAULT_C3;
637
3/4
✓ Branch 0 taken 135 times.
✓ Branch 1 taken 1068 times.
✓ Branch 2 taken 135 times.
✗ Branch 3 not taken.
1203 sOpt = extractModeDefaults(fx, "o1"); check1 = (sOpt >= 0) ? (bool)sOpt : false;
638
4/4
✓ Branch 0 taken 110 times.
✓ Branch 1 taken 1093 times.
✓ Branch 2 taken 25 times.
✓ Branch 3 taken 85 times.
1203 sOpt = extractModeDefaults(fx, "o2"); check2 = (sOpt >= 0) ? (bool)sOpt : false;
639
3/4
✓ Branch 0 taken 109 times.
✓ Branch 1 taken 1094 times.
✓ Branch 2 taken 109 times.
✗ Branch 3 not taken.
1203 sOpt = extractModeDefaults(fx, "o3"); check3 = (sOpt >= 0) ? (bool)sOpt : false;
640
2/2
✓ Branch 0 taken 240 times.
✓ Branch 1 taken 963 times.
1203 sOpt = extractModeDefaults(fx, "m12"); if (sOpt >= 0) map1D2D = constrain(sOpt, 0, 7); else map1D2D = M12_Pixels; // reset mapping if not defined (2D FX may not work)
641
2/2
✓ Branch 0 taken 158 times.
✓ Branch 1 taken 1045 times.
1203 sOpt = extractModeDefaults(fx, "si"); if (sOpt >= 0) soundSim = constrain(sOpt, 0, 3);
642
2/2
✓ Branch 0 taken 7 times.
✓ Branch 1 taken 1196 times.
1203 sOpt = extractModeDefaults(fx, "rev"); if (sOpt >= 0) reverse = (bool)sOpt;
643
2/2
✓ Branch 0 taken 7 times.
✓ Branch 1 taken 1196 times.
1203 sOpt = extractModeDefaults(fx, "mi"); if (sOpt >= 0) mirror = (bool)sOpt; // NOTE: setting this option is a risky business
644
2/2
✓ Branch 0 taken 7 times.
✓ Branch 1 taken 1196 times.
1203 sOpt = extractModeDefaults(fx, "rY"); if (sOpt >= 0) reverse_y = (bool)sOpt;
645
2/2
✓ Branch 0 taken 7 times.
✓ Branch 1 taken 1196 times.
1203 sOpt = extractModeDefaults(fx, "mY"); if (sOpt >= 0) mirror_y = (bool)sOpt; // NOTE: setting this option is a risky business
646
2/2
✓ Branch 0 taken 293 times.
✓ Branch 1 taken 910 times.
1203 sOpt = extractModeDefaults(fx, "pal"); if (sOpt >= 0) setPalette(sOpt); //else setPalette(0);
647 }
648 1203 sOpt = extractModeDefaults(fx, "pal"); // always extract 'pal' to set _default_palette
649
2/2
✓ Branch 0 taken 976 times.
✓ Branch 1 taken 227 times.
1203 if(sOpt <= 0) sOpt = 6; // partycolors if zero or not set
650 1203 _default_palette = sOpt; // _deault_palette is loaded into pal0 in loadPalette() (if selected)
651 1203 markForReset();
652 1203 stateChanged = true; // send UDP/WS broadcast
653 }
654 1203 return *this;
655 }
656
657 293 Segment &Segment::setPalette(uint8_t pal) {
658
2/4
✓ Branch 0 taken 293 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 293 times.
293 if (pal < 245 && pal > GRADIENT_PALETTE_COUNT+13) pal = 0; // built in palettes
659
2/8
✗ Branch 0 not taken.
✓ Branch 1 taken 293 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✓ Branch 7 taken 293 times.
293 if (pal > 245 && (strip().customPalettes.size() == 0 || 255U-pal > strip().customPalettes.size()-1)) pal = 0; // custom palettes
660
2/2
✓ Branch 0 taken 227 times.
✓ Branch 1 taken 66 times.
293 if (pal != palette) {
661 //DEBUG_PRINTF_P(PSTR("- Starting palette transition: %d\n"), pal);
662 227 startTransition(strip().getTransition());
663 227 palette = pal;
664 227 stateChanged = true; // send UDP/WS broadcast
665 }
666 293 return *this;
667 }
668
669 ✗ Segment &Segment::setName(const char *newName) {
670 ✗ if (newName) {
671 ✗ const int newLen = min(strlen(newName), (size_t)WLED_MAX_SEGNAME_LEN);
672 ✗ if (newLen) {
673 // realloc() into a temporary. Assigning its result straight to name
674 // would drop the old pointer on failure and leave name null, and the
675 // terminator write below would then dereference it. Keep the current
676 // name when memory cannot be had.
677 ✗ char *grown = static_cast<char*>(name ? realloc(name, newLen+1)
678 ✗ : malloc(newLen+1));
679 ✗ if (!grown) return *this;
680 ✗ name = grown;
681 ✗ strncpy(name, newName, newLen+1);
682 ✗ name[newLen] = 0;
683 ✗ return *this;
684 }
685 }
686 ✗ return clearName();
687 }
688
689 // 2D matrix
690 14967 unsigned Segment::virtualWidth() const {
691 14967 unsigned groupLen = groupLength();
692
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 14967 times.
14967 unsigned vWidth = ((transpose ? height() : width()) + groupLen - 1) / groupLen;
693
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 14967 times.
14967 if (mirror) vWidth = (vWidth + 1) /2; // divide by 2 if mirror, leave at least a single LED
694 14967 return vWidth;
695 }
696
697 15256 unsigned Segment::virtualHeight() const {
698 15256 unsigned groupLen = groupLength();
699
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15256 times.
15256 unsigned vHeight = ((transpose ? width() : height()) + groupLen - 1) / groupLen;
700
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15256 times.
15256 if (mirror_y) vHeight = (vHeight + 1) /2; // divide by 2 if mirror, leave at least a single LED
701 15256 return vHeight;
702 }
703
704 // Constants for mapping mode "Pinwheel"
705 #ifndef WLED_DISABLE_2D
706 constexpr int Fixed_Scale = 16384; // fixpoint scaling factor (14bit for fraction)
707 // Pinwheel helper function: matrix dimensions to number of rays
708 ✗ static int getPinwheelLength(int vW, int vH) {
709 // Returns multiple of 8, prevents over drawing
710 ✗ return (max(vW, vH) + 15) & ~7;
711 }
712 ✗ static void setPinwheelParameters(int i, int vW, int vH, int& startx, int& starty, int* cosVal, int* sinVal, bool getPixel = false) {
713 ✗ int steps = getPinwheelLength(vW, vH);
714 ✗ int baseAngle = ((0xFFFF + steps / 2) / steps); // 360° / steps, in 16 bit scale round to nearest integer
715 ✗ int rotate = 0;
716 ✗ if (getPixel) rotate = baseAngle / 2; // rotate by half a ray width when reading pixel color
717 ✗ for (int k = 0; k < 2; k++) // angular steps for two consecutive rays
718 {
719 ✗ int angle = (i + k) * baseAngle + rotate;
720 ✗ cosVal[k] = (cos16_t(angle) * Fixed_Scale) >> 15; // step per pixel in fixed point, cos16 output is -0x7FFF to +0x7FFF
721 ✗ sinVal[k] = (sin16_t(angle) * Fixed_Scale) >> 15; // using explicit bit shifts as dividing negative numbers is not equivalent (rounding error is acceptable)
722 }
723 ✗ startx = (vW * Fixed_Scale) / 2; // + cosVal[0] / 4; // starting position = center + 1/4 pixel (in fixed point)
724 ✗ starty = (vH * Fixed_Scale) / 2; // + sinVal[0] / 4;
725 ✗ }
726 #endif
727
728 // 1D strip
729 10609 uint16_t Segment::virtualLength() const {
730 #ifndef WLED_DISABLE_2D
731
2/2
✓ Branch 0 taken 6103 times.
✓ Branch 1 taken 4506 times.
10609 if (is2D()) {
732 6103 unsigned vW = virtualWidth();
733 6103 unsigned vH = virtualHeight();
734 unsigned vLen;
735
4/5
✓ Branch 0 taken 287 times.
✓ Branch 1 taken 36 times.
✓ Branch 2 taken 162 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 5618 times.
6103 switch (map1D2D) {
736 287 case M12_pBar:
737 287 vLen = vH;
738 287 break;
739 36 case M12_pCorner:
740 36 vLen = max(vW,vH); // get the longest dimension
741 36 break;
742 162 case M12_pArc:
743 162 vLen = sqrt32_bw(vH*vH + vW*vW); // use diagonal
744 162 break;
745 ✗ case M12_sPinwheel:
746 ✗ vLen = getPinwheelLength(vW, vH);
747 ✗ break;
748 5618 default:
749 5618 vLen = vW * vH; // use all pixels from segment
750 5618 break;
751 }
752 6103 return vLen;
753 }
754 #endif
755 4506 unsigned groupLen = groupLength(); // is always >= 1
756 4506 unsigned vLength = (length() + groupLen - 1) / groupLen;
757
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 4506 times.
4506 if (mirror) vLength = (vLength + 1) /2; // divide by 2 if mirror, leave at least a single LED
758 4506 return vLength;
759 }
760
761 // pixel is clipped if it falls outside clipping range (_modeBlend==true) or is inside clipping range (_modeBlend==false)
762 // if clipping start > stop the clipping range is inverted
763 // _modeBlend==true -> old effect during transition
764 // _modeBlend==false -> new effect during transition
765 258781 bool IRAM_ATTR_YN Segment::isPixelClipped(int i) const {
766 #ifndef WLED_DISABLE_MODE_BLEND
767 if (_clipStart != _clipStop && blendingStyle > BLEND_STYLE_FADE) {
768 bool invert = _clipStart > _clipStop; // ineverted start & stop
769 int start = invert ? _clipStop : _clipStart;
770 int stop = invert ? _clipStart : _clipStop;
771 if (blendingStyle == BLEND_STYLE_FAIRY_DUST) {
772 unsigned len = stop - start;
773 if (len < 2) return false;
774 unsigned shuffled = hashInt(i) % len;
775 unsigned pos = (shuffled * 0xFFFFU) / len;
776 return (progress() <= pos) ^ _modeBlend;
777 }
778 const bool iInside = (i >= start && i < stop);
779 //if (!invert && iInside) return _modeBlend;
780 //if ( invert && !iInside) return _modeBlend;
781 //return !_modeBlend;
782 return !iInside ^ invert ^ _modeBlend; // thanks @willmmiles (https://github.com/wled-dev/WLED/pull/3877#discussion_r1554633876)
783 }
784 #endif
785 258781 return false;
786 }
787
788 1212379 void IRAM_ATTR_YN Segment::setPixelColor(int i, uint32_t col) const
789 {
790
5/6
✓ Branch 0 taken 1212379 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✓ Branch 3 taken 1212375 times.
✓ Branch 4 taken 4 times.
✓ Branch 5 taken 1212375 times.
1212379 if (!isActive() || i < 0) return; // not active or invalid index
791 #ifndef WLED_DISABLE_2D
792 1212375 int vStrip = 0;
793 #endif
794 1212375 int vL = vLength();
795 // if the 1D effect is using virtual strips "i" will have virtual strip id stored in upper 16 bits
796 // in such case "i" will be > virtualLength()
797
2/2
✓ Branch 0 taken 21590 times.
✓ Branch 1 taken 1190785 times.
1212375 if (i >= vL) {
798 // check if this is a virtual strip
799 #ifndef WLED_DISABLE_2D
800 21590 vStrip = i>>16; // hack to allow running on virtual strips (2D segment columns/rows)
801 21590 i &= 0xFFFF; //truncate vstrip index
802
2/2
✓ Branch 0 taken 44 times.
✓ Branch 1 taken 21546 times.
21590 if (i >= vL) return; // if pixel would still fall out of segment just exit
803 #else
804 return;
805 #endif
806 }
807
808 #ifndef WLED_DISABLE_2D
809
2/2
✓ Branch 0 taken 985826 times.
✓ Branch 1 taken 226505 times.
1212331 if (is2D()) {
810 985826 const int vW = vWidth(); // segment width in logical pixels (can be 0 if segment is inactive)
811 985826 const int vH = vHeight(); // segment height in logical pixels (is always >= 1)
812 // pre-scale color for all pixels
813 985826 col = color_fade(col, _segBri);
814 985826 _colorScaled = true;
815
4/6
✓ Branch 0 taken 961254 times.
✓ Branch 1 taken 21174 times.
✓ Branch 2 taken 2907 times.
✓ Branch 3 taken 491 times.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
985826 switch (map1D2D) {
816 961254 case M12_Pixels:
817 // use all available pixels as a long strip
818 961254 setPixelColorXY(i % vW, i / vW, col);
819 961254 break;
820 21174 case M12_pBar:
821 // expand 1D effect vertically or have it play on virtual strips
822
2/2
✓ Branch 0 taken 19957 times.
✓ Branch 1 taken 1217 times.
21174 if (vStrip > 0) setPixelColorXY(vStrip - 1, vH - i - 1, col);
823
2/2
✓ Branch 0 taken 32210 times.
✓ Branch 1 taken 1217 times.
33427 else for (int x = 0; x < vW; x++) setPixelColorXY(x, vH - i - 1, col);
824 21174 break;
825 2907 case M12_pArc:
826 // expand in circular fashion from center
827
2/2
✓ Branch 0 taken 121 times.
✓ Branch 1 taken 2786 times.
2907 if (i == 0)
828 121 setPixelColorXY(0, 0, col);
829 else {
830 2786 float r = i;
831 2786 float step = HALF_PI / (2.8284f * r + 4); // we only need (PI/4)/(r/sqrt(2)+1) steps
832
2/2
✓ Branch 0 taken 72198 times.
✓ Branch 1 taken 2786 times.
74984 for (float rad = 0.0f; rad <= (HALF_PI/2)+step/2; rad += step) {
833 72198 int x = roundf(sin_t(rad) * r);
834 72198 int y = roundf(cos_t(rad) * r);
835 // exploit symmetry
836 72198 setPixelColorXY(x, y, col);
837 72198 setPixelColorXY(y, x, col);
838 }
839 // Bresenham’s Algorithm (may not fill every pixel)
840 //int d = 3 - (2*i);
841 //int y = i, x = 0;
842 //while (y >= x) {
843 // setPixelColorXY(x, y, col);
844 // setPixelColorXY(y, x, col);
845 // x++;
846 // if (d > 0) {
847 // y--;
848 // d += 4 * (x - y) + 10;
849 // } else {
850 // d += 4 * x + 6;
851 // }
852 //}
853 }
854 2907 break;
855 491 case M12_pCorner:
856
2/2
✓ Branch 0 taken 7664 times.
✓ Branch 1 taken 491 times.
8155 for (int x = 0; x <= i; x++) setPixelColorXY(x, i, col);
857
2/2
✓ Branch 0 taken 7173 times.
✓ Branch 1 taken 491 times.
7664 for (int y = 0; y < i; y++) setPixelColorXY(i, y, col);
858 491 break;
859 ✗ case M12_sPinwheel: {
860 // Uses Bresenham's algorithm to place coordinates of two lines in arrays then draws between them
861 int startX, startY, cosVal[2], sinVal[2]; // in fixed point scale
862 ✗ setPinwheelParameters(i, vW, vH, startX, startY, cosVal, sinVal);
863
864 ✗ unsigned maxLineLength = max(vW, vH) + 2; // pixels drawn is always smaller than dx or dy, +1 pair for rounding errors
865 ✗ uint16_t lineCoords[2][maxLineLength]; // uint16_t to save ram
866 ✗ int lineLength[2] = {0};
867
868 static int prevRays[2] = {INT_MAX, INT_MAX}; // previous two ray numbers
869 ✗ int closestEdgeIdx = INT_MAX; // index of the closest edge pixel
870
871 ✗ for (int lineNr = 0; lineNr < 2; lineNr++) {
872 ✗ int x0 = startX; // x, y coordinates in fixed scale
873 ✗ int y0 = startY;
874 ✗ int x1 = (startX + (cosVal[lineNr] << 9)); // outside of grid
875 ✗ int y1 = (startY + (sinVal[lineNr] << 9)); // outside of grid
876 ✗ const int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1; // x distance & step
877 ✗ const int dy = -abs(y1-y0), sy = y0<y1 ? 1 : -1; // y distance & step
878 ✗ uint16_t* coordinates = lineCoords[lineNr]; // 1D access is faster
879 ✗ int* length = &lineLength[lineNr]; // faster access
880 ✗ x0 /= Fixed_Scale; // convert to pixel coordinates
881 ✗ y0 /= Fixed_Scale;
882
883 // Bresenham's algorithm
884 ✗ int idx = 0;
885 ✗ int err = dx + dy;
886 while (true) {
887 ✗ if (unsigned(x0) >= vW || unsigned(y0) >= vH) {
888 ✗ closestEdgeIdx = min(closestEdgeIdx, idx-2);
889 ✗ break; // stop if outside of grid (exploit unsigned int overflow)
890 }
891 ✗ coordinates[idx++] = x0;
892 ✗ coordinates[idx++] = y0;
893 ✗ (*length)++;
894 // note: since endpoint is out of grid, no need to check if endpoint is reached
895 ✗ int e2 = 2 * err;
896 ✗ if (e2 >= dy) { err += dy; x0 += sx; }
897 ✗ if (e2 <= dx) { err += dx; y0 += sy; }
898 ✗ }
899 }
900
901 // fill up the shorter line with missing coordinates, so block filling works correctly and efficiently
902 ✗ int diff = lineLength[0] - lineLength[1];
903 ✗ int longLineIdx = (diff > 0) ? 0 : 1;
904 ✗ int shortLineIdx = longLineIdx ? 0 : 1;
905 ✗ if (diff != 0) {
906 ✗ int idx = (lineLength[shortLineIdx] - 1) * 2; // last valid coordinate index
907 ✗ int lastX = lineCoords[shortLineIdx][idx++];
908 ✗ int lastY = lineCoords[shortLineIdx][idx++];
909 ✗ bool keepX = lastX == 0 || lastX == vW - 1;
910 ✗ for (int d = 0; d < abs(diff); d++) {
911 ✗ lineCoords[shortLineIdx][idx] = keepX ? lastX :lineCoords[longLineIdx][idx];
912 ✗ idx++;
913 ✗ lineCoords[shortLineIdx][idx] = keepX ? lineCoords[longLineIdx][idx] : lastY;
914 ✗ idx++;
915 }
916 }
917
918 // draw and block-fill the line coordinates. Note: block filling only efficient if angle between lines is small
919 ✗ closestEdgeIdx += 2;
920 ✗ int max_i = getPinwheelLength(vW, vH) - 1;
921 ✗ bool drawFirst = !(prevRays[0] == i - 1 || (i == 0 && prevRays[0] == max_i)); // draw first line if previous ray was not adjacent including wrap
922 ✗ bool drawLast = !(prevRays[0] == i + 1 || (i == max_i && prevRays[0] == 0)); // same as above for last line
923 ✗ for (int idx = 0; idx < lineLength[longLineIdx] * 2;) { //!! should be long line idx!
924 ✗ int x1 = lineCoords[0][idx];
925 ✗ int x2 = lineCoords[1][idx++];
926 ✗ int y1 = lineCoords[0][idx];
927 ✗ int y2 = lineCoords[1][idx++];
928 int minX, maxX, minY, maxY;
929 ✗ (x1 < x2) ? (minX = x1, maxX = x2) : (minX = x2, maxX = x1);
930 ✗ (y1 < y2) ? (minY = y1, maxY = y2) : (minY = y2, maxY = y1);
931
932 // fill the block between the two x,y points
933 ✗ bool alwaysDraw = (drawFirst && drawLast) || // No adjacent rays, draw all pixels
934 ✗ (idx > closestEdgeIdx) || // Edge pixels on uneven lines are always drawn
935 ✗ (i == 0 && idx == 2) || // Center pixel special case
936 ✗ (i == prevRays[1]); // Effect drawing twice in 1 frame
937 ✗ for (int x = minX; x <= maxX; x++) {
938 ✗ for (int y = minY; y <= maxY; y++) {
939 ✗ bool onLine1 = x == x1 && y == y1;
940 ✗ bool onLine2 = x == x2 && y == y2;
941 ✗ if ((alwaysDraw) ||
942 ✗ (!onLine1 && (!onLine2 || drawLast)) || // Middle pixels and line2 if drawLast
943 ✗ (!onLine2 && (!onLine1 || drawFirst)) // Middle pixels and line1 if drawFirst
944 ) {
945 ✗ setPixelColorXY(x, y, col);
946 }
947 }
948 }
949 }
950 ✗ prevRays[1] = prevRays[0];
951 ✗ prevRays[0] = i;
952 ✗ break;
953 ✗ }
954 }
955 985826 return;
956
2/8
✗ Branch 0 not taken.
✓ Branch 1 taken 226505 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✓ Branch 7 taken 226505 times.
226505 } else if (Segment::maxHeight != 1 && (width() == 1 || height() == 1)) {
957 ✗ if (start < Segment::maxWidth*Segment::maxHeight) {
958 // we have a vertical or horizontal 1D segment (WARNING: virtual...() may be transposed)
959 ✗ int x = 0, y = 0;
960 ✗ if (vHeight() > 1) y = i;
961 ✗ if (vWidth() > 1) x = i;
962 ✗ setPixelColorXY(x, y, col);
963 ✗ return;
964 }
965 }
966 #endif
967
968 #ifndef WLED_DISABLE_MODE_BLEND
969 // if we blend using "push" style we need to "shift" new mode to left or right
970 if (isInTransition() && !_modeBlend && (blendingStyle == BLEND_STYLE_PUSH_RIGHT || blendingStyle == BLEND_STYLE_PUSH_LEFT)) {
971 unsigned prog = 0xFFFF - progress();
972 unsigned dI = prog * vL / 0xFFFF;
973 if (blendingStyle == BLEND_STYLE_PUSH_RIGHT) i -= dI;
974 else i += dI;
975 }
976 #endif
977
978
4/8
✓ Branch 0 taken 226505 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 226505 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 226505 times.
✗ Branch 6 not taken.
✓ Branch 7 taken 226505 times.
226505 if (i >= vL || i < 0 || isPixelClipped(i)) return; // handle clipping on 1D
979
980 226505 unsigned len = length();
981 // if color is unscaled
982
2/2
✓ Branch 0 taken 162565 times.
✓ Branch 1 taken 63940 times.
226505 if (!_colorScaled) col = color_fade(col, _segBri);
983
984 // expand pixel (taking into account start, grouping, spacing [and offset])
985 226505 i = i * groupLength();
986
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 226505 times.
226505 if (reverse) { // is segment reversed?
987 ✗ if (mirror) { // is segment mirrored?
988 ✗ i = (len - 1) / 2 - i; //only need to index half the pixels
989 } else {
990 ✗ i = (len - 1) - i;
991 }
992 }
993 226505 i += start; // starting pixel in a group
994
995 226505 uint32_t tmpCol = col;
996 // set all the pixels in the group
997
2/2
✓ Branch 0 taken 226505 times.
✓ Branch 1 taken 226505 times.
453010 for (int j = 0; j < grouping; j++) {
998
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 226505 times.
226505 unsigned indexSet = i + ((reverse) ? -j : j);
999
2/4
✓ Branch 0 taken 226505 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 226505 times.
✗ Branch 3 not taken.
226505 if (indexSet >= start && indexSet < stop) {
1000
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 226505 times.
226505 if (mirror) { //set the corresponding mirrored pixel
1001 ✗ unsigned indexMir = stop - indexSet + start - 1;
1002 ✗ indexMir += offset; // offset/phase
1003 ✗ if (indexMir >= stop) indexMir -= len; // wrap
1004 #ifndef WLED_DISABLE_MODE_BLEND
1005 // _modeBlend==true -> old effect
1006 if (_modeBlend && blendingStyle == BLEND_STYLE_FADE) tmpCol = color_blend16(strip().getPixelColor(indexMir), col, 0xFFFFU - progress());
1007 #endif
1008 ✗ strip().setPixelColor(indexMir, tmpCol);
1009 }
1010 226505 indexSet += offset; // offset/phase
1011
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 226505 times.
226505 if (indexSet >= stop) indexSet -= len; // wrap
1012 #ifndef WLED_DISABLE_MODE_BLEND
1013 // _modeBlend==true -> old effect
1014 if (_modeBlend && blendingStyle == BLEND_STYLE_FADE) tmpCol = color_blend16(strip().getPixelColor(indexSet), col, 0xFFFFU - progress());
1015 #endif
1016 226505 strip().setPixelColor(indexSet, tmpCol);
1017 }
1018 }
1019 }
1020
1021 #ifdef WLED_USE_AA_PIXELS
1022 // anti-aliased normalized version of setPixelColor()
1023 void Segment::setPixelColor(float i, uint32_t col, bool aa) const
1024 {
1025 if (!isActive()) return; // not active
1026 int vStrip = int(i/10.0f); // hack to allow running on virtual strips (2D segment columns/rows)
1027 i -= int(i);
1028
1029 if (i<0.0f || i>1.0f) return; // not normalized
1030
1031 float fC = i * (virtualLength()-1);
1032 if (aa) {
1033 unsigned iL = roundf(fC-0.49f);
1034 unsigned iR = roundf(fC+0.49f);
1035 float dL = (fC - iL)*(fC - iL);
1036 float dR = (iR - fC)*(iR - fC);
1037 uint32_t cIL = getPixelColor(iL | (vStrip<<16));
1038 uint32_t cIR = getPixelColor(iR | (vStrip<<16));
1039 if (iR!=iL) {
1040 // blend L pixel
1041 cIL = color_blend(col, cIL, uint8_t(dL*255.0f));
1042 setPixelColor(iL | (vStrip<<16), cIL);
1043 // blend R pixel
1044 cIR = color_blend(col, cIR, uint8_t(dR*255.0f));
1045 setPixelColor(iR | (vStrip<<16), cIR);
1046 } else {
1047 // exact match (x & y land on a pixel)
1048 setPixelColor(iL | (vStrip<<16), col);
1049 }
1050 } else {
1051 setPixelColor(int(roundf(fC)) | (vStrip<<16), col);
1052 }
1053 }
1054 #endif
1055
1056 76958 uint32_t IRAM_ATTR_YN Segment::getPixelColor(int i) const
1057 {
1058
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 76958 times.
76958 if (!isActive()) return 0; // not active
1059
1060 76958 int vL = vLength();
1061
4/4
✓ Branch 0 taken 69443 times.
✓ Branch 1 taken 7515 times.
✓ Branch 2 taken 4 times.
✓ Branch 3 taken 69439 times.
76958 if (i >= vL || i < 0) return 0;
1062
1063 #ifndef WLED_DISABLE_2D
1064
2/2
✓ Branch 0 taken 37163 times.
✓ Branch 1 taken 32276 times.
69439 if (is2D()) {
1065 37163 const int vW = vWidth(); // segment width in logical pixels (can be 0 if segment is inactive)
1066 37163 const int vH = vHeight(); // segment height in logical pixels (is always >= 1)
1067
4/6
✓ Branch 0 taken 35647 times.
✓ Branch 1 taken 78 times.
✓ Branch 2 taken 1098 times.
✓ Branch 3 taken 340 times.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
37163 switch (map1D2D) {
1068 35647 case M12_Pixels:
1069
1/2
✓ Branch 0 taken 35647 times.
✗ Branch 1 not taken.
35647 return getPixelColorXY(i % vW, i / vW);
1070 break;
1071 78 case M12_pBar: {
1072 78 int vStrip = i>>16; // virtual strips are only relevant in Bar expansion mode
1073
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 78 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
78 if (vStrip > 0) return getPixelColorXY(vStrip - 1, vH - (i & 0xFFFF) -1);
1074
1/2
✓ Branch 0 taken 78 times.
✗ Branch 1 not taken.
78 else return getPixelColorXY(0, vH - i -1);
1075 break; }
1076 1098 case M12_pArc:
1077
3/4
✓ Branch 0 taken 60 times.
✓ Branch 1 taken 1038 times.
✓ Branch 2 taken 60 times.
✗ Branch 3 not taken.
1098 if (i >= vW && i >= vH) {
1078
1/2
✓ Branch 0 taken 60 times.
✗ Branch 1 not taken.
60 unsigned vI = sqrt32_bw(i*i/2);
1079
1/2
✓ Branch 0 taken 60 times.
✗ Branch 1 not taken.
60 return getPixelColorXY(vI,vI); // use diagonal
1080 }
1081 case M12_pCorner:
1082 // use longest dimension
1083
2/6
✓ Branch 0 taken 1378 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1378 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
1378 return vW>vH ? getPixelColorXY(i, 0) : getPixelColorXY(0, i);
1084 break;
1085 ✗ case M12_sPinwheel:
1086 // not 100% accurate, returns pixel at outer edge
1087 int x, y, cosVal[2], sinVal[2];
1088 ✗ setPinwheelParameters(i, vW, vH, x, y, cosVal, sinVal, true);
1089 ✗ int maxX = (vW-1) * Fixed_Scale;
1090 ✗ int maxY = (vH-1) * Fixed_Scale;
1091 // trace ray from center until we hit any edge - to avoid rounding problems, we use fixed point coordinates
1092 ✗ while ((x < maxX) && (y < maxY) && (x > Fixed_Scale) && (y > Fixed_Scale)) {
1093 ✗ x += cosVal[0]; // advance to next position
1094 ✗ y += sinVal[0];
1095 }
1096 ✗ x /= Fixed_Scale;
1097 ✗ y /= Fixed_Scale;
1098 ✗ return getPixelColorXY(x, y);
1099 break;
1100 }
1101 ✗ return 0;
1102 }
1103 #endif
1104
1105 #ifndef WLED_DISABLE_MODE_BLEND
1106 if (isInTransition() && !_modeBlend && (blendingStyle == BLEND_STYLE_PUSH_RIGHT || blendingStyle == BLEND_STYLE_PUSH_LEFT)) {
1107 unsigned prog = 0xFFFF - progress();
1108 unsigned dI = prog * vL / 0xFFFF;
1109 if (blendingStyle == BLEND_STYLE_PUSH_RIGHT) i -= dI;
1110 else i += dI;
1111 }
1112 #endif
1113
1114
4/8
✓ Branch 0 taken 32276 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 32276 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 32276 times.
✗ Branch 6 not taken.
✓ Branch 7 taken 32276 times.
32276 if (i >= vL || i < 0 || isPixelClipped(i)) return 0; // handle clipping on 1D
1115
1116
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 32276 times.
32276 if (reverse) i = vL - i - 1;
1117 32276 i *= groupLength();
1118 32276 i += start;
1119 // offset/phase
1120 32276 i += offset;
1121
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 32276 times.
32276 if (i >= stop) i -= length();
1122 32276 return strip().getPixelColor(i);
1123 }
1124
1125 ✗ uint8_t Segment::differs(const Segment& b) const {
1126 ✗ uint8_t d = 0;
1127 ✗ if (start != b.start) d |= SEG_DIFFERS_BOUNDS;
1128 ✗ if (stop != b.stop) d |= SEG_DIFFERS_BOUNDS;
1129 ✗ if (offset != b.offset) d |= SEG_DIFFERS_GSO;
1130 ✗ if (grouping != b.grouping) d |= SEG_DIFFERS_GSO;
1131 ✗ if (spacing != b.spacing) d |= SEG_DIFFERS_GSO;
1132 ✗ if (opacity != b.opacity) d |= SEG_DIFFERS_BRI;
1133 ✗ if (mode != b.mode) d |= SEG_DIFFERS_FX;
1134 ✗ if (speed != b.speed) d |= SEG_DIFFERS_FX;
1135 ✗ if (intensity != b.intensity) d |= SEG_DIFFERS_FX;
1136 ✗ if (palette != b.palette) d |= SEG_DIFFERS_FX;
1137 ✗ if (custom1 != b.custom1) d |= SEG_DIFFERS_FX;
1138 ✗ if (custom2 != b.custom2) d |= SEG_DIFFERS_FX;
1139 ✗ if (custom3 != b.custom3) d |= SEG_DIFFERS_FX;
1140 ✗ if (startY != b.startY) d |= SEG_DIFFERS_BOUNDS;
1141 ✗ if (stopY != b.stopY) d |= SEG_DIFFERS_BOUNDS;
1142
1143 //bit pattern: (msb first)
1144 // set:2, sound:2, mapping:3, transposed, mirrorY, reverseY, [reset,] paused, mirrored, on, reverse, [selected]
1145 ✗ if ((options & 0b1111111111011110U) != (b.options & 0b1111111111011110U)) d |= SEG_DIFFERS_OPT;
1146 ✗ if ((options & 0x0001U) != (b.options & 0x0001U)) d |= SEG_DIFFERS_SEL;
1147 ✗ for (unsigned i = 0; i < NUM_COLORS; i++) if (colors[i] != b.colors[i]) d |= SEG_DIFFERS_COL;
1148
1149 ✗ return d;
1150 }
1151
1152 1203 void Segment::refreshLightCapabilities() {
1153 1203 unsigned capabilities = 0;
1154 1203 unsigned segStartIdx = 0xFFFFU;
1155 1203 unsigned segStopIdx = 0;
1156
1157
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1203 times.
1203 if (!isActive()) {
1158 ✗ _capabilities = 0;
1159 ✗ return;
1160 }
1161
1162
1/2
✓ Branch 0 taken 1203 times.
✗ Branch 1 not taken.
1203 if (start < Segment::maxWidth * Segment::maxHeight) {
1163 // we are withing 2D matrix (includes 1D segments)
1164
4/4
✓ Branch 0 taken 417786 times.
✓ Branch 1 taken 12636 times.
✓ Branch 2 taken 12636 times.
✓ Branch 3 taken 1203 times.
431625 for (int y = startY; y < stopY; y++) for (int x = start; x < stop; x++) {
1165 417786 unsigned index = strip().getMappedPixelIndex(x + Segment::maxWidth * y); // convert logical address to physical
1166
1/2
✓ Branch 0 taken 417786 times.
✗ Branch 1 not taken.
417786 if (index < 0xFFFFU) {
1167
2/2
✓ Branch 0 taken 1203 times.
✓ Branch 1 taken 416583 times.
417786 if (segStartIdx > index) segStartIdx = index;
1168
2/2
✓ Branch 0 taken 397804 times.
✓ Branch 1 taken 19982 times.
417786 if (segStopIdx < index) segStopIdx = index;
1169 }
1170
2/2
✓ Branch 0 taken 1203 times.
✓ Branch 1 taken 416583 times.
417786 if (segStartIdx == segStopIdx) segStopIdx++; // we only have 1 pixel segment
1171 }
1172 } else {
1173 // we are on the strip located after the matrix
1174 ✗ segStartIdx = start;
1175 ✗ segStopIdx = stop;
1176 }
1177
1178
2/2
✓ Branch 0 taken 1203 times.
✓ Branch 1 taken 1203 times.
2406 for (unsigned b = 0; b < BusManager::getNumBusses(); b++) {
1179 1203 const Bus *bus = BusManager::getBus(b);
1180
3/6
✓ Branch 0 taken 1203 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1203 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 1203 times.
1203 if (!bus || !bus->isOk()) break;
1181
3/6
✓ Branch 0 taken 1203 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1203 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 1203 times.
1203 if (bus->getStart() >= segStopIdx || bus->getStart() + bus->getLength() <= segStartIdx) continue;
1182
2/8
✗ Branch 0 not taken.
✓ Branch 1 taken 1203 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
✓ Branch 6 taken 1203 times.
✗ Branch 7 not taken.
1203 if (bus->hasRGB() || (strip().cctFromRgb && bus->hasCCT())) capabilities |= SEG_CAPABILITY_RGB;
1183
3/6
✓ Branch 0 taken 1203 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1203 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 1203 times.
1203 if (!strip().cctFromRgb && bus->hasCCT()) capabilities |= SEG_CAPABILITY_CCT;
1184
2/8
✗ Branch 0 not taken.
✓ Branch 1 taken 1203 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✓ Branch 7 taken 1203 times.
1203 if (strip().correctWB && (bus->hasRGB() || bus->hasCCT())) capabilities |= SEG_CAPABILITY_CCT; //white balance correction (CCT slider)
1185
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 1202 times.
1203 if (bus->hasWhite()) {
1186
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 unsigned aWM = Bus::getGlobalAWMode() == AW_GLOBAL_DISABLED ? bus->getAutoWhiteMode() : Bus::getGlobalAWMode();
1187
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1 times.
1 bool whiteSlider = (aWM == RGBW_MODE_DUAL || aWM == RGBW_MODE_MANUAL_ONLY); // white slider allowed
1188 // if auto white calculation from RGB is active (Accurate/Brighter), force RGB controls even if there are no RGB busses
1189
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 if (!whiteSlider) capabilities |= SEG_CAPABILITY_RGB;
1190 // if auto white calculation from RGB is disabled/optional (None/Dual), allow white channel adjustments
1191
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 if ( whiteSlider) capabilities |= SEG_CAPABILITY_W;
1192 }
1193 }
1194 1203 _capabilities = capabilities;
1195 }
1196
1197 /*
1198 * Fills segment with black
1199 */
1200 ✗ void Segment::clear() {
1201 ✗ if (!isActive()) return; // not active
1202 ✗ unsigned oldVW = _vWidth;
1203 ✗ unsigned oldVH = _vHeight;
1204 ✗ unsigned oldVL = _vLength;
1205 ✗ unsigned oldSB = _segBri;
1206 ✗ _vWidth = virtualWidth();
1207 ✗ _vHeight = virtualHeight();
1208 ✗ _vLength = virtualLength();
1209 ✗ _segBri = currentBri();
1210 ✗ fill(BLACK);
1211 ✗ _vWidth = oldVW;
1212 ✗ _vHeight = oldVH;
1213 ✗ _vLength = oldVL;
1214 ✗ _segBri = oldSB;
1215 }
1216
1217 /*
1218 * Fills segment with color
1219 */
1220 1201 void Segment::fill(uint32_t c) {
1221
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1201 times.
1201 if (!isActive()) return; // not active
1222
2/2
✓ Branch 0 taken 771 times.
✓ Branch 1 taken 430 times.
1201 const int cols = is2D() ? vWidth() : vLength();
1223 1201 const int rows = vHeight(); // will be 1 for 1D
1224 // pre-scale color for all pixels
1225 1201 c = color_fade(c, _segBri);
1226 1201 _colorScaled = true;
1227
4/4
✓ Branch 0 taken 300293 times.
✓ Branch 1 taken 8789 times.
✓ Branch 2 taken 8789 times.
✓ Branch 3 taken 1201 times.
310283 for (int y = 0; y < rows; y++) for (int x = 0; x < cols; x++) {
1228
2/2
✓ Branch 0 taken 236353 times.
✓ Branch 1 taken 63940 times.
300293 if (is2D()) setPixelColorXY(x, y, c);
1229 63940 else setPixelColor(x, c);
1230 }
1231 1201 _colorScaled = false;
1232 }
1233
1234 /*
1235 * fade out function, higher rate = quicker fade
1236 * fading is highly dependant on frame rate (higher frame rates, faster fading)
1237 * each frame will fade at max 9% or as little as 0.8%
1238 */
1239 770 void Segment::fade_out(uint8_t rate) {
1240
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 770 times.
770 if (!isActive()) return; // not active
1241
2/2
✓ Branch 0 taken 636 times.
✓ Branch 1 taken 134 times.
770 const int cols = is2D() ? vWidth() : vLength();
1242 770 const int rows = vHeight(); // will be 1 for 1D
1243
1244 770 rate = (256-rate) >> 1;
1245 770 const int mappedRate = 256 / (rate + 1);
1246
1247
4/4
✓ Branch 0 taken 277483 times.
✓ Branch 1 taken 8503 times.
✓ Branch 2 taken 8503 times.
✓ Branch 3 taken 770 times.
286756 for (int y = 0; y < rows; y++) for (int x = 0; x < cols; x++) {
1248
2/2
✓ Branch 0 taken 257383 times.
✓ Branch 1 taken 20100 times.
277483 uint32_t color = is2D() ? getPixelColorXY(x, y) : getPixelColor(x);
1249
2/2
✓ Branch 0 taken 74659 times.
✓ Branch 1 taken 202824 times.
277483 if (color == colors[1]) continue; // already at target color
1250
2/2
✓ Branch 0 taken 811296 times.
✓ Branch 1 taken 202824 times.
1014120 for (int i = 0; i < 32; i += 8) {
1251 811296 uint8_t c2 = (colors[1]>>i); // get background channel
1252 811296 uint8_t c1 = (color>>i); // get foreground channel
1253 // we can't use bitshift since we are using int
1254 811296 int delta = (c2 - c1) * mappedRate / 256;
1255 // if fade isn't complete, make sure delta is at least 1 (fixes rounding issues)
1256
6/6
✓ Branch 0 taken 496512 times.
✓ Branch 1 taken 314784 times.
✓ Branch 2 taken 48909 times.
✓ Branch 3 taken 447603 times.
✓ Branch 4 taken 20926 times.
✓ Branch 5 taken 27983 times.
811296 if (delta == 0) delta += (c2 == c1) ? 0 : (c2 > c1) ? 1 : -1;
1257 // stuff new value back into color
1258 811296 color &= ~(0xFF<<i);
1259 811296 color |= ((c1 + delta) & 0xFF) << i;
1260 }
1261
2/2
✓ Branch 0 taken 185768 times.
✓ Branch 1 taken 17056 times.
202824 if (is2D()) setPixelColorXY(x, y, color);
1262 17056 else setPixelColor(x, color);
1263 }
1264 }
1265
1266 // fades all pixels to secondary color
1267 ✗ void Segment::fadeToSecondaryBy(uint8_t fadeBy) {
1268 ✗ if (!isActive() || fadeBy == 0) return; // optimization - no scaling to apply
1269 ✗ const int cols = is2D() ? vWidth() : vLength();
1270 ✗ const int rows = vHeight(); // will be 1 for 1D
1271
1272 ✗ for (int y = 0; y < rows; y++) for (int x = 0; x < cols; x++) {
1273 ✗ if (is2D()) setPixelColorXY(x, y, color_blend(getPixelColorXY(x,y), colors[1], fadeBy));
1274 ✗ else setPixelColor(x, color_blend(getPixelColor(x), colors[1], fadeBy));
1275 }
1276 }
1277
1278 // fades all pixels to black using nscale8()
1279 1114 void Segment::fadeToBlackBy(uint8_t fadeBy) {
1280
5/6
✓ Branch 0 taken 1114 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 17 times.
✓ Branch 3 taken 1097 times.
✓ Branch 4 taken 17 times.
✓ Branch 5 taken 1097 times.
1114 if (!isActive() || fadeBy == 0) return; // optimization - no scaling to apply
1281
2/2
✓ Branch 0 taken 1077 times.
✓ Branch 1 taken 20 times.
1097 const int cols = is2D() ? vWidth() : vLength();
1282 1097 const int rows = vHeight(); // will be 1 for 1D
1283
1284
4/4
✓ Branch 0 taken 232195 times.
✓ Branch 1 taken 8990 times.
✓ Branch 2 taken 8990 times.
✓ Branch 3 taken 1097 times.
242282 for (int y = 0; y < rows; y++) for (int x = 0; x < cols; x++) {
1285
2/2
✓ Branch 0 taken 229195 times.
✓ Branch 1 taken 3000 times.
232195 if (is2D()) setPixelColorXY(x, y, color_fade(getPixelColorXY(x,y), 255-fadeBy));
1286 3000 else setPixelColor(x, color_fade(getPixelColor(x), 255-fadeBy));
1287 }
1288 }
1289
1290 /*
1291 * blurs segment content, source: FastLED colorutils.cpp
1292 * Note: for blur_amount > 215 this function does not work properly (creates alternating pattern)
1293 */
1294 422 void Segment::blur(uint8_t blur_amount, bool smear) {
1295
5/6
✓ Branch 0 taken 422 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 191 times.
✓ Branch 3 taken 231 times.
✓ Branch 4 taken 191 times.
✓ Branch 5 taken 231 times.
422 if (!isActive() || blur_amount == 0) return; // optimization: 0 means "don't blur"
1296 #ifndef WLED_DISABLE_2D
1297
2/2
✓ Branch 0 taken 224 times.
✓ Branch 1 taken 7 times.
231 if (is2D()) {
1298 // compatibility with 2D
1299 224 blur2D(blur_amount, blur_amount, smear); // symmetrical 2D blur
1300 //box_blur(map(blur_amount,1,255,1,3), smear);
1301 224 return;
1302 }
1303 #endif
1304
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 7 times.
7 uint8_t keep = smear ? 255 : 255 - blur_amount;
1305 7 uint8_t seep = blur_amount >> 1;
1306 7 unsigned vlength = vLength();
1307 7 uint32_t carryover = BLACK;
1308 uint32_t lastnew; // not necessary to initialize lastnew and last, as both will be initialized by the first loop iteration
1309 uint32_t last;
1310 7 uint32_t curnew = BLACK;
1311
2/2
✓ Branch 0 taken 1050 times.
✓ Branch 1 taken 7 times.
1057 for (unsigned i = 0; i < vlength; i++) {
1312 1050 uint32_t cur = getPixelColor(i);
1313 1050 uint32_t part = color_fade(cur, seep);
1314 1050 curnew = color_fade(cur, keep);
1315
2/2
✓ Branch 0 taken 1043 times.
✓ Branch 1 taken 7 times.
1050 if (i > 0) {
1316
2/2
✓ Branch 0 taken 750 times.
✓ Branch 1 taken 293 times.
1043 if (carryover) curnew = color_add(curnew, carryover);
1317 1043 uint32_t prev = color_add(lastnew, part);
1318 // optimization: only set pixel if color has changed
1319
1/2
✓ Branch 0 taken 1043 times.
✗ Branch 1 not taken.
1043 if (last != prev) setPixelColor(i - 1, prev);
1320 7 } else setPixelColor(i, curnew); // first pixel
1321 1050 lastnew = curnew;
1322 1050 last = cur; // save original value for comparison on next iteration
1323 1050 carryover = part;
1324 }
1325 7 setPixelColor(vlength - 1, curnew);
1326 }
1327
1328 /*
1329 * Put a value 0 to 255 in to get a color value.
1330 * The colours are a transition r -> g -> b -> back to r
1331 * Inspired by the Adafruit examples.
1332 */
1333 262446 uint32_t Segment::color_wheel(uint8_t pos) const {
1334
2/2
✓ Branch 0 taken 108561 times.
✓ Branch 1 taken 153885 times.
262446 if (palette) return color_from_palette(pos, false, true, 0); // perhaps "strip().paletteBlend < 2" should be better instead of "true"
1335 153885 uint8_t w = W(getCurrentColor(0));
1336 153885 pos = 255 - pos;
1337
2/2
✓ Branch 0 taken 49730 times.
✓ Branch 1 taken 104155 times.
153885 if (pos < 85) {
1338 49730 return RGBW32((255 - pos * 3), 0, (pos * 3), w);
1339
2/2
✓ Branch 0 taken 56263 times.
✓ Branch 1 taken 47892 times.
104155 } else if (pos < 170) {
1340 56263 pos -= 85;
1341 56263 return RGBW32(0, (pos * 3), (255 - pos * 3), w);
1342 } else {
1343 47892 pos -= 170;
1344 47892 return RGBW32((pos * 3), (255 - pos * 3), 0, w);
1345 }
1346 }
1347
1348 /*
1349 * Gets a single color from the currently selected palette.
1350 * @param i Palette Index (if mapping is true, the full palette will be _virtualSegmentLength long, if false, 255). Will wrap around automatically.
1351 * @param mapping if true, LED position in segment is considered for color
1352 * @param moving FastLED palettes will usually wrap back to the start smoothly. Set to true if effect has moving palette and you want wrap.
1353 * @param mcol If the default palette 0 is selected, return the standard color 0, 1 or 2 instead. If >2, Party palette is used instead
1354 * @param pbri Value to scale the brightness of the returned color by. Default is 255. (no scaling)
1355 * @returns Single color from palette
1356 */
1357 634936 uint32_t Segment::color_from_palette(uint16_t i, bool mapping, bool moving, uint8_t mcol, uint8_t pbri) const {
1358
2/2
✓ Branch 0 taken 588205 times.
✓ Branch 1 taken 46731 times.
634936 uint32_t color = getCurrentColor(mcol < NUM_COLORS ? mcol : 0);
1359 // default palette or no RGB support on segment
1360
5/6
✓ Branch 0 taken 351324 times.
✓ Branch 1 taken 283612 times.
✓ Branch 2 taken 14064 times.
✓ Branch 3 taken 337260 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 297676 times.
634936 if ((palette == 0 && mcol < NUM_COLORS) || !_isRGB) {
1361
1/2
✓ Branch 0 taken 337260 times.
✗ Branch 1 not taken.
337260 return color_fade(color, pbri, true);
1362 }
1363
1364 297676 const int vL = vLength();
1365 297676 unsigned paletteIndex = i;
1366
3/4
✓ Branch 0 taken 80114 times.
✓ Branch 1 taken 217562 times.
✓ Branch 2 taken 80114 times.
✗ Branch 3 not taken.
297676 if (mapping && vL > 1) paletteIndex = (i*255)/(vL -1);
1367 // paletteBlend: 0 - wrap when moving, 1 - always wrap, 2 - never wrap, 3 - none (undefined/no interpolation of palette entries)
1368 // ColorFromPalette interpolations are: NOBLEND, LINEARBLEND, LINEARBLEND_NOWRAP
1369 297676 TBlendType blend = NOBLEND;
1370
2/6
✓ Branch 0 taken 297676 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 297676 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
297676 switch (strip().paletteBlend) { // NOTE: paletteBlend should be global
1371
2/2
✓ Branch 0 taken 120844 times.
✓ Branch 1 taken 176832 times.
297676 case 0: blend = moving ? LINEARBLEND : LINEARBLEND_NOWRAP; break;
1372 ✗ case 1: blend = LINEARBLEND; break;
1373 ✗ case 2: blend = LINEARBLEND_NOWRAP; break;
1374 }
1375
1/2
✓ Branch 0 taken 297676 times.
✗ Branch 1 not taken.
297676 CRGBW palcol = ColorFromPalette(_currentPalette, paletteIndex, pbri, blend);
1376 297676 palcol.w = W(color);
1377
1378 297676 return palcol.color32;
1379 }
1380
1381
1382 ///////////////////////////////////////////////////////////////////////////////
1383 // WS2812FX class implementation
1384 ///////////////////////////////////////////////////////////////////////////////
1385
1386 //do not call this method from system context (network callback)
1387 4455 void WS2812FX::finalizeInit() {
1388 //reset segment runtimes
1389 4455 restartRuntime();
1390
1391 // for the lack of better place enumerate ledmaps here
1392 // if we do it in json.cpp (serializeInfo()) we are getting flashes on LEDs
1393 // unfortunately this means we do not get updates after uploads
1394 // the other option is saving UI settings which will cause enumeration
1395 4455 enumerateLedmaps();
1396
1397 4455 _hasWhiteChannel = _isOffRefreshRequired = false;
1398
1399 4455 unsigned digitalCount = 0;
1400 #if defined(ARDUINO_ARCH_ESP32) && !defined(CONFIG_IDF_TARGET_ESP32C3)
1401 // determine if it is sensible to use parallel I2S outputs on ESP32 (i.e. more than 5 outputs = 1 I2S + 4 RMT)
1402 unsigned maxLedsOnBus = 0;
1403 for (const auto &bus : busConfigs) {
1404 if (Bus::isDigital(bus.type) && !Bus::is2Pin(bus.type)) {
1405 digitalCount++;
1406 if (bus.count > maxLedsOnBus) maxLedsOnBus = bus.count;
1407 }
1408 }
1409 DEBUG_PRINTF_P(PSTR("Maximum LEDs on a bus: %u\nDigital buses: %u\n"), maxLedsOnBus, digitalCount);
1410 // we may remove 300 LEDs per bus limit when NeoPixelBus is updated beyond 2.9.0
1411 if (maxLedsOnBus <= 300 && useParallelI2S) BusManager::useParallelOutput(); // must call before creating buses
1412 else useParallelI2S = false; // enforce single I2S
1413 #endif
1414
1415 // create buses/outputs
1416 4455 unsigned mem = 0;
1417 4455 digitalCount = 0;
1418
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 4455 times.
4455 for (const auto &bus : busConfigs) {
1419 ✗ mem += bus.memUsage(Bus::isDigital(bus.type) && !Bus::is2Pin(bus.type) ? digitalCount++ : 0); // includes global buffer
1420 ✗ if (mem <= MAX_LED_MEMORY) {
1421 ✗ if (BusManager::add(bus) == -1) break;
1422 } else DEBUG_PRINTF_P(PSTR("Out of LED memory! Bus %d (%d) #%u not created."), (int)bus.type, (int)bus.count, digitalCount);
1423 }
1424 4455 busConfigs.clear();
1425 4455 busConfigs.shrink_to_fit();
1426
1427 //if busses failed to load, add default (fresh install, FS issue, ...)
1428
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 4455 times.
4455 if (BusManager::getNumBusses() == 0) {
1429 DEBUG_PRINTLN(F("No busses, init default"));
1430 ✗ constexpr unsigned defDataTypes[] = {LED_TYPES};
1431 ✗ constexpr unsigned defDataPins[] = {DATA_PINS};
1432 ✗ constexpr unsigned defCounts[] = {PIXEL_COUNTS};
1433 ✗ constexpr unsigned defNumTypes = ((sizeof defDataTypes) / (sizeof defDataTypes[0]));
1434 ✗ constexpr unsigned defNumPins = ((sizeof defDataPins) / (sizeof defDataPins[0]));
1435 ✗ constexpr unsigned defNumCounts = ((sizeof defCounts) / (sizeof defCounts[0]));
1436
1437 static_assert(validatePinsAndTypes(defDataTypes, defNumTypes, defNumPins),
1438 "The default pin list defined in DATA_PINS does not match the pin requirements for the default buses defined in LED_TYPES");
1439
1440 ✗ unsigned prevLen = 0;
1441 ✗ unsigned pinsIndex = 0;
1442 ✗ digitalCount = 0;
1443 ✗ for (unsigned i = 0; i < WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES; i++) {
1444 uint8_t defPin[OUTPUT_MAX_PINS];
1445 // if we have less types than requested outputs and they do not align, use last known type to set current type
1446 ✗ unsigned dataType = defDataTypes[(i < defNumTypes) ? i : defNumTypes -1];
1447 ✗ unsigned busPins = Bus::getNumberOfPins(dataType);
1448
1449 // if we need more pins than available all outputs have been configured
1450 ✗ if (pinsIndex + busPins > defNumPins) break;
1451
1452 // Assign all pins first so we can check for conflicts on this bus
1453 ✗ for (unsigned j = 0; j < busPins && j < OUTPUT_MAX_PINS; j++) defPin[j] = defDataPins[pinsIndex + j];
1454
1455 ✗ for (unsigned j = 0; j < busPins && j < OUTPUT_MAX_PINS; j++) {
1456 ✗ bool validPin = true;
1457 // When booting without config (1st boot) we need to make sure GPIOs defined for LED output don't clash with hardware
1458 // i.e. DEBUG (GPIO1), DMX (2), SPI RAM/FLASH (16&17 on ESP32-WROVER/PICO), read/only pins, etc.
1459 // Pin should not be already allocated, read/only or defined for current bus
1460 ✗ while (PinManager::isPinAllocated(defPin[j]) || !PinManager::isPinOk(defPin[j],true)) {
1461 ✗ if (validPin) {
1462 DEBUG_PRINTLN(F("Some of the provided pins cannot be used to configure this LED output."));
1463 ✗ defPin[j] = 1; // start with GPIO1 and work upwards
1464 ✗ validPin = false;
1465 ✗ } else if (defPin[j] < WLED_NUM_PINS) {
1466 ✗ defPin[j]++;
1467 } else {
1468 DEBUG_PRINTLN(F("No available pins left! Can't configure output."));
1469 ✗ return;
1470 }
1471 // is the newly assigned pin already defined or used previously?
1472 // try next in line until there are no clashes or we run out of pins
1473 bool clash;
1474 ✗ do {
1475 ✗ clash = false;
1476 // check for conflicts on current bus
1477 ✗ for (const auto &pin : defPin) {
1478 ✗ if (&pin != &defPin[j] && pin == defPin[j]) {
1479 ✗ clash = true;
1480 ✗ break;
1481 }
1482 }
1483 // We already have a clash on current bus, no point checking next buses
1484 ✗ if (!clash) {
1485 // check for conflicts in defined pins
1486 ✗ for (const auto &pin : defDataPins) {
1487 ✗ if (pin == defPin[j]) {
1488 ✗ clash = true;
1489 ✗ break;
1490 }
1491 }
1492 }
1493 ✗ if (clash) defPin[j]++;
1494 ✗ if (defPin[j] >= WLED_NUM_PINS) break;
1495 } while (clash);
1496 }
1497 }
1498 ✗ pinsIndex += busPins;
1499
1500 ✗ unsigned start = prevLen;
1501 // if we have less counts than pins and they do not align, use last known count to set current count
1502 ✗ unsigned count = defCounts[(i < defNumCounts) ? i : defNumCounts -1];
1503 // analog always has length 1
1504 ✗ if (Bus::isPWM(dataType) || Bus::isOnOff(dataType)) count = 1;
1505 ✗ prevLen += count;
1506 ✗ BusConfig defCfg = BusConfig(dataType, defPin, start, count, DEFAULT_LED_COLOR_ORDER, false, 0, RGBW_MODE_MANUAL_ONLY, 0, useGlobalLedBuffer);
1507 ✗ mem += defCfg.memUsage(Bus::isDigital(dataType) && !Bus::is2Pin(dataType) ? digitalCount++ : 0);
1508 ✗ if (BusManager::add(defCfg) == -1) break;
1509 }
1510 }
1511 DEBUG_PRINTF_P(PSTR("LED buffer size: %uB/%uB\n"), mem, BusManager::memUsage());
1512
1513 4455 _length = 0;
1514
2/2
✓ Branch 0 taken 4455 times.
✓ Branch 1 taken 4455 times.
8910 for (int i=0; i<BusManager::getNumBusses(); i++) {
1515 4455 Bus *bus = BusManager::getBus(i);
1516
4/8
✓ Branch 0 taken 4455 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4455 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 4455 times.
✗ Branch 6 not taken.
✓ Branch 7 taken 4455 times.
4455 if (!bus || !bus->isOk() || bus->getStart() + bus->getLength() > MAX_LEDS) break;
1517 //RGBW mode is enabled if at least one of the strips is RGBW
1518 4455 _hasWhiteChannel |= bus->hasWhite();
1519 //refresh is required to remain off if at least one of the strips requires the refresh.
1520
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 4455 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
4455 _isOffRefreshRequired |= bus->isOffRefreshRequired() && !bus->isPWM(); // use refresh bit for phase shift with analog
1521 4455 unsigned busEnd = bus->getStart() + bus->getLength();
1522
1/2
✓ Branch 0 taken 4455 times.
✗ Branch 1 not taken.
4455 if (busEnd > _length) _length = busEnd;
1523
1524 // This must be done after all buses have been created, as some kinds (parallel I2S) interact
1525 4455 bus->begin();
1526 4455 bus->setBrightness(bri);
1527 }
1528 DEBUG_PRINTF_P(PSTR("Heap after buses: %d\n"), ESP.getFreeHeap());
1529
1530 4455 Segment::maxWidth = _length;
1531 4455 Segment::maxHeight = 1;
1532
1533 //segments are created in makeAutoSegments();
1534 DEBUG_PRINTLN(F("Loading custom palettes"));
1535 4455 loadCustomPalettes(); // (re)load all custom palettes
1536 DEBUG_PRINTLN(F("Loading custom ledmaps"));
1537 4455 deserializeMap(); // (re)load default ledmap (will also setUpMatrix() if ledmap does not exist)
1538 }
1539
1540 8723 void WS2812FX::service() {
1541 8723 unsigned long nowUp = millis(); // Be aware, millis() rolls over every 49 days
1542 8723 now = nowUp + timebase;
1543
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 8723 times.
8723 if (_suspend) return;
1544 8723 unsigned long elapsed = nowUp - _lastServiceShow;
1545
1546
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 8723 times.
8723 if (elapsed <= MIN_FRAME_DELAY) return; // keep wifi alive - no matter if triggered or unlimited
1547
2/4
✓ Branch 0 taken 8723 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 8723 times.
✗ Branch 3 not taken.
8723 if ( !_triggered && (_targetFps != FPS_UNLIMITED)) { // unlimited mode = no frametime
1548
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 8723 times.
8723 if (elapsed < _frametime) return; // too early for service
1549 }
1550
1551 8723 bool doShow = false;
1552
1553 8723 _isServicing = true;
1554 8723 _segment_index = 0;
1555
1556
2/2
✓ Branch 0 taken 8723 times.
✓ Branch 1 taken 8723 times.
17446 for (segment &seg : _segments) {
1557
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 8723 times.
8723 if (_suspend) break; // immediately stop processing segments if suspend requested during service()
1558
1559 // process transition (mode changes in the middle of transition)
1560
1/2
✓ Branch 0 taken 8723 times.
✗ Branch 1 not taken.
8723 seg.handleTransition();
1561 // reset the segment runtime data if needed
1562
1/2
✓ Branch 0 taken 8723 times.
✗ Branch 1 not taken.
8723 seg.resetIfRequired();
1563
1564
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 8723 times.
8723 if (!seg.isActive()) continue;
1565
1566 // last condition ensures all solid segments are updated at the same time
1567
4/8
✓ Branch 0 taken 18 times.
✓ Branch 1 taken 8705 times.
✓ Branch 2 taken 18 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 18 times.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
8723 if (nowUp >= seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC))
1568 {
1569 8705 doShow = true;
1570
1/2
✓ Branch 0 taken 8705 times.
✗ Branch 1 not taken.
8705 unsigned frameDelay = FRAMETIME;
1571
1572
1/2
✓ Branch 0 taken 8705 times.
✗ Branch 1 not taken.
8705 if (!seg.freeze) { //only run effect function if not frozen
1573 8705 int oldCCT = BusManager::getSegmentCCT(); // store original CCT value (actually it is not Segment based)
1574 // when correctWB is true we need to correct/adjust RGB value according to desired CCT value, but it will also affect actual WW/CW ratio
1575 // when cctFromRgb is true we implicitly calculate WW and CW from RGB values
1576
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 8705 times.
8705 if (cctFromRgb) BusManager::setSegmentCCT(-1);
1577
1/2
✓ Branch 0 taken 8705 times.
✗ Branch 1 not taken.
8705 else BusManager::setSegmentCCT(seg.currentBri(true), correctWB);
1578 // Effect blending
1579 // When two effects are being blended, each may have different segment data, this
1580 // data needs to be saved first and then restored before running previous mode.
1581 // The blending will largely depend on the effect behaviour since actual output (LEDs) may be
1582 // overwritten by later effect. To enable seamless blending for every effect, additional LED buffer
1583 // would need to be allocated for each effect and then blended together for each pixel.
1584
1/2
✓ Branch 0 taken 8705 times.
✗ Branch 1 not taken.
8705 seg.beginDraw(); // set up parameters for get/setPixelColor()
1585 #ifndef WLED_DISABLE_MODE_BLEND
1586 Segment::setClippingRect(0, 0); // disable clipping (just in case)
1587 if (seg.isInTransition()) {
1588 // a hack to determine if effect has changed
1589 uint8_t m = seg.currentMode();
1590 Segment::modeBlend(true); // set semaphore
1591 bool sameEffect = (m == seg.currentMode());
1592 Segment::modeBlend(false); // clear semaphore
1593 // set clipping rectangle
1594 // new mode is run inside clipping area and old mode outside clipping area
1595 unsigned p = seg.progress();
1596 unsigned w = seg.is2D() ? Segment::vWidth() : Segment::vLength();
1597 unsigned h = Segment::vHeight();
1598 unsigned dw = p * w / 0xFFFFU + 1;
1599 unsigned dh = p * h / 0xFFFFU + 1;
1600 unsigned orgBS = blendingStyle;
1601 if (w*h == 1) blendingStyle = BLEND_STYLE_FADE; // disable style for single pixel segments (use fade instead)
1602 else if (sameEffect && (blendingStyle & BLEND_STYLE_PUSH_MASK)) {
1603 // when effect stays the same push will look awful, change it to swipe
1604 switch (blendingStyle) {
1605 case BLEND_STYLE_PUSH_BR:
1606 case BLEND_STYLE_PUSH_TR:
1607 case BLEND_STYLE_PUSH_RIGHT: blendingStyle = BLEND_STYLE_SWIPE_RIGHT; break;
1608 case BLEND_STYLE_PUSH_BL:
1609 case BLEND_STYLE_PUSH_TL:
1610 case BLEND_STYLE_PUSH_LEFT: blendingStyle = BLEND_STYLE_SWIPE_LEFT; break;
1611 case BLEND_STYLE_PUSH_DOWN: blendingStyle = BLEND_STYLE_SWIPE_DOWN; break;
1612 case BLEND_STYLE_PUSH_UP: blendingStyle = BLEND_STYLE_SWIPE_UP; break;
1613 }
1614 }
1615 switch (blendingStyle) {
1616 case BLEND_STYLE_FAIRY_DUST: // fairy dust (must set entire segment, see isPixelXYClipped())
1617 Segment::setClippingRect(0, w, 0, h);
1618 break;
1619 case BLEND_STYLE_SWIPE_RIGHT: // left-to-right
1620 case BLEND_STYLE_PUSH_RIGHT: // left-to-right
1621 Segment::setClippingRect(0, dw, 0, h);
1622 break;
1623 case BLEND_STYLE_SWIPE_LEFT: // right-to-left
1624 case BLEND_STYLE_PUSH_LEFT: // right-to-left
1625 Segment::setClippingRect(w - dw, w, 0, h);
1626 break;
1627 case BLEND_STYLE_PINCH_OUT: // corners
1628 Segment::setClippingRect((w + dw)/2, (w - dw)/2, (h + dh)/2, (h - dh)/2); // inverted!!
1629 break;
1630 case BLEND_STYLE_INSIDE_OUT: // outward
1631 Segment::setClippingRect((w - dw)/2, (w + dw)/2, (h - dh)/2, (h + dh)/2);
1632 break;
1633 case BLEND_STYLE_SWIPE_DOWN: // top-to-bottom (2D)
1634 case BLEND_STYLE_PUSH_DOWN: // top-to-bottom (2D)
1635 Segment::setClippingRect(0, w, 0, dh);
1636 break;
1637 case BLEND_STYLE_SWIPE_UP: // bottom-to-top (2D)
1638 case BLEND_STYLE_PUSH_UP: // bottom-to-top (2D)
1639 Segment::setClippingRect(0, w, h - dh, h);
1640 break;
1641 case BLEND_STYLE_OPEN_H: // horizontal-outward (2D) same look as INSIDE_OUT on 1D
1642 Segment::setClippingRect((w - dw)/2, (w + dw)/2, 0, h);
1643 break;
1644 case BLEND_STYLE_OPEN_V: // vertical-outward (2D)
1645 Segment::setClippingRect(0, w, (h - dh)/2, (h + dh)/2);
1646 break;
1647 case BLEND_STYLE_PUSH_TL: // TL-to-BR (2D)
1648 Segment::setClippingRect(0, dw, 0, dh);
1649 break;
1650 case BLEND_STYLE_PUSH_TR: // TR-to-BL (2D)
1651 Segment::setClippingRect(w - dw, w, 0, dh);
1652 break;
1653 case BLEND_STYLE_PUSH_BR: // BR-to-TL (2D)
1654 Segment::setClippingRect(w - dw, w, h - dh, h);
1655 break;
1656 case BLEND_STYLE_PUSH_BL: // BL-to-TR (2D)
1657 Segment::setClippingRect(0, dw, h - dh, h);
1658 break;
1659 }
1660 frameDelay = (*_mode[m])(); // run new/current mode
1661 // now run old/previous mode
1662 Segment::tmpsegd_t _tmpSegData;
1663 Segment::modeBlend(true); // set semaphore
1664 seg.swapSegenv(_tmpSegData); // temporarily store new mode state (and swap it with transitional state)
1665 seg.beginDraw(); // set up parameters for get/setPixelColor()
1666 frameDelay = min(frameDelay, (unsigned)(*_mode[seg.currentMode()])()); // run old mode
1667 seg.call++; // increment old mode run counter
1668 seg.restoreSegenv(_tmpSegData); // restore mode state (will also update transitional state)
1669 Segment::modeBlend(false); // unset semaphore
1670 blendingStyle = orgBS; // restore blending style if it was modified for single pixel segment
1671 } else
1672 #endif
1673
1/2
✓ Branch 0 taken 8705 times.
✗ Branch 1 not taken.
8705 frameDelay = (*_mode[seg.mode])(); // run effect mode (not in transition)
1674 8705 seg.call++;
1675
8/10
✓ Branch 0 taken 5973 times.
✓ Branch 1 taken 2732 times.
✓ Branch 2 taken 5973 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 356 times.
✓ Branch 5 taken 5617 times.
✓ Branch 6 taken 356 times.
✓ Branch 7 taken 8349 times.
✓ Branch 8 taken 356 times.
✗ Branch 9 not taken.
8705 if (seg.isInTransition() && frameDelay > FRAMETIME) frameDelay = FRAMETIME; // force faster updates during transition
1676 8705 BusManager::setSegmentCCT(oldCCT); // restore old CCT for ABL adjustments
1677 }
1678
1679 8705 seg.next_time = nowUp + frameDelay;
1680 }
1681 8723 _segment_index++;
1682 }
1683 #ifndef WLED_DISABLE_MODE_BLEND
1684 Segment::setClippingRect(0, 0); // disable clipping for overlays
1685 #endif
1686 8723 _isServicing = false;
1687 8723 _triggered = false;
1688
1689 #ifdef WLED_DEBUG
1690 if ((_targetFps != FPS_UNLIMITED) && (millis() - nowUp > _frametime)) DEBUG_PRINTF_P(PSTR("Slow effects %u/%d.\n"), (unsigned)(millis()-nowUp), (int)_frametime);
1691 #endif
1692
2/2
✓ Branch 0 taken 8705 times.
✓ Branch 1 taken 18 times.
8723 if (doShow) {
1693 yield();
1694 8705 Segment::handleRandomPalette(); // slowly transition random palette; move it into for loop when each segment has individual random palette
1695 8705 _lastServiceShow = nowUp; // update timestamp, for precise FPS control
1696
1/2
✓ Branch 0 taken 8705 times.
✗ Branch 1 not taken.
8705 if (!_suspend) show();
1697 }
1698 #ifdef WLED_DEBUG
1699 if ((_targetFps != FPS_UNLIMITED) && (millis() - nowUp > _frametime)) DEBUG_PRINTF_P(PSTR("Slow strip %u/%d.\n"), (unsigned)(millis()-nowUp), (int)_frametime);
1700 #endif
1701 }
1702
1703 2547107 void IRAM_ATTR WS2812FX::setPixelColor(unsigned i, uint32_t col) const {
1704 2547107 i = getMappedPixelIndex(i);
1705
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2547107 times.
2547107 if (i >= _length) return;
1706 2547107 BusManager::setPixelColor(i, col);
1707 }
1708
1709 775299 uint32_t IRAM_ATTR WS2812FX::getPixelColor(unsigned i) const {
1710 775299 i = getMappedPixelIndex(i);
1711
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 775299 times.
775299 if (i >= _length) return 0;
1712 775299 return BusManager::getPixelColor(i);
1713 }
1714
1715 8705 void WS2812FX::show() {
1716 // avoid race condition, capture _callback value
1717 8705 show_callback callback = _callback;
1718
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 8705 times.
8705 if (callback) callback();
1719 8705 unsigned long showNow = millis();
1720
1721 // some buses send asynchronously and this method will return before
1722 // all of the data has been sent.
1723 // See https://github.com/Makuna/NeoPixelBus/wiki/ESP32-NeoMethods#neoesp32rmt-methods
1724 8705 BusManager::show();
1725
1726 8705 size_t diff = showNow - _lastShow;
1727
1728
1/2
✓ Branch 0 taken 8705 times.
✗ Branch 1 not taken.
8705 if (diff > 0) { // skip calculation if no time has passed
1729 8705 size_t fpsCurr = (1000 << FPS_CALC_SHIFT) / diff; // fixed point math
1730 8705 _cumulativeFps = (FPS_CALC_AVG * _cumulativeFps + fpsCurr + FPS_CALC_AVG / 2) / (FPS_CALC_AVG + 1); // "+FPS_CALC_AVG/2" for proper rounding
1731 8705 _lastShow = showNow;
1732 }
1733 8705 }
1734
1735 ✗ void WS2812FX::setTargetFps(unsigned fps) {
1736 ✗ if (fps <= 250) _targetFps = fps;
1737 ✗ if (_targetFps > 0) _frametime = 1000 / _targetFps;
1738 ✗ else _frametime = MIN_FRAME_DELAY; // unlimited mode
1739 ✗ }
1740
1741 ✗ void WS2812FX::setCCT(uint16_t k) {
1742 ✗ for (segment &seg : _segments) {
1743 ✗ if (seg.isActive() && seg.isSelected()) {
1744 ✗ seg.setCCT(k);
1745 }
1746 }
1747 ✗ }
1748
1749 // direct=true either expects the caller to call show() themselves (realtime modes) or be ok waiting for the next frame for the change to apply
1750 // direct=false immediately triggers an effect redraw
1751 ✗ void WS2812FX::setBrightness(uint8_t b, bool direct) {
1752 if (gammaCorrectBri) b = gamma8(b);
1753 ✗ if (_brightness == b) return;
1754 ✗ _brightness = b;
1755 ✗ if (_brightness == 0) { //unfreeze all segments on power off
1756 ✗ for (segment &seg : _segments) {
1757 ✗ seg.freeze = false;
1758 }
1759 }
1760 // setting brightness with NeoPixelBusLg has no effect on already painted pixels,
1761 // so we need to force an update to existing buffer
1762 ✗ BusManager::setBrightness(b);
1763 ✗ if (!direct) {
1764 ✗ unsigned long t = millis();
1765 ✗ if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_FRAME_DELAY) trigger(); //apply brightness change immediately if no refresh soon
1766 }
1767 }
1768
1769 ✗ uint8_t WS2812FX::getActiveSegsLightCapabilities(bool selectedOnly) const {
1770 ✗ uint8_t totalLC = 0;
1771 ✗ for (const segment &seg : _segments) {
1772 ✗ if (seg.isActive() && (!selectedOnly || seg.isSelected())) totalLC |= seg.getLightCapabilities();
1773 }
1774 ✗ return totalLC;
1775 }
1776
1777 ✗ uint8_t WS2812FX::getFirstSelectedSegId() const {
1778 ✗ size_t i = 0;
1779 ✗ for (const segment &seg : _segments) {
1780 ✗ if (seg.isActive() && seg.isSelected()) return i;
1781 ✗ i++;
1782 }
1783 // if none selected, use the main segment
1784 ✗ return getMainSegmentId();
1785 }
1786
1787 ✗ void WS2812FX::setMainSegmentId(unsigned n) {
1788 ✗ _mainSegment = 0;
1789 ✗ if (n < _segments.size()) {
1790 ✗ _mainSegment = n;
1791 }
1792 ✗ return;
1793 }
1794
1795 ✗ uint8_t WS2812FX::getLastActiveSegmentId() const {
1796 ✗ for (size_t i = _segments.size() -1; i > 0; i--) {
1797 ✗ if (_segments[i].isActive()) return i;
1798 }
1799 ✗ return 0;
1800 }
1801
1802 51 uint8_t WS2812FX::getActiveSegmentsNum() const {
1803 51 uint8_t c = 0;
1804
2/2
✓ Branch 0 taken 51 times.
✓ Branch 1 taken 51 times.
102 for (size_t i = 0; i < _segments.size(); i++) {
1805
1/2
✓ Branch 0 taken 51 times.
✗ Branch 1 not taken.
51 if (_segments[i].isActive()) c++;
1806 }
1807 51 return c;
1808 }
1809
1810 2904 uint16_t WS2812FX::getLengthTotal() const {
1811 2904 unsigned len = Segment::maxWidth * Segment::maxHeight; // will be _length for 1D (see finalizeInit()) but should cover whole matrix for 2D
1812
2/4
✓ Branch 0 taken 2904 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 2904 times.
2904 if (isMatrix && _length > len) len = _length; // for 2D with trailing strip
1813 2904 return len;
1814 }
1815
1816 ✗ uint16_t WS2812FX::getLengthPhysical() const {
1817 ✗ unsigned len = 0;
1818 ✗ for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
1819 ✗ Bus *bus = BusManager::getBus(b);
1820 ✗ if (bus->isVirtual()) continue; //exclude non-physical network busses
1821 ✗ len += bus->getLength();
1822 }
1823 ✗ return len;
1824 }
1825
1826 //used for JSON API info.leds.rgbw. Little practical use, deprecate with info.leds.rgbw.
1827 //returns if there is an RGBW bus (supports RGB and White, not only white)
1828 //not influenced by auto-white mode, also true if white slider does not affect output white channel
1829 ✗ bool WS2812FX::hasRGBWBus() const {
1830 ✗ for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
1831 ✗ const Bus *bus = BusManager::getBus(b);
1832 ✗ if (!bus || !bus->isOk()) break;
1833 ✗ if (bus->hasRGB() && bus->hasWhite()) return true;
1834 }
1835 ✗ return false;
1836 }
1837
1838 ✗ bool WS2812FX::hasCCTBus() const {
1839 ✗ if (cctFromRgb && !correctWB) return false;
1840 ✗ for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
1841 ✗ const Bus *bus = BusManager::getBus(b);
1842 ✗ if (!bus || !bus->isOk()) break;
1843 ✗ if (bus->hasCCT()) return true;
1844 }
1845 ✗ return false;
1846 }
1847
1848 ✗ void WS2812FX::purgeSegments() {
1849 // remove all inactive segments (from the back)
1850 ✗ int deleted = 0;
1851 ✗ if (_segments.size() <= 1) return;
1852 ✗ for (size_t i = _segments.size()-1; i > 0; i--)
1853 ✗ if (_segments[i].stop == 0) {
1854 ✗ deleted++;
1855 ✗ _segments.erase(_segments.begin() + i);
1856 }
1857 ✗ if (deleted) {
1858 ✗ _segments.shrink_to_fit();
1859 ✗ setMainSegmentId(0);
1860 }
1861 }
1862
1863 ✗ Segment& WS2812FX::getSegment(unsigned id) {
1864 ✗ return _segments[id >= _segments.size() ? getMainSegmentId() : id]; // vectors
1865 }
1866
1867 ✗ void WS2812FX::resetSegments() {
1868 ✗ _segments.clear(); // destructs all Segment as part of clearing
1869 #ifndef WLED_DISABLE_2D
1870 ✗ segment seg = isMatrix ? Segment(0, Segment::maxWidth, 0, Segment::maxHeight) : Segment(0, _length);
1871 #else
1872 segment seg = Segment(0, _length);
1873 #endif
1874 ✗ _segments.push_back(seg);
1875 ✗ _segments.shrink_to_fit(); // just in case ...
1876 ✗ _mainSegment = 0;
1877 ✗ }
1878
1879 ✗ void WS2812FX::makeAutoSegments(bool forceReset) {
1880 ✗ if (autoSegments) { //make one segment per bus
1881 ✗ unsigned segStarts[MAX_NUM_SEGMENTS] = {0};
1882 ✗ unsigned segStops [MAX_NUM_SEGMENTS] = {0};
1883 ✗ size_t s = 0;
1884
1885 #ifndef WLED_DISABLE_2D
1886 // 2D segment is the 1st one using entire matrix
1887 ✗ if (isMatrix) {
1888 ✗ segStarts[0] = 0;
1889 ✗ segStops[0] = Segment::maxWidth*Segment::maxHeight;
1890 ✗ s++;
1891 }
1892 #endif
1893
1894 ✗ for (size_t i = s; i < BusManager::getNumBusses(); i++) {
1895 ✗ const Bus *bus = BusManager::getBus(i);
1896 ✗ if (!bus || !bus->isOk()) break;
1897
1898 ✗ segStarts[s] = bus->getStart();
1899 ✗ segStops[s] = segStarts[s] + bus->getLength();
1900
1901 #ifndef WLED_DISABLE_2D
1902 ✗ if (isMatrix && segStops[s] <= Segment::maxWidth*Segment::maxHeight) continue; // ignore buses comprising matrix
1903 ✗ if (isMatrix && segStarts[s] < Segment::maxWidth*Segment::maxHeight) segStarts[s] = Segment::maxWidth*Segment::maxHeight;
1904 #endif
1905
1906 //check for overlap with previous segments
1907 ✗ for (size_t j = 0; j < s; j++) {
1908 ✗ if (segStops[j] > segStarts[s] && segStarts[j] < segStops[s]) {
1909 //segments overlap, merge
1910 ✗ segStarts[j] = min(segStarts[s],segStarts[j]);
1911 ✗ segStops [j] = max(segStops [s],segStops [j]); segStops[s] = 0;
1912 ✗ s--;
1913 }
1914 }
1915 ✗ s++;
1916 }
1917
1918 ✗ _segments.clear();
1919 ✗ _segments.reserve(s); // prevent reallocations
1920 // there is always at least one segment (but we need to differentiate between 1D and 2D)
1921 #ifndef WLED_DISABLE_2D
1922 ✗ if (isMatrix)
1923 ✗ _segments.push_back(Segment(0, Segment::maxWidth, 0, Segment::maxHeight));
1924 else
1925 #endif
1926 ✗ _segments.push_back(Segment(segStarts[0], segStops[0]));
1927 ✗ for (size_t i = 1; i < s; i++) {
1928 ✗ _segments.push_back(Segment(segStarts[i], segStops[i]));
1929 }
1930 DEBUG_PRINTF_P(PSTR("%d auto segments created.\n"), _segments.size());
1931
1932 } else {
1933
1934 ✗ if (forceReset || getSegmentsNum() == 0) resetSegments();
1935 //expand the main seg to the entire length, but only if there are no other segments, or reset is forced
1936 ✗ else if (getActiveSegmentsNum() == 1) {
1937 ✗ size_t i = getLastActiveSegmentId();
1938 #ifndef WLED_DISABLE_2D
1939 ✗ _segments[i].start = 0;
1940 ✗ _segments[i].stop = Segment::maxWidth;
1941 ✗ _segments[i].startY = 0;
1942 ✗ _segments[i].stopY = Segment::maxHeight;
1943 ✗ _segments[i].grouping = 1;
1944 ✗ _segments[i].spacing = 0;
1945 #else
1946 _segments[i].start = 0;
1947 _segments[i].stop = _length;
1948 #endif
1949 }
1950 }
1951 ✗ _mainSegment = 0;
1952
1953 ✗ fixInvalidSegments();
1954 ✗ }
1955
1956 ✗ void WS2812FX::fixInvalidSegments() {
1957 //make sure no segment is longer than total (sanity check)
1958 ✗ for (size_t i = getSegmentsNum()-1; i > 0; i--) {
1959 ✗ if (isMatrix) {
1960 #ifndef WLED_DISABLE_2D
1961 ✗ if (_segments[i].start >= Segment::maxWidth * Segment::maxHeight) {
1962 // 1D segment at the end of matrix
1963 ✗ if (_segments[i].start >= _length || _segments[i].startY > 0 || _segments[i].stopY > 1) { _segments.erase(_segments.begin()+i); continue; }
1964 ✗ if (_segments[i].stop > _length) _segments[i].stop = _length;
1965 ✗ continue;
1966 }
1967 ✗ if (_segments[i].start >= Segment::maxWidth || _segments[i].startY >= Segment::maxHeight) { _segments.erase(_segments.begin()+i); continue; }
1968 ✗ if (_segments[i].stop > Segment::maxWidth) _segments[i].stop = Segment::maxWidth;
1969 ✗ if (_segments[i].stopY > Segment::maxHeight) _segments[i].stopY = Segment::maxHeight;
1970 #endif
1971 } else {
1972 ✗ if (_segments[i].start >= _length) { _segments.erase(_segments.begin()+i); continue; }
1973 ✗ if (_segments[i].stop > _length) _segments[i].stop = _length;
1974 }
1975 }
1976 // if any segments were deleted free memory
1977 ✗ purgeSegments();
1978 // this is always called as the last step after finalizeInit(), update covered bus types
1979 ✗ for (segment &seg : _segments)
1980 ✗ seg.refreshLightCapabilities();
1981 ✗ }
1982
1983 //true if all segments align with a bus, or if a segment covers the total length
1984 //irrelevant in 2D set-up
1985 ✗ bool WS2812FX::checkSegmentAlignment() const {
1986 ✗ bool aligned = false;
1987 ✗ for (const segment &seg : _segments) {
1988 ✗ for (unsigned b = 0; b<BusManager::getNumBusses(); b++) {
1989 ✗ const Bus *bus = BusManager::getBus(b);
1990 ✗ if (!bus || !bus->isOk()) break;
1991 ✗ if (seg.start == bus->getStart() && seg.stop == bus->getStart() + bus->getLength()) aligned = true;
1992 }
1993 ✗ if (seg.start == 0 && seg.stop == _length) aligned = true;
1994 ✗ if (!aligned) return false;
1995 }
1996 ✗ return true;
1997 }
1998
1999 // used by analog clock overlay
2000 ✗ void WS2812FX::setRange(uint16_t i, uint16_t i2, uint32_t col) {
2001 ✗ if (i2 < i) std::swap(i,i2);
2002 ✗ for (unsigned x = i; x <= i2; x++) setPixelColor(x, col);
2003 ✗ }
2004
2005 #ifdef WLED_DEBUG
2006 void WS2812FX::printSize() {
2007 size_t size = 0;
2008 for (const Segment &seg : _segments) size += seg.getSize();
2009 DEBUG_PRINTF_P(PSTR("Segments: %d -> %u/%dB\n"), _segments.size(), size, Segment::getUsedSegmentData());
2010 for (const Segment &seg : _segments) DEBUG_PRINTF_P(PSTR(" Seg: %d,%d [A=%d, 2D=%d, RGB=%d, W=%d, CCT=%d]\n"), seg.width(), seg.height(), seg.isActive(), seg.is2D(), seg.hasRGB(), seg.hasWhite(), seg.isCCT());
2011 DEBUG_PRINTF_P(PSTR("Modes: %d*%d=%uB\n"), sizeof(mode_ptr), _mode.size(), (_mode.capacity()*sizeof(mode_ptr)));
2012 DEBUG_PRINTF_P(PSTR("Data: %d*%d=%uB\n"), sizeof(const char *), _modeData.size(), (_modeData.capacity()*sizeof(const char *)));
2013 DEBUG_PRINTF_P(PSTR("Map: %d*%d=%uB\n"), sizeof(uint16_t), (int)customMappingSize, customMappingSize*sizeof(uint16_t));
2014 }
2015 #endif
2016
2017 4455 void WS2812FX::loadCustomPalettes() {
2018 #ifndef WLED_DISABLE_FPP
2019 byte tcp[72]; //support gradient palettes with up to 18 entries
2020 CRGBPalette16 targetPalette;
2021 customPalettes.clear(); // start fresh
2022 for (int index = 0; index<10; index++) {
2023 char fileName[32];
2024 sprintf_P(fileName, PSTR("/palette%d.json"), index);
2025
2026 StaticJsonDocument<1536> pDoc; // barely enough to fit 72 numbers
2027 if (WLED_FS.exists(fileName)) {
2028 DEBUG_PRINT(F("Reading palette from "));
2029 DEBUG_PRINTLN(fileName);
2030
2031 if (readObjectFromFile(fileName, nullptr, &pDoc)) {
2032 JsonArray pal = pDoc[F("palette")];
2033 if (!pal.isNull() && pal.size()>3) { // not an empty palette (at least 2 entries)
2034 if (pal[0].is<int>() && pal[1].is<const char *>()) {
2035 // we have an array of index & hex strings
2036 size_t palSize = MIN(pal.size(), 36);
2037 palSize -= palSize % 2; // make sure size is multiple of 2
2038 for (size_t i=0, j=0; i<palSize && pal[i].as<int>()<256; i+=2, j+=4) {
2039 uint8_t rgbw[] = {0,0,0,0};
2040 tcp[ j ] = (uint8_t) pal[ i ].as<int>(); // index
2041 colorFromHexString(rgbw, pal[i+1].as<const char *>()); // will catch non-string entires
2042 for (size_t c=0; c<3; c++) tcp[j+1+c] = gamma8(rgbw[c]); // only use RGB component
2043 DEBUG_PRINTF_P(PSTR("%d(%d) : %d %d %d\n"), i, int(tcp[j]), int(tcp[j+1]), int(tcp[j+2]), int(tcp[j+3]));
2044 }
2045 } else {
2046 size_t palSize = MIN(pal.size(), 72);
2047 palSize -= palSize % 4; // make sure size is multiple of 4
2048 for (size_t i=0; i<palSize && pal[i].as<int>()<256; i+=4) {
2049 tcp[ i ] = (uint8_t) pal[ i ].as<int>(); // index
2050 tcp[i+1] = gamma8((uint8_t) pal[i+1].as<int>()); // R
2051 tcp[i+2] = gamma8((uint8_t) pal[i+2].as<int>()); // G
2052 tcp[i+3] = gamma8((uint8_t) pal[i+3].as<int>()); // B
2053 DEBUG_PRINTF_P(PSTR("%d(%d) : %d %d %d\n"), i, int(tcp[i]), int(tcp[i+1]), int(tcp[i+2]), int(tcp[i+3]));
2054 }
2055 }
2056 customPalettes.push_back(targetPalette.loadDynamicGradientPalette(tcp));
2057 } else {
2058 DEBUG_PRINTLN(F("Wrong palette format."));
2059 }
2060 }
2061 } else {
2062 break;
2063 }
2064 }
2065 #endif
2066 4455 }
2067
2068 //load custom mapping table from JSON file (called from finalizeInit() or deserializeState())
2069 4455 bool WS2812FX::deserializeMap(unsigned n) {
2070 // 2D support creates its own ledmap (on the fly) if a ledmap.json exists it will overwrite built one.
2071 #ifndef WLED_DISABLE_FPP
2072
2073 char fileName[32];
2074 strcpy_P(fileName, PSTR("/ledmap"));
2075 if (n) sprintf(fileName +7, "%d", n);
2076 strcat_P(fileName, PSTR(".json"));
2077 bool isFile = WLED_FS.exists(fileName);
2078
2079 customMappingSize = 0; // prevent use of mapping if anything goes wrong
2080 currentLedmap = 0;
2081 if (n == 0 || isFile) interfaceUpdateCallMode = CALL_MODE_WS_SEND; // schedule WS update (to inform UI)
2082
2083 if (!isFile && n==0 && isMatrix) {
2084 setUpMatrix();
2085 return false;
2086 }
2087
2088 if (!isFile || !requestJSONBufferLock(7)) return false;
2089
2090 StaticJsonDocument<64> filter;
2091 filter[F("width")] = true;
2092 filter[F("height")] = true;
2093 if (!readObjectFromFile(fileName, nullptr, pDoc, &filter)) {
2094 DEBUG_PRINT(F("ERROR Invalid ledmap in ")); DEBUG_PRINTLN(fileName);
2095 releaseJSONBufferLock();
2096 return false; // if file does not load properly then exit
2097 }
2098
2099 suspend();
2100
2101 JsonObject root = pDoc->as<JsonObject>();
2102 // if we are loading default ledmap (at boot) set matrix width and height from the ledmap (compatible with WLED MM ledmaps)
2103 if (isMatrix && n == 0 && (!root[F("width")].isNull() || !root[F("height")].isNull())) {
2104 Segment::maxWidth = min(max(root[F("width")].as<int>(), 1), 128);
2105 Segment::maxHeight = min(max(root[F("height")].as<int>(), 1), 128);
2106 }
2107
2108 if (customMappingTable) free(customMappingTable);
2109 customMappingTable = static_cast<uint16_t*>(malloc(sizeof(uint16_t)*getLengthTotal()));
2110 if (customMappingTable) {
2111 DEBUG_PRINT(F("Reading LED map from ")); DEBUG_PRINTLN(fileName);
2112 File f = WLED_FS.open(fileName, "r");
2113 f.find("\"map\":[");
2114 while (f.available()) { // f.position() < f.size() - 1
2115 char number[32];
2116 size_t numRead = f.readBytesUntil(',', number, sizeof(number)-1); // read a single number (may include array terminating "]" but not number separator ',')
2117 number[numRead] = 0;
2118 if (numRead > 0) {
2119 char *end = strchr(number,']'); // we encountered end of array so stop processing if no digit found
2120 bool foundDigit = (end == nullptr);
2121 int i = 0;
2122 if (end != nullptr) do {
2123 if (number[i] >= '0' && number[i] <= '9') foundDigit = true;
2124 if (foundDigit || &number[i++] == end) break;
2125 } while (i < 32);
2126 if (!foundDigit) break;
2127 int index = atoi(number);
2128 if (index < 0 || index > 16384) index = 0xFFFF;
2129 customMappingTable[customMappingSize++] = index;
2130 if (customMappingSize > getLengthTotal()) break;
2131 } else break; // there was nothing to read, stop
2132 }
2133 currentLedmap = n;
2134 f.close();
2135
2136 #ifdef WLED_DEBUG
2137 DEBUG_PRINT(F("Loaded ledmap:"));
2138 for (unsigned i=0; i<customMappingSize; i++) {
2139 if (!(i%Segment::maxWidth)) DEBUG_PRINTLN();
2140 DEBUG_PRINTF_P(PSTR("%4d,"), customMappingTable[i]);
2141 }
2142 DEBUG_PRINTLN();
2143 #endif
2144 /*
2145 JsonArray map = root[F("map")];
2146 if (!map.isNull() && map.size()) { // not an empty map
2147 customMappingSize = min((unsigned)map.size(), (unsigned)getLengthTotal());
2148 for (unsigned i=0; i<customMappingSize; i++) customMappingTable[i] = (uint16_t) (map[i]<0 ? 0xFFFFU : map[i]);
2149 currentLedmap = n;
2150 }
2151 */
2152 } else {
2153 DEBUG_PRINTLN(F("ERROR LED map allocation error."));
2154 }
2155 #else
2156 4455 setUpMatrix();
2157
2158 #endif
2159
2160 4455 resume();
2161
2162 4455 releaseJSONBufferLock();
2163 4455 return (customMappingSize > 0);
2164 }
2165
2166
2167 const char JSON_mode_names[] PROGMEM = R"=====(["FX names moved"])=====";
2168 const char JSON_palette_names[] PROGMEM = R"=====([
2169 "Default","* Random Cycle","* Color 1","* Colors 1&2","* Color Gradient","* Colors Only","Party","Cloud","Lava","Ocean",
2170 "Forest","Rainbow","Rainbow Bands","Sunset","Rivendell","Breeze","Red & Blue","Yellowout","Analogous","Splash",
2171 "Pastel","Sunset 2","Beach","Vintage","Departure","Landscape","Beech","Sherbet","Hult","Hult 64",
2172 "Drywet","Jul","Grintage","Rewhi","Tertiary","Fire","Icefire","Cyane","Light Pink","Autumn",
2173 "Magenta","Magred","Yelmag","Yelblu","Orange & Teal","Tiamat","April Night","Orangery","C9","Sakura",
2174 "Aurora","Atlantica","C9 2","C9 New","Temperature","Aurora 2","Retro Clown","Candy","Toxy Reaf","Fairy Reaf",
2175 "Semi Blue","Pink Candy","Red Reaf","Aqua Flash","Yelblu Hot","Lite Light","Red Flash","Blink Red","Red Shift","Red Tide",
2176 "Candy2","Traffic Light"
2177 ])=====";
2178