Optimize euclidean pattern by changing from an array of ints to a bitmask.

This commit is contained in:
2025-07-01 12:23:50 -07:00
parent ceb01bf03f
commit edddfd5879

View File

@ -1,7 +1,7 @@
#ifndef EUCLIDEAN_H
#define EUCLIDEAN_H
#define MAX_PATTERN_LEN 16
#define MAX_PATTERN_LEN 32
struct PatternState {
uint8_t steps;
@ -26,9 +26,12 @@ class Pattern {
updatePattern();
}
PatternState GetState() { return {steps_, hits_}; }
PatternState GetState() const { return {steps_, hits_}; }
Step GetCurrentStep(byte i) { return pattern_[i]; }
Step GetCurrentStep(byte i) {
if (i >= MAX_PATTERN_LEN) return REST;
return (pattern_bitmap_ & (1UL << i)) ? HIT : REST;
}
void SetSteps(int steps) {
steps_ = constrain(steps, 1, MAX_PATTERN_LEN);
@ -47,8 +50,6 @@ class Pattern {
uint8_t GetHits() { return hits_; }
uint8_t GetStepIndex() { return step_index_; }
// Get the current step value and advance the euclidean rhythm step index
// to the next step in the pattern.
Step NextStep() {
if (steps_ == 0) return REST;
@ -61,19 +62,23 @@ class Pattern {
uint8_t steps_ = 0;
uint8_t hits_ = 0;
volatile uint8_t step_index_ = 0;
Step pattern_[MAX_PATTERN_LEN];
uint32_t pattern_bitmap_ = 0;
// Update the euclidean rhythm pattern when attributes change.
// Update the euclidean rhythm pattern using bitmap
void updatePattern() {
pattern_bitmap_ = 0; // Clear the bitmap
if (steps_ == 0) return;
byte bucket = 0;
pattern_[0] = HIT;
// Set the first bit (index 0) if it's a HIT
pattern_bitmap_ |= (1UL << 0);
for (int i = 1; i < steps_; i++) {
bucket += hits_;
if (bucket >= steps_) {
bucket -= steps_;
pattern_[i] = HIT;
} else {
pattern_[i] = REST;
pattern_bitmap_ |= (1UL << i);
}
}
}