Repository navigation
Description
With 0.14 we've got proper blending of color and palettes across all segments, 0.15 improved on that and allowed effects to be blended as well. Recent blending styles (#4158) introduced effect transitions with different styles.
What is missing IMO is correct segment blending/layering with different blending modes known to Photoshop users, i.e. lighten, darken, multiply, add, subtract, difference, etc.
I've recently come across a snippet that I find useful and relatively simple to implement in WLED. Unfortunately it would require re-implementation of pixel drawing functions.
Let's first see the code and then discuss the nuances:
void WS2812FX::blendSegments(const Segment &top, const Segment &bottom) {
constexpr auto top = [](uint8_t a, uint8_t b){ return a; };
constexpr auto bottom = [](uint8_t a, uint8_t b){ return b; };
constexpr auto add = [](uint8_t a, uint8_t b){ return a + b; };
constexpr auto subtract = [](uint8_t a, uint8_t b){ return b > a ? (b - a) : 0; };
constexpr auto difference = [](uint8_t a, uint8_t b){ return b > a ? (b - a) : (a - b); };
constexpr auto average = [](uint8_t a, uint8_t b){ return (a + b) >> 1; };
constexpr auto multiply = [](uint8_t a, uint8_t b){ return a * b; };
constexpr auto divide = [](uint8_t a, uint8_t b){ return b != 0 ? a / b : 0; };
constexpr auto lighten = [](uint8_t a, uint8_t b){ return a>b ? a : b; };
constexpr auto darken = [](uint8_t a, uint8_t b){ return a<b ? a : b; };
constexpr auto screen = [](uint8_t a, uint8_t b){ return uint8_t(0xFF - ~a * ~b); }; // 255 - (255-a)*(255-b)
constexpr auto overlay = [](uint8_t a, uint8_t b){ return uint8_t(a<0x80 ? 2*a*b : (0xFF - 2 * ~a * ~b)); };
using FuncType = uint8_t(*)(uint8_t, uint8_t);
FuncType funcs[] = {
top, bottom, add, subtract, difference, average, multiply, divide, lighten, darken, screen, overlay
};
const uint8_t blendMode = top.blendMode;
auto func = funcs[blendMode % (sizeof(funcs) / sizeof(FuncType))];
for (auto i = 0; i<top.length(); i++) {
uint32_t c_a = top.getPixelColor(i);
uint32_t c_b = bottom.getPixelColor(i);
auto r_a = R(c_a);
auto g_a = G(c_a);
auto b_a = B(c_a);
auto w_a = W(c_a);
auto r_b = R(c_b);
auto g_b = G(c_b);
auto b_b = B(c_b);
auto w_b = W(c_b);
pixels[i] = RGBW32(func(r_a,r_b), func(g_a,g_b), func(b_a,b_b), func(w_a,w_b));
}
}This assumes that Segment::getPixelColor() returns unmodified value set by Segment::setPixelColor() during effect execution. To achieve that, each segment must maintain its own pixel drawing buffer (also known in the past as setUpLeds())
Next it also assumes WS2812FX instance will maintain its entire canvas buffer (called pixels[]; similar to global buffer).
The process with which segments/layers would be blended is:
- render each effect in its segment buffer (entirely independent and unaware of other segments)
- blend all segment buffers into canvas buffer starting with black canvas and adding segments from bottom to top
- transfer canvas buffer to LEDs
This process does not handle color/palette blending (which does not change from current) or effect transition (from one effect to another) but only allows users to stack segments one atop another which would allow mixing of content of two segments even if effect function does not support layering.
The price is of course memory and (possibly) speed degradation as there will be more operations per pixel. However, segment's setPixelColor()/getPixelColor() could be simplified and there would be no need for WS2812FX::setPixelColor().
I would like to get some feedback and thoughts about layering and the implementation. An if it is worth the effort even if speed would be impaired.
Activity
willmmiles commentedon Feb 13, 2025
Your proposed pipeline is more-or-less how I'd've expected WLED to be implemented, before I got in to the actual code. I'd thought of it more of "segment" renders to a texture buffer; textures are then rendered to the frame buffer (with grouping, spacing, any other stretching/scaling transformations going on here); and finally the frame buffer is mapped to pixels on the outputs bus(es).
Memory costs aside: we've observed in prototype implementations that having the FX write directly to local texture buffers (
setUpLeds()style) can often yield an FPS speedup. There's potential that pipelining the other aspects (texture to frame buffer, and frame to physical) may also yield net speed improvements as the code for each phase becomes simpler -- less indirection, fewer conditionals, and easier to fit in cache. Some ESP models (S3, I'm looking at you!) also offer SIMD instructions that can also further accelerate pipelined simple transforms.Lastly I think the pipelined approach will also make the code simpler and easier to follow. The key is breaking "Segment" down into the component parts -- the FX renderer, the texture->frame renderer, and the physical mapper can all be pulled into individual stages and components instead of packing everything into one giant class.
blazoncek commentedon Feb 14, 2025
Thanks. This is an interesting approach which indeed simplifies single segment processing (and reduces memory requirements) but will inevitably create blending into "frame buffer" more complex (imagine two partially overlapping segments with spacing and grouping set).
I would leave frame buffer to physical mapping in the bus level logic but that would make anything but Cartesian coordinate system difficult to implement (mapping arbitrary 3D location of pixels into frame rendering logic, especially sparse set-up). But we can leave this mapping out of the scope of this discussion.
DedeHai commentedon Feb 14, 2025
In general I think this is a good approach!
Some thoughts:
just an idea: use a "mask" checkmark in segment settings to treat an FX as a transparency mask instead of using its colors, the mask could be R+G+B or even something more elaborate.
willmmiles commentedon Feb 14, 2025
By "frame buffer", I mean what you are calling a "canvas buffer": a single global buffer of all LEDs in the virtual space to which all segments are rendered, top to bottom, for each output frame (eg. show() call). I would expect that segment spacing and grouping would be best implemented as part of the segment->canvas render process -- if output canvas coordinates overlap from one segment to the next, you blend; if not, they'll end up interleaved as expected.
Mostly I was trying to highlight that I had expected an implementation with the same sequence of concepts, but I'd've used different names -- I don't think there's any significant difference between what I described and what you proposed.
willmmiles commentedon Feb 14, 2025
RGBA at the FX level would be very practical if we're serious about considering blending, I think...
If we really want to get radical, I'd also float the idea of struct-of-arrays instead of array-of-structs, eg.
struct pixel_buf { vector<uint8_t> R, G, B, A; };I've heard tell that some algorithms can operate much faster in this space. Loop unrolling can make it quite efficient, and it vectorizes to SIMD instructions well.This is the true crux of this approach. If we move to this architecture, the solution might be to explicitly develop a sparse canvas buffer abstraction. Sparse matrices have a lot of prior art in numeric processing code, I'm sure there's some insights there that could be helpful.
blazoncek commentedon Feb 14, 2025
If we introduce alpha channel (instead of W in effect functions) I would assume it only applies to that segment in regards to blending it with lower segment. Right?
Would it only be used when blending into frame/canvas buffer alongside segment's opacity? Even though it would work on pixel level that's sort of duplicate functionality IMO.
I do admit that it will open new possibilities when writing new effects, but none of current effects are written to utilise it so there will be no immediate gain.
So, if I summarize what we've defined so far:
uint32_t; RGBA, but A my be interpreted as W for some effects)setPixelColor()operates on "condensed" segment without grouping and spacing (currentvirtualLength()orvirtualWidth()/virtualHeight()) writing only to pixel bufferstrip.show()functionCaveats:
willmmiles commentedon Feb 14, 2025
Yes -- I'd expect segment-level opacity to apply "on top" of the FX computed alpha channel, much the same way segment-level brightness applies "on top" of the FX computed colors. IIRC the computation is something like
blend_A = pixel[index].A * segment.A / 255-- we don't have to blend twice.Maybe
Segmentwants a "buffer type" indicator, set or carried by the FX selection, to inform the blending layer how to composite the segment to the canvas.Bikeshedding a bit, but I'd probably put the canvas to bus functionality in its own free function(s) to start off with. Some
renderToBus(Bus&, canvas, ledmap)type call. This operation is not really involved in managing buses, so IMHO it doesn't belong to BusManager.I think it's reasonable to flush everything (segments, transitions, etc.) and start clean if the bus configuration changes. If we can't re-allocate everything from a clean slate, the config is in trouble anyways...
One neat feature of this architecture is that transitions can be implemented as part of canvas composition -- each segment need only contain enough information for the compositor to know which pixels to draw. So I'd suggest trying a broad approach of "don't re-use segments or buffers at all" as the place to start.
From there we can explore progressively more sophisticated fallbacks to handle cases where memory is tight. Some ideas:
esp_mmu_map()The segment object itself shouldn't be big enough to matter (compared to the pixel buffers), so we can just allocate new ones whenever it's convenient.
This is on my todo list already -- the render loop really needs to be mutexed with any source of segment state changes. Every platform we support has multiple tasks, even ESP8266! I believe this may be responsible for some crash cases in some configurations in the current code. I haven't had time to look at it yet -- either we want a new "render state lock", or we can expand the scope of the current JSON buffer lock to cover any case of reading/writing the core state.
blazoncek commentedon Feb 15, 2025
Just a thought that sparked: We have to distinguish effect transitions (i.e. change form one effect to another), color transition and palette transition. Each of those apply to one segment only. With transition styles two effect runs may be necessary (this part needs tweaking).
Transitionstruct is responsible for holding old/temporary values and buffers.These have nothing to do with layer/segment blending.
@willmmiles I will read your post again when I have more time and properly reply.
blazoncek commentedon Feb 15, 2025
I pushed a brief 1D untested POC. 2D shouldn't be more difficult but that was all I managed to conjure today.
https://github.com/blazoncek/WLED/tree/layer-blend
blazoncek commentedon Feb 16, 2025
I think blending is now completely implemented.
All of the rendering to frame buffer happens in
blendSegment()which is called inservice()just beforeshow().It may need a review from @DedeHai as raw setPixelColorXY had his optimisation which I moved into
blendSegment().Segment's
setPixelColor()now only stores pixel value in localpixelsarray. It does no mirroring or reversing (or transposing in XY variant) or spacing or grouping. Some effects that were modified to keep previous pixel values in_databuffer may need another rewrite to remove those modifications as they have become obsolete.@willmmiles if you have the time please take a look. There are 3 relevant commits.
willmmiles commentedon Feb 17, 2025
I wish I had more time to spend - code would speak more precisely than words. :(
I'm suggesting implementing all transitions as running the effect twice with different settings, and using dynamic blending to actually effect the visible transition. For example, for a brightness change: the old copy keeps running with the old brightness, the new copy runs with the new brightness, and the alpha used for blending shifts over time from one to the other.
The basic implementation is some "struct transition_instructions" on each segment that the blending layer uses to modify the segment parameters before blending is executed. Traditional blending is done by altering the blending alpha; push/swipe/etc. alter the target canvas coordinates; and so forth.
It makes the code simple and the transitions easy to implement, no matter what the actual transition style is. (In fact you also get clever things like transitions that work even if segment boundaries change!) Each transition style is implemented as a time-varying change to the blending, where "old" and "new" segments get opposite transition states (eg. one counts down, the other counts up).
Then, once that's working well, allow FX to opt in to optimized transitions when the right conditions match. Each FX gets to decide what transition optimizations they support, eg. single FX call for color/palette blending, smooth settings changes, etc. -- only for certain blending styles, or only if segment size hasn't changed, and so on and so forth. The neat implemention trick is that these optimized blendings can be "just another bit of state" in the transition_instructions that adjusts the segment parameters before the FX renderer is called.
You may note I am glossing over what happens to FX state data during transition. Truthfully, we need to move past
allocateData()and on to proper FX setup/copy/move routines; @DedeHai's particle system clearly demonstrates the need for and value of having more structure there. Letting each FX setup know about the type of, and interact with the data from previous FX state (copy it, move it, or whatever makes sense!) offers a number of opportunities for improved displays. (And will also likely offer yet another some small FX speedups, as state data checking can be moved to Segment creation time.)Thanks, I'll take a look when I've got time to do a proper review - probably won't be until later in the week. I'm rather behind at the moment. :(
blazoncek commentedon Feb 17, 2025
That's why all my replies tend to be short. 😄
That's how it is implemented in my branch.
Clipping pixels happen in
Segment::setPixelColor().Segment::setPixelColor()no longer callsWS2812FX::setPixelColor(), it only fills segmen's pixel buffer. On the other handSegment::getPixelColor()returns value from pixel buffer.All of the magic happens in
WS2812FX::service(). With a bit of help from `Segment::setClippingRect().Caveat: This approach may interfere with live data (i.e. DDP, Art-Net, E1.31) as that still directly writes to NPB.
blazoncek commentedon Feb 17, 2025
And ... it works!!!!
18 remaining items
DedeHai commentedon Aug 30, 2025
@robertvb83 that is a good point, thanks for finding this.
I think since text overlay is used a lot, this should be possible. I will add a new blending style "stencil" that just puts whatever is not black on top of underlaying segments.
TripleWhy commentedon Aug 30, 2025
Well photoshop has something wled doesn't: alpha channels. I guess you could emulate alpha channels the following way:
0: base layer with purple sparkle
1: mask layer with black on white text, in multiply mode
2: color layer with blue on black text, in addition mode
However, apparently, black on white text isn't possible for some reason. (And with blending modes, this reason might be obsolete.)
I also tried to trick WLED into producing this with the new copy segment color changing thing, but it has no invert option (and no darken, just lighten options).
DedeHai commentedon Aug 30, 2025
Copy segment has no darken option because you can use segment brightness to do that, however, it will apply that after blending.
We did discuss using the currently unused white channel (unused in FX not in general) of RGBW buffer as an alpha channel but it is unclear on how that would be put to good use and the copy FX + layer blending kind of makes it redundant. I am sure there are some cases where having an alpha channel would be useful.
blazoncek commentedon Aug 30, 2025
Workaround as suggested by @TripleWhy :
FYI I'm already working on alpha channel but may not be available immediately.
robertvb83 commentedon Aug 30, 2025
I tested the workaround but still get white pixels in the text
blazoncek commentedon Aug 30, 2025
Leave Gr black.
robertvb83 commentedon Aug 30, 2025
This does not change the outcome, still white pixels
blazoncek commentedon Aug 30, 2025
It does work on my end. However, if text scrolls both text segments need to be restarted at the same time.
willmmiles commentedon Aug 30, 2025
The general term for this approach is "chroma key". I'd recommend using the FX background color as the "transparent" color instead of hardcoding black.
robertvb83 commentedon Aug 30, 2025
Using the effects bg color does not work, but i played around with colors a bit and found, if i set the middle text color to green, it seems to work. Maybe you get a clue why?
willmmiles commentedon Aug 30, 2025
I was commenting on @DedeHai 's suggestion of implementing a new blending style. It's not written yet.
TripleWhy commentedon Aug 30, 2025
It works because green is the complementary color of magenta. When you multiply them, they cancel out. This works in your specific case, but I was trying to come up with a general approach. And I was using multiply mode to get something similar to alpha channels. If you just need a stencil mask, using white on black with in subtract mode for the middle layer will also work.
(For this approach, a copy segment effect that could turn white into blue would again eliminate the need to synchronize the text layers.)
TripleWhy commentedon Aug 30, 2025
Sorry for the spam, but the other way round works, of course:
0: base layer with purple sparkle
1: mask layer with copy segment 2, lighten 255, in subtract mode
2: color layer with blue on black text, in addition mode
DedeHai commentedon Aug 30, 2025
It is now :)
blazoncek commentedon Aug 30, 2025
@willmmiles not all effects have background color.