]> git.donarmstrong.com Git - qmk_firmware.git/blob - lib/lib8tion/lib8tion.h
[Keyboard] fixed pins for numpad_5x4 layout (#6311)
[qmk_firmware.git] / lib / lib8tion / lib8tion.h
1 #ifndef __INC_LIB8TION_H
2 #define __INC_LIB8TION_H
3
4 /*
5
6  Fast, efficient 8-bit math functions specifically
7  designed for high-performance LED programming.
8
9  Because of the AVR(Arduino) and ARM assembly language
10  implementations provided, using these functions often
11  results in smaller and faster code than the equivalent
12  program using plain "C" arithmetic and logic.
13
14
15  Included are:
16
17
18  - Saturating unsigned 8-bit add and subtract.
19    Instead of wrapping around if an overflow occurs,
20    these routines just 'clamp' the output at a maxumum
21    of 255, or a minimum of 0.  Useful for adding pixel
22    values.  E.g., qadd8( 200, 100) = 255.
23
24      qadd8( i, j) == MIN( (i + j), 0xFF )
25      qsub8( i, j) == MAX( (i - j), 0 )
26
27  - Saturating signed 8-bit ("7-bit") add.
28      qadd7( i, j) == MIN( (i + j), 0x7F)
29
30
31  - Scaling (down) of unsigned 8- and 16- bit values.
32    Scaledown value is specified in 1/256ths.
33      scale8( i, sc) == (i * sc) / 256
34      scale16by8( i, sc) == (i * sc) / 256
35
36    Example: scaling a 0-255 value down into a
37    range from 0-99:
38      downscaled = scale8( originalnumber, 100);
39
40    A special version of scale8 is provided for scaling
41    LED brightness values, to make sure that they don't
42    accidentally scale down to total black at low
43    dimming levels, since that would look wrong:
44      scale8_video( i, sc) = ((i * sc) / 256) +? 1
45
46    Example: reducing an LED brightness by a
47    dimming factor:
48      new_bright = scale8_video( orig_bright, dimming);
49
50
51  - Fast 8- and 16- bit unsigned random numbers.
52    Significantly faster than Arduino random(), but
53    also somewhat less random.  You can add entropy.
54      random8()       == random from 0..255
55      random8( n)     == random from 0..(N-1)
56      random8( n, m)  == random from N..(M-1)
57
58      random16()      == random from 0..65535
59      random16( n)    == random from 0..(N-1)
60      random16( n, m) == random from N..(M-1)
61
62      random16_set_seed( k)    ==  seed = k
63      random16_add_entropy( k) ==  seed += k
64
65
66  - Absolute value of a signed 8-bit value.
67      abs8( i)     == abs( i)
68
69
70  - 8-bit math operations which return 8-bit values.
71    These are provided mostly for completeness,
72    not particularly for performance.
73      mul8( i, j)  == (i * j) & 0xFF
74      add8( i, j)  == (i + j) & 0xFF
75      sub8( i, j)  == (i - j) & 0xFF
76
77
78  - Fast 16-bit approximations of sin and cos.
79    Input angle is a uint16_t from 0-65535.
80    Output is a signed int16_t from -32767 to 32767.
81       sin16( x)  == sin( (x/32768.0) * pi) * 32767
82       cos16( x)  == cos( (x/32768.0) * pi) * 32767
83    Accurate to more than 99% in all cases.
84
85  - Fast 8-bit approximations of sin and cos.
86    Input angle is a uint8_t from 0-255.
87    Output is an UNsigned uint8_t from 0 to 255.
88        sin8( x)  == (sin( (x/128.0) * pi) * 128) + 128
89        cos8( x)  == (cos( (x/128.0) * pi) * 128) + 128
90    Accurate to within about 2%.
91
92
93  - Fast 8-bit "easing in/out" function.
94      ease8InOutCubic(x) == 3(x^i) - 2(x^3)
95      ease8InOutApprox(x) ==
96        faster, rougher, approximation of cubic easing
97      ease8InOutQuad(x) == quadratic (vs cubic) easing
98
99  - Cubic, Quadratic, and Triangle wave functions.
100    Input is a uint8_t representing phase withing the wave,
101      similar to how sin8 takes an angle 'theta'.
102    Output is a uint8_t representing the amplitude of
103      the wave at that point.
104        cubicwave8( x)
105        quadwave8( x)
106        triwave8( x)
107
108  - Square root for 16-bit integers.  About three times
109    faster and five times smaller than Arduino's built-in
110    generic 32-bit sqrt routine.
111      sqrt16( uint16_t x ) == sqrt( x)
112
113  - Dimming and brightening functions for 8-bit
114    light values.
115      dim8_video( x)  == scale8_video( x, x)
116      dim8_raw( x)    == scale8( x, x)
117      dim8_lin( x)    == (x<128) ? ((x+1)/2) : scale8(x,x)
118      brighten8_video( x) == 255 - dim8_video( 255 - x)
119      brighten8_raw( x) == 255 - dim8_raw( 255 - x)
120      brighten8_lin( x) == 255 - dim8_lin( 255 - x)
121    The dimming functions in particular are suitable
122    for making LED light output appear more 'linear'.
123
124
125  - Linear interpolation between two values, with the
126    fraction between them expressed as an 8- or 16-bit
127    fixed point fraction (fract8 or fract16).
128      lerp8by8(   fromU8, toU8, fract8 )
129      lerp16by8(  fromU16, toU16, fract8 )
130      lerp15by8(  fromS16, toS16, fract8 )
131        == from + (( to - from ) * fract8) / 256)
132      lerp16by16( fromU16, toU16, fract16 )
133        == from + (( to - from ) * fract16) / 65536)
134      map8( in, rangeStart, rangeEnd)
135        == map( in, 0, 255, rangeStart, rangeEnd);
136
137  - Optimized memmove, memcpy, and memset, that are
138    faster than standard avr-libc 1.8.
139       memmove8( dest, src,  bytecount)
140       memcpy8(  dest, src,  bytecount)
141       memset8(  buf, value, bytecount)
142
143  - Beat generators which return sine or sawtooth
144    waves in a specified number of Beats Per Minute.
145    Sine wave beat generators can specify a low and
146    high range for the output.  Sawtooth wave beat
147    generators always range 0-255 or 0-65535.
148      beatsin8( BPM, low8, high8)
149          = (sine(beatphase) * (high8-low8)) + low8
150      beatsin16( BPM, low16, high16)
151          = (sine(beatphase) * (high16-low16)) + low16
152      beatsin88( BPM88, low16, high16)
153          = (sine(beatphase) * (high16-low16)) + low16
154      beat8( BPM)  = 8-bit repeating sawtooth wave
155      beat16( BPM) = 16-bit repeating sawtooth wave
156      beat88( BPM88) = 16-bit repeating sawtooth wave
157    BPM is beats per minute in either simple form
158    e.g. 120, or Q8.8 fixed-point form.
159    BPM88 is beats per minute in ONLY Q8.8 fixed-point
160    form.
161
162 Lib8tion is pronounced like 'libation': lie-BAY-shun
163
164 */
165
166
167
168 #include <stdint.h>
169
170 #define LIB8STATIC static inline
171 #define LIB8STATIC_ALWAYS_INLINE static inline
172
173 #if !defined(__AVR__)
174 #include <string.h>
175 // for memmove, memcpy, and memset if not defined here
176 #endif
177
178 #if defined(__arm__)
179
180 #if defined(FASTLED_TEENSY3)
181 // Can use Cortex M4 DSP instructions
182 #define QADD8_C 0
183 #define QADD7_C 0
184 #define QADD8_ARM_DSP_ASM 1
185 #define QADD7_ARM_DSP_ASM 1
186 #else
187 // Generic ARM
188 #define QADD8_C 1
189 #define QADD7_C 1
190 #endif
191
192 #define QSUB8_C 1
193 #define SCALE8_C 1
194 #define SCALE16BY8_C 1
195 #define SCALE16_C 1
196 #define ABS8_C 1
197 #define MUL8_C 1
198 #define QMUL8_C 1
199 #define ADD8_C 1
200 #define SUB8_C 1
201 #define EASE8_C 1
202 #define AVG8_C 1
203 #define AVG7_C 1
204 #define AVG16_C 1
205 #define AVG15_C 1
206 #define BLEND8_C 1
207
208
209 #elif defined(__AVR__)
210
211 // AVR ATmega and friends Arduino
212
213 #define QADD8_C 0
214 #define QADD7_C 0
215 #define QSUB8_C 0
216 #define ABS8_C 0
217 #define ADD8_C 0
218 #define SUB8_C 0
219 #define AVG8_C 0
220 #define AVG7_C 0
221 #define AVG16_C 0
222 #define AVG15_C 0
223
224 #define QADD8_AVRASM 1
225 #define QADD7_AVRASM 1
226 #define QSUB8_AVRASM 1
227 #define ABS8_AVRASM 1
228 #define ADD8_AVRASM 1
229 #define SUB8_AVRASM 1
230 #define AVG8_AVRASM 1
231 #define AVG7_AVRASM 1
232 #define AVG16_AVRASM 1
233 #define AVG15_AVRASM 1
234
235 // Note: these require hardware MUL instruction
236 //       -- sorry, ATtiny!
237 #if !defined(LIB8_ATTINY)
238 #define SCALE8_C 0
239 #define SCALE16BY8_C 0
240 #define SCALE16_C 0
241 #define MUL8_C 0
242 #define QMUL8_C 0
243 #define EASE8_C 0
244 #define BLEND8_C 0
245 #define SCALE8_AVRASM 1
246 #define SCALE16BY8_AVRASM 1
247 #define SCALE16_AVRASM 1
248 #define MUL8_AVRASM 1
249 #define QMUL8_AVRASM 1
250 #define EASE8_AVRASM 1
251 #define CLEANUP_R1_AVRASM 1
252 #define BLEND8_AVRASM 1
253 #else
254 // On ATtiny, we just use C implementations
255 #define SCALE8_C 1
256 #define SCALE16BY8_C 1
257 #define SCALE16_C 1
258 #define MUL8_C 1
259 #define QMUL8_C 1
260 #define EASE8_C 1
261 #define BLEND8_C 1
262 #define SCALE8_AVRASM 0
263 #define SCALE16BY8_AVRASM 0
264 #define SCALE16_AVRASM 0
265 #define MUL8_AVRASM 0
266 #define QMUL8_AVRASM 0
267 #define EASE8_AVRASM 0
268 #define BLEND8_AVRASM 0
269 #endif
270
271 #else
272
273 // unspecified architecture, so
274 // no ASM, everything in C
275 #define QADD8_C 1
276 #define QADD7_C 1
277 #define QSUB8_C 1
278 #define SCALE8_C 1
279 #define SCALE16BY8_C 1
280 #define SCALE16_C 1
281 #define ABS8_C 1
282 #define MUL8_C 1
283 #define QMUL8_C 1
284 #define ADD8_C 1
285 #define SUB8_C 1
286 #define EASE8_C 1
287 #define AVG8_C 1
288 #define AVG7_C 1
289 #define AVG16_C 1
290 #define AVG15_C 1
291 #define BLEND8_C 1
292
293 #endif
294
295 ///@defgroup lib8tion Fast math functions
296 ///A variety of functions for working with numbers.
297 ///@{
298
299
300 ///////////////////////////////////////////////////////////////////////
301 //
302 // typdefs for fixed-point fractional types.
303 //
304 // sfract7 should be interpreted as signed 128ths.
305 // fract8 should be interpreted as unsigned 256ths.
306 // sfract15 should be interpreted as signed 32768ths.
307 // fract16 should be interpreted as unsigned 65536ths.
308 //
309 // Example: if a fract8 has the value "64", that should be interpreted
310 //          as 64/256ths, or one-quarter.
311 //
312 //
313 //  fract8   range is 0 to 0.99609375
314 //                 in steps of 0.00390625
315 //
316 //  sfract7  range is -0.9921875 to 0.9921875
317 //                 in steps of 0.0078125
318 //
319 //  fract16  range is 0 to 0.99998474121
320 //                 in steps of 0.00001525878
321 //
322 //  sfract15 range is -0.99996948242 to 0.99996948242
323 //                 in steps of 0.00003051757
324 //
325
326 /// ANSI unsigned short _Fract.  range is 0 to 0.99609375
327 ///                 in steps of 0.00390625
328 typedef uint8_t   fract8;   ///< ANSI: unsigned short _Fract
329
330 ///  ANSI: signed short _Fract.  range is -0.9921875 to 0.9921875
331 ///                 in steps of 0.0078125
332 typedef int8_t    sfract7;  ///< ANSI: signed   short _Fract
333
334 ///  ANSI: unsigned _Fract.  range is 0 to 0.99998474121
335 ///                 in steps of 0.00001525878
336 typedef uint16_t  fract16;  ///< ANSI: unsigned       _Fract
337
338 ///  ANSI: signed _Fract.  range is -0.99996948242 to 0.99996948242
339 ///                 in steps of 0.00003051757
340 typedef int16_t   sfract15; ///< ANSI: signed         _Fract
341
342
343 // accumXY types should be interpreted as X bits of integer,
344 //         and Y bits of fraction.
345 //         E.g., accum88 has 8 bits of int, 8 bits of fraction
346
347 typedef uint16_t  accum88;  ///< ANSI: unsigned short _Accum.  8 bits int, 8 bits fraction
348 typedef int16_t   saccum78; ///< ANSI: signed   short _Accum.  7 bits int, 8 bits fraction
349 typedef uint32_t  accum1616;///< ANSI: signed         _Accum. 16 bits int, 16 bits fraction
350 typedef int32_t   saccum1516;///< ANSI: signed         _Accum. 15 bits int, 16 bits fraction
351 typedef uint16_t  accum124; ///< no direct ANSI counterpart. 12 bits int, 4 bits fraction
352 typedef int32_t   saccum114;///< no direct ANSI counterpart. 1 bit int, 14 bits fraction
353
354
355
356 #include "math8.h"
357 #include "scale8.h"
358 #include "random8.h"
359 #include "trig8.h"
360
361 ///////////////////////////////////////////////////////////////////////
362
363
364
365
366
367
368
369 ///////////////////////////////////////////////////////////////////////
370 //
371 // float-to-fixed and fixed-to-float conversions
372 //
373 // Note that anything involving a 'float' on AVR will be slower.
374
375 /// sfract15ToFloat: conversion from sfract15 fixed point to
376 ///                  IEEE754 32-bit float.
377 LIB8STATIC float sfract15ToFloat( sfract15 y)
378 {
379     return y / 32768.0;
380 }
381
382 /// conversion from IEEE754 float in the range (-1,1)
383 ///                  to 16-bit fixed point.  Note that the extremes of
384 ///                  one and negative one are NOT representable.  The
385 ///                  representable range is basically
386 LIB8STATIC sfract15 floatToSfract15( float f)
387 {
388     return f * 32768.0;
389 }
390
391
392
393 ///////////////////////////////////////////////////////////////////////
394 //
395 // memmove8, memcpy8, and memset8:
396 //   alternatives to memmove, memcpy, and memset that are
397 //   faster on AVR than standard avr-libc 1.8
398
399 #if defined(__AVR__)
400 void * memmove8( void * dst, const void * src, uint16_t num );
401 void * memcpy8 ( void * dst, const void * src, uint16_t num )  __attribute__ ((noinline));
402 void * memset8 ( void * ptr, uint8_t value, uint16_t num ) __attribute__ ((noinline)) ;
403 #else
404 // on non-AVR platforms, these names just call standard libc.
405 #define memmove8 memmove
406 #define memcpy8 memcpy
407 #define memset8 memset
408 #endif
409
410
411 ///////////////////////////////////////////////////////////////////////
412 //
413 // linear interpolation, such as could be used for Perlin noise, etc.
414 //
415
416 // A note on the structure of the lerp functions:
417 // The cases for b>a and b<=a are handled separately for
418 // speed: without knowing the relative order of a and b,
419 // the value (a-b) might be overflow the width of a or b,
420 // and have to be promoted to a wider, slower type.
421 // To avoid that, we separate the two cases, and are able
422 // to do all the math in the same width as the arguments,
423 // which is much faster and smaller on AVR.
424
425 /// linear interpolation between two unsigned 8-bit values,
426 /// with 8-bit fraction
427 LIB8STATIC uint8_t lerp8by8( uint8_t a, uint8_t b, fract8 frac)
428 {
429     uint8_t result;
430     if( b > a) {
431         uint8_t delta = b - a;
432         uint8_t scaled = scale8( delta, frac);
433         result = a + scaled;
434     } else {
435         uint8_t delta = a - b;
436         uint8_t scaled = scale8( delta, frac);
437         result = a - scaled;
438     }
439     return result;
440 }
441
442 /// linear interpolation between two unsigned 16-bit values,
443 /// with 16-bit fraction
444 LIB8STATIC uint16_t lerp16by16( uint16_t a, uint16_t b, fract16 frac)
445 {
446     uint16_t result;
447     if( b > a ) {
448         uint16_t delta = b - a;
449         uint16_t scaled = scale16(delta, frac);
450         result = a + scaled;
451     } else {
452         uint16_t delta = a - b;
453         uint16_t scaled = scale16( delta, frac);
454         result = a - scaled;
455     }
456     return result;
457 }
458
459 /// linear interpolation between two unsigned 16-bit values,
460 /// with 8-bit fraction
461 LIB8STATIC uint16_t lerp16by8( uint16_t a, uint16_t b, fract8 frac)
462 {
463     uint16_t result;
464     if( b > a) {
465         uint16_t delta = b - a;
466         uint16_t scaled = scale16by8( delta, frac);
467         result = a + scaled;
468     } else {
469         uint16_t delta = a - b;
470         uint16_t scaled = scale16by8( delta, frac);
471         result = a - scaled;
472     }
473     return result;
474 }
475
476 /// linear interpolation between two signed 15-bit values,
477 /// with 8-bit fraction
478 LIB8STATIC int16_t lerp15by8( int16_t a, int16_t b, fract8 frac)
479 {
480     int16_t result;
481     if( b > a) {
482         uint16_t delta = b - a;
483         uint16_t scaled = scale16by8( delta, frac);
484         result = a + scaled;
485     } else {
486         uint16_t delta = a - b;
487         uint16_t scaled = scale16by8( delta, frac);
488         result = a - scaled;
489     }
490     return result;
491 }
492
493 /// linear interpolation between two signed 15-bit values,
494 /// with 8-bit fraction
495 LIB8STATIC int16_t lerp15by16( int16_t a, int16_t b, fract16 frac)
496 {
497     int16_t result;
498     if( b > a) {
499         uint16_t delta = b - a;
500         uint16_t scaled = scale16( delta, frac);
501         result = a + scaled;
502     } else {
503         uint16_t delta = a - b;
504         uint16_t scaled = scale16( delta, frac);
505         result = a - scaled;
506     }
507     return result;
508 }
509
510 ///  map8: map from one full-range 8-bit value into a narrower
511 /// range of 8-bit values, possibly a range of hues.
512 ///
513 /// E.g. map myValue into a hue in the range blue..purple..pink..red
514 /// hue = map8( myValue, HUE_BLUE, HUE_RED);
515 ///
516 /// Combines nicely with the waveform functions (like sin8, etc)
517 /// to produce continuous hue gradients back and forth:
518 ///
519 ///          hue = map8( sin8( myValue), HUE_BLUE, HUE_RED);
520 ///
521 /// Mathematically simiar to lerp8by8, but arguments are more
522 /// like Arduino's "map"; this function is similar to
523 ///
524 ///          map( in, 0, 255, rangeStart, rangeEnd)
525 ///
526 /// but faster and specifically designed for 8-bit values.
527 LIB8STATIC uint8_t map8( uint8_t in, uint8_t rangeStart, uint8_t rangeEnd)
528 {
529     uint8_t rangeWidth = rangeEnd - rangeStart;
530     uint8_t out = scale8( in, rangeWidth);
531     out += rangeStart;
532     return out;
533 }
534
535
536 ///////////////////////////////////////////////////////////////////////
537 //
538 // easing functions; see http://easings.net
539 //
540
541 /// ease8InOutQuad: 8-bit quadratic ease-in / ease-out function
542 ///                Takes around 13 cycles on AVR
543 #if EASE8_C == 1
544 LIB8STATIC uint8_t ease8InOutQuad( uint8_t i)
545 {
546     uint8_t j = i;
547     if( j & 0x80 ) {
548         j = 255 - j;
549     }
550     uint8_t jj  = scale8(  j, j);
551     uint8_t jj2 = jj << 1;
552     if( i & 0x80 ) {
553         jj2 = 255 - jj2;
554     }
555     return jj2;
556 }
557
558 #elif EASE8_AVRASM == 1
559 // This AVR asm version of ease8InOutQuad preserves one more
560 // low-bit of precision than the C version, and is also slightly
561 // smaller and faster.
562 LIB8STATIC uint8_t ease8InOutQuad(uint8_t val) {
563     uint8_t j=val;
564     asm volatile (
565       "sbrc %[val], 7 \n"
566       "com %[j]       \n"
567       "mul %[j], %[j] \n"
568       "add r0, %[j]   \n"
569       "ldi %[j], 0    \n"
570       "adc %[j], r1   \n"
571       "lsl r0         \n" // carry = high bit of low byte of mul product
572       "rol %[j]       \n" // j = (j * 2) + carry // preserve add'l bit of precision
573       "sbrc %[val], 7 \n"
574       "com %[j]       \n"
575       "clr __zero_reg__   \n"
576       : [j] "+&a" (j)
577       : [val] "a" (val)
578       : "r0", "r1"
579       );
580     return j;
581 }
582
583 #else
584 #error "No implementation for ease8InOutQuad available."
585 #endif
586
587 /// ease16InOutQuad: 16-bit quadratic ease-in / ease-out function
588 // C implementation at this point
589 LIB8STATIC uint16_t ease16InOutQuad( uint16_t i)
590 {
591     uint16_t j = i;
592     if( j & 0x8000 ) {
593         j = 65535 - j;
594     }
595     uint16_t jj  = scale16( j, j);
596     uint16_t jj2 = jj << 1;
597     if( i & 0x8000 ) {
598         jj2 = 65535 - jj2;
599     }
600     return jj2;
601 }
602
603
604 /// ease8InOutCubic: 8-bit cubic ease-in / ease-out function
605 ///                 Takes around 18 cycles on AVR
606 LIB8STATIC fract8 ease8InOutCubic( fract8 i)
607 {
608     uint8_t ii  = scale8_LEAVING_R1_DIRTY(  i, i);
609     uint8_t iii = scale8_LEAVING_R1_DIRTY( ii, i);
610
611     uint16_t r1 = (3 * (uint16_t)(ii)) - ( 2 * (uint16_t)(iii));
612
613     /* the code generated for the above *'s automatically
614        cleans up R1, so there's no need to explicitily call
615        cleanup_R1(); */
616
617     uint8_t result = r1;
618
619     // if we got "256", return 255:
620     if( r1 & 0x100 ) {
621         result = 255;
622     }
623     return result;
624 }
625
626 /// ease8InOutApprox: fast, rough 8-bit ease-in/ease-out function
627 ///                   shaped approximately like 'ease8InOutCubic',
628 ///                   it's never off by more than a couple of percent
629 ///                   from the actual cubic S-curve, and it executes
630 ///                   more than twice as fast.  Use when the cycles
631 ///                   are more important than visual smoothness.
632 ///                   Asm version takes around 7 cycles on AVR.
633
634 #if EASE8_C == 1
635 LIB8STATIC fract8 ease8InOutApprox( fract8 i)
636 {
637     if( i < 64) {
638         // start with slope 0.5
639         i /= 2;
640     } else if( i > (255 - 64)) {
641         // end with slope 0.5
642         i = 255 - i;
643         i /= 2;
644         i = 255 - i;
645     } else {
646         // in the middle, use slope 192/128 = 1.5
647         i -= 64;
648         i += (i / 2);
649         i += 32;
650     }
651
652     return i;
653 }
654
655 #elif EASE8_AVRASM == 1
656 LIB8STATIC uint8_t ease8InOutApprox( fract8 i)
657 {
658     // takes around 7 cycles on AVR
659     asm volatile (
660         "  subi %[i], 64         \n\t"
661         "  cpi  %[i], 128        \n\t"
662         "  brcc Lshift_%=        \n\t"
663
664         // middle case
665         "  mov __tmp_reg__, %[i] \n\t"
666         "  lsr __tmp_reg__       \n\t"
667         "  add %[i], __tmp_reg__ \n\t"
668         "  subi %[i], 224        \n\t"
669         "  rjmp Ldone_%=         \n\t"
670
671         // start or end case
672         "Lshift_%=:              \n\t"
673         "  lsr %[i]              \n\t"
674         "  subi %[i], 96         \n\t"
675
676         "Ldone_%=:               \n\t"
677
678         : [i] "+&a" (i)
679         :
680         : "r0", "r1"
681         );
682     return i;
683 }
684 #else
685 #error "No implementation for ease8 available."
686 #endif
687
688
689
690 /// triwave8: triangle (sawtooth) wave generator.  Useful for
691 ///           turning a one-byte ever-increasing value into a
692 ///           one-byte value that oscillates up and down.
693 ///
694 ///           input         output
695 ///           0..127        0..254 (positive slope)
696 ///           128..255      254..0 (negative slope)
697 ///
698 /// On AVR this function takes just three cycles.
699 ///
700 LIB8STATIC uint8_t triwave8(uint8_t in)
701 {
702     if( in & 0x80) {
703         in = 255 - in;
704     }
705     uint8_t out = in << 1;
706     return out;
707 }
708
709
710 // quadwave8 and cubicwave8: S-shaped wave generators (like 'sine').
711 //           Useful for turning a one-byte 'counter' value into a
712 //           one-byte oscillating value that moves smoothly up and down,
713 //           with an 'acceleration' and 'deceleration' curve.
714 //
715 //           These are even faster than 'sin8', and have
716 //           slightly different curve shapes.
717 //
718
719 /// quadwave8: quadratic waveform generator.  Spends just a little more
720 ///            time at the limits than 'sine' does.
721 LIB8STATIC uint8_t quadwave8(uint8_t in)
722 {
723     return ease8InOutQuad( triwave8( in));
724 }
725
726 /// cubicwave8: cubic waveform generator.  Spends visibly more time
727 ///             at the limits than 'sine' does.
728 LIB8STATIC uint8_t cubicwave8(uint8_t in)
729 {
730     return ease8InOutCubic( triwave8( in));
731 }
732
733 /// squarewave8: square wave generator.  Useful for
734 ///           turning a one-byte ever-increasing value
735 ///           into a one-byte value that is either 0 or 255.
736 ///           The width of the output 'pulse' is
737 ///           determined by the pulsewidth argument:
738 ///
739 ///~~~
740 ///           If pulsewidth is 255, output is always 255.
741 ///           If pulsewidth < 255, then
742 ///             if input < pulsewidth  then output is 255
743 ///             if input >= pulsewidth then output is 0
744 ///~~~
745 ///
746 /// the output looking like:
747 ///
748 ///~~~
749 ///     255   +--pulsewidth--+
750 ///      .    |              |
751 ///      0    0              +--------(256-pulsewidth)--------
752 ///~~~
753 ///
754 /// @param in
755 /// @param pulsewidth
756 /// @returns square wave output
757 LIB8STATIC uint8_t squarewave8( uint8_t in, uint8_t pulsewidth)
758 {
759     if( in < pulsewidth || (pulsewidth == 255)) {
760         return 255;
761     } else {
762         return 0;
763     }
764 }
765
766
767 // Beat generators - These functions produce waves at a given
768 //                   number of 'beats per minute'.  Internally, they use
769 //                   the Arduino function 'millis' to track elapsed time.
770 //                   Accuracy is a bit better than one part in a thousand.
771 //
772 //       beat8( BPM ) returns an 8-bit value that cycles 'BPM' times
773 //                    per minute, rising from 0 to 255, resetting to zero,
774 //                    rising up again, etc..  The output of this function
775 //                    is suitable for feeding directly into sin8, and cos8,
776 //                    triwave8, quadwave8, and cubicwave8.
777 //       beat16( BPM ) returns a 16-bit value that cycles 'BPM' times
778 //                    per minute, rising from 0 to 65535, resetting to zero,
779 //                    rising up again, etc.  The output of this function is
780 //                    suitable for feeding directly into sin16 and cos16.
781 //       beat88( BPM88) is the same as beat16, except that the BPM88 argument
782 //                    MUST be in Q8.8 fixed point format, e.g. 120BPM must
783 //                    be specified as 120*256 = 30720.
784 //       beatsin8( BPM, uint8_t low, uint8_t high) returns an 8-bit value that
785 //                    rises and falls in a sine wave, 'BPM' times per minute,
786 //                    between the values of 'low' and 'high'.
787 //       beatsin16( BPM, uint16_t low, uint16_t high) returns a 16-bit value
788 //                    that rises and falls in a sine wave, 'BPM' times per
789 //                    minute, between the values of 'low' and 'high'.
790 //       beatsin88( BPM88, ...) is the same as beatsin16, except that the
791 //                    BPM88 argument MUST be in Q8.8 fixed point format,
792 //                    e.g. 120BPM must be specified as 120*256 = 30720.
793 //
794 //  BPM can be supplied two ways.  The simpler way of specifying BPM is as
795 //  a simple 8-bit integer from 1-255, (e.g., "120").
796 //  The more sophisticated way of specifying BPM allows for fractional
797 //  "Q8.8" fixed point number (an 'accum88') with an 8-bit integer part and
798 //  an 8-bit fractional part.  The easiest way to construct this is to multiply
799 //  a floating point BPM value (e.g. 120.3) by 256, (e.g. resulting in 30796
800 //  in this case), and pass that as the 16-bit BPM argument.
801 //  "BPM88" MUST always be specified in Q8.8 format.
802 //
803 //  Originally designed to make an entire animation project pulse with brightness.
804 //  For that effect, add this line just above your existing call to "FastLED.show()":
805 //
806 //     uint8_t bright = beatsin8( 60 /*BPM*/, 192 /*dimmest*/, 255 /*brightest*/ ));
807 //     FastLED.setBrightness( bright );
808 //     FastLED.show();
809 //
810 //  The entire animation will now pulse between brightness 192 and 255 once per second.
811
812
813 // The beat generators need access to a millisecond counter.
814 // On Arduino, this is "millis()".  On other platforms, you'll
815 // need to provide a function with this signature:
816 //   uint32_t get_millisecond_timer();
817 // that provides similar functionality.
818 // You can also force use of the get_millisecond_timer function
819 // by #defining USE_GET_MILLISECOND_TIMER.
820 #if (defined(ARDUINO) || defined(SPARK) || defined(FASTLED_HAS_MILLIS)) && !defined(USE_GET_MILLISECOND_TIMER)
821 // Forward declaration of Arduino function 'millis'.
822 //uint32_t millis();
823 #define GET_MILLIS millis
824 #else
825 uint32_t get_millisecond_timer(void);
826 #define GET_MILLIS get_millisecond_timer
827 #endif
828
829 // beat16 generates a 16-bit 'sawtooth' wave at a given BPM,
830 ///        with BPM specified in Q8.8 fixed-point format; e.g.
831 ///        for this function, 120 BPM MUST BE specified as
832 ///        120*256 = 30720.
833 ///        If you just want to specify "120", use beat16 or beat8.
834 LIB8STATIC uint16_t beat88( accum88 beats_per_minute_88, uint32_t timebase)
835 {
836     // BPM is 'beats per minute', or 'beats per 60000ms'.
837     // To avoid using the (slower) division operator, we
838     // want to convert 'beats per 60000ms' to 'beats per 65536ms',
839     // and then use a simple, fast bit-shift to divide by 65536.
840     //
841     // The ratio 65536:60000 is 279.620266667:256; we'll call it 280:256.
842     // The conversion is accurate to about 0.05%, more or less,
843     // e.g. if you ask for "120 BPM", you'll get about "119.93".
844     return (((GET_MILLIS()) - timebase) * beats_per_minute_88 * 280) >> 16;
845 }
846
847 /// beat16 generates a 16-bit 'sawtooth' wave at a given BPM
848 LIB8STATIC uint16_t beat16( accum88 beats_per_minute, uint32_t timebase)
849 {
850     // Convert simple 8-bit BPM's to full Q8.8 accum88's if needed
851     if( beats_per_minute < 256) beats_per_minute <<= 8;
852     return beat88(beats_per_minute, timebase);
853 }
854
855 /// beat8 generates an 8-bit 'sawtooth' wave at a given BPM
856 LIB8STATIC uint8_t beat8( accum88 beats_per_minute, uint32_t timebase)
857 {
858     return beat16( beats_per_minute, timebase) >> 8;
859 }
860
861 /// beatsin88 generates a 16-bit sine wave at a given BPM,
862 ///           that oscillates within a given range.
863 ///           For this function, BPM MUST BE SPECIFIED as
864 ///           a Q8.8 fixed-point value; e.g. 120BPM must be
865 ///           specified as 120*256 = 30720.
866 ///           If you just want to specify "120", use beatsin16 or beatsin8.
867 LIB8STATIC uint16_t beatsin88( accum88 beats_per_minute_88, uint16_t lowest, uint16_t highest, uint32_t timebase, uint16_t phase_offset)
868 {
869     uint16_t beat = beat88( beats_per_minute_88, timebase);
870     uint16_t beatsin = (sin16( beat + phase_offset) + 32768);
871     uint16_t rangewidth = highest - lowest;
872     uint16_t scaledbeat = scale16( beatsin, rangewidth);
873     uint16_t result = lowest + scaledbeat;
874     return result;
875 }
876
877 /// beatsin16 generates a 16-bit sine wave at a given BPM,
878 ///           that oscillates within a given range.
879 LIB8STATIC uint16_t beatsin16(accum88 beats_per_minute, uint16_t lowest, uint16_t highest, uint32_t timebase, uint16_t phase_offset)
880 {
881     uint16_t beat = beat16( beats_per_minute, timebase);
882     uint16_t beatsin = (sin16( beat + phase_offset) + 32768);
883     uint16_t rangewidth = highest - lowest;
884     uint16_t scaledbeat = scale16( beatsin, rangewidth);
885     uint16_t result = lowest + scaledbeat;
886     return result;
887 }
888
889 /// beatsin8 generates an 8-bit sine wave at a given BPM,
890 ///           that oscillates within a given range.
891 LIB8STATIC uint8_t beatsin8( accum88 beats_per_minute, uint8_t lowest, uint8_t highest, uint32_t timebase, uint8_t phase_offset)
892 {
893     uint8_t beat = beat8( beats_per_minute, timebase);
894     uint8_t beatsin = sin8( beat + phase_offset);
895     uint8_t rangewidth = highest - lowest;
896     uint8_t scaledbeat = scale8( beatsin, rangewidth);
897     uint8_t result = lowest + scaledbeat;
898     return result;
899 }
900
901
902 /// Return the current seconds since boot in a 16-bit value.  Used as part of the
903 /// "every N time-periods" mechanism
904 LIB8STATIC uint16_t seconds16(void)
905 {
906     uint32_t ms = GET_MILLIS();
907     uint16_t s16;
908     s16 = ms / 1000;
909     return s16;
910 }
911
912 /// Return the current minutes since boot in a 16-bit value.  Used as part of the
913 /// "every N time-periods" mechanism
914 LIB8STATIC uint16_t minutes16(void)
915 {
916     uint32_t ms = GET_MILLIS();
917     uint16_t m16;
918     m16 = (ms / (60000L)) & 0xFFFF;
919     return m16;
920 }
921
922 /// Return the current hours since boot in an 8-bit value.  Used as part of the
923 /// "every N time-periods" mechanism
924 LIB8STATIC uint8_t hours8(void)
925 {
926     uint32_t ms = GET_MILLIS();
927     uint8_t h8;
928     h8 = (ms / (3600000L)) & 0xFF;
929     return h8;
930 }
931
932 ///@}
933
934 #endif