Skip to content
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

improved & refactored Android FX #4522

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

DedeHai
Copy link
Collaborator

@DedeHai DedeHai commented Jan 26, 2025

  • returns FRAMETIME -> no more flickering in transitions and overlay, instead uses strip.now for timing
  • no more double-painting of pixels: each pixel is only set once

Summary by CodeRabbit

  • New Features
    • Introduced a wide array of LED effect modes to enrich visual displays.
    • Enjoy dynamic animations such as vibrant solid patterns, multi-hued simulations, and flowing, flickering effects.
    • Experience immersive 2D animations featuring plasma, scrolling visuals, and playful movement patterns for a more engaging lighting experience.

- returns FRAMETIME -> no more flickering in transitions and overlay
- no more double-painting of pixels
@DedeHai DedeHai added this to the 0.15.1 candidate milestone Jan 26, 2025
@DedeHai DedeHai added effect optimization re-working an existing feature to be faster, or use less memory labels Jan 26, 2025
@DedeHai
Copy link
Collaborator Author

DedeHai commented Jan 26, 2025

I would like someone to confirm it still looks the same as before.

@netmindz
Copy link
Member

Maybe worth mentioning testing required on discord if you haven't done already?

@DedeHai
Copy link
Collaborator Author

DedeHai commented Jan 28, 2025

I did test it, I even compared the variable contents in excel and it was identical, but I did only test up to 256 pixels. I am pretty sure it is identical but there may be edge cases...

@netmindz
Copy link
Member

netmindz commented Feb 9, 2025

@coderabbitai review

Copy link

coderabbitai bot commented Feb 9, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

coderabbitai bot commented Feb 9, 2025

Walkthrough

This change introduces multiple new LED effect modes to the WS2812FX class. The new methods implement a variety of visual patterns and animations, such as static patterns with alternating colors, plasma effects with rotation, simulated TV sunrise/sunset, multi-candle flickering, and several 2D visual effects including spaceships, crazy bees, ghost rider, and more. Each method is added as a public entity in the WS2812FX class within the FX.cpp file.

Changes

File Change Summary
wled00/FX.cpp Added new effect methods to the WS2812FX class: mode_static_pattern, mode_tri_static_pattern, mode_blends, mode_tv_simulator, mode_candle_multi, mode_flow, mode_chunchun, mode_dancing_shadows, mode_washing_machine, mode_2Dplasmarotozoom, mode_2Dspaceships, mode_2Dcrazybees, mode_2Dghostrider, mode_2Dfloatingblobs, mode_2Dscrollingtext, mode_2Ddriftrose, mode_2Ddistortionwaves, mode_2Dsoap, mode_2Doctopus, mode_2Dwavingcell

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Application
    participant WS2812FX

    User->>Application: Select LED effect (e.g., mode_flow)
    Application->>WS2812FX: Invoke effect method (mode_flow)
    WS2812FX->>WS2812FX: Execute effect logic based on new mode
    WS2812FX-->>Application: Return status/confirmation
    Application-->>User: Update applied effect
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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. (Beta)
  • @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

@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: 1

🔭 Outside diff range comments (4)
wled00/FX.cpp (4)

1401-1408: Potential off-by-one error in Two Dots effect.

The effect uses SEGLEN-1 for indexing but doesn't validate that indexR and indexB are within bounds.

Add bounds checking to prevent potential buffer overflows:

-    SEGMENT.setPixelColor(indexR, color1);
-    SEGMENT.setPixelColor(indexB, color2);
+    if (indexR < SEGLEN) SEGMENT.setPixelColor(indexR, color1);
+    if (indexB < SEGLEN) SEGMENT.setPixelColor(indexB, color2);

2069-2154: Fire2012 effect needs optimization for memory usage.

The effect allocates memory for each virtual strip which could be excessive for large matrices.

Consider:

  1. Using a single buffer and recomputing for each strip
  2. Adding bounds checking for array accesses
  3. Optimizing memory allocation by reusing buffers
-  if (!SEGENV.allocateData(dataSize * strips)) return mode_static();
+  if (!SEGENV.allocateData(dataSize)) return mode_static();

6333-6397: 2D Swirl effect needs better error handling.

The effect doesn't properly handle allocation failures or invalid dimensions.

Add proper error handling:

+  if (cols < 2 || rows < 2) return mode_static();
+  if (!SEGENV.allocateData(sizeof(float) * 3)) return mode_static();

7659-7678: Potential issue in effect addition logic.

The addEffect() function could allow duplicate effect IDs under certain conditions.

Add additional checks:

 uint8_t WS2812FX::addEffect(uint8_t id, mode_ptr mode_fn, const char *mode_name) {
+  if (id >= 255) return 255; // Invalid ID
+  if (mode_fn == nullptr || mode_name == nullptr) return 255; // Invalid parameters
   if (id == 255) {
     for (size_t i=1; i<_mode.size(); i++) 
       if (_modeData[i] == _data_RESERVED) { id = i; break; }
   }
🧹 Nitpick comments (2)
wled00/FX.cpp (2)

3401-3495: Potential performance bottleneck in 2D Blobs effect.

The effect performs many floating point calculations per frame which could be slow on some hardware.

Consider:

  1. Using fixed-point math instead of floating point
  2. Pre-calculating common values
  3. Reducing the number of trigonometric calculations

Example optimization:

// Pre-calculate sine/cosine values
const float sinTable[256];
const float cosTable[256];
// Use lookup tables instead of direct calculations
float sin_val = sinTable[angle & 0xFF];

7679-7897: Effect setup needs optimization for memory usage.

The setupEffectData() function allocates a lot of memory upfront which could be problematic on memory-constrained devices.

Consider:

  1. Lazy loading of effects
  2. Dynamic allocation of effect data
  3. Grouping similar effects to share resources

Consider implementing a plugin system to allow:

  1. Dynamic loading/unloading of effects
  2. Better memory management
  3. Easier addition of new effects
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 61b9947 and 81f2e38.

📒 Files selected for processing (1)
  • wled00/FX.cpp (1 hunks)

Comment on lines 801 to 838
/*
* Android loading circle
* Android loading circle, refactored by @dedehai
*/
uint16_t mode_android(void) {

if (!SEGENV.allocateData(sizeof(uint32_t))) return mode_static();
uint32_t* counter = reinterpret_cast<uint32_t*>(SEGENV.data);
unsigned size = SEGENV.aux1 >> 1; // upper 15 bit
unsigned shrinking = SEGENV.aux1 & 0x01; // lowest bit
if(strip.now >= SEGENV.step) {
SEGENV.step = strip.now + 3 + ((8 * (uint32_t)(255 - SEGMENT.speed)) / SEGLEN);
if (size > (SEGMENT.intensity * SEGLEN) / 255)
shrinking = 1;
else if (size < 2)
shrinking = 0;
if (!shrinking) { // growing
if ((*counter % 3) == 1)
SEGENV.aux0++; // advance start position
else
size++;
} else { // shrinking
SEGENV.aux0++;
if ((*counter % 3) != 1)
size--;
}
SEGENV.aux1 = size << 1 | shrinking; // save back
(*counter)++;
if (SEGENV.aux0 >= SEGLEN) SEGENV.aux0 = 0;
}
uint32_t start = SEGENV.aux0;
uint32_t end = (SEGENV.aux0 + size) % SEGLEN;
for (unsigned i = 0; i < SEGLEN; i++) {
SEGMENT.setPixelColor(i, SEGMENT.color_from_palette(i, true, PALETTE_SOLID_WRAP, 1));
}

if (SEGENV.aux1 > (SEGMENT.intensity*SEGLEN)/255)
{
SEGENV.aux0 = 1;
} else
{
if (SEGENV.aux1 < 2) SEGENV.aux0 = 0;
}

unsigned a = SEGENV.step & 0xFFFFU;

if (SEGENV.aux0 == 0)
{
if (SEGENV.call %3 == 1) {a++;}
else {SEGENV.aux1++;}
} else
{
a++;
if (SEGENV.call %3 != 1) SEGENV.aux1--;
}

if (a >= SEGLEN) a = 0;

if (a + SEGENV.aux1 < SEGLEN)
{
for (unsigned i = a; i < a+SEGENV.aux1; i++) {
SEGMENT.setPixelColor(i, SEGCOLOR(0));
}
} else
{
for (unsigned i = a; i < SEGLEN; i++) {
SEGMENT.setPixelColor(i, SEGCOLOR(0));
}
for (unsigned i = 0; i < SEGENV.aux1 - (SEGLEN -a); i++) {
if ((start < end && i >= start && i < end) || (start >= end && (i >= start || i < end)))
SEGMENT.setPixelColor(i, SEGCOLOR(0));
}
else
SEGMENT.setPixelColor(i, SEGMENT.color_from_palette(i, true, PALETTE_SOLID_WRAP, 1));
}
SEGENV.step = a;

return 3 + ((8 * (uint32_t)(255 - SEGMENT.speed)) / SEGLEN);
return FRAMETIME;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improved Android loading circle effect with better memory management and cleaner code.

The refactored Android loading circle effect now:

  1. Uses proper memory allocation with allocateData()
  2. Stores state in a single 32-bit counter variable
  3. Improves readability by using clearer variable names and logic
  4. Fixes potential memory issues by properly handling allocation failures

Consider adding bounds checking for size to prevent potential buffer overflows:

-    if (size > (SEGMENT.intensity * SEGLEN) / 255)
+    if (size > min((SEGMENT.intensity * SEGLEN) / 255, SEGLEN/2))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting testing effect optimization re-working an existing feature to be faster, or use less memory
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants