Skip to content

Added new effect usermod - Diffusion Fire #4667

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

mryndzionek
Copy link

@mryndzionek mryndzionek commented Apr 29, 2025

Updated PR #4473

Summary by CodeRabbit

  • New Features
    • Introduced a new usermod for custom LED effects, including a "Diffusion Fire" animation for 2D LED matrices.
  • Documentation
    • Added a README describing the purpose of the usermod and its usage.
  • Chores
    • Added a library metadata file for the new usermod.
    • Assigned a unique ID for the usermod in the system.

Copy link
Contributor

coderabbitai bot commented Apr 29, 2025

Walkthrough

This update introduces a new usermod named "user_fx" designed to provide custom LED effects for a 2D LED matrix. The changes add a new module directory containing a README, a library descriptor, source and header files implementing the usermod, and an updated constant definition for the usermod ID. The usermod implements two effect modes: a static mode and a "Diffusion Fire" animation, with logic for effect parameters, palette usage, and memory management. The module is integrated into the system through setup and registration mechanisms, and its unique ID is defined in the global constants header.

Changes

Files/Paths Change Summary
usermods/user_fx/README.md Added a README describing the purpose of the "user_fx" usermod as a repository for user LED effects.
usermods/user_fx/library.json Added a library descriptor JSON file with the module name.
usermods/user_fx/user_fx.cpp
usermods/user_fx/user_fx.h
Introduced the "UserFxUsermod" class implementing and declaring setup, loop, and getId methods; provides static and "Diffusion Fire" LED effects for a 2D matrix.
wled00/const.h Added a new usermod ID constant: USERMOD_ID_USER_FX with value 58.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d54bb92 and 7abc5d2.

📒 Files selected for processing (2)
  • usermods/user_fx/library.json (1 hunks)
  • usermods/user_fx/user_fx.cpp (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • usermods/user_fx/user_fx.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • usermods/user_fx/library.json
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (7)
usermods/user_fx/README.md (1)

1-4: Consider enhancing documentation.

While the README provides a basic explanation of the usermod's purpose, it would be more helpful for users if you included:

  • Description of the included effects (e.g., Diffusion Fire)
  • Configuration parameters
  • Example usage
  • Any dependencies or requirements
usermods/user_fx/user_fx.h (1)

1-12: Class structure looks good, but consider adding documentation.

The UserFxUsermod class follows standard WLED usermod structure with the required methods. Consider:

  1. Adding comments to describe what each method does
  2. Including documentation for the "Diffusion Fire" effect mentioned in the summary
  3. Declaring any private member variables needed for the effects

This will improve maintainability and make it easier for others to contribute to or use your code.

usermods/user_fx/user_fx.cpp (5)

13-14: Remove the unused call counter

call is written but never read, so it produces dead code and wasted RAM.

-  static uint32_t call = 0;
...
-    call = 0;
...
-    call++;

Also applies to: 34-41


42-48: Replace byte-wise scroll with memmove to cut copy time by ~3×

Nested loops copy one byte at a time. A single memmove per row is both clearer and faster, especially on ESP32 where memcpy is optimised.

-    for (unsigned y = 1; y < rows; y++)
-      for (unsigned x = 0; x < cols; x++) {
-        unsigned src = XY(x, y);
-        unsigned dst = XY(x, y - 1);
-        SEGMENT.data[dst] = SEGMENT.data[src];
-      }
+    for (unsigned y = 1; y < rows; y++) {
+      memmove(&SEGMENT.data[XY(0, y - 1)],
+              &SEGMENT.data[XY(0, y)],
+              cols);                     // copy whole row in one shot
+    }

71-71: Scratch buffer is wider (uint16_t) than necessary

tmp_row stores values clamped to 0-255, yet each cell consumes 2 bytes.
Switching to uint8_t halves RAM consumption and removes the alignment headache mentioned earlier.


86-87: Consider returning refresh_ms for power-saving

The function always returns FRAMETIME (~16 ms) even when the effect is configured for a slower refresh_ms (e.g. 50 ms).
Returning the actual period lets WLED sleep longer and reduces CPU-load on constrained boards.
If FRAMETIME is required by the engine, a brief comment would help future maintainers understand the choice.


5-5: Out-of-bounds safety for XY() macro

XY() blindly computes x + SEG_W * y. A stray index can corrupt memory.
Adding a debug assertion (or at least documenting the expectation) prevents painful pixel-buffer overruns in user presets.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f721efc and 14653f8.

📒 Files selected for processing (5)
  • usermods/user_fx/README.md (1 hunks)
  • usermods/user_fx/library.json (1 hunks)
  • usermods/user_fx/user_fx.cpp (1 hunks)
  • usermods/user_fx/user_fx.h (1 hunks)
  • wled00/const.h (1 hunks)
🔇 Additional comments (2)
wled00/const.h (1)

213-213: Properly registered new usermod ID.

The USERMOD_ID_USER_FX constant with value 58 is correctly defined, following the sequential numbering pattern of existing usermod IDs.

usermods/user_fx/user_fx.cpp (1)

50-56: Turbulence parameter appears inverted – please confirm intent

The current logic only spawns sparks when random8() > turbulence.
That means raising turbulence actually decreases spark probability, which feels counter-intuitive for a “turbulence” control.
Verify whether the comparison should be < instead.

Comment on lines 27 to 30
unsigned dataSize = SEGMENT.length() + (cols * sizeof(uint16_t));
if (!SEGENV.allocateData(dataSize))
return mode_static(); // allocation failed

Copy link
Contributor

@coderabbitai coderabbitai bot Apr 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid re-allocating the scratch buffer every frame

SEGENV.allocateData() is invoked on every call even after memory has been assigned, which can lead to heap fragmentation and skips a precious few µs of CPU time per frame.

-  if (!SEGENV.allocateData(dataSize))
+  if (SEGENV.data == nullptr && !SEGENV.allocateData(dataSize))
     return mode_static();  // allocation failed
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
unsigned dataSize = SEGMENT.length() + (cols * sizeof(uint16_t));
if (!SEGENV.allocateData(dataSize))
return mode_static(); // allocation failed
unsigned dataSize = SEGMENT.length() + (cols * sizeof(uint16_t));
- if (!SEGENV.allocateData(dataSize))
+ if (SEGENV.data == nullptr && !SEGENV.allocateData(dataSize))
return mode_static(); // allocation failed

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is ok as allocateData() does its checks.
Even though SEGENV.data is not null it may point to a memory not allocated by the effect and may not be of correct size.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No description provided.

@DedeHai
Copy link
Collaborator

DedeHai commented Apr 29, 2025

thanks for updating, can you close the other PR?
what is the purpose of the header file?
also, pay attention to what the rabbit sais, it is right about the alignment and the error in the json file.

Can you add a short description of your effect in the readme? if more FX are added, it will give a good overview of what these effect do and are intended for.

@mryndzionek
Copy link
Author

what is the purpose of the header file?

Just followed the other usermods. Also, the new system won't pick up header files.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
usermods/user_fx/user_fx.cpp (1)

27-29: Avoid re-allocating the scratch buffer on every frame

The current implementation calls SEGENV.allocateData() on every frame, even after memory has been successfully allocated. This can lead to heap fragmentation and unnecessary CPU overhead.

-  if (!SEGENV.allocateData(dataSize))
+  if (SEGENV.data == nullptr && !SEGENV.allocateData(dataSize))
     return mode_static();  // allocation failed
🧹 Nitpick comments (5)
usermods/user_fx/user_fx.cpp (5)

12-14: Remove unused static counter

The static uint32_t call = 0 variable is declared and incremented (line 43) but never used meaningfully in the function. Consider removing it to improve code clarity.

 static uint16_t mode_diffusionfire(void) {
-  static uint32_t call = 0;
 

Also remove the related initialization in line 34:

   if (SEGENV.call == 0) {
     SEGMENT.fill(BLACK);
     SEGENV.step = 0;
-    call = 0;
   }

And the increment in line 43:

     uint16_t *tmp_row = reinterpret_cast<uint16_t *>(aligned);
     SEGENV.step = strip.now;
-    call++;

65-75: Add clarifying comments for the diffusion algorithm

The diffusion algorithm's mathematical model (particularly the formula v * 100 / (300 + diffusion)) lacks explanatory comments. Adding comments would make the code more maintainable for future developers.

     // diffuse
     for (unsigned y = 0; y < rows; y++) {
       for (unsigned x = 0; x < cols; x++) {
+        // Sum the current pixel with its horizontal neighbors
         unsigned v = SEGMENT.data[XY(x, y)];
         if (x > 0) {
           v += SEGMENT.data[XY(x - 1, y)];
         }
         if (x < (cols - 1)) {
           v += SEGMENT.data[XY(x + 1, y)];
         }
+        // Apply diffusion factor - higher values cause faster cooling/fading
+        // The 300 base value ensures some persistence, while diffusion (0-100) controls decay rate
         tmp_row[x] = min(255, (int)(v * 100 / (300 + diffusion)));
       }

91-94: Add comment clarifying the default palette selection

The effect defaults to palette 35, but it's not clear what this palette represents. A comment would help future developers understand this choice.

 static const char _data_FX_MODE_DIFFUSIONFIRE[] PROGMEM =
     "Diffusion Fire@!,Spark rate,Diffusion Speed,Turbulence,,Use "
-    "palette;;Color;;2;pal=35";
+    "palette;;Color;;2;pal=35"; // Default to Fire palette (35)

59-60: Consider variable spark intensity

Currently, all sparks are set to maximum intensity (255). For more visual variety, consider randomizing the spark intensity.

         if (p < spark_rate) {
           unsigned dst = XY(x, rows - 1);
-          SEGMENT.data[dst] = 255;
+          // Randomize spark intensity between 192-255 for more natural variation
+          SEGMENT.data[dst] = random8(192, 256);
         }

95-97: Potential magic number in effect registration

The code uses the value 255 when registering the effect. Consider using a named constant or adding a comment explaining what this value represents.

 void UserFxUsermod::setup() {
-  strip.addEffect(255, &mode_diffusionfire, _data_FX_MODE_DIFFUSIONFIRE);
+  // 255 means the effect will be added at the end of effects list
+  strip.addEffect(255, &mode_diffusionfire, _data_FX_MODE_DIFFUSIONFIRE);
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b042c3a and d54bb92.

📒 Files selected for processing (1)
  • usermods/user_fx/user_fx.cpp (1 hunks)
🔇 Additional comments (2)
usermods/user_fx/user_fx.cpp (2)

53-62: Consider checking turbulence parameter range/validation

The turbulence parameter is directly compared with a random value without validation. Consider adding bounds checking or normalization to ensure consistent behavior.

Random values from hw_random8() range from 0-255. If turbulence is somehow set to a value higher than 255, the condition hw_random8() > turbulence would always be false, preventing spark generation entirely. While SEGMENT.custom2 (which provides turbulence) is likely limited to 0-255 in the UI, it's good practice to ensure this in the code:

-    if (hw_random8() > turbulence) {
+    // Ensure turbulence is within valid range (0-255)
+    if (hw_random8() > min(255, turbulence)) {

39-41: Good implementation of aligned memory access

The code properly handles memory alignment for the temporary buffer to avoid hardware faults on architectures that don't support unaligned memory access (like ESP8266). This is a solid implementation that follows best practices.

@@ -1,6 +1,6 @@
{
"name:": "sht",
"name": "sht",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

revert, it will be fixed with this pending PR: #4623

@@ -1,4 +1,4 @@
{
"name:": "EXAMPLE",
"name": "EXAMPLE",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

revert, see #4623

@@ -0,0 +1,3 @@
{
"name:": "user_fx"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is what you want to fix

}

if ((strip.now - SEGENV.step) >= refresh_ms) {
// Reserve one extra byte and align to 2-byte boundary to avoid hard-faults
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you did not reserve the extra byte...
also this is much more readable:

uintptr_t addr = reinterpret_cast<uintptr_t>(original_pointer);
uintptr_t aligned = (addr + 1) & ~1;

@DedeHai
Copy link
Collaborator

DedeHai commented Apr 30, 2025

please do not force push on PR's in review, it screws up file comparison and comments.

@mryndzionek
Copy link
Author

please do not force push on PR's in review, it screws up file comparison and comments.

Okay, sorry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants