Test2


Informatik

Link zum Orf

https://cdn1.thr.com/sites/default/files/2016/02/simp2006_homerarmscrossed_f_hires2_-_h_2016.jpg

Advertisements

Point Cloud


Processing 2.0

Der Kinect Sensor bietet die einzigartige Möglichkeit die Distanz der einzelnen Bildpunkte zur Kamera zu messen. Wir nutzen diese Möglichkeit jetzt und zeichnen alle einzelnen Bildpunkte, die der Sensor liefert einfach im 3-dimensionalen Raum darzustellen. Das ganze bezeichnet man als Point Cloud.

141104_113108_52

/** Copyright 2014 Thomas Koberger
 */

// https://lernprocessing.wordpress.com/
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import SimpleOpenNI.*;
import java.util.Calendar;

SimpleOpenNI kinect;

void setup() {
  size(1200, 768, P3D);
  kinect = new SimpleOpenNI(this);
  kinect.enableDepth();
  stroke(255);
}

void draw() {
  background(0);
  kinect.update();

  // Verschiebe die Szene in den Mittelpunkt des Fensters
  translate(width/2, height/2, -500);
  // vertikal drehen, damit die Szene nicht auf dem Kopf steht
  rotateX(radians(180));
  // Rotationspunkt in die Mitte der Szene verschieben

  translate(0, 0, 1500);
  randomSeed(20);
  // Damit die Szene automatisch rotiert.
  rotateY((float)frameCount/50);
  translate(0, 0, -1500);

  // Einkommentieren, wenn man die Szene per Maus rotieren will!
  //  rotateY(map(mouseX, 0, width, -PI, PI));
  //  rotateX(map(mouseY, 0, width, -PI, PI));

  // Hier liefert die Kinect ein Array mit Vektoren
  PVector[] depthPoints = kinect.depthMapRealWorld();

  // Wir zeichnen nicht jeden Punkt, um die Sache zu beschleunigen
  for (int i = 0; i < depthPoints.length; i+= (int)random(2, 10)) {
    PVector currentPoint = depthPoints[i];
    stroke(map(currentPoint.z, 0, 7000, 255, 80));
    point(currentPoint.x, currentPoint.y, currentPoint.z);
  }
}

void keyReleased() {
  if (key == DELETE || key == BACKSPACE) background(360);
  if (key == 's' || key == 'S') saveFrame(timestamp()+"_##.png");
} 

//timestamp
String timestamp() {
  Calendar now = Calendar.getInstance();
  println("Frame saved");
  return String.format("%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS", now);
}

Farbe

Nun können wir auch beide Kameras der Kinect nutzen und den Punkten ihre entsprechende Farbe zuweisen. Dabei kommen die Tiefeninformationen von der IR und die Farbinformationen von der RGB Kamera. Die dafür notwendigen mathematischen Operationen, nämlich das Auffinden der korrespondierenden Punkte der beiden Kameras, erledigt die Kinect.

141107_164425_59

</pre>
<pre>/** Copyright 2014 Thomas Koberger
 */

// https://lernprocessing.wordpress.com/
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import SimpleOpenNI.*;
import java.util.Calendar;

SimpleOpenNI kinect;

void setup() {
  size(1200, 768, P3D);
  kinect = new SimpleOpenNI(this);
  kinect.enableDepth();
  // Aktiviert die RGB Kamera der Kinect
  kinect.enableRGB();
  //Berechnet die korresponierenden Punkte der beiden Kameras
  //Dadurch bekommen die korrespondierenden Punkte der Tiefen- und der RGB Kamera
  //die gleichen Indizes
  kinect.alternativeViewPointDepthToImage();
}

void draw() {
  background(0);
  kinect.update();

  // Verschiebe die Szene in den Mittelpunkt des Fensters
  translate(width/2, height/2, -500);
  // vertikal drehen, damit die Szene nicht auf dem Kopf steht
  rotateX(radians(180));
  // Rotationspunkt in die Mitte der Szene verschieben

  translate(0, 0, 1500);
 
  // Damit die Szene automatisch rotiert.
  rotateY((float)frameCount/50);
  translate(0, 0, -1500);

  // Einkommentieren, wenn man die Szene per Maus rotieren will!
  //  rotateY(map(mouseX, 0, width, -PI, PI));
  //  rotateX(map(mouseY, 0, width, -PI, PI));

  // Hier liefert die Kinect ein Array mit Vektoren
  PVector[] depthPoints = kinect.depthMapRealWorld();
  PImage rgbImage = kinect.rgbImage();
 
  // Wir zeichnen nicht jeden Punkt, um die Sache zu beschleunigen
  for (int i = 0; i < depthPoints.length; i+= 10) {
    PVector currentPoint = depthPoints[i];
    
    // Hiermit färben wir die Punkte der Tiefeninformation mit der entsprechend
    // Farbe aus der RGB Kamera ein.
    stroke(rgbImage.pixels[i],map(currentPoint.z,0,7000,255,80));
    point(currentPoint.x, currentPoint.y, currentPoint.z);
  }
  println(frameRate);
}

void keyReleased() {
  if (key == DELETE || key == BACKSPACE) background(360);
  if (key == 's' || key == 'S') saveFrame(timestamp()+"_##.png");
} 

//timestamp
String timestamp() {
  Calendar now = Calendar.getInstance();
  println("Frame saved");
  return String.format("%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS", now);
}

Linien

Nun kann man die einzelnen Punkte auch mit Linien verbinden.

 

/** Copyright 2014 Thomas Koberger
 */

// https://lernprocessing.wordpress.com/
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import SimpleOpenNI.*;
import java.util.Calendar;

SimpleOpenNI kinect;

void setup() {
  size(1200, 768, P3D);
  kinect = new SimpleOpenNI(this);
  kinect.enableDepth();
  // Aktiviert die RGB Kamera der Kinect
  kinect.enableRGB();
  //Berechnet die korresponierenden Punkte der beiden Kameras
  //Dadurch bekommen die korrespondierenden Punkte der Tiefen- und der RGB Kamera
  //die gleichen Indizes
  kinect.alternativeViewPointDepthToImage();
  noSmooth();
}

void draw() {
  background(0);
  kinect.update();

  // Verschiebe die Szene in den Mittelpunkt des Fensters
  translate(width/2, height/2, -500);
  // vertikal drehen, damit die Szene nicht auf dem Kopf steht
  rotateX(radians(180));
  // Rotationspunkt in die Mitte der Szene verschieben

  translate(0, 0, 1500);

  // Damit die Szene automatisch rotiert.
  rotateY((float)frameCount/50);
  translate(0, 0, -1500);

  // Einkommentieren, wenn man die Szene per Maus rotieren will!
  //  rotateY(map(mouseX, 0, width, -PI, PI));
  //  rotateX(map(mouseY, 0, width, -PI, PI));

  // Hier liefert die Kinect ein Array mit Vektoren
  PVector[] depthPoints = kinect.depthMapRealWorld();
  PImage rgbImage = kinect.rgbImage();
  strokeWeight(1);
  PVector prevPoint, currentPoint;
  prevPoint = new PVector(0, 0, 0);
  // Wir zeichnen nicht jeden Punkt, um die Sache zu beschleunigen
  for (int i = 20; i < depthPoints.length; i+= 3) {

    currentPoint = depthPoints[i];

    stroke(rgbImage.pixels[i]); 

    if (prevPoint.x!=0 && currentPoint.x!=0) {
      line(currentPoint.x, currentPoint.y, currentPoint.z, prevPoint.x, prevPoint.y, prevPoint.z);
    }
    
    // Wie speichern die Koordinaten des aktuellen Punkts als letzten Punkt
    prevPoint = currentPoint;
  }
  println(frameRate);
}

void keyReleased() {
  if (key == DELETE || key == BACKSPACE) background(360);
  if (key == 's' || key == 'S') saveFrame(timestamp()+"_##.png");
} 

//timestamp
String timestamp() {
  Calendar now = Calendar.getInstance();
  println("Frame saved");
  return String.format("%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS", now);
}

Kinect und Processing


Habe heute den Kinect Sensor bekommen. In Java kann man ihn mit verschiedenen Bibliotheken nutzen. Z.B. mit der Simple-OpenNI Bibliothek, welche die vielfältigsten Möglichkeiten bietet. Die Simple OpenNI ist ein OpenNI- und NITE Wrapper für Processing. Die Installation unter Win7 laut dieser Anleitung ist sehr einfach. Dann kann man den ersten Processing Code laufen lassen.

141103_145804_933
/** Copyright 2012 Thomas Koberger
 */
// https://lernprocessing.wordpress.com/
// Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import SimpleOpenNI.*;
import java.util.*;
SimpleOpenNI kinect;

void setup()
{
  size(640*2, 480);
  kinect = new SimpleOpenNI(this);
  kinect.enableDepth();
  kinect.enableIR();
}

void draw()
{
  kinect.update();
  image(kinect.depthImage(), 0, 0);
  image(kinect.irImage(), 640, 0);
  println(frameRate);
}

void keyReleased() {
  if (key == DELETE || key == BACKSPACE) background(360);
  if (key == 's' || key == 'S') saveFrame(timestamp()+&quot;_##.png&quot;);
}  


// timestamp
String timestamp() {
  Calendar now = Calendar.getInstance();
  return String.format(&quot;%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS&quot;, now);
}


Was also kann der Kinect Sensor leisten?

Er liefert neben dem RGB Bild ein, durch einen IR-Emitter und einen IR-Sensor erzeugtes, Tiefenbild der Umgebung (eine DepthMap).  Das versetzt uns als Programmierer in die Lage, die Position von Objekten festzustellen und darauf zu reagieren. Der Kinect Sensor kann also die Lage von Objekten im Raum erkennen. Die Bilder haben eine Auflösung von 640 x 480 Pixel.

Die Technik hat allerdings noch ein paar Einschränkungen. Erstens funktioniert der Tiefensensor erst ab einer Distanz von ~50 cm. Zweitens werfen Objekte im Vordergrund natürlich einen Schatten. Für im Schatten liegende Objekte ist natürlich keine Tiefen-Information verfügbar.

Eine kleine Rolle in diesem Zusammenhang spielt bei diesen Überlegungen auch, dass die RGB- und Tiefenkamera in einem Abstand von einigen cm ihren Blick auf die Welt offenbaren.

Ubuntu 12.04 laut Anleitung installiert.

Die Geburt der Sonne


Processing 2.0

Hierbei handelt es sich um eine Kombination der Techniken Additive Blending und Flocking. Es werden Partikel erzeugt, die sich dann in der Mitte verdichten.

Der Sketch wäre vielleicht in Processing 2.x auch mit anderen Techniken zu realisieren. Ich habe ihn aber nur von der Version 1.5 portiert.

/** Copyright 2014 Thomas Koberger
 */
// based on a flocking algorithm by Daniel Shiffman
// https://lernprocessing.wordpress.com/
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import processing.opengl.*;
import peasy.*;
import javax.media.opengl.*;
import javax.media.opengl.GL2;
import java.util.*;

// Flock
Flock flock;
Stars stars;

GL2 gl; 
PGraphicsOpenGL pgl;

PVector l[];
float str;

void setup() {
 size(1280, 720, OPENGL);

 // Create Flock
 flock = new Flock();
 stars = new Stars(400);

 for (int x = 0; x < 350; x+=1) {
 flock.addBoid(new Boid(new PVector(random(-500, 500), random(-500, 500)), random(5.0, 2), 0.5, 10000));
 Boid b = (Boid) flock.boids.get(flock.boids.size()-1);
 b.desiredseparation=random(3, 20);
 }

 for (int x = 0; x < 15; x+=1) {
 flock.addBoid(new Boid(new PVector(random(-500, 500), random(-500, 500)), random(29.0, 2), 0.5, 10000));
 Boid b = (Boid) flock.boids.get(flock.boids.size()-1);
 b.desiredseparation=random(20, 50);
 }
}

void draw() {
 hint(DISABLE_DEPTH_TEST);
 fill(0, 15);
 rect(-width, -height, width*2, height*2);
 translate(width/2, height/2, 300);

 pgl = (PGraphicsOpenGL) g; // g may change
 gl = ((PJOGL)beginPGL()).gl.getGL2();

 gl.glEnable( GL.GL_BLEND ); 
 gl.glEnable(GL.GL_LINE_SMOOTH); 

 // This fixes the overlap issue
 gl.glDisable(GL.GL_DEPTH_TEST);

 // Define the blend mode
 gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);

 stars.drawStars(gl);
 flock.run(gl);

 gl.glDisable(GL.GL_BLEND);
 endPGL();
 if (frameCount%100==1) println("Rate: "+frameRate);
 //saveFrame("line-####.jpg");
}

void keyReleased() {
 //if (key == DELETE || key == BACKSPACE) background(360);
 if (key == 's' || key == 'S') saveFrame(timestamp()+"_##.jpg");
} 

// timestamp
String timestamp() {
 Calendar now = Calendar.getInstance();
 println("Frame saved");
 return String.format("%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS", now);
}
// The Boid class

class Boid {

 PVector loc;
 PVector vel;
 PVector acc;

 float maxforce; // Maximum steering force
 float maxspeed; // Maximum speed
 float maxVertspeed; // Maximum speed vertical
 float maxVertforce; // Maximum speed vertical
 int lifeTime;

 float desiredseparation;// Distance to separate from neighbours
 float neighbordistAlgn; // Distance to align with neighbours
 float neighbordist; // Distance to stick to neighbours
 float desiredAvoidDist; // Distance to avoid Avoid Hunters

 float r, g, b, alpha;

 Boid(PVector l, float ms, float mf, int lt) {
 acc = new PVector(0, 0, 0 );
 vel = new PVector(0, 0, 0);
 loc = l.get();
 r = 2.0;
 maxspeed = ms;
 maxforce = mf;
 lifeTime= lt;
 maxVertspeed=ms*3;

 desiredseparation = 30.0;
 neighbordistAlgn = 15.0;
 neighbordist = 40.0;
 desiredAvoidDist = 300;
 }

 void run(ArrayList boids, GL2 gl) {
 flock(boids, gl);
 update();
 render(gl);
 lifeTime-=1;
 }

 // We accumulate a new acceleration each time based on three rules
 void flock(ArrayList boids, GL2 gl) {
 PVector sep = separate(boids); // Separation
 PVector ali = align(boids); // Alignment
 PVector coh = cohesion(boids, gl); // Cohesion
 PVector target = target(); // Food
 // Arbitrarily weight these forces
 sep.mult(2);
 ali.mult(0.5);
 coh.mult(1.0);
 target.mult(1.0);
 // Add the force vectors to acceleration
 acc.add(sep);
 acc.add(ali);
 acc.add(coh);
 acc.add(target);
 }

 // Method to update location
 void update() {
 // Update velocity
 vel.add(acc);
 // Limit speed
 vel.limit(maxspeed);
 loc.add(vel);
 // Reset accelertion to 0 each cycle
 acc.mult(0);
 }

 void render(GL2 gl) {
 PVector modelOrientation = new PVector(0, 0, 1); 
 PVector heading=new PVector(vel.x, vel.y, vel.z);
 heading.mult(2);

 if (PVector.dist(loc, new PVector(0, 0, 0))>70) {
 int lines=5;
 gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);

 for (int i=lines;i>0;i-=4) {
 gl.glLineWidth(i);
 gl.glColor4f(float(1-i/lines), 0.5-i/lines, 0.2+i/lines, 
 alpha/i);
 gl.glBegin(GL.GL_LINES); 
 gl.glVertex2f(loc.x-heading.x, loc.y-heading.y);
 gl.glVertex2f(loc.x, loc.y);
 gl.glEnd();
 }
 }
 }

 void seek(PVector target) {
 acc.add(steer(target, false));
 }

 void arrive(PVector target) {
 acc.add(steer(target, true));
 }

 // A method that calculates a steering vector towards a target
 // Takes a second argument, if true, it slows down as it approaches the target
 PVector steer(PVector target, boolean slowdown) {
 PVector steer; // The steering vector
 PVector desired = target.sub(target, loc); // A vector pointing from the location to the target
 float d = desired.mag(); // Distance from the target is the magnitude of the vector
 // If the distance is greater than 0, calc steering (otherwise return zero vector)
 if (d > 0) {
 // Normalize desired
 desired.normalize();
 // Two options for desired vector magnitude (1 -- based on distance, 2 -- maxspeed)
 if ((slowdown) && (d < 100.0)) desired.mult(maxspeed*(d/100.0)); // This damping is somewhat arbitrary
 else desired.mult(maxspeed);
 // Steering = Desired minus Velocity
 steer = target.sub(desired, vel);
 steer.limit(maxforce); // Limit to maximum steering force
 } 
 else {
 steer = new PVector(0, 0, 0);
 }
 return steer;
 }

 // Separation
 // Method checks for nearby boids and steers away
 PVector separate (ArrayList boids) {
 PVector steer = new PVector(0, 0, 0);
 int count = 0;
 // For every boid in the system, check if it's too close
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = PVector.dist(loc, other.loc);

 //verändert, damit der Scwarm besser zusammenhält
 // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
 if ((d > 0) && (d < desiredseparation/3)) {
 // Calculate vector pointing away from neighbor
 PVector diff = PVector.sub(loc, other.loc);
 diff.normalize();
 diff.div(d*10); // Weight by distance
 steer.add(diff);
 count++; // Keep track of how many
 }

 if ((d > 0) && (d < desiredseparation)) {
 // Calculate vector pointing away from neighbor
 PVector diff = PVector.sub(loc, other.loc);
 diff.normalize();
 diff.div(d/16); // Weight by distance
 steer.add(diff);
 count++; // Keep track of how many
 }
 }
 // Average -- divide by how many
 if (count > 0) {
 steer.div((float)count);
 }

 // As long as the vector is greater than 0
 if (steer.mag() > 0) {
 // Implement Reynolds: Steering = Desired - Velocity
 steer.normalize();
 steer.mult(maxspeed);
 steer.sub(vel);
 steer.limit(maxforce);
 }
 return steer;
 }

 // Alignment
 // For every nearby boid in the system, calculate the average velocity
 PVector align (ArrayList boids) {
 PVector steer = new PVector(0, 0, 0);
 int count = 0;
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = PVector.dist(loc, other.loc);
 if ((d > 0) && (d < neighbordistAlgn)) {
 steer.add(other.vel);
 count++;
 }
 }
 if (count > 0) {
 steer.div((float)count);
 }
 // As long as the vector is greater than 0
 if (steer.mag() > 0) {
 // Implement Reynolds: Steering = Desired - Velocity
 steer.normalize();
 steer.mult(maxspeed);
 steer.sub(vel);
 steer.limit(maxforce);
 }
 return steer;
 }

 // Cohesion
 // For the average location (i.e. center) of all nearby boids, calculate steering vector towards that location
 PVector cohesion (ArrayList boids, GL2 gl) {
 PVector sum = new PVector(0, 0, 0); // Start with empty vector to accumulate all locations
 int count = 0;

 gl.glEnable( GL.GL_BLEND ); 
 gl.glColor4f(0.95, 0.3, 0.2, 0.007);
 gl.glLineWidth(6);
 gl.glBegin(GL2.GL_POLYGON); 
 gl.glVertex2f(loc.x, loc.y);
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = loc.dist(other.loc); 

 if ((d > 0) && (d < neighbordist)) {
 sum.add(other.loc); // Add location
 count++;

 gl.glVertex2f(other.loc.x, other.loc.y);
 }
 }
 gl.glDisable( GL.GL_BLEND );
 gl.glEnd();

 // für Farbverdichtungen
 alpha = map(count, 0, 50, 0, 0.9);

 if (count > 0) {
 sum.div((float)count);
 return steer(sum, true); // Steer towards the location
 }
 return sum;
 }

 // Move Towards Target
 PVector target () {
 PVector sum = new PVector(0, 0, 0); // Start with empty vector to accumulate all locations
 //sum.limit(maxforce);
 return steer(sum, true); // Steer towards the location
 }

 boolean alive() {
 if (lifeTime<0) return false;
 else return true;
 }
}

// The Flock (a list of Boid objects)

class Flock {
 ArrayList boids; // An arraylist for all the boids

 Flock() {
 boids = new ArrayList(); // Initialize the arraylist
 }

 void run(ArrayList hunters, GL gl) {
 for (int i = 0; i < boids.size(); i++) {
 Boid b = (Boid) boids.get(i);
 }
 }
 void run(GL2 gl) {

 for (int i = 0; i < boids.size(); i++) {
 Boid b = (Boid) boids.get(i); 

 b.run(boids, gl); // Passing the entire list of boids to each boid individually

 if (!b.alive()) boids.remove(i);
 }
 }


 void addBoid(Boid b) {
 boids.add(b);
 }
}

// The Boid class

class Stars {

 PVector [] stars; 

 Stars(int amt) {

 stars = new PVector [amt];
 
 for (int i=0; i < amt; i++) {
 stars[i] = new PVector (random(-width/2, width/2), random(-height/2, height/2), 0);
 }
 }

 void drawStars(GL2 gl) {
 for (int i=0; i<stars.length;i++) {
 if(frameCount%5==0){
 gl.glColor4f(1, 1, 1, random(0.02, 0.2));
 float w=random(0.3, 1.2);
 gl.glLineWidth(w*2);
 gl.glBegin(GL.GL_LINES); 
 gl.glVertex3f(stars[i].x-w/2, stars[i].y, stars[i].z);
 gl.glVertex3f(stars[i].x+w/2, stars[i].y, stars[i].z);
 gl.glVertex3f(stars[i].x, stars[i].y-w/2, stars[i].z);
 gl.glVertex3f(stars[i].x, stars[i].y+w/2, stars[i].z);
 gl.glEnd();
 }
 }
 }
}


 

Polarlichter


Processing 2.0

Hierbei handelt es sich um eine Kombination der Techniken Additive Blending und Flocking. Es werden an zufälligen Koordinaten Partikelschwärme erzeugt, deren Partikel dann mit Linien verbunden werden. Diese werden dann additiv übereinander geblendet und ergeben farbliche Verdichtungen, die mich an Polarlichter erinnern. Außerdem werden im Hintergrund Sterne gezeichnet.

Der Sketch wäre vielleicht in Processing 2.x auch mit anderen Techniken zu realisieren. Ich habe ihn aber nur von der Version 1.5 portiert.

/** Copyright 2014 Thomas Koberger
 */
// based on a flocking algorithm by Daniel Shiffman
// https://lernprocessing.wordpress.com/
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import processing.opengl.*;
import javax.media.opengl.*;
import javax.media.opengl.GL2;
import java.util.*;

Flock flock;
Stars stars;

//Über diese Objekte kann man auf OPENGL features zugreifen
GL2 gl;
PGraphicsOpenGL pgl;

PVector l[];
float str;

void setup() {
 size(1280, 720, OPENGL);

 //Sterne und Schwarm erzeugen
 flock = new Flock();
 stars = new Stars(350);
}

void draw() {
 //Verhindert, dass Objekte am Schirm, die von anderen verdeckt werden nicht gezeichnet werden
 hint(DISABLE_DEPTH_TEST);
 fill(0, 20);
 rect(-width, -height, width*2, height*2);
 translate (width/2, height/2, -200);

 // OpenGL Object Setup
 pgl = (PGraphicsOpenGL) g; // g may change
 gl = ((PJOGL)beginPGL()).gl.getGL2();
 gl.glEnable( GL.GL_BLEND );
 gl.glEnable(GL.GL_LINE_SMOOTH); 

 // This fixes the overlap issue
 gl.glDisable(GL.GL_DEPTH_TEST);

 // Define the blend mode
 gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);

 //zeichne Sterne
 stars.drawStars(gl);

 if (frameCount%6==0) {
 //Add an initial set of boids into the system
 float x=random(-width/1.3, width/1.3);
 float y=random(-height/1.3, height/1.3);
 for (int i =(int) random(5,25); i > 0; i-=1) {
 flock.addBoid(new Boid(new PVector(x, y, 0), 10.0, 0.1, 300));
 }
 } 

 flock.run(gl);
 gl.glDisable(GL.GL_BLEND);
 endPGL();
 if (frameCount%100==1) println("Rate: "+frameRate);

 //einkommentieren, wenn man die Frames speichern will
 //saveFrame(timestamp()+"_##.jpg");
}

void mousePressed() {
 //fügt neue Boids hinzu
 if ( mouseButton==LEFT) {
 for (int x = 0; x < 30; x+=1) {
 flock.addBoid(new Boid(new PVector(mouseX-width*2/3, mouseY-height*2/3), 10.0, 0.1, 500));
 }
 }
}

void keyReleased() {
 //if (key == DELETE || key == BACKSPACE) background(360);
 if (key == 's' || key == 'S') saveFrame(timestamp()+"_##.jpg");
} 

// timestamp
String timestamp() {
 Calendar now = Calendar.getInstance();
 println("Frame saved");
 return String.format("%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS", now);
}

// The Boid class
// Original by Danial Shiffman modified by Thomas Koberger

class Boid {

 PVector loc;
 PVector vel;
 PVector acc;
 //float r;
 float maxforce; // Maximum steering force
 float maxspeed; // Maximum speed
 float maxVertspeed; // Maximum speed vertical
 float maxVertforce; // Maximum speed vertical
 int lifeTime;

 float desiredseparation;// Distance to separate from neighbours
 float neighbordistAlgn; // Distance to align with neighbours
 float neighbordist; // Distance to stick to neighbours
 float desiredAvoidDist; // Distance to avoid Avoid Hunters

 float r, g, b, alpha; 

 Boid(PVector l, float ms, float mf, int lt) {
 acc = new PVector(0, 0, 0 );
 vel = new PVector(0, 0, 0);
 loc = l.get();
 r = 2.0;
 maxspeed = ms;
 maxforce = mf;

 //definiert eine Lebensspanne für die einzelnen Boids
 lifeTime= lt;

 //definiert die Abstände, innerhalb derer sich die einzelnen Boids gegenseitig beeinflussen
 maxVertspeed=ms*3;
 desiredseparation = 8.0;
 neighbordistAlgn = 100.0;
 neighbordist = 60.0;
 }

 void run(ArrayList boids, GL2 gl) {
 flock(boids, gl);
 update();
 //borders();
 render(gl);
 lifeTime-=1;
 }

 // We accumulate a new acceleration each time based on three rules
 void flock(ArrayList boids, GL2 gl) {
 PVector sep = separate(boids); // Separation
 PVector ali = align(boids); // Alignment
 PVector coh = cohesion(boids, gl); // Cohesion
 PVector target = target(); // Food
 // Arbitrarily weight these forces
 sep.mult(2);
 ali.mult(1.0);
 coh.mult(0.1);
 target.mult(0.6);
 // Add the force vectors to acceleration
 acc.add(sep);
 acc.add(ali);
 acc.add(coh);
 acc.add(target);
 }

 // Method to update location
 void update() {
 // Update velocity
 vel.add(acc);
 // Limit speed
 vel.limit(maxspeed);
 loc.add(vel);
 // Reset accelertion to 0 each cycle
 acc.mult(0);
 }

 //Zeichne die Boids
 void render(GL2 gl) {
 PVector modelOrientation = new PVector(0, 0, 1);
 PVector heading=new PVector(vel.x, vel.y, vel.z);
 heading.mult(2);

 int lines=1;
 gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);
 for (int i=lines;i>0;i-=4) {
 gl.glLineWidth(i);
 gl.glColor4f(1-alpha*i/lines, 0.5-alpha*i/lines, alpha*i/lines,
 alpha/8);
 gl.glBegin(GL.GL_LINES);
 gl.glVertex2f(loc.x-heading.x, loc.y-heading.y);
 gl.glVertex2f(loc.x, loc.y);
 gl.glEnd();
 }
 }

 void seek(PVector target) {
 acc.add(steer(target, false));
 }

 void arrive(PVector target) {
 acc.add(steer(target, true));
 }

 // A method that calculates a steering vector towards a target
 // Takes a second argument, if true, it slows down as it approaches the target
 PVector steer(PVector target, boolean slowdown) {
 PVector steer; // The steering vector
 PVector desired = target.sub(target, loc); // A vector pointing from the location to the target
 float d = desired.mag(); // Distance from the target is the magnitude of the vector
 // If the distance is greater than 0, calc steering (otherwise return zero vector)
 if (d > 0) {
 // Normalize desired
 desired.normalize();
 // Two options for desired vector magnitude (1 -- based on distance, 2 -- maxspeed)
 if ((slowdown) && (d < 100.0)) desired.mult(maxspeed*(d/100.0)); // This damping is somewhat arbitrary
 else desired.mult(maxspeed);
 // Steering = Desired minus Velocity
 steer = target.sub(desired, vel);
 steer.limit(maxforce); // Limit to maximum steering force
 }
 else {
 steer = new PVector(0, 0, 0);
 }
 return steer;
 }

 // Separation
 // Method checks for nearby boids and steers away
 PVector separate (ArrayList boids) {
 PVector steer = new PVector(0, 0, 0);
 int count = 0;
 // For every boid in the system, check if it's too close
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = PVector.dist(loc, other.loc);

 //verändert, damit der Scwarm besser zusammenhält
 // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
 if ((d > 0) && (d < desiredseparation/3)) {
 // Calculate vector pointing away from neighbor
 PVector diff = PVector.sub(loc, other.loc);
 diff.normalize();
 diff.div(d*10); // Weight by distance
 steer.add(diff);
 count++; // Keep track of how many
 }

 if ((d > 0) && (d < desiredseparation)) {
 // Calculate vector pointing away from neighbor
 PVector diff = PVector.sub(loc, other.loc);
 diff.normalize();
 diff.div(d/16); // Weight by distance
 steer.add(diff);
 count++; // Keep track of how many
 }
 }
 // Average -- divide by how many
 if (count > 0) {
 steer.div((float)count);
 }

 // As long as the vector is greater than 0
 if (steer.mag() > 0) {
 // Implement Reynolds: Steering = Desired - Velocity
 steer.normalize();
 steer.mult(maxspeed);
 steer.sub(vel);
 steer.limit(maxforce);
 }
 return steer;
 }

 // Alignment
 // For every nearby boid in the system, calculate the average velocity
 PVector align (ArrayList boids) {
 PVector steer = new PVector(0, 0, 0);
 int count = 0;
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = PVector.dist(loc, other.loc);
 if ((d > 0) && (d < neighbordistAlgn)) {
 steer.add(other.vel);
 count++;
 }
 }
 if (count > 0) {
 steer.div((float)count);
 }
 //definiert den Rot Wert
 r=map(steer.mag(), 0, 10, 0, 0.9);
 // As long as the vector is greater than 0
 if (steer.mag() > 0) {
 // Implement Reynolds: Steering = Desired - Velocity
 steer.normalize();
 steer.mult(maxspeed);
 steer.sub(vel);
 steer.limit(maxforce);
 }
 return steer;
 }

 // Cohesion
 // For the average location (i.e. center) of all nearby boids, calculate steering vector towards that location
 PVector cohesion (ArrayList boids, GL2 gl) {
 PVector sum = new PVector(0, 0, 0); // Start with empty vector to accumulate all locations
 int count = 0;

 // Define the blend mode
 gl.glEnable( GL.GL_BLEND );
 gl.glColor4f(r, g, b, 0.004);
 gl.glLineWidth(8);
 gl.glBegin(GL2.GL_POLYGON);
 gl.glVertex2f(loc.x, loc.y);
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = loc.dist(other.loc);

 //definiert den Blau und Grün Wert
 b=map(d, 0, neighbordist*12, 0, 0.9);
 g=map(vel.mag(), 0, 10, 0, 0.9);

 if ((d > 0) && (d < neighbordist)) {
 sum.add(other.loc); // Add location
 count++;

 gl.glVertex2f(other.loc.x, other.loc.y);
 }
 }
 gl.glEnd();

 // für Farbverdichtungen
 alpha = map(count, 0, 50, 0, 1);

 if (count > 0) {
 sum.div((float)count);
 return steer(sum, true); // Steer towards the location
 }
 return sum;
 }

 // Move Towards Target
 PVector target () {
 PVector sum = new PVector(0, 0, 0); // Start with empty vector to accumulate all locations
 return steer(sum, true); // Steer towards the location
 }

 boolean alive() {
 if (lifeTime<0) return false;
 else return true;
 }
}

// The Flock (a list of Boid objects)

class Flock {
 ArrayList boids; // An arraylist for all the boids

 Flock() {
 boids = new ArrayList(); // Initialize the arraylist
 }

 void run(ArrayList hunters) {
 for (int i = 0; i < boids.size(); i++) {
 Boid b = (Boid) boids.get(i);
 }
 }
 void run(GL2 gl) {
 for (int i = 0; i < boids.size(); i++) {
 Boid b = (Boid) boids.get(i);
 b.run(boids, gl); // Passing the entire list of boids to each boid individually

 //Elimiert Boids, wenn sie den sichbaren bereich verlassen
 if (!b.alive() || b.loc.x>1200 || b.loc.x<-1200 || b.loc.y>1200 || b.loc.y<-1200) {
 boids.remove(i);
 }
 }
 }

 void addBoid(Boid b) {
 boids.add(b);
 }
}

// The Boid class

class Stars {

 PVector [] stars; 

 Stars(int amt) {

 stars = new PVector [amt];

 for (int i=0; i < amt; i++) {
 stars[i] = new PVector (random(-width, width), random(-height, height), 0);
 }
 }

 void drawStars(GL2 gl) {
 for (int i=0; i<stars.length;i++) {
 if(frameCount%5==0){
 gl.glColor4f(1, 1, 1, random(0.02, 0.2));
 float w=random(0.3, 1.2);
 gl.glLineWidth(w*2);
 gl.glBegin(GL.GL_LINES);
 gl.glVertex3f(stars[i].x-w/2, stars[i].y, stars[i].z);
 gl.glVertex3f(stars[i].x+w/2, stars[i].y, stars[i].z);
 gl.glVertex3f(stars[i].x, stars[i].y-w/2, stars[i].z);
 gl.glVertex3f(stars[i].x, stars[i].y+w/2, stars[i].z);
 gl.glEnd();
 }
 }
 }
}

 

Voronoi und die französiche Revolution


Processing 2.0

Hier nun 2 Anwendungsbeispiele für Voronoi Diagramme zum Thema „französische Revolution“.
Eine Erklärung, wie so ein Diagramm funktioniert findest du hier. Im ersten Beispiel wird eine Library verwendet, mit der man Schriftzüge in einzelne Punkte auflösen kann. Die Geomerative Library. Infos dazu gibts hier.

Beispiel 1: Hier werden die Schriftzüge der Werte Liberté  Égalité  Fraternité (Freiheit, Gleichheit, Brüderlichkeit) zerlegt, in Voronoi Bereiche aufgespalten und dann entsprechend eingefärbt. Blau für die Freiheit, Weiß für Gleichheit und Rot für Brüderlichkeit.

140109_082800_01

/** Copyright 2013 Thomas Koberger
*/

// https://lernprocessing.wordpress.com/
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import java.util.Calendar;
import megamu.mesh.*;
import geomerative.*;

RShape shp, shp1, shp2;
RPoint[] pnts, pnts1;
PImage qr;

String BspText1 = "Liberté  Égalité  Fraternité";

ArrayList<Integer> voroPoints;
Voronoi myVoronoi;
float[][] points;

void setup() {
size(4000, 1000);
voroPoints = new ArrayList<Integer> ();

translate(width/2, height*2/12);

RG.init(this);
// 3 Shape - Objekte werden erzeugt.
// Die Schrift mit dem Namen "Ubuntu-R.ttf" muss im data Ordner platziert werden
shp1 = RG.getText(BspText1, "Ubuntu-R.ttf", width*8/120, CENTER);

// Punkte an der Schriftkontur finden
//Abstand der Punkte
RCommand.setSegmentLength (3);
//Modus
RCommand.setSegmentator(RCommand.UNIFORMLENGTH);
//RCommand.setSegmentator(RCommand.ADAPTATIVE);

// Die Shapes werdem gezeichnet und positioneiert
shp1.translate(0, height*7/12);
fill(180, 160);

// Finden der Konturpunkte
pnts = shp1.getPoints();

// Variation der einzelnen Punkte
for (int i=0;i<pnts.length; i+=1) {
stroke(255, 0, 0);
point(pnts[i].x, pnts[i].y);

int var=(int) random(-2, 2);
int x = (int) pnts[i].x+var;
var=(int) random(-2, 2);
int y = (int) pnts[i].y+var;

//Damit nicht 2 Punkte die gleichen Koordinaten haben
boolean coordAvailable=true;
for (int j=0; j<voroPoints.size(); j+=2) {
if (((int)voroPoints.get(j)==x && (int)voroPoints.get(j+1)==y)
|| x==0 || y==0) {
coordAvailable=false;
}
}

if (coordAvailable) {
voroPoints.add(x);
voroPoints.add(y);
}
else println("sameCoord");
}
println("NumPoints: "+voroPoints.size());
createVoronoi () ;
qr =loadImage("qrcode.png");
}

void draw() {
background(255);
translate(width/2, 0);

//get and draw VoroRegions
MPolygon[] myRegions = myVoronoi.getRegions();

for (int i=0; i<myRegions.length; i++) {
// an array of points
float[][] regionCoordinates = myRegions[i].getCoords();

int col= (int)random(0, 3);
if (col==0) fill(0, 0, 255);
else if (col==1) fill(255, 40);
else fill(255, 0, 0);
stroke(80, 50);
strokeWeight(1);
myRegions[i].draw(this); // draw this shape
}

//draw Points
strokeWeight(2);
stroke(80, 150);
for (int i=0; i<voroPoints.size(); i+=2) {
point((int)voroPoints.get(i), (int)voroPoints.get(i+1));
}
image(qr, width/2-height/5, height-height/5, height/10, height/10);
saveFrame(timestamp()+"_##.png");
}

void createVoronoi () {
points = new float[voroPoints.size()/2][2];
for (int i=0; i<voroPoints.size(); i+=2) {

//Hierbei muss die Art des Objekts in der ArrayList festgelegt werden.
points[i/2][0] =(int) voroPoints.get(i);
points[i/2][1] =(int) voroPoints.get(i+1);
}
myVoronoi = new Voronoi( points );
}

void keyReleased() {
if (key == 's' || key == 'S') saveFrame(timestamp()+"_##.png");
}

//timestamp
String timestamp() {
Calendar now = Calendar.getInstance();
return String.format("%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS", now);
}

Beispiel 2: Visualisierung der Werte Liberté  Égalité  Fraternité (Freiheit, Gleichheit, Brüderlichkeit) in Form von  Voronoi Diagrammen.Fertig

/** Copyright 2013 Thomas Koberger
*/

// https://lernprocessing.wordpress.com/
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
*
* MOUSE
*
* KEYS
* Toggle Mode
* 0                   : Freiheit
* 1                   : Gleichheit
* 1                   : Brüderlichkeit
* s                   : save png
*/

import java.util.Calendar;
import megamu.mesh.*;

ArrayList<Integer> voroPoints;
Voronoi myVoronoi;
float[][] points;

//Freiheit = 0
//Gleichheit = 1
//Brüderlichkeit = 2
int mode=0;

void setup() {
size(800, 800);
voroPoints = new ArrayList<Integer> ();
createFreiheit();
noLoop();
}

void draw() {
createVoronoi();
if (mode==0) {
fill(0, 0, 190, 255);
stroke(200);
}
else if (mode==1) {
fill(255);
stroke(80);
}
else {
fill(220, 0, 0);
stroke(200);
}
if (voroPoints.size()>1) {

//getRegions
strokeWeight(1);
MPolygon[] myRegions = myVoronoi.getRegions();

for (int i=0; i<myRegions.length; i++)
{
// an array of points
float[][] regionCoordinates = myRegions[i].getCoords();
myRegions[i].draw(this); // draw this shape
}
}

// draw Points
strokeWeight(6);
for (int i=0; i<voroPoints.size(); i+=2) {
point((int)voroPoints.get(i), (int)voroPoints.get(i+1));
}
}

void createFreiheit() {
voroPoints = new ArrayList<Integer> ();

for (int i=160; i<width-80;i+=80) {
for (int j=160; j<height-80;j+=80) {

if (i==400 && j ==400) {
voroPoints.add(i+(int)random(-40, 40));
voroPoints.add(j+(int)random(-40, 40));
}
else {
voroPoints.add(i);
voroPoints.add(j);
}
}
}
}

void createGleichheit() {
voroPoints = new ArrayList<Integer> ();

for (int i=160; i<width-80;i+=80) {
for (int j=160; j<height-80;j+=80) {
voroPoints.add(i);
voroPoints.add(j);
}
}
}

void createBruederlichkeit() {
voroPoints = new ArrayList<Integer> ();

for (int i=160; i<width-80;i+=80) {
for (int j=160; j<height-80;j+=80) {
if (i==400 && j ==400) {
voroPoints.add(i);
voroPoints.add(j+20);
} else if (i==400 && j ==480) {
voroPoints.add(i);
voroPoints.add(j-20);
}else {
voroPoints.add(i);
voroPoints.add(j);
}
}
}
}

void createVoronoi () {
points = new float[voroPoints.size()/2][2];
for (int i=0; i<voroPoints.size(); i+=2) {

points[i/2][0] =(int) voroPoints.get(i);
points[i/2][1] =(int) voroPoints.get(i+1);
}
myVoronoi = new Voronoi( points );
}

void keyReleased() {
if (key == DELETE || key == BACKSPACE) background(360);
if (key == 's' || key == 'S') saveFrame(timestamp()+"_##.png");
if (key == '0') {
mode=0;
createFreiheit();
}
if (key == '1') {
mode=1;
createGleichheit();
}
if (key == '2') {
mode=2;
createBruederlichkeit();
}
loop();
}

//timestamp
String timestamp() {
Calendar now = Calendar.getInstance();
return String.format("%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS", now);
}

einstieg in die programmierung mit processing

%d Bloggern gefällt das: