import static util.Common.hsb360;
import static util.SVGUtil.*;

public class BookCoverPolar {
	private static double startX, startY, width, height;
	private static int cols, rows;

	//== 極方程式を描画

	// x = r cos(θ) + cx
	// y = r sin(θ) + cy
	// r/t = 1 + sc sin(stc θ) + cc cos(ctc θ)

	// 何倍で表示するか t
	// sinの係数 sc
	// cosの係数 cc
	// sinのθの係数 stc
	// cosのθの係数 ctc

	// 荒さ (255の約数であることを推奨) d
	private static void polar(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 = (1.0 + cc)*t;
		double ly = 0;
		// 色
		int cr = 0xFF;
		int cg = 0x00;
		int cb = 0x00;

		for (i = 1; i <= len; i++) {
			// 極方程式
			double a = i * 2*PI / len;
			double tr = 1.0 + sc*sin(a*stc) + cc*cos(a*ctc);
			double nx = tr*cos(a)*t;
			double ny = 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;
			}
		}
	}


	private static void CardSpec(double sx, double sy, double dx, double dy, int c, int r) {
		startX = sx; startY = sy; width = dx; height = dy;
		cols = c; rows = r;
	}
	
	private static void CardSpec(double sx, double sy, int c, int r) {
		CardSpec(sx, sy, (pageWidth() - sx * 2) / c , (pageHeight() - sy * 2) / r, c, r);
	}

	private static void init() {
	}

	private static void drawFrame() {
		strokeWeight(0.1);
		stroke(bw1(0));
		noFill();
		rect(0, 0, width, height);
	}

	private static void drawCard(int n, int i, int j, double ratio) {
		double sc = 0.1 * n;
		double cc = 0.1 * (rows * cols - n);
		double stc = 5;
		double ctc = 10;

		noStroke();
//		drawFrame();									// デバッグ用
//		fill(hsb360(ratio*360+30, 100, 100));          // ★　色の指定
//		textFont("Times New Roman", 4);
//		text(String.format("r ＝ 1 ＋ %.2f sin(%.2f θ) ＋ %.2f cos(%.2f θ)", sc, stc, cc, ctc), 10, 50);
		
		noFill();
		pushMatrix();
		strokeWeight(1);
		translate(width*0.5, height*0.5);
		polar(6.0, sc, cc, (int)stc, (int)ctc, 1);
		popMatrix();
	}

	public static void main(String[] args) {
		int i, j, n=0;
		double x;
		start();
		rulers();
		init();
		
//		CardSpec(20, 28, 4, 3);  // A4 縦 3 x 横 4 の場合
		CardSpec(20, 28, 5, 4);    // A4 縦 4 x 横 5 の場合
//		CardSpec(20, 28, 6, 5);    // A4 縦 5 x 横 6 の場合
		
		x = startX;
		for (i=0; i<cols; i++) {
			double y = startY;
			for (j=0; j<rows; j++, n++) {
				pushMatrix();
				translate(x, y);
				drawCard(n, i, j, (double)n/(cols*rows));
				popMatrix();
				y += height;
			}
			x += width;
		}
		finish();
	}
}
