#include <math.h>
#include "svg.h"

#define CENTER_X  148.5
#define CENTER_Y  105.0

#define MY_PI  3.1415926535

//== 極方程式を描画

// x = r cos(θ) + cx
// y = r sin(θ) + cy
// r/t = 1 + sc sin(stc θ) + cc cos(ctc θ)

// 中心座標 cx cy
// 何倍で表示するか t
// sinの係数 sc
// cosの係数 cc
// sinのθの係数 stc
// cosのθの係数 ctc

// 荒さ (255の約数であることを推奨) d
void polar(double cx, double cy, double t, double sc, double cc, int stc, int ctc, int d) {
    int i;
    int unit = (0xFF / d) + 1;
    int len = 6*unit;
    // 点座標
    double lx = cx + (1.0 + cc)*t;
    double ly = cy;
    // 色
    int cr = 0xFF;
    int cg = 0x00;
    int cb = 0x00;

    for (i = 1; i <= len; i++) {
        // 極方程式
        double a = i * 2*MY_PI / len;
        double tr = 1.0 + sc*sin(a*stc) + cc*cos(a*ctc);
        double nx = cx + tr*cos(a)*t;
        double ny = cy - tr*sin(a)*t;
        // 色 (RGB)
        stroke(rgb255(cr, cg, cb));
        // 描画
        line(lx, ly, nx, ny);
        // 座標更新
        lx = nx;
        ly = ny;
        // 色更新
        if (i % unit == 0) continue;
        switch (i / unit) {
        case 0: cg += d; break;
        case 1: cr -= d; break;
        case 2: cb += d; break;
        case 3: cg -= d; break;
        case 4: cr += d; break;
        case 5: cb -= d; break;
        }
    }
}

// EntryPoint
int main(void) {
    start();
    rulers();

    // 第三引数が大きさ
    // 第四～第七引数 (式の係数) を変えると大きく形が変わる
    // 最後の引数を小さくすると角ばった図形にできる
    polar(CENTER_X, CENTER_Y, 40, 0.5, 0.3, 6, 24, 17);

    finish();
    return 0;
}
