モノ創りで国造りを

ハード/ソフト問わず知見をまとめてます

Processingでシミュレーション---pixels使うと早い---

Processingでシミュレーションすると 各グリッドの描画に時間がかかる事が判明し、
対策としてpixelを活用すれば良いことがわかった。

例えば以下のような、砂嵐を描画するコードの場合

int cols = 600;
int rows = 600;

void setup() {
  size(600, 600);
  background(255);
  smooth();
  frameRate(60);
}

void draw() {
  for (int x = 0; x< cols; x++) {
    for (int y = 0; y< rows; y++) {
      color tmp = color(random(255));
      stroke(random(255));
      point(x, y);
    }
  }
}

グリッドが600x600だとPCの処理能力を大幅に超えるため、FPSがわずか2~3程度の劇遅に。

ここでpixelを活用すると、FPSは設定した通り60になる。

int cols = 600;
int rows = 600;

void setup() {
  size(600, 600);
  background(255);
  smooth();
  frameRate(60);

  loadPixels();//追加
}

void draw() {
  for (int x = 0; x< cols; x++) {
    for (int y = 0; y< rows; y++) {
      color tmp = color(random(255));
      //stroke(random(255));
      //point(x, y);
      pixels[y*width + x] = int(tmp);//追加
    }
  }
  updatePixels();//追加
}

わずか3行追加するだけで爆速になる。

ここまでは前回の投稿で述べた通り。
さて、問題はこのpixelを3Dシミュレーションに活用できるかどうか。
以下のようにP3Dにそのままpixelを活用しても、
残念ながら、描画は2Dだった。

int cols = 600;
int rows = 600;

void setup() {
  size(600, 600, P3D);
  background(255);
  smooth();
  frameRate(60);

  loadPixels();
}

void draw() {
  rotateY(PI/8);
  for (int x = 0; x< cols; x++) {
    for (int y = 0; y< rows; y++) {
      color tmp = color(random(255));
      //stroke(random(255));
      //point(x, y);
      pixels[y*width + x] = int(tmp);
    }
  }
  updatePixels();
}

うーむ、どうしたものか・・・
今後3Dのシミュレーション結果を高速で表示する方法を調査していきます。