package sample.svg;
import static util.SVGUtil.*;

public class Hilbert {
	private static int color;
	private static int dcolor = 1;

	private static void forwardPlus(double d) {
	    forward(d);
	    stroke(color = rotateH360(color, dcolor));
	}

	private static void hilbertA(int n, double d) {
	    if (n==0) return;
	    turn(90);
	    hilbertB(n-1, d);
	    forwardPlus(d);
	    turn(-90);
	    hilbertA(n-1, d);
	    forwardPlus(d);
	    hilbertA(n-1, d);
	    turn(-90);
	    forwardPlus(d);
	    hilbertB(n-1, d);
	    turn(90);
	}

	private static void hilbertB(int n, double d) {
	    if (n==0) return;
	    turn(-90);
	    hilbertA(n-1, d);
	    forwardPlus(d);
	    turn(90);
	    hilbertB(n-1, d);
	    forwardPlus(d);
	    hilbertB(n-1, d);
	    turn(90);
	    forwardPlus(d);
	    hilbertA(n-1, d);
	    turn(-90);
	}

	private static void moor(int n, double d) {
	    hilbertA(n-1, d);
	    forwardPlus(d);
	    hilbertA(n-1, d);
	    turn(-90);
	    forwardPlus(d);
	    turn(-90);
	    hilbertA(n-1, d);
	    forwardPlus(d);
	    hilbertA(n-1, d);
	}

	public static void main(String[] args) {
	    int n = 5;
	    double d = 5.5;

	    start();
	    stroke(color = hsb360(0, 100, 100));
	    strokeWeight(0.5);
	    penUp();
	    forward(-(16-0.5)*d);  /* 16 = pow(2, n-1) */
	    turn(90);
	    forward(-d/2);
	    penDown();
	        
	    forwardPlus(d);
	    turn(-90);
	    moor(n, d);
	    finish();
	}
}
