import utime
import display
import math

FPS = 25
SLEEP_TIME = 1 / FPS  # seconds
WIDTH =  160
HEIGHT =  80
TWO_PI = 3.14 * 2

buffer = []

# table of sine values for faster processing
sin_table = []

def init_sin_table():
    tab_size = 500
    for i in range(tab_size):
        x = i/tab_size * TWO_PI
        sin_table.append( math.sin(x) )

def mysin(x):
    global sin_table

    x2 = x % TWO_PI
    x3 = len(sin_table) * x2 / TWO_PI
    return sin_table[int(x3)]

def mycos(x):
    return mysin(x + 3.14)

def init_buffer():
    global buffer

    for _x in range(WIDTH):
        for _y in range(HEIGHT):
            buffer.append(0)

def handle_px(x, y, t, p):
    v = mysin(1*(p['x']*x*mysin(t/2) +
                 p['y']*y*mycos(t/3)) + t)
    # -1 < sin() < +1
    # therfore correct the value and bring into range [0, 1]
    v = (v+1.0) / 2.0
    return v

def draw_image_buffered(t, disp, param):
    global buffer

    for x in range(WIDTH):
        for y in range(HEIGHT):
            # drawing not every pixel
            if x % 6 == 0 and y % 6 == 0:
                v = handle_px(x, y, t, param)
                c = 255 if v>0.5 else 0

                index = y * WIDTH + x
                c_buf = buffer[index]
                # only draw if value in buffer changed
                if c != c_buf:
                    col = (c, c, 0)
                    disp.circ(x,y,3,col=col)
                    buffer[index] = c

    disp.update()

def main():
    t = 0.0
    disp = display.open()

    init_buffer()
    init_sin_table()

    utime.sleep(1)

    disp.clear()
    params = {'x': 0.3, 'y': 1.2, 'current': 'x'}
    while True:
        draw_image_buffered(t, disp, params)
        t += 0.1

    disp.close()

print("Starting rotplasma")
main()