Skip to content

Instantly share code, notes, and snippets.

@micromeeeter
Created May 18, 2017 05:53
Show Gist options
  • Save micromeeeter/86210e9f1d9ffbb84149a5956a8a2f8e to your computer and use it in GitHub Desktop.
Save micromeeeter/86210e9f1d9ffbb84149a5956a8a2f8e to your computer and use it in GitHub Desktop.
n次ベジェ曲線を実装する
//SFC17「CGとCADの数理」で出たn次ベジェ曲線を実装する課題
//本当はaddDegreeとかやりたくない、addPointだけでやりたいから時間が出来たらやる
//コメントがめんどくさいのであとでやる
class BezierCurve {
ArrayList<Integer> Px = new ArrayList<Integer>();
ArrayList<Integer> Py = new ArrayList<Integer>();
PVector[] R;
int tn;
int n; //degree
BezierCurve() { //constructor
tn = 20;
R = new PVector[tn];
n = 1;
}
void addPoint(int x, int y) {
Px.add(x);
Py.add(y);
}
void addDegree(int degree) {
n = degree;
}
void draw() {
int tt;
float t = 0.0;
float ts = (float)1 / tn;
float[] Bt = new float[n+1];
int[] coefData = {1, 1,1, 1,2,1, 1,3,3,1, 1,4,6,4,1, 1,5,10,10,5,1, 1,6,15,20,15,6,1, 1,7,21,35,35,21,7,1, 1,8,28,56,70,56,28,8,1, 1,9,36,84,126,126,84,36,9,1};
int[] coef = new int[n+1];
int begin = 0;
for (int k = 1; k <= n; k++) {
begin += k;
}
for (int k = 0; k <= n; k++) {
coef[k] = coefData[begin+k];
}
stroke(0, 255, 255);
fill(0, 255, 255, 30);
for (int k = 0; k < n; k++) {
line(Px.get(k), Py.get(k), Px.get(k+1), Py.get(k+1));
}
line(Px.get(n), Py.get(n), Px.get(0), Py.get(0));
for (int k = 0; k < n+1; k++) {
fill(0, 255, 255);
ellipse(Px.get(k), Py.get(k), 10, 10);
fill(255, 255, 255);
text('P' + k, Px.get(k), Py.get(k));
}
noFill();
stroke(255, 255, 255);
for (tt = 0; tt < tn; tt += 1) {
for (int k = 0; k < n+1; k++) {
Bt[k] = 1.0;
}
for (int k = 0; k < n+1; k++) {
Bt[k] = (float)coef[k];
for (int j = 0; j < k; j++) Bt[k] = Bt[k] * t;
for (int l = 0; l < n-k; l++) Bt[k] = Bt[k] * (1-t);
}
R[tt] = new PVector();
R[tt].x = 0.0;
R[tt].y = 0.0;
for (int g = 0; g < n+1; g++) {
R[tt].x += Px.get(g) * Bt[g];
R[tt].y += Py.get(g) * Bt[g];
}
if (tt != 0) {
line(R[tt-1].x, R[tt-1].y, R[tt].x, R[tt].y);
}
t = t + ts;
}
line(R[tt-1].x, R[tt-1].y, Px.get(n), Py.get(n));
}
}
BezierCurve b0;
void setup() {
size(400, 400);
b0 = new BezierCurve();
int[] px = new int[9];
int[] py = new int[9];
px[0] = 20; py[0] = 300;
px[1] = 140; py[1] = 100;
px[2] = 280; py[2] = 100;
px[3] = 380; py[3] = 300;
px[4] = 300; py[4] = 300;
px[5] = 280; py[5] = 200;
px[6] = 150; py[6] = 180;
px[7] = 140; py[7] = 170;
px[8] = 130; py[8] = 300;
for (int i = 0; i < 8; i++) {
b0.addPoint(px[i], py[i]);
}
b0.addDegree(7); //input degree
}
void draw() {
background(40);
text("BezierCurve", 10, 20);
b0.draw();
stop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment