-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheffects.py
More file actions
6401 lines (5590 loc) · 258 KB
/
Copy patheffects.py
File metadata and controls
6401 lines (5590 loc) · 258 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
import time
import array
import gc
import micropython
from math import sin, cos, pi, sqrt, atan2, floor
from helpers import EffectsHelpers
# Precomputed Sine Table (256 entries, -127 to 127)
_SIN_TAB = array.array('b', [int(127 * sin(i * 6.283185 / 256)) for i in range(256)])
def _fast_sin(phase_rad):
return _SIN_TAB[int(phase_rad * 40.7436) & 0xFF]
def _fast_cos(phase_rad):
return _fast_sin(phase_rad + 1.570796)
# Constants for LED1 layout
LED1_CIRCLE_CW = [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,3,2,1,0]
LED1_INNER_ARC_V = [37,38,39,40,41,42,43,44,45,46,47,48]
LED1_CHORDS_LOW_V = [49,50,51,52,53,54,55,56,57,58,59,60]
LED1_CHORDS_HIGH_V = [62,63,64,65,66,67,68,69,70,71]
LED1_TREE_ALL_V = LED1_CHORDS_LOW_V + LED1_CHORDS_HIGH_V
_wfall2 = bytearray(138 * 3 * 3) # Waterfall buffer
# Pre-allocated shape templates for _fx_shapes (avoid per-frame tuple creation)
_SHAPE_SPARK = (
(0, 0, 255),
(-1, 0, 210), (1, 0, 210), (0, -1, 210), (0, 1, 210),
(-1, -1, 160), (-1, 1, 160), (1, -1, 160), (1, 1, 160),
(-2, 0, 100), (2, 0, 100), (0, -2, 100), (0, 2, 100),
(-2, -1, 60), (-2, 1, 60), (2, -1, 60), (2, 1, 60),
(-1, -2, 60), (1, -2, 60), (-1, 2, 60), (1, 2, 60),
)
_SHAPE_STAR = (
(0, 0, 255),
(-1, 0, 240), (1, 0, 240), (0, -1, 240), (0, 1, 240),
(-2, 0, 220), (2, 0, 220), (0, -2, 220), (0, 2, 220),
(-3, 0, 150), (3, 0, 150), (0, -3, 150), (0, 3, 150),
(-1, -1, 70), (-1, 1, 70), (1, -1, 70), (1, 1, 70),
)
_SHAPE_DIAMOND = (
(0, 0, 180),
(-1, 0, 160), (1, 0, 160), (0, -1, 160), (0, 1, 160),
(-1, -1, 210), (-1, 1, 210), (1, -1, 210), (1, 1, 210),
(-2, 0, 255), (2, 0, 255), (0, -2, 255), (0, 2, 255),
(-2, -1, 200), (-2, 1, 200), (2, -1, 200), (2, 1, 200),
(-1, -2, 200), (1, -2, 200), (-1, 2, 200), (1, 2, 200),
)
_SHAPE_RING = (
(0, 0, 50),
(-1, 0, 80), (1, 0, 80), (0, -1, 80), (0, 1, 80),
(-1, -1, 110), (-1, 1, 110), (1, -1, 110), (1, 1, 110),
(-2, 0, 255), (2, 0, 255), (0, -2, 255), (0, 2, 255),
(-2, -1, 240), (-2, 1, 240), (2, -1, 240), (2, 1, 240),
(-1, -2, 240), (1, -2, 240), (-1, 2, 240), (1, 2, 240),
(-2, -2, 170), (-2, 2, 170), (2, -2, 170), (2, 2, 170),
)
_SHAPE_CROSS_X = (
(0, 0, 255),
(-1, -1, 230), (-1, 1, 230), (1, -1, 230), (1, 1, 230),
(-2, -2, 200), (-2, 2, 200), (2, -2, 200), (2, 2, 200),
(-3, -3, 130), (-3, 3, 130), (3, -3, 130), (3, 3, 130),
(-1, 0, 60), (1, 0, 60), (0, -1, 60), (0, 1, 60),
)
_SHAPE_COMET = (
(0, 0, 255), (-1, 0, 200), (1, 0, 200), (-2, 0, 110), (2, 0, 110),
(0, 1, 215), (-1, 1, 160), (1, 1, 160),
(0, 2, 160), (-1, 2, 100), (1, 2, 100),
(0, 3, 100), (-1, 3, 50), (1, 3, 50),
(0, 4, 45),
)
class AudioEffects(EffectsHelpers):
"""Audio visualization effects engine - reads directly from Controller audio data."""
def __init__(self, controller, led_device, rows=138, cols=3,
# GLOBAL OPTIONS (apply to all modes)
smoothing=0.7,
peak_hold_ms = 300,
peak_fall_ms = 80,
peak_color=None,
peak_minimum=10.0,
brightness=255,
bands=12):
"""
GLOBAL OPTIONS (apply to all render modes)
Args:
brightness: Global brightness (0-255, where 255=100%, 127=~50%, 0=off)
"""
self.c = controller
self.led = led_device
self.led_id = led_device.id
self.aled = led_device.aled_object
self.rows = self.led.rows
self.cols = self.led.cols
self.n_leds = self.aled.n
self.bands = bands
self.brightness = max(0, min(255, int(brightness))) # 0-255 range (8x precision)
# Geometry caching fields
self.order = self.aled.order
self.order0 = self.order[0]
self.order1 = self.order[1]
self.order2 = self.order[2]
self.buffer = self.aled.aled_buffer
self.noise_threshold = 2.0
self.smoothing = max(0.0, min(1.0, smoothing))
# PALETTE
self.pal_len = self.c.pal_length
# bands mapped evenly from the Controller palette for vivid saturated colors
self.spectrum_palette = self.hsv_palette(self.bands)
# GLOBAL OPTIONS
self.peak_color = peak_color or self._pal_color(self.pal_len // 6)
self.peak_minimum = max(0.0, peak_minimum)
# --- UNIFIED STATE BUFFERS (Using arrays/bytearrays for speed & memory) ---
# Fixed size 32 covers up to 24 bands comfortably and avoids fragmentation.
# Positions and intensities (0-255 range)
self._peak_positions = bytearray(self.bands)
self._peak_intensity = bytearray(self.bands)
# Timing buffers (ticks_ms unsigned long)
self._peak_timers = array.array('I', [0] * self.bands)
self._peak_last_hit = array.array('I', [0] * self.bands)
# Float state buffers (FFT values, smoothing)
self._prev_raw_val = array.array('f', [0.0] * self.bands)
self._bar_smooth = array.array('f', [0.0] * self.bands)
# Configuration physics
self.PEAK_HOLD_MS = peak_hold_ms
self.PEAK_FALL_MS = peak_fall_ms
self.BAR_FALL_SPEED = 12.0
# STATE (smoothing & peak tracking)
# BUFFER & PHYSICAL MAPPING
self.phys_rows = self.rows
# Optimization Cache
self._dist_map = []
self._init_dist_map()
# UNIFIED PRE-ALLOCATED PARTICLE POOLS (lazy init — prevents MemoryError / GC stalls)
self._sparkles_pool = None
self._sparkles_count = 0
self._rain_pool = None
self._rain_count = 0
self._sparks_pool = None
self._sparks_count = 0
self._grav_pool = None
self._grav_count = 0
self._bounce_pool = None
self._bounce_count = 0
self._trail_pool = None
self._trail_count = 0
self._comets = None
self._comet_trails = None
self._comet_trail_len = None
self._edge_path = None
self._orbit_pool = None
self._orbit_count = 0
self._cascade_pool = None
self._cascade_count = 0
self._planet_pool = None
self._planet_count = 0
self._blackhole_pool = None
self._blackhole_count = 0
# EffectsAnimations / EffectsHelpers state
self.pal_offset = 0
self.pal_step = 1
self.counter = 0
self.step = 1
self.direction = 1
self.last_time = time.ticks_ms()
self.delay = 25
self.sections = None
self.fade_in = False
self.fade_out = False
self.intermediate = False
self.repeats = 0
self.offset = 0
self._effect_count = 0
self._effect_max = 0
self._effect_fields = []
self._array_pool = {}
self._occupied = bytearray(self.n_leds)
self._fire_heat = None
self._fire_heat_scaled = None
self._fire_particles = None # Lazy init as array.array
self._fs_data = None # Fire spark particle data
self._fire_idx = None # LED index cache for fire render
self._fire_frame = 0 # Cool-table frame offset
# Particle state buffers (storm, magdalenas, fade_effect via EffectsAnimations)
self._particle_status = bytearray(self.n_leds)
self._particle_color = bytearray(self.n_leds * self.aled.bpp)
self._particle_mult = array.array('f', [0.0] * self.n_leds)
self._particle_int0 = bytearray(self.n_leds)
def hsv_palette(self, colors_qty=12):
palette = []
for i in range(colors_qty):
h = (i * 242) // colors_qty
rgb = self._hsv_to_rgb(h, 255, 255)
color = self.aled.apply_gamma(rgb, self.brightness, self.c.gamma_table)
palette.append(color)
return palette
def teardown(self, free_pools=True):
"""Free all particle pools and caches. Call before gc.collect() on effect switch."""
self._sparkles_count = 0
self._rain_count = 0
self._sparks_count = 0
self._grav_count = 0
self._bounce_count = 0
self._trail_count = 0
self._orbit_count = 0
self._cascade_count = 0
self._planet_count = 0
self._blackhole_count = 0
if self._comet_trail_len is not None:
for i in range(len(self._comet_trail_len)):
self._comet_trail_len[i] = 0
if hasattr(self, '_radial_count'):
self._radial_count = 0
self._effect_count = 0
for i in range(self.n_leds):
self._occupied[i] = 0
self._fire_heat = None
self._fire_heat_scaled = None
self._fire_particles = None
self._fs_data = None
self._fire_idx = None
self._fire_frame = 0
self._edge_path = None
self._shape_lanes_h = None
self._shape_lanes_v = None
self._cross_cx = None
self._orb_ring = None
self._orb_path_c = None
self._orb_path_r = None
if hasattr(self, '_orb_path_idx'): self._orb_path_idx = None
if hasattr(self, '_orb_wipe_tot'): self._orb_wipe_tot = 0.0
if free_pools:
self._sparkles_pool = None
self._rain_pool = None
self._sparks_pool = None
self._grav_pool = None
self._bounce_pool = None
self._trail_pool = None
self._comets = None
self._comet_trails = None
self._comet_trail_len = None
self._orbit_pool = None
self._cascade_pool = None
self._planet_pool = None
self._blackhole_pool = None
self._fountain_particles = None
self._fountain_palettes = None
def reset_effect_state(self):
"""Reset effect state on switch (prevents stale state / leaks)."""
self.teardown(free_pools=False)
self.last_time = time.ticks_add(time.ticks_ms(), -20000)
self.sections = None
self.fade_in = False
self.fade_out = False
self.intermediate = False
self.counter = 0
self.repeats = 0
self._active_envelope = 0.0
def _ensure_pool(self, name, size, template):
pool = getattr(self, name, None)
if pool is None:
pool = [list(template) for _ in range(size)]
setattr(self, name, pool)
return pool
def _ensure_sparkles_pool(self):
return self._ensure_pool('_sparkles_pool', 80, [0, (0, 0, 0), 0.0])
def _ensure_rain_pool(self):
return self._ensure_pool('_rain_pool', 50, [0, 0.0, 0.0, 0.0, (0, 0, 0)])
def _ensure_sparks_pool(self):
return self._ensure_pool('_sparks_pool', 20, [0.0, 0, 0.0, 0.0])
def _ensure_grav_pool(self):
return self._ensure_pool('_grav_pool', 42, [0.0, 0.0, 0.0, 0.0, 0.0, 0])
def _ensure_bounce_pool(self):
return self._ensure_pool('_bounce_pool', 15, [0.0, 0.0, 0.0, 0.0, 0, 0.0, 0])
def _ensure_trail_pool(self):
return self._ensure_pool('_trail_pool', 16, [0, 0, 0.0])
def _ensure_comets_pool(self):
if self._comets is None:
self._comets = []
for col in range(self.cols):
self._comets.append([self.rows * 0.5, 2.5, self.rows * 0.5, int(col * 4) % 12])
self._comet_trails = [[[0, 0.0] for _ in range(8)] for _ in range(self.cols)]
self._comet_trail_len = [0] * self.cols
return self._comets
def _ensure_orbit_pool(self):
return self._ensure_pool('_orbit_pool', 60, [0.0, 0.0, 0.0, 0.0, 0.0, 0])
def _ensure_cascade_pool(self):
return self._ensure_pool('_cascade_pool', 50, [0.0, 0.0, 0.0, 0.0, 0.0, 0])
def _ensure_planet_pool(self):
return self._ensure_pool('_planet_pool', 40, [0.0, 0.0, 0.0, 0.0, 0.0, 0])
def _ensure_blackhole_pool(self):
return self._ensure_pool('_blackhole_pool', 80, [0.0, 0.0, 0.0, 0.0, 0.0, 0])
def _check_active(self, clear=True):
"""Return True if audio energy exceeds threshold, else clear and return None."""
if clear:
self.aled.clear()
if not hasattr(self, '_active_envelope'):
self._active_envelope = 0.0
energy = 0.0
if hasattr(self.c, 'mv_feat') and len(self.c.mv_feat) > 51:
energy = float(self.c.mv_feat[51])
if energy >= self.noise_threshold:
self._active_envelope = 1.0
else:
self._active_envelope *= 0.95
if self._active_envelope > 0.02:
return True
return None
def _warm_color(self, intensity):
"""Fire-like warm color from palette (red-orange-yellow range)."""
if self.pal_len > 0:
idx = int((1.0 - max(0.0, min(1.0, intensity))) * 20)
return self._pal_color(idx)
return (200, 15, 0)
def _cool_color(self, intensity):
"""Ice-like cool color from palette (cyan-blue range)."""
if self.pal_len > 0:
idx = 85 + int((1.0 - max(0.0, min(1.0, intensity))) * 35)
return self._pal_color(idx)
return (0, 100, 200)
def _init_dist_map(self):
"""Pre-calculate distance/angle maps and index lookup for heavy renderers."""
self._dist_map = [0.0] * self.n_leds
self._tunnel_dist = [0.0] * self.n_leds
self._rift_r = [0.0] * self.n_leds
self._rift_a = [0.0] * self.n_leds
self._idx_map = [-1] * (self.rows * self.cols)
cx = self.cols / 2.0
cy = self.rows / 2.0
for row in range(self.rows):
dy_raw = row - cy
for col in range(self.cols):
dx_raw = col - cx
dist_raw = sqrt(dx_raw*dx_raw + dy_raw*dy_raw)
# Tunnel scaled distance
dx_t = dx_raw * 0.5
dy_t = dy_raw * 0.1
dist_t = sqrt(dx_t*dx_t + dy_t*dy_t)
# Rift normalized coords (fixed center approximation for speed)
dx_r = dx_raw / self.cols
dy_r = dy_raw / self.rows
r_r = sqrt(dx_r*dx_r + dy_r*dy_r)
a_r = atan2(dy_r, dx_r)
idx = self._physical_index(col, row)
map_idx = row * self.cols + col
if 0 <= idx < self.n_leds:
self._dist_map[idx] = dist_raw
self._tunnel_dist[idx] = dist_t
self._rift_r[idx] = r_r
self._rift_a[idx] = a_r
self._idx_map[map_idx] = idx
def _physical_index(self, a, b, c=None):
"""Unified indexing supporting both (x, y) and (led_id, x, y) calls."""
if c is not None:
led_id = a
x = b
y = c
else:
led_id = self.led_id
x = a
y = b
return self.c.get_led_index(led_id, x, y)
def _calc_brightness(self, color, local_brightness=255):
lb = local_brightness
if lb <= 0:
return (0, 0, 0)
if lb > 255:
lb = 255
gb = self.brightness
if gb <= 0:
return (0, 0, 0)
if gb > 255:
gb = 255
r, g, b = color
# Full brightness fast path — no multiply needed.
if gb == 255 and lb == 255:
return r, g, b
else:
# 8-bit x 8-bit -> 8-bit scale
br = (gb * lb) >> 8
return self.aled.change_brightness(color, br)
def _set_led(self, idx, color, local_brightness=255):
"""Set LED by physical index with current global brightness."""
self.aled[idx] = self._calc_brightness(color, local_brightness)
_set_pixel = _set_led
def _update_peak(self, band_idx, current_bar_height, now=None):
if now is None: now = time.ticks_ms()
old_peak = self._peak_positions[band_idx]
if current_bar_height >= old_peak:
self._peak_positions[band_idx] = current_bar_height
self._peak_timers[band_idx] = time.ticks_add(now, self.PEAK_HOLD_MS)
self._peak_last_hit[band_idx] = now
else:
if time.ticks_diff(self._peak_timers[band_idx], now) <= 0:
if old_peak > 0:
self._peak_positions[band_idx] = old_peak - 1
self._peak_timers[band_idx] = time.ticks_add(now, self.PEAK_FALL_MS)
return self._peak_positions[band_idx]
def _ghosting_or_clear(self, enable_ghosting, ghosting_factor):
"""Apply ghosting trail or clear buffer."""
if enable_ghosting:
self.aled.apply_brightness_to_buffer(int(ghosting_factor * 255))
else:
self.aled.clear()
def _smooth_bar(self, band_idx, raw_target):
"""Smoothed bar rise/fall. Returns smoothed value."""
curr_s = self._bar_smooth[band_idx]
if raw_target > curr_s:
curr_s = raw_target
else:
curr_s = max(0.0, curr_s - self.BAR_FALL_SPEED)
self._bar_smooth[band_idx] = curr_s
return curr_s
def _update_peak_flash(self, band_idx, raw, h, max_height, gb):
"""Update peak flash intensity and return colored peak. White->Red transition."""
diff = raw - self._prev_raw_val[band_idx]
self._prev_raw_val[band_idx] = raw
intensity = int(self._peak_intensity[band_idx])
if diff > 35 or (h >= max_height and h > 0):
intensity = 255
else:
intensity = max(0, intensity - 12)
self._peak_intensity[band_idx] = intensity
p_color = self.get_dynamic_peak_color(band_idx, intensity)
if gb != 255:
p_color = self.aled.change_brightness(p_color, gb)
return p_color
def _apply_peak_fade(self, p_color, band_idx, now, fade_factor):
"""Fade peak color after hold time. Returns dimmed color."""
time_passed = time.ticks_diff(now, self._peak_last_hit[band_idx])
if time_passed > self.PEAK_HOLD_MS:
fade = 1000000 - ((time_passed - self.PEAK_HOLD_MS) * fade_factor)
if fade < 50000:
fade = 50000
if fade < 1000000:
p_color = ((p_color[0] * fade) // 1000000,
(p_color[1] * fade) // 1000000,
(p_color[2] * fade) // 1000000)
return p_color
def get_dynamic_peak_color(self, band_idx, intensity):
"""Płynne przejście koloru: intensity 255 = Biały, 0 = Czerwony"""
# Przy intensity=0 mamy (255, 0, 0) -> Czerwony
return (255, int(intensity), int(intensity))
def set_brightness(self, value):
"""Set global brightness 0-255 (255=full, 0=off)."""
self.brightness = max(0, min(255, int(value)))
# ── EffectsAnimations / EffectsHelpers adapter API ──────────────────────
@property
def segment_length(self):
return self.n_leds
@property
def pal_length(self):
return self.pal_len
@property
def palette(self):
return self.c.palette
@property
def aled_object(self):
return self.aled
@property
def controller(self):
return self.c
def update(self):
pass # write is handled by the main loop
def _set_pixel_rc(self, row, col, color, rows=None, cols=None):
idx = self._physical_index(col, row)
if 0 <= idx < self.n_leds:
self._set_led(idx, color)
def clear_sequence(self, color=(0, 0, 0)):
if color[0] == 0 and color[1] == 0 and color[2] == 0:
self.aled.clear()
else:
self.aled.set_all(color, self.brightness)
def clear_particles(self):
self._effect_count = 0
n = self.n_leds
self._occupied[:] = b'\x00' * n
self._particle_status[:] = b'\x00' * n
self._particle_color[:] = b'\x00' * (n * self.aled.bpp)
self._particle_int0[:] = b'\x00' * n
pm = self._particle_mult
for i in range(n):
pm[i] = 0.0
if hasattr(self, '_fountain_particles') and self._fountain_particles is not None:
for i in range(len(self._fountain_particles)):
self._fountain_particles[i] = 0.0
def direction_change(self):
self.direction *= -1
def set_speed(self, speed):
self.delay = max(1, 1000 // max(1, speed))
def set_direction(self, direction):
self.direction = direction
def _prepare_effect_arrays(self, max_count, **specs):
same_fields = True
if not hasattr(self, '_effect_fields') or len(self._effect_fields) != len(specs):
same_fields = False
else:
for name in specs.keys():
if name not in self._effect_fields:
same_fields = False
break
if same_fields and hasattr(self, '_effect_max') and self._effect_max >= max_count:
return
self._effect_count = 0
self._effect_max = max_count
self._effect_fields = list(specs.keys())
for name, typecode in specs.items():
key = (name, typecode)
existing = self._array_pool.get(key)
if existing is None or len(existing) < max_count:
self._array_pool[key] = array.array(typecode, [0] * max_count)
setattr(self, '_arr_' + name, self._array_pool[key])
for i in range(self.n_leds):
self._occupied[i] = 0
def _effect_swap_remove(self, idx):
last = self._effect_count - 1
if idx != last:
self._arr_led[idx] = self._arr_led[last]
for name in self._effect_fields:
arr = getattr(self, '_arr_' + name)
arr[idx] = arr[last]
self._effect_count -= 1
def render_center_split(self, max_height=36, center_offset=-7, show_peaks=True,
enable_ghosting=True, ghosting_factor=0.7,
enable_peak_flash=True):
"""Modified render_center_split with ghosting and peak flash."""
is_active = self.c.mv_feat[51]
bands = self.c.mv_bands
rows = self.rows
cols = self.cols
gb = self.brightness
now = time.ticks_ms()
self._ghosting_or_clear(enable_ghosting, ghosting_factor)
center_row = rows // 2 + center_offset
fade_factor = int((1.0 - ghosting_factor) * 10000)
spectrum_palette = self.spectrum_palette
sp_len = len(spectrum_palette)
for x in range(cols):
for mode in range(3):
if mode == 0:
band_idx = x
color = spectrum_palette[band_idx % sp_len]
elif mode == 1:
band_idx = x + 3
color = spectrum_palette[(band_idx + 1) % sp_len]
else:
band_idx = x + 6
color = spectrum_palette[(band_idx + 2) % sp_len]
if band_idx >= len(bands) or band_idx >= self.bands: continue
raw = self._smooth_bar(band_idx, float(bands[band_idx]) if is_active else 0.0)
h = max(0, min(max_height, int((raw / 255.0) * max_height)))
peak_pos = self._update_peak(band_idx, h, now)
if gb != 255: color = self.aled.change_brightness(color, gb)
p_color = self.peak_color
if enable_peak_flash:
p_color = self._update_peak_flash(band_idx, raw, h, max_height, gb)
p_color = self._apply_peak_fade(p_color, band_idx, now, fade_factor)
# Rendering
if mode == 0: # Down (from center)
if h > 0:
for r in range(h):
y = center_row - 1 - r
if 0 <= y < rows:
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = color
if show_peaks and peak_pos > 0:
y = center_row - 1 - peak_pos
if 0 <= y < rows:
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = p_color
elif mode == 1: # Up (from center)
if h > 0:
for r in range(h):
y = center_row + r
if 0 <= y < rows:
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = color
if show_peaks and peak_pos > 0:
y = center_row + peak_pos
if 0 <= y < rows:
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = p_color
else: # Upper (from top)
if h > 0:
for r in range(h):
y = rows - 1 - r
if 0 <= y < rows:
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = color
if show_peaks and peak_pos > 0:
y = rows - 1 - peak_pos
if 0 <= y < rows:
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = p_color
def render_bars(self, orientation='v', bar_size=8, spacing=2, start_row=18,
visible_bands=None, reverse_bands=True, direction='auto', show_peaks=False,
enable_ghosting=True, ghosting_factor=0.7,
enable_symmetric=False, enable_peak_flash=True, peak_flash_threshold=5, center_offset=-10):
"""Unified rendering for bars. Optimized version with cinematic ghosting and peak transitions."""
is_active = self.c.mv_feat[51]
bands = self.c.mv_bands
n_leds = self.n_leds
rows = self.rows
cols = self.cols
gb = self.brightness
now = time.ticks_ms()
if visible_bands is None:
band_indices = list(range(self.bands))
else:
band_indices = [i for i, v in enumerate(visible_bands) if v]
if reverse_bands:
band_indices = list(reversed(band_indices))
if direction == 'auto':
direction = 'up' if orientation == 'v' else 'left'
mid_row = rows // 2 + center_offset
current_pos = start_row
self._ghosting_or_clear(enable_ghosting, ghosting_factor)
fade_factor = int((1.0 - ghosting_factor) * 10000)
spectrum_palette = self.spectrum_palette
sp_len = len(spectrum_palette)
for display_slot, band_idx in enumerate(band_indices):
if band_idx >= len(bands) or band_idx >= self.bands: break
raw_val = self._smooth_bar(band_idx, float(bands[band_idx]) if is_active else 0.0)
norm = self._norm(raw_val)
# Base color scaled by global brightness
base_color = spectrum_palette[band_idx % sp_len]
if gb != 255:
color = self.aled.change_brightness(base_color, gb)
else:
color = base_color
# VERTICAL MODE
if orientation == 'v':
h_float = norm * bar_size
h_full = int(h_float)
h_frac = h_float - h_full
peak_pos = self._update_peak(band_idx, h_full, now)
p_color = self._update_peak_flash(band_idx, raw_val, h_full, bar_size, gb)
row_start = current_pos
row_end = min(rows, row_start + bar_size)
if direction == 'up':
for r in range(h_full):
y = row_start + r
if row_start <= y < row_end:
for x in range(cols):
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = color
if h_frac > 0.02 and h_full < bar_size:
y = row_start + h_full
if row_start <= y < row_end:
frac_color = self.aled.change_brightness(color, int(h_frac * 255))
for x in range(cols):
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = frac_color
if show_peaks and peak_pos > 0 and peak_pos < bar_size:
p_color = self._apply_peak_fade(p_color, band_idx, now, fade_factor)
y = row_start + peak_pos
if row_start <= y < row_end:
for x in range(cols):
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = p_color
else:
y_base = row_start + bar_size - 1
for r in range(h_full):
y = y_base - r
if row_start <= y < row_end:
for x in range(cols):
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = color
if h_frac > 0.02 and h_full < bar_size:
y = y_base - h_full
if row_start <= y < row_end:
frac_color = self.aled.change_brightness(color, int(h_frac * 255))
for x in range(cols):
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = frac_color
if show_peaks and peak_pos > 0 and peak_pos < bar_size:
p_color = self._apply_peak_fade(p_color, band_idx, now, fade_factor)
y = y_base - peak_pos
if row_start <= y < row_end:
for x in range(cols):
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = p_color
current_pos += bar_size + spacing
# HORIZONTAL MODE
elif orientation == 'h':
if direction == 'left':
cols_range = range(cols)
else:
cols_range = range(cols - 1, -1, -1)
if enable_symmetric:
half_spacing = max(1, spacing // 2)
offset = (display_slot // 2) * (bar_size + spacing) + half_spacing
if display_slot % 2 == 0:
row_start = mid_row + offset
else:
row_start = mid_row - offset - bar_size
else:
row_start = current_pos
row_end = min(rows, row_start + bar_size)
rows_minus_1 = rows - 1
inv_cols = 1.0 / cols
for col_idx, x in enumerate(cols_range):
r_min = col_idx * inv_cols
r_max = (col_idx + 1) * inv_cols
b = 0.0
if norm >= r_max:
b = 1.0
elif norm > r_min:
b = (norm - r_min) * cols # Simplified (norm-r_min)/(1/cols)
if enable_ghosting and b < 1.0:
b = b * ghosting_factor
if b > 0.01 and 0 <= row_start < rows:
# Pre-calculate dimmed color
dim_color = self.aled.change_brightness(color, int(b * 255))
for y in range(row_start, row_end):
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = dim_color
if not enable_symmetric:
current_pos += bar_size + spacing
def render_classic(self, direction='bottom-up', max_height=None, start_row=None, show_peaks=True,
enable_ghosting=True, ghosting_factor=0.7, enable_peak_flash=True, peak_flash_threshold=180, gain=1.0):
"""Classic 3-bar visualization"""
is_active = self.c.mv_feat[51]
now = time.ticks_ms()
gb = self.brightness
fade_factor = int((1.0 - ghosting_factor) * 10000)
self._ghosting_or_clear(enable_ghosting, ghosting_factor)
rows = self.rows
cols = self.cols
if max_height is None:
max_height = rows
if start_row is None:
start_row = 0
spectrum_palette = self.spectrum_palette
sp_len = len(spectrum_palette)
bands = self.c.mv_bands
num_bands = len(bands)
for x in range(cols):
band_idx = (x * self.bands) // cols if cols > 0 else 0
if band_idx >= self.bands:
band_idx = self.bands - 1
if band_idx < 0:
band_idx = 0
# Safe index for reading from FFT bands memoryview
fft_band_idx = band_idx
if fft_band_idx >= num_bands:
fft_band_idx = num_bands - 1 if num_bands > 0 else 0
raw_target = float(bands[fft_band_idx]) * gain if (is_active and num_bands > 0) else 0.0
# Smoothing (using helper)
curr_s = self._smooth_bar(band_idx, raw_target)
raw = curr_s
norm = min(1.0, raw / 255.0)
h = int(norm * max_height)
peak_pos = self._update_peak(band_idx, h, now)
c_idx = x * self.bands // cols
color = spectrum_palette[c_idx % sp_len]
if gb != 255: color = self.aled.change_brightness(color, gb)
# Peak Color & Flash Logic (using helpers)
p_color = self.peak_color
if enable_peak_flash:
p_color = self._update_peak_flash(band_idx, raw, h, max_height, gb)
p_color = self._apply_peak_fade(p_color, band_idx, now, fade_factor)
if direction == 'top-down':
for r in range(h):
y = self.rows - 1 - start_row - r
if 0 <= y < self.rows:
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = color
if show_peaks and peak_pos > 0:
y = self.rows - 1 - start_row - peak_pos
if 0 <= y < self.rows:
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = p_color
else: # bottom-up
for r in range(h):
y = start_row + r
if 0 <= y < self.rows:
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = color
if show_peaks and peak_pos > 0:
y = start_row + peak_pos
if 0 <= y < self.rows:
idx = self._physical_index(x, y)
if idx >= 0: self.aled[idx] = p_color
def render_analog_clock(self, show_marks=True, h_width=1.2, m_width=1.0, s_width=0.8, target_brightness=255,
auto_brightness=True):
"""
Analog clock for addressable LEDs. Centered 12 o'clock between LEDs 11 and 12.
"""
if auto_brightness:
target_brightness = max(6, self.c.process_lux(self.c.lux))
h, m, s = self.c.hour, self.c.minutes, self.c.seconds
total_seconds = s
total_minutes = m + (total_seconds / 60.0)
total_hours = (h % 12) + (total_minutes / 60.0)
# 3. Centrowanie godziny 12
LED_OFFSET = 12
h_pos = (total_hours * 3.0 + LED_OFFSET) % 36
m_pos = (total_minutes * 0.6 + LED_OFFSET) % 36
s_pos = (total_seconds * 0.6 + LED_OFFSET) % 36
led_buffer = [[0, 0, 0] for _ in range(36)]
if show_marks:
for i in range(12):
idx = int(floor((i * 3 + LED_OFFSET) % 36))
led_buffer[idx] = [96 ,96, 96]
def _apply_sweeping_light(buffer, exact_pos, color_rgb, width):
base_idx = int(floor(exact_pos))
for offset in range(-2, 3):
idx = (base_idx + offset) % 36
distance = abs(idx - exact_pos)
if distance > 18:
distance = 36 - distance
if distance < width:
factor = 1.0 - (distance / width)
r = min(255, buffer[idx][0] + int(color_rgb[0] * factor))
g = min(255, buffer[idx][1] + int(color_rgb[1] * factor))
b = min(255, buffer[idx][2] + int(color_rgb[2] * factor))
buffer[idx] = [r, g, b]
_apply_sweeping_light(led_buffer, h_pos, (255, 0, 0), width=h_width) # Godzina
_apply_sweeping_light(led_buffer, m_pos, (0, 255, 0), width=m_width) # Minuta
_apply_sweeping_light(led_buffer, s_pos, (0, 0, 255), width=s_width) # Sekunda
self.aled.clear()
for physical_idx, raw_color in enumerate(led_buffer):
self._set_led(physical_idx, tuple(raw_color), target_brightness)
def render_sparkles(self, sparkle_count=3, enable_ghosting=True, ghosting_factor=0.7):
"""Przykładowy efekt generujący losowe iskry nakładane na smugę czasu"""
if not self._check_active(clear=False):
self._ghosting_or_clear(enable_ghosting, ghosting_factor)
return
pal = self.c.palette
self._ghosting_or_clear(enable_ghosting, ghosting_factor)
for _ in range(sparkle_count):
random_led = random.getrandbits(9) % self.n_leds
random_factor = random.getrandbits(9) % self.pal_len
random_color = self._pal_color(random_factor)
self.aled[random_led] = random_color
def render_spiral_audio(self, rotation_speed=3.0, arms=3, enable_ghosting=True, ghosting_factor=0.6):