<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
      <title>Tagged with #particles - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/feed.rss?Tag=%23particles</link>
      <pubDate>Sun, 08 Aug 2021 17:50:57 +0000</pubDate>
         <description>Tagged with #particles - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/tagged%23particles/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>Increasing maximum available memory testing. How to get better results?</title>
      <link>https://forum.processing.org/two/discussion/28047/increasing-maximum-available-memory-testing-how-to-get-better-results</link>
      <pubDate>Fri, 08 Jun 2018 03:03:32 +0000</pubDate>
      <dc:creator>bontempos</dc:creator>
      <guid isPermaLink="false">28047@/two/discussions</guid>
      <description><![CDATA[<p>This is a  i7-8700, 32Gb of RAM, NVIDIA GeForce GTX 1080, running Windows 10 and Java 8 (171) installed and heap memory set to max 32Gb(-Xmx32g) (?) on run parameters.</p>

<p>I think this is not a question about library. However, as experiment, I am running an example from <strong>box2D library for processing</strong> named <strong>Liquidy.pde</strong> where I changed the sketch <code>size</code>to (600,300) and tested 3 renderers (default, <code>JAVA2D</code> and <code>P3D</code>). <code>P2D</code> was way too slow to be considered at this point.
I am printing the total memory, allocated memory, free memory, n of particles, fps in the title of the sketch.
I am also declaring the sketch to run at 60 fps using <code>frameRate(60);</code>
I have tried to <em>increase maximum available memory</em>, but when the option was disabled, I have got a slightly better performance in fps.</p>

<p>When running the sketch, a click of mouse will generate a particle system.
10 clicks would generate an environment with about 1000 particles, and 15 clicks will stay around 1700. See attached picture:
<img src="" alt="" /></p>

<p>With 10 particle systems, each rendered kept sketch running around 60 fps:<code>JAVA2D</code> a little worse than default. <code>P3D</code> performed just a little better.
for 15 particle systems, frame rate will decrease to 15 fps (<code>P3D</code>), 19fps (<code>JAVA2D</code> and default).</p>

<p>Disabling the "increase maximum available memory" in preferences (and restarting?) made default renderer and <code>JAVA2D</code> to perform a little better when running 15 particle systems. From ~20fps, they jumped to 25fps.</p>

<p>I am not running out of memory and I wonder if there is any way to improve the performance of my sketches.
Thanks</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/715/M8AC02EYRNU1.JPG" alt="Capture5" title="Capture5" /></p>
]]></description>
   </item>
   <item>
      <title>Frame Rate keeps getting lower</title>
      <link>https://forum.processing.org/two/discussion/27931/frame-rate-keeps-getting-lower</link>
      <pubDate>Mon, 07 May 2018 06:13:02 +0000</pubDate>
      <dc:creator>dehyde</dc:creator>
      <guid isPermaLink="false">27931@/two/discussions</guid>
      <description><![CDATA[<p>Hi</p>

<p>I working on a code running particles to represent refugee data
The code limits the number of particles to keep the frameRate but even after using a steady number of particles, it keeps getting slower with lower frameRate.</p>

<p>I'm really not sure what I can do to make this run faster / smoother. Why does it keep getting slower?</p>

<p>Here's the data folder for the Sketch:
<a href="https://www.dropbox.com/sh/z69phco3tahqklu/AAB8PLMpBQMoFUX5NGSie-5fa?dl=0" target="_blank" rel="nofollow">https://www.dropbox.com/sh/z69phco3tahqklu/AAB8PLMpBQMoFUX5NGSie-5fa?dl=0</a></p>

<pre><code>PImage texture;
PGraphics pg;
PShape worldMap;
import java.util.Map;  
int filterPSystemsNum;

PGraphics sumPG;

// ========== Table Data Stuff 

Table immigrationTable;
Table conflictTable;
Table countryLocations;

int k = 0;
String[] destCountryArray = new String[0];
String[] sourceCountryArray = new String[0];

String destCountry = "";
String prevDestCountry = "";

String sourceCountry;

float mapMultiplyX = 4;
float mapOffsetX = -100;
float mapMultiplyY = 4;
float mapOffsetY = 50;

// ========

int amountSum = 1;

String displayType = "Circular";

int maxParticles = 9000;

ParticleSystem ps;
ParticleSystem ps2;

int n = 0, n2=0;
int emmitMultiplyer = 1;
int emmitFreq = 1;
float particleSpeed = 1;

float locationX = 250;
float locationY = 450;

int[] sourceX = {10, 40, 200, 400, 700};
int[] destX = {300, 600, 300, 600, 600};
int[] amount = {10, 100, 500, 800, 1000};
int highestAmount;

float radius = 300;

float tempLong;
float tempLat;

int yearFilterMin = 1996;
int yearFilterMax = 2016;


ParticleSystem[] PSystems;

HashMap&lt;String, Country&gt; countries = new HashMap&lt;String, Country&gt;();

void setup() {
  size(1200, 800, P2D);
  ((PGraphicsOpenGL)g).textureSampling(3);

  texture = loadImage("paper_texture.jpg");
  //worldMap = loadShape("worldLow.svg");

  //=============== load immigrationTable and create an array of countries


  immigrationTable = loadTable("asylum_seekers_all.csv", "header");
  countryLocations = loadTable("LatLonCountries2.csv", "header");
  conflictTable = loadTable("ged171.csv", "header");

  destCountryArray = (String[]) append(destCountryArray, "Israel");

  sumPG = createGraphics(width, height);

  pg = createGraphics(width, height);
  pg.beginDraw();
  pg.background(177);

  pg.endDraw();
  image(pg, 0, 0);

  for (TableRow row : immigrationTable.rows()) {
    if (row.getInt("Year") &lt;= yearFilterMax &amp;&amp; row.getInt("Year") &gt;= yearFilterMin) {

      String tempCountryHolder = row.getString("Country / territory of asylum/residence");

      boolean exists = countryExists(tempCountryHolder);
      if (exists==true) {

        continue;
      }

      destCountryArray = (String[]) append(destCountryArray, tempCountryHolder);
    }
  }

  for (TableRow row : immigrationTable.rows()) {
    if (row.getInt("Year") &lt;= yearFilterMax &amp;&amp; row.getInt("Year") &gt;= yearFilterMin) {

      String tempCountryHolder = row.getString("Origin");

      boolean exists = countryExists(tempCountryHolder);
      if (exists==true) { //println("exists, skipping");
        continue;
      }
      destCountryArray = (String[]) append(destCountryArray, tempCountryHolder);
    }
  }
  destCountryArray = sort(destCountryArray);



  //============================ country hashmaps ======================================

  for (int i = 0; i &lt; destCountryArray.length; i++) {
    String name = destCountryArray[i];




    for (TableRow row : countryLocations.rows()) {


      if (name.equals(row.getString("name"))) {

        tempLong = row.getFloat("longitude");
        tempLat = row.getFloat("latitude");
      }
    }

    countries.put(name, new Country(name, width/2+(tempLong*mapMultiplyX)+mapOffsetX, height/2-(tempLat*mapMultiplyY)+mapOffsetY));

  }

  for (String key : countries.keySet()) {
    Country c = countries.get(key);

  }

  //============================ PSystems =============

  PSystems = new ParticleSystem[immigrationTable.getRowCount()];
  int j = 0;

highestAmount = 291664;

  println(amountSum);
  for (TableRow row : immigrationTable.rows()) {
    if (row.getInt("Year") &lt;= yearFilterMax &amp;&amp; row.getInt("Year") &gt;= yearFilterMin) {
      int tempAmount = row.getInt("decisions_recognized");
      String tempDestCountry = row.getString("Country / territory of asylum/residence");
      String tempSourceCountry = row.getString("Origin");
      int tempYear = row.getInt("Year");

      float sourceEmmiterX = countries.get(tempSourceCountry).x;
      float sourceEmmiterY = countries.get(tempSourceCountry).y;
      float destEmmiterX = countries.get(tempDestCountry).x;
      float destEmitterY = countries.get(tempDestCountry).y;

      PSystems[j] = new ParticleSystem(1, new Vector3D(sourceEmmiterX, sourceEmmiterY, 0), new Vector3D(destEmmiterX, destEmitterY, 0), tempAmount, tempYear);
      println("----");
      filterPSystemsNum++;

      println("tempAmount "+tempAmount);
      println("maxParticles "+maxParticles);
      println("amountSum "+amountSum);
      println("tempAmount*maxParticles "+tempAmount*maxParticles);
      println("tempAmount*(maxParticles/amountSum) "+tempAmount*maxParticles/amountSum); 
      //println("PSystems " + i + " is " +PSystems[i]);
      j++;
    }
  }

  smooth();
}
int currentYear = 2000;
void draw() {

  blendMode(MULTIPLY);
  background(247, 245, 246, 1);
  fill(1, 1, 1, 1);

  tint(255, 1);
  image(pg, 0, 0);

  for (int i = 0; i&lt;filterPSystemsNum; i++) {

    boolean overCountryOrigin = overCountry(int(PSystems[i].origin.x), int(PSystems[i].origin.y), 10);
    boolean overCountryDest = overCountry(int(PSystems[i].dest.x), int(PSystems[i].dest.y), 10);
    boolean isOver = (overCountryOrigin || overCountryDest);
    PSystems[i].run(isOver);
  }


  //  =======

  int allPCount = 0;
  for (int k = 0; k&lt;filterPSystemsNum; k++) {

    Vector3D b=new Vector3D(PSystems[k].origin.x, PSystems[k].origin.y+abs(PSystems[k].origin.x-PSystems[k].dest.x)/2, 0);
    Vector3D c=new Vector3D(PSystems[k].dest.x, PSystems[k].dest.y+abs(PSystems[k].origin.x-PSystems[k].dest.x)/2, 0);


    boolean isTherePLimit = PSystems[k].PLimit != 0;

    if (isTherePLimit){

    boolean isThisAPlayingFrame = frameCount % int(sqrt(highestAmount/PSystems[k].PLimit)) == 0;
    boolean isThisTheRightYear = PSystems[k].year == currentYear;
    boolean areThereAnyMoreParticles = PSystems[k].PCount&lt;PSystems[k].PLimit;

    if (isThisAPlayingFrame &amp;&amp; isThisTheRightYear &amp;&amp; areThereAnyMoreParticles) {
      for(int s = 0; s&lt;emmitMultiplyer; s++){
      PSystems[k].addParticle();
      PSystems[k].PCount++;
      n++;
      }
    }
  }
    }



  // =========================================================== country labels




  for (int i = 0; i&lt;destCountryArray.length; i++) {
    float tempX = countries.get(destCountryArray[i]).x;
    float tempY = countries.get(destCountryArray[i]).y;
    float tempAng = atan((tempY-height/2)/(tempX-width/2));
    float labelMargin;
    translate(tempX, tempY);
    textSize(8);

    rotate(tempAng);
    fill(0);
    if (tempX&lt;width/2) {
      textAlign(RIGHT);
      labelMargin = -7;
    } else {
      textAlign(LEFT);
      labelMargin = 7;
    }

    if (overCountry(int(tempX), int(tempY), 9)==true) {
      fill(50, 100, 250);
      ellipse(0, 0, 5, 5);
      fill(0, 0, 255);
      text(countries.get(destCountryArray[i]).name, labelMargin, 2);
    } else {
      fill (200);
      fill(30, 100-sq(dist(mouseX, mouseY, tempX, tempY)));
      text(countries.get(destCountryArray[i]).name, labelMargin, 2);
    }

    if (countries.get(destCountryArray[i]).name == "Israel") {

      textAlign(RIGHT);
      textSize(10);
      fill(255);
      rotate(-tempAng);
      translate(-tempX, -tempY);
      rect(-6, -8, -textWidth("you are here")-7, 14);

      fill(200, 40, 40);
      text ("you are here", mouseX, mouseY);
      noFill();
      strokeWeight(0.5);
      stroke(255, 0, 0);

      bezier(mouseX, mouseY, (mouseX+tempX)/2+100, mouseY, tempX, (mouseY+tempY)/2, tempX, tempY);
      noStroke();
      translate(tempX, tempY);
      rotate(tempAng);
      ellipse(0, 0, 4, 4);
    }
    rotate(-tempAng);
    translate(-tempX, -tempY);
  }

  fill(0);
  text("Frame rate: "
    + int(frameRate), 10, 20);
  text("Each point: " + int(amountSum/maxParticles) +" people", 10, 30);
  text("number of refugees: " + n*int(amountSum/maxParticles), 10, 40);
  text("number of particles is: " +n, 10, 50);
  text("max particles is: " +maxParticles, 10, 60);
  textSize(80);
  blendMode(BLEND);
  fill(128, 130, 131);
  text(round(float(n)*float(amountSum)/float(maxParticles)), 10, 160);
  textSize(20);
  text("RECOGNIZED REFUGEES (" +yearFilterMin+ " - " + yearFilterMax+")", 10, 180);

  println("n = "+n);
  println("amountSum = "+amountSum);
  println("maxParticles = "+maxParticles);
}




// ==============================//  A simple Particle class  // ===============================================//




class Particle {

  Vector3D loc;
  Vector3D des;
  Vector3D vel;
  Vector3D acc;
  Vector3D locHome, b, c;
  float relativeSpeed;

  float r;
  float timer;

  float t=0.0; 
  float a = random(TWO_PI);
  Particle(Vector3D l, Vector3D m, int accum) {

    acc = new Vector3D(0, 0, 0); //  new Vector3D(random(-0.1, 0.1), random(-0.02, 0), 0);
    loc = l.copy();
    des = m.copy();
    locHome = l.copy();

    float rescale = 0.5;

    locHome.x = locHome.x+ cos(a)*random(0, sqrt(accum)*rescale);
    locHome.y = locHome.y+ sin(a)*random(0, sqrt(accum)*rescale);


    des.x = des.x+ cos(a)*random(0, sqrt(accum)*rescale);
    des.y = des.y+ sin(a)*random(0, sqrt(accum)*rescale);

    relativeSpeed = random(0.1, 0.02);


    r = random(0.9, 3);  // particle radius
    timer = 10000.0;   // particles lifespan


    b=new Vector3D(l.copy().x, l.copy().y+abs(l.copy().x-m.copy().x)/2, 0);
    c=new Vector3D(m.copy().x, m.copy().y+abs(l.copy().x-m.copy().x)/2, 0);

  }

  void run(boolean onMouseOverPSystem) {
    update();
    render(onMouseOverPSystem);
  }



  // Method to update location
  void update() {
    if (t&gt;=1)
      return;

    loc.x = bezierPoint(locHome.x, b.x, c.x, des.x, t);
    loc.y = bezierPoint(locHome.y, b.y, c.y, des.y, t);

    t = lerp(t, 1, particleSpeed*relativeSpeed/2);

  }

  void render(boolean isSelected) {
    ellipseMode(CENTER);
    noStroke();
    blendMode(BLEND);

    if (isSelected == false) {
      fill(128, 129, 129, 150);
    } 
    if (t==lerp(0, 1, particleSpeed*relativeSpeed/2)) {
      pg.beginDraw();
      pg.blendMode(BLEND);
      pg.fill(0, 0, 0);
      pg.noStroke();
      pg.ellipse(loc.x, loc.y, r, r);
      pg.endDraw();
    } else { 
      fill(4*255*t-3*255);
    }
    ellipse(loc.x, loc.y, r, r);

  }

  // Is the particle still useful?
  boolean dead() {
    if (t==1) {
      pg.beginDraw();
      pg.blendMode(BLEND);
      pg.fill(255, 255, 255, 255);
      pg.noStroke();
      pg.ellipse(loc.x, loc.y, r, r);
      pg.endDraw();
      return true;
    } else {
      return false;
    }
  }
}


// ==============================//  A ParticleSystem  // ===============================================// 


// A class to describe a group of Particles
// An ArrayList is used to manage the list of Particles
class ParticleSystem {

  ArrayList particles;    // An arraylist for all the particles
  Vector3D origin;        // An origin point for where particles are birthed
  Vector3D dest;
  int PLimit;
  int PCount;
  int year;

  float ratio = PLimit/highestAmount;

  //ParticleSystem( number of particles / frame, source, destination, frequency);
  ParticleSystem(int num, Vector3D v, Vector3D d, int f, int y) {
    particles = new ArrayList();              // Initialize the arraylist
    origin = v.copy();     // Store the origin point
    dest = d.copy();
    year = y;
    PLimit = f;


    //if (frameCount % (1/f) == 0){
    for (int i = 0; i &lt; num; i++) {
      //  particles.add(new Particle(origin, dest));    // Add "num" amount of particles to the arraylist
    }
    //}
  }

  void run(boolean onMouseOverPSystem) {


    for (int i = particles.size()-1; i &gt;= 0; i--) {
      Particle p = (Particle) particles.get(i);
      p.run(onMouseOverPSystem);
      if (p.dead()) {
        particles.remove(i);
        //PCount--;
        //n--;
      }

    }
  }

  void addParticle() {
    particles.add(new Particle(origin, dest, PCount));
  }



  // A method to test if the particle system still has particles
  boolean dead() {
    if (particles.isEmpty()) {
      return true;
    } else {
      return false;
    }
  }
}

//=================================================== Class Country

class Country {
  String name;
  float x, y, lon, lat, migrationIndex, incoming, outgoing;
  // more things here?

  Country(String name, float x, float y) {
    this.name = name;
    this.x = x;
    this.y = y;
  }
}

// ================================================ Simple Vector3D Class


public class Vector3D {

  public float x;
  public float y;
  public float z;

  Vector3D(float x_, float y_, float z_) {
    x = x_; 
    y = y_; 
    z = z_;
  }

  Vector3D(float x_, float y_) {
    x = x_; 
    y = y_; 
    z = 0f;
  }

  Vector3D() {
    x = 0f; 
    y = 0f; 
    z = 0f;
  }

  void setX(float x_) {
    x = x_;
  }

  void setY(float y_) {
    y = y_;
  }

  void setZ(float z_) {
    z = z_;
  }

  void setXY(float x_, float y_) {
    x = x_;
    y = y_;
  }

  void setXYZ(float x_, float y_, float z_) {
    x = x_;
    y = y_;
    z = z_;
  }

  void setXYZ(Vector3D v) {
    x = v.x;
    y = v.y;
    z = v.z;
  }

  public float magnitude() {
    return (float) Math.sqrt(x*x + y*y + z*z);
  }

  public Vector3D copy() {
    return new Vector3D(x, y, z);
  }

  public Vector3D copy(Vector3D v) {
    return new Vector3D(v.x, v.y, v.z);
  }

  public void add(Vector3D v) {
    x += v.x;
    y += v.y;
    z += v.z;
  }

  public void sub(Vector3D v) {
    x -= v.x;
    y -= v.y;
    z -= v.z;
  }

  public void mult(float n) {
    x *= n;
    y *= n;
    z *= n;
  }

  public void div(float n) {
    x /= n;
    y /= n;
    z /= n;
  }

  public void normalize() {
    float m = magnitude();
    if (m &gt; 0) {
      div(m);
    }
  }

  public void limit(float max) {
    if (magnitude() &gt; max) {
      normalize();
      mult(max);
    }
  }

  public float heading2D() {
    float angle = (float) Math.atan2(-y, x);
    return -1*angle;
  }

  public Vector3D add(Vector3D v1, Vector3D v2) {
    Vector3D v = new Vector3D(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
    return v;
  }

  public Vector3D sub(Vector3D v1, Vector3D v2) {
    Vector3D v = new Vector3D(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
    return v;
  }

  public Vector3D div(Vector3D v1, float n) {
    Vector3D v = new Vector3D(v1.x/n, v1.y/n, v1.z/n);
    return v;
  }

  public Vector3D mult(Vector3D v1, float n) {
    Vector3D v = new Vector3D(v1.x*n, v1.y*n, v1.z*n);
    return v;
  }

  public float distance (Vector3D v1, Vector3D v2) {
    float dx = v1.x - v2.x;
    float dy = v1.y - v2.y;
    float dz = v1.z - v2.z;
    return (float) Math.sqrt(dx*dx + dy*dy + dz*dz);
  }
}

boolean countryExists(String tempCountryHolder) {

  for (int i = 0; i &lt; destCountryArray.length; i++) {

    if (tempCountryHolder.equals(destCountryArray[i]) == true) {

      return true; // it exists
    } //if
  } //for
  return false ; // not found
}//func


//============================================= onMouseOver Bolean Class


boolean overParticle(int x, int y, int diameter) {
  float disX = x - mouseX;
  float disY = y - mouseY;
  if (sqrt(sq(disX) + sq(disY)) &lt; diameter/2 ) {
    return true;
  } else {
    return false;
  }
}

boolean overCountry(int x, int y, int diameter) {
  float disX = x - mouseX;
  float disY = y - mouseY;
  if (sqrt(sq(disX) + sq(disY)) &lt; diameter/2 ) {
    return true;
  } else {
    return false;
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Class scope Problem.</title>
      <link>https://forum.processing.org/two/discussion/27403/class-scope-problem</link>
      <pubDate>Tue, 27 Mar 2018 18:07:51 +0000</pubDate>
      <dc:creator>DDv2FF</dc:creator>
      <guid isPermaLink="false">27403@/two/discussions</guid>
      <description><![CDATA[<p>Hi again.<br />
I've been trying to make this creature with particles around it. I have 4 issues, that maybe someone can help me to solve.<br />
1- After some time I figured out how to make the particles follow the creature. But the code doenst seem clean(? I would like to make it right.<br />
2- The scope issue. In the Particle Class, the particle is showed using "this.xtotal" and "this.ytotal", and I know that those variables wherent declared in the constructor function. But if I do it, then I have no animation for my particles. This generate multiple messages in the console.<br />
<a rel="nofollow" href="https://preview.ibb.co/k1wwpn/Captura.png">https://preview.ibb.co/k1wwpn/Captura.png</a><br />
How can I fix it ?<br />
3- I want to constrain the random position that the particles might have. I think that for this issue, I could simply do :</p>

<pre><code>this.xtotal = constrain(this.xtotal, this.x - this.dist, this.x + this.dist);
this.ytotal = constrain(this.ytotal, this.y - this.dist, this.y + this.dist);
</code></pre>

<p>but that generate errors to.<br />
4- The last issue is focused in the optimization of my code. Because I have  lagg with more than 5 particles. That might be related to the first issue.</p>

<pre><code>let particulas = [];
let criatura;

function setup() {
    createCanvas(1200, 600);
    criatura = new Criatura(600, 300);

    for(var i = 0; i &lt; 5; i++){
        particulas.push(new Particula(criatura));
    }

}

function draw() {
    background(60);

    criatura.show();
    criatura.update();

    for(let partic of particulas){
        partic.show();
        partic.update();

        //the part that I dont like to have in the sketch file,
        //it just doesnt seem belong here.
        partic.x = criatura.x;
        partic.y = criatura.y;

    }

}

function keyPressed(){

    if(keyCode === 39){
        criatura.xvelocidad = 1;
    } else if(keyCode === 37){
        criatura.xvelocidad = -1;
    }

    if(keyCode === 38){
        criatura.yvelocidad = -1;
    } else if(keyCode === 40){
        criatura.yvelocidad = 1;
    }

}

function keyReleased(){
    criatura.xvelocidad = 0;
    criatura.yvelocidad = 0;
}
</code></pre>

<p>The classes</p>

<pre><code>class Particula{
  constructor(object){
    this.x = object.x;
    this.y = object.y;
    this.dist = object.r;
    //give random positions araound the creature
    this.xm = random(-object.r, object.r);
    this.ym = random(-object.r, object.r);

    //for the particle efect
    this.history = [];

  }

  update(){
    //vibration effect
    this.xm+= random(-5, 5);
    this.ym+= random(-5, 5);

    //the problem with the scope
    this.xtotal = this.x + this.xm;
    this.ytotal = this.y + this.ym;
    //track of the particle
    let v = createVector(this.xtotal, this.ytotal);
    this.history.push(v);
    if(this.history.length &gt; 20){
      this.history.splice(0, 1);
    }

  }

  show(){
    push();
    fill(50, 150);
    ellipse(this.xtotal, this.ytotal, 40);
    pop();

    for(var i = 0; i &lt; this.history.length; i++){
      fill(random(200), random(200), random(200));
      let pos = this.history[i];
      ellipse(pos.x, pos.y, i);
    }

  }


}
</code></pre>

<p>The criature</p>

<pre><code>class Criatura{
  constructor(x, y){

    this.x = x;
    this.y = y;
    this.r = 125;

    this.xvelocidad = 0;
    this.yvelocidad = 0;
  }

  update(){
    this.x+= this.xvelocidad * 5;
    this.y+=this.yvelocidad * 5;

    if(this.x &gt; width - this.r){
      this.x = width - this.r;
    } else if(this.x &lt; this.r){
      this.x = this.r;
    }
    if(this.y &gt; height - this.r){
      this.y = height - this.r;
    } else if (this.y &lt; this.r){
      this.y = this.r;
    }

  }

  show(){
    push();
    fill(250, 50, 100);
    ellipse(this.x, this.y, this.r * 2);
    pop();
  }

}
</code></pre>

<p>10x 4 reading</p>
]]></description>
   </item>
   <item>
      <title>making particles attract to a specific point</title>
      <link>https://forum.processing.org/two/discussion/26700/making-particles-attract-to-a-specific-point</link>
      <pubDate>Wed, 07 Mar 2018 17:54:02 +0000</pubDate>
      <dc:creator>dehyde</dc:creator>
      <guid isPermaLink="false">26700@/two/discussions</guid>
      <description><![CDATA[<p>Hi,
I'm want to use a simple particles code to visualize migration of refugees and asylum seekers.
The code should run on processing.js as a web canvas.</p>

<p>Each source country is an emitter, and each destination country should be a concentration point.</p>

<p>right now I'm trying to make the particles move to a destination point, but I'm unsure why they don't (they just overshoot).
Problem is probably in "update()" or in "Particle()"</p>

<pre><code>// All Examples Written by Casey Reas and Ben Fry

// unless otherwise stated.

ParticleSystem ps;
ParticleSystem ps2;

int n = 0;
int emmitMultiplyer = 5;

float locationX = 250;
float locationY = 450;

void setup() {

  size(800,600);

  //frameRate(30);

  //colorMode(RGB,255,255,255,255);

  ps = new ParticleSystem(1,new Vector3D(width/2,height/2,0));
  ps2 = new ParticleSystem(1,new Vector3D(100,200,0));

  smooth();



}



void draw() {

  background(0);
  ellipse(locationX,locationY,5,5);
  ps.run();
  ps2.run();

  for (int i = 0; i&lt;emmitMultiplyer; i++)
  {
    ps.addParticle();
    ps2.addParticle();
    n++;
    //println(n);
  }
  fill(255);
  text("Frame rate: " + int(frameRate), 10, 20);

}





// A simple Particle class



class Particle {

  Vector3D loc;

  Vector3D vel;

  Vector3D acc;

  float r;

  float timer;

  // Another constructor (the one we are using here)

  Particle(Vector3D l) {

//acc = new Vector3D(0,0.0005,0);  // particle acceleration

    vel = new Vector3D(random(-0.1,0.1),random(-0.02,0),0);

    loc = l.copy();

    acc = new Vector3D((locationX-loc.x)*0.000001, (locationY-loc.y)*0.000001,0);

    r = 1.5;  // particle radius

    timer = 10000.0;   // particles lifespan
                      // * emmitMultiplyer = number of living

  }





  void run() {

    update();

    render();

  }



  // Method to update location

  void update() {

    vel.add(acc);

    loc.add(vel);

    timer -= 1.0;

  }



  // Method to display

  void render() {

    ellipseMode(CENTER);

    noStroke();

    fill(255,timer);

    ellipse(loc.x,loc.y,r,r);

  }



  // Is the particle still useful?

  boolean dead() {

    if (timer &lt;= 0.0) {

      return true;

    } else {

      return false;

    }

  }

}





// A class to describe a group of Particles

// An ArrayList is used to manage the list of Particles 



class ParticleSystem {



  ArrayList particles;    // An arraylist for all the particles

  Vector3D origin;        // An origin point for where particles are birthed



  ParticleSystem(int num, Vector3D v) {

    particles = new ArrayList();              // Initialize the arraylist

    origin = v.copy();                        // Store the origin point

    for (int i = 0; i &lt; num; i++) {

      particles.add(new Particle(origin));    // Add "num" amount of particles to the arraylist

    }

  }



  void run() {

    // Cycle through the ArrayList backwards b/c we are deleting

    for (int i = particles.size()-1; i &gt;= 0; i--) {

      Particle p = (Particle) particles.get(i);

      p.run();

      if (p.dead()) {
        n--;
        particles.remove(i);

      }

    }

  }



  void addParticle() {

    particles.add(new Particle(origin));

  }



  void addParticle(Particle p) {

    particles.add(p);

  }



  // A method to test if the particle system still has particles

  boolean dead() {

    if (particles.isEmpty()) {

      return true;

    } else {

      return false;

    }

  }



}







// Simple Vector3D Class 



public class Vector3D {

  public float x;

  public float y;

  public float z;



  Vector3D(float x_, float y_, float z_) {

    x = x_; y = y_; z = z_;

  }



  Vector3D(float x_, float y_) {

    x = x_; y = y_; z = 0f;

  }



  Vector3D() {

    x = 0f; y = 0f; z = 0f;

  }



  void setX(float x_) {

    x = x_;

  }



  void setY(float y_) {

    y = y_;

  }



  void setZ(float z_) {

    z = z_;

  }



  void setXY(float x_, float y_) {

    x = x_;

    y = y_;

  }



  void setXYZ(float x_, float y_, float z_) {

    x = x_;

    y = y_;

    z = z_;

  }



  void setXYZ(Vector3D v) {

    x = v.x;

    y = v.y;

    z = v.z;

  }

  public float magnitude() {

    return (float) Math.sqrt(x*x + y*y + z*z);

  }



  public Vector3D copy() {

    return new Vector3D(x,y,z);

  }



  public Vector3D copy(Vector3D v) {

    return new Vector3D(v.x, v.y,v.z);

  }



  public void add(Vector3D v) {

    x += v.x;

    y += v.y;

    z += v.z;

  }



  public void sub(Vector3D v) {

    x -= v.x;

    y -= v.y;

    z -= v.z;

  }



  public void mult(float n) {

    x *= n;

    y *= n;

    z *= n;

  }



  public void div(float n) {

    x /= n;

    y /= n;

    z /= n;

  }



  public void normalize() {

    float m = magnitude();

    if (m &gt; 0) {

       div(m);

    }

  }



  public void limit(float max) {

    if (magnitude() &gt; max) {

      normalize();

      mult(max);

    }

  }



  public float heading2D() {

    float angle = (float) Math.atan2(-y, x);

    return -1*angle;

  }



  public Vector3D add(Vector3D v1, Vector3D v2) {

    Vector3D v = new Vector3D(v1.x + v2.x,v1.y + v2.y, v1.z + v2.z);

    return v;

  }



  public Vector3D sub(Vector3D v1, Vector3D v2) {

    Vector3D v = new Vector3D(v1.x - v2.x,v1.y - v2.y,v1.z - v2.z);

    return v;

  }



  public Vector3D div(Vector3D v1, float n) {

    Vector3D v = new Vector3D(v1.x/n,v1.y/n,v1.z/n);

    return v;

  }



  public Vector3D mult(Vector3D v1, float n) {

    Vector3D v = new Vector3D(v1.x*n,v1.y*n,v1.z*n);

    return v;

  }



  public float distance (Vector3D v1, Vector3D v2) {

    float dx = v1.x - v2.x;

    float dy = v1.y - v2.y;

    float dz = v1.z - v2.z;

    return (float) Math.sqrt(dx*dx + dy*dy + dz*dz);

  }



}
</code></pre>
]]></description>
   </item>
   <item>
      <title>how to delete particles from an array list?</title>
      <link>https://forum.processing.org/two/discussion/25447/how-to-delete-particles-from-an-array-list</link>
      <pubDate>Fri, 08 Dec 2017 00:31:12 +0000</pubDate>
      <dc:creator>CSoulo</dc:creator>
      <guid isPermaLink="false">25447@/two/discussions</guid>
      <description><![CDATA[<p>I was wondering how to go about deleting particles from my array list particle trail. I want a stream of particles to be shown when the mouse cursor is moved and when the mouse cursor is moved away a certain distance I want the particles to be deleted. This is the code I have so far</p>

<p>`ArrayList particles = new ArrayList();
ArrayList gone = new ArrayList();</p>

<p>class particle {
  float X;
  float Y;
  float speed_X;
  float speed_Y;</p>

<p>void draw() {
    strokeWeight(1);
    stroke(255);
    fill(random(0, 255), random(0, 255), random(0, 255));
    ellipse(X, Y, 8, 8);
    X = X + speed_X;
    Y = Y + speed_Y;
  }
}</p>

<p>void P_Particles() {</p>

<p>for (particle Pa : particles) {
    Pa.draw();
     if (Pa.X &gt; mouseX + 50) {
     continue;
     }
     if (Pa.X &lt; mouseX - 50) {
     continue;
     }
     if (Pa.Y &gt; mouseY + 50) {
     continue;
     }
     if (Pa.Y &lt; mouseY - 50) {
     continue;
     }
     gone.add(Pa);
     }
     particles = gone;
  }</p>

<p>particle  Pa = new particle();
  Pa.X = mouseX;
  Pa.Y = mouseY;
  Pa.speed_X = random(0.1, 0.3);
  Pa.speed_Y = random(0.1, 0.3);
  particles.add(Pa);
}
void draw() { 
//the rest of my game code to much to put it all in here
P_Particles();
}`</p>
]]></description>
   </item>
   <item>
      <title>Performance optimization for p5.js of particles system?</title>
      <link>https://forum.processing.org/two/discussion/25254/performance-optimization-for-p5-js-of-particles-system</link>
      <pubDate>Tue, 28 Nov 2017 16:35:11 +0000</pubDate>
      <dc:creator>qniff</dc:creator>
      <guid isPermaLink="false">25254@/two/discussions</guid>
      <description><![CDATA[<p>The idea of this program is to implement data visualization in form of "Tron" trails (like in the movie), with additional random color change functionality. Eventually it will visualize the way devices move in the building. I used particle system to implement the trail. The problem is that the sketch doesn't run at a constant FPS. I know that functions <strong>randomMovement()</strong> and <strong>changeColor()</strong> look a bit loaded, but profiling indicated that the <strong>addTrail()</strong> function takes the most of the time and provides the greatest load on the program. Right now the program uses some randomly generated coordinates to align and move devices, but eventually the real data will be involved and number of devices will increase up to 1000 and at the moment program is overwhelmed with only 100 of them. So I was wondering if there is a way to optimize this trail system. I am relatively new to Js and am hoping that someone could run through my code to see if it could be optimized. Any help will be greatly appreciated.</p>

<pre><code>let x1 = [];
let y1 = [];
let Devices = [];

function setup() {

    createCanvas(displayWidth, displayHeight);
    getDummyDevices(100);
}

function draw() {

    background(100);
    for(let i = Devices.length - 1; i &gt; 0; i--){
        Devices[i].goTo(x1[i], y1[i]);
        Devices[i].show();
    }

    showFps();
}

function showFps(){
    textSize(32);
    fill(70,250,5);
    text("FPS: " + frameRate().toFixed(2), 10, height - 10);
}

function getDummyDevices(number){

    for(let i = 0; i &lt;= number; i++){

        let x = random(0, width);
        let y = random(0, height);

        let temp = new Device(x,y);
        Devices.push(temp);

        let x1p = random(0, width);
        let y1p = random(0, height);
        x1.push(x1p);
        y1.push(y1p);
    }

}


class Device {

    constructor(x0,y0) {
        this.x = x0;
        this.y = y0;

        this.diameter = 25;                           // diameter of the device
        this.speed = 2;                               // movement speed of the device

        if(random(-1,1) &gt;= 0) {
            this.trailColor = color(255,0,0);         // trailColor: color variable
            this.trailColorString = "red";            // trailColorString: string indicator of color
        }
        else {
            this.trailColor = color(0,0,255); 
            this.trailColorString = "blue";
        }
        this.changeColorPeriod = random(100,200);     // How often device should change color
        this.lastChangedColorTime = 0;                // keeps track of last change of color
        this.colorChangeSpeed = 20;                   // speed of color change of the device (lower -&gt; slower)

        this.deviceColor = color(8, 20, 33);          // color of the device

        this.particles = [];                          // stores particles representing trail of the device
        this.particleFrequency = 7;                   // per how many frames new particle appears
        this.particleCounter = 0;

        this.changeDirectionPeriod = random(50, 150); // How often device should change direction
        this.lastChangedDirectionTime = 0;            // keeps track of last change of direction
        this.currentDirection = random(-1, 1);        // signs direction of device
    }

    show() {
        fill(this.deviceColor);
        ellipse(this.x, this.y, this.diameter);
    }

    goTo(x1, y1) {

        this.randomMovement(x1, y1);
        this.addTrail();
        this.changeColor();
    }

    // simple 'random' movement to destination point, random means device randomly follows x or y first
    randomMovement(x1, y1){

        this.lastChangedDirectionTime += 1;

        if(this.lastChangedDirectionTime &gt;= this.changeDirectionPeriod)
        {
            this.currentDirection *= -1;
            this.lastChangedDirectionTime = 0;
        }

        if(this.currentDirection &lt; 0){

            // simple movement (first x, then y)
            if(!this.inDistanceOf("x", x1)){
                if(this.x &lt; x1) this.x += this.speed;
                else if(this.x &gt; x1) this.x -= this.speed;
            }
            else if(!this.inDistanceOf("y", y1)){
                if(this.y &lt; y1) this.y += this.speed;
                else if(this.y &gt; y1) this.y -= this.speed;
            }
        } else {

            // first y, then x
            if(!this.inDistanceOf("y", y1)){
                if(this.y &lt; y1) this.y += this.speed;
                else if(this.y &gt; y1) this.y -= this.speed;
            }
            else if(!this.inDistanceOf("x", x1)){
                if(this.x &lt; x1) this.x += this.speed;
                else if(this.x &gt; x1) this.x -= this.speed;
            }
        }
    }

    addTrail(){

        if(this.particleCounter &gt;= this.particleFrequency){

            let p = new Particle(this.x, this.y, this.speed, this.trailColor);
            this.particles.push(p);
            this.particleCounter = 0;
        }
        this.particleCounter += 1;

        for(let i = this.particles.length - 1; i &gt;= 0; i--){

            this.particles[i].show();

            if(this.particles[i].finished()){
                this.particles.splice(i, 1);
            }
        }
    }

    // function to periodically change color of the trail
    changeColor(){

        this.lastChangedColorTime += 1;

        if(this.lastChangedColorTime &gt;= this.changeColorPeriod)
        {
            if(this.trailColorString == "red") this.trailColorString = "blue";
            else this.trailColorString = "red";
            this.lastChangedColorTime = 0;
        }

        let r = red(this.trailColor);
        let b = blue(this.trailColor);

        if(this.trailColorString == "blue")
        {
            if(r &gt; 0){
                r -= this.colorChangeSpeed;
                if(r &lt; 122) b += this.colorChangeSpeed;
            }
            else if(r &gt;= 0 &amp;&amp; b &lt; 255)
            {
                b += this.colorChangeSpeed;
            }
        }
        else {
            if(b &gt; 0){
                b -= this.colorChangeSpeed;
                if(b &lt; 122) r += this.colorChangeSpeed;
            }
            else if(b &gt;= 0 &amp;&amp; r &lt; 255)
            {
                r += this.colorChangeSpeed;
            }
        }

        this.trailColor = color(r, 0, b);
    }

    // due to the fact that destination point is not an integer, 
    // I use this function to determine if device is close enough to the destination and can stop moving
    inDistanceOf(axis, xy){
        let distance = 3;
        let toReturn = false;

        let check0, check1;

        if(axis == "x"){
            check0 = this.x - xy;
            check1 = xy - this.xy;

            if((check0 &lt; distance) &amp;&amp; ( check0 &gt; -distance)) toReturn = true;

            if((check1 &lt; distance) &amp;&amp; ( check1 &gt; -distance)) toReturn = true;
        }

        if(axis == "y"){
            check0 = this.y - xy;
            check1 = xy - this.y;

            if((check0 &lt; distance) &amp;&amp; ( check0 &gt; -distance)) toReturn = true;

            if((check1 &lt; distance) &amp;&amp; ( check1 &gt; -distance)) toReturn = true;
        }
        return toReturn;
    }

}


class Particle {

    constructor(x0, y0, speed, color) {
        this.x = x0;
        this.y = y0;
        this.diameter = 20;
        this.alpha = 255;
        this.speed = speed;

        this.r = red(color);
        this.b = blue(color);
    }

    show() {

        noStroke();
        fill(this.r, 0, this.b, this.alpha);
        ellipse(this.x, this.y, this.diameter);

        this.update();
    }

    // steadily decreases transparency of particles to make view of moving trail
    update() {
        if(this.alpha &gt; 200){
            this.alpha -= 1.2*this.speed;
        }
        else if(this.alpha &gt; 150){
            this.alpha -= 1*this.speed;
        }
        else if(this.alpha &gt; 100){
            this.alpha -= 0.8*this.speed;
        }
        else if(this.alpha &gt; 50){
            this.alpha -= 0.5*this.speed;
        }
        else{
            this.alpha -= 0.3*this.speed;
        }
    }

    finished() {
        return this.alpha &lt;= 0;
    }

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Why do my particles avoid the edge pixels</title>
      <link>https://forum.processing.org/two/discussion/25069/why-do-my-particles-avoid-the-edge-pixels</link>
      <pubDate>Fri, 17 Nov 2017 20:44:59 +0000</pubDate>
      <dc:creator>canalesbr1</dc:creator>
      <guid isPermaLink="false">25069@/two/discussions</guid>
      <description><![CDATA[<p>Hello Processing Community</p>

<p>I am new to the forum and I am also  a complete rookie when it comes to coding but have been studying some processing books and tutorials in my spare time and am loving every second of it. That being said, I apologize for the confusing explanation/question that follows.</p>

<p>I am attempting to make a separation steering behavior that not only reacts to particles in the system but also reacts to trails left by the particles themselves. Even though I am not entirely satisfied with the behavior yet, I am working on improving it. Yet, my question is not regarding the behavior itself, but instead it is about how the particles are detecting the edges. It seems like the particles are detecting black pixels beyond the canvas and therefore are steering away from the edges which is not what I intend them to do. I would like the particles to ignore the edges entirely and go beyond the extents of the canvas. Any input on how to fix this or why this is happening would be greatly appreciated.</p>

<pre><code>int num =50;

int d = 0;

ArrayList&lt;Particle&gt; plist = new ArrayList&lt;Particle&gt;();

void setup(){
  size(1400,900);
  background(240);
  strokeWeight(1);

  //fill(0);
  //ellipse(width/2,height/2,200,200);

  for (int i= 0; i&lt;num; i++){
    plist.add(new Particle(random(width),random(height)));
  }
}

void draw(){


  for (Particle p: plist){
    p.run();
  }
}

class Particle{
  PVector location;
  PVector velocity;
  PVector acceleration;
  PVector pastloc;

  float maxspeed = 2;
  float maxforce =.1;

  int range = 50;

  float ran = .1;

  Particle(float x, float y){
    location = new PVector (x,y);
    velocity = new PVector (0,0);
    acceleration = new PVector (0,0);
    pastloc = new PVector(location.x,location.y);
  }

  void separate(){
    loadPixels();
    PVector black;
    PVector sum = new PVector();
    int count = 0;

    for(int i=-range;i&lt;range;i++){
      for(int j=-range;j&lt;range;j++){
        int x = round(location.x)+j;
        int y = round(location.y)+i;
        color c = get(x,y);
        black = new PVector (x,y);
        float d = PVector.dist(location,black);
        if ((brightness(c)&lt;10)&amp;&amp;(d&gt;10)){
          count++;


          PVector diff = PVector.sub(location,black);
          diff.normalize();
          diff.div(d);
          sum.add(diff);
        }
      } 
    }

    println(count);
    if (count &gt; 0){
      sum.setMag(maxspeed);
      PVector steer = PVector.sub(sum,velocity);
      steer.limit(maxforce);
      applyForce(steer);
    }

   }




  void applyForce(PVector steer){
    acceleration.add(steer);
  }

  void run(){
    separate();
    update();
    display();
  }

  void display(){
    line(location.x,location.y,pastloc.x,pastloc.y);
    pastloc.x = location.x;
    pastloc.y = location.y;
  }

  void update(){
    velocity.add(acceleration);
    location.add(velocity);
    acceleration.mult(0);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>making particle system more efficient (in particular when they are deleted)</title>
      <link>https://forum.processing.org/two/discussion/23257/making-particle-system-more-efficient-in-particular-when-they-are-deleted</link>
      <pubDate>Thu, 29 Jun 2017 13:37:40 +0000</pubDate>
      <dc:creator>secondsky</dc:creator>
      <guid isPermaLink="false">23257@/two/discussions</guid>
      <description><![CDATA[<p>Hi all, i'm trying to do a particle system where basically i have a matrix of drops that is gonna fall down. 
Kind o the simulation of a 3d water courtain.</p>

<p>As in the Shiffman examples, i'm using a OOP approach, where each particle is an object in an arraylist and when they go too fare are deleted to free memory.</p>

<p>The only difference is that the particle system is executed in a parallel thread and the main one just get a copy of the particles to represent them, when is needed.</p>

<p>What i don't understand, is why the sketch slow down so much when the drops approach the distance where they are deleted.
After all, the check happen to every loop anyway. Is there some technique to make this more efficient?</p>

<pre><code>import peasy.*;

PeasyCam cam;

ParticleSystem ps;

void setup() {

  size(600, 600, P3D);

  cam = new PeasyCam(this, 15, 30, 15, 100);
  cam.setMinimumDistance(50);
  cam.setMaximumDistance(500);
  ps = new ParticleSystem();
}

void draw() {

  background(255);
  noFill();
  strokeWeight(1);

  pushMatrix();
  translate(15, -5, 15);
  box(30, 10, 30);
  popMatrix();

  pushMatrix();
  translate(15, 50, 15);
  box(30, 30, 30);
  popMatrix();

  pushMatrix();
  strokeWeight(0.1);

  ArrayList&lt;Particle&gt; particles = ps.particles();
  for (int i = 0; i&lt; particles.size(); i++ ) {

    point(
      particles.get(i).position.x, 
      particles.get(i).position.y, 
      particles.get(i).position.z
      );
  }

  popMatrix();
}

public  class ParticleSystem implements Runnable {

  boolean loop = true;
  ArrayList&lt;Particle&gt; particles;

  long lastUpdate;
  int updateInterval = 10;

  float maxTravelDistance = 35 ;
  float pRF = 0.005;  // particlesRandomFactor


  public ParticleSystem() {


    particles = new ArrayList&lt;Particle&gt;();

    for (int x = 0; x &lt; 15; x++) {
      for (int z = 0; z &lt; 15; z++) {
        for (int i = 0; i &lt; 1000; i++)
        {
          particles.add(new Particle(new PVector(x*2, 0, z*2), new PVector(random(-pRF, pRF), random(-pRF, pRF), random(-pRF, pRF))));
        }
      }
    }
    new Thread(this).start();
    println(particles.size());
  }

  @ Override
  public void run() {

    while (loop) {
      if (millis()-lastUpdate &gt; updateInterval &amp;&amp; millis() &gt; 3000) {
        if (particles.size() &gt;0) {
          for (int i = particles.size()-1; i&gt;0; i--) {
            if (particles.get(i).position.y &gt; maxTravelDistance) particles.remove(i);
            else  particles.get(i).update();
          }
        }
        lastUpdate = millis();
      }
    }
  }


  ///////////particles
  public synchronized ArrayList&lt;Particle&gt; particles() {
    return particles;
  }




  public synchronized PVector[] getPositions() {

    //ArrayList&lt;Particle&gt;particlesToExport = particles().toArray(new Particle[particles.size()]);

    ArrayList&lt;Particle&gt;particlesToExport = particles;
    PVector[] output = new PVector[particlesToExport.size()];

    for (int i = 0; i &lt; output.length; i++)
    {
      output[i] = particlesToExport.get(i).position();
    }

    return output;
  }
}


public  class  Particle {

  float mass;
  boolean isDead = false;
  float airDrag = 0.95;


  PVector position;
  PVector oldPosition;

  PVector speed;
  PVector acceleration;

  public Particle(PVector p, PVector s) {
    mass = random(0.9, 1.1);
    position = p;
    speed = s;
    acceleration = new PVector(0, 0.02*mass, 0);
  }

  void update() {
    //oldPosition = position;
    if (abs(speed.x) &gt;=0.05 || abs(speed.z) &gt;= 0.05) speed.mult(airDrag);
    if (!(speed.y &gt; 10)) speed.add(acceleration);
    position.add(speed);
  }

  ///////////position
  public synchronized void position(PVector input) {
    position = input;
  }
  public synchronized PVector position() {
    return position;
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Wind map with Processing</title>
      <link>https://forum.processing.org/two/discussion/20461/wind-map-with-processing</link>
      <pubDate>Wed, 25 Jan 2017 10:48:19 +0000</pubDate>
      <dc:creator>thalesrm</dc:creator>
      <guid isPermaLink="false">20461@/two/discussions</guid>
      <description><![CDATA[<p>Hi there, 
I'm trying to create some visuals based on a Wind Map. I got the visuals to work with the parameters setting the thickness and turbulence of the particles but I would like to be able to control those parameters through sliders on an interface so I have more control of it.</p>

<p>I added the sliders to control these parameters but It's not changing the visuals live for some reason. I think it might be because of the positioning of the elements in my code, so I will past it here a section of my code and hopefully someone with experience can point me where i'm getting this wrong?</p>

<pre><code>int sParticles = 5000;
int sNoiseScale = 5000;
int sLength = 5;

float sRandomA = .5;
float sRandomB = 2;



int num = sParticles;
Particle[] particles = new Particle[num];
float noiseScale=sNoiseScale, noiseStrength=5; // Turbulence

void setup() {

  cp5 = new ControlP5(this);
  cp5.addSlider("sParticles").setPosition(0,0).setRange(0,10000);
  cp5.addSlider("sNoiseScale").setPosition(160,0).setRange(0,10000);
  cp5.addSlider("sLength").setPosition(330,0).setRange(0,20);

  cp5.addSlider("sRandomA").setPosition(490,0).setRange(0,5);
  cp5.addSlider("sRandomB").setPosition(650,0).setRange(0,5);

  size(1920, 1080);
  noStroke();
  for (int i=0; i&lt;num; i++) { 
    PVector loc = new PVector(random(width*1.2), 
    random(height), random(sRandomA, sRandomB)); // Thickness

    float angle = random(TWO_PI);
    PVector dir = new PVector(cos(angle), sin(angle));
    float speed = random(.5, 2);
    particles[i]= new Particle(loc, dir, speed);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Project problems (ParticleSystem / Video)</title>
      <link>https://forum.processing.org/two/discussion/19387/project-problems-particlesystem-video</link>
      <pubDate>Tue, 29 Nov 2016 10:24:45 +0000</pubDate>
      <dc:creator>JamesHewitt</dc:creator>
      <guid isPermaLink="false">19387@/two/discussions</guid>
      <description><![CDATA[<p>Hello all I am new to processing and have a question with regards to how I would fix my code.</p>

<pre><code>import processing.video.*;

Capture video;

PImage prevFrame;

float threshold = 50;

void setup() {
  size(600,400);
  video = new Capture(this, 640, 480,30);
  video.start();
  ps = new ParticleSystem(new PVector(width/2, 50));
  prevFrame = createImage(video.width, video.height, RGB);
}

void captureEvent(Capture video) {
  prevFrame.copy(video, 0, 0, video.width, video.height, 0, 0, video.width, video.height);
  prevFrame.updatePixels();
  video.read();
}

void draw() {
  background(0);
  image(video, 0, 0);
  ps.addParticle();
  ps.run();
  loadPixels();
  video.loadPixels();
  prevFrame.loadPixels();

  float sumX = 0;
  float sumY = 0;
  int motionCount = 0;

  for (int x = 0; x &lt; video.width; x++ ) {
    for (int y = 0; y &lt; video.height; y++ ) {
      color current = video.pixels[x+y*video.width];

      color previous = prevFrame.pixels[x+y*video.width];

      float r1 = red(current);
      float g1 = green(current);
      float b1 = blue(current);
      float r2 = red(previous); 
      float g2 = green(previous);
      float b2 = blue(previous);

      float diff = dist(r1, g1, b1, r2, g2, b2);

      if (diff &gt; threshold){
        sumX += x;
        sumY += y;
        motionCount ++;
      }
    }
  }

  float avgX = sumX / motionCount;
  float avgY = sumY / motionCount;


  smooth();
  noStroke();
  fill(0);
  ellipse(avgX, avgY, 16, 16);
}

  ParticleSystem ps;


class ParticleSystem {
  ArrayList&lt;Particle&gt; particles;
  PVector origin;

  ParticleSystem(PVector position) {
    origin = position.copy();
    particles = new ArrayList&lt;Particle&gt;();
  }

  void addParticle() {
    particles.add(new Particle(origin));
  }

  void run() {
    for (int i = particles.size()-1; i &gt;= 0; i--) {
      Particle p = particles.get(i);
      p.run();
      if (p.isDead()) {
        particles.remove(i);
      }
    }
  }
}

class Particle {
  PVector position;
  PVector velocity;
  PVector acceleration;
  float lifespan;

  Particle(PVector l) {
    acceleration = new PVector(0, 0.05);
    velocity = new PVector(random(-1, 1), random(-2, 0));
    position = l.copy();
    lifespan = 255.0;
  }

  void run() {
    update();
    display();
  }

  void update() {
    velocity.add(acceleration);
    position.add(velocity);
    lifespan -= 1.0;
  }

  void display() {
    stroke(255, lifespan);
    fill(255, lifespan);
    ellipse(avgX, avgY, 8, 8);
  }

  boolean isDead() {
    if (lifespan &lt; 0.0) {
      return true;
    } else {
      return false;
    }
  }
}
</code></pre>

<p>I have two pieces of code with one being able to detect motion and place a dot where it is detected and the other is a particle system and I am trying to place the particle system where movement is detected but I am unsure as to why it is not working, any help is appreciated!</p>
]]></description>
   </item>
   <item>
      <title>Particles appear in the same place (Video / Particles)</title>
      <link>https://forum.processing.org/two/discussion/19424/particles-appear-in-the-same-place-video-particles</link>
      <pubDate>Wed, 30 Nov 2016 07:43:42 +0000</pubDate>
      <dc:creator>JamesHewitt</dc:creator>
      <guid isPermaLink="false">19424@/two/discussions</guid>
      <description><![CDATA[<p>Hello all I have working piece of motion detection that is supposed to place my particles where it is detected but I am having an error on line 67 ish with the argX and argY saying that they do not exist? Any help is appreciated!</p>

<p>__    import processing.video.*;</p>

<pre><code>Capture video;

PImage prevFrame;

float threshold = 50;

float avgX; 
float avgY;

void setup() {
  size(600,400);
  video = new Capture(this, 640, 480,30);
  video.start();
  ps = new ParticleSystem(new PVector(width/2, 50));
  prevFrame = createImage(video.width, video.height, RGB);
  minim = new Minim(this);
  player = minim.loadFile("sandstorm.mp3", 2048);
  player.play();
}

void captureEvent(Capture video) {
  prevFrame.copy(video, 0, 0, video.width, video.height, 0, 0, video.width, video.height);
  prevFrame.updatePixels();
  video.read();
}

void draw() {
  background(0);
  image(video, 0, 0);
  loadPixels();
  video.loadPixels();
  prevFrame.loadPixels();

  float sumX = 0;
  float sumY = 0;
  int motionCount = 0;

  for (int x = 0; x &lt; video.width; x++ ) {
    for (int y = 0; y &lt; video.height; y++ ) {
      color current = video.pixels[x+y*video.width];

      color previous = prevFrame.pixels[x+y*video.width];

      float r1 = red(current);
      float g1 = green(current);
      float b1 = blue(current);
      float r2 = red(previous); 
      float g2 = green(previous);
      float b2 = blue(previous);

      float diff = dist(r1, g1, b1, r2, g2, b2);

      if (diff &gt; threshold){
        sumX += x;
        sumY += y;
        motionCount ++;
      }
    }
  }

  avgX = sumX / motionCount;
  avgY = sumY / motionCount;


  ps.addParticle(new PVector(argX, argY));
  ps.run();


  smooth();
  noStroke();
}

  ParticleSystem ps;


class ParticleSystem {
  ArrayList&lt;Particle&gt; particles;
  PVector origin;

  ParticleSystem(PVector position) {
    origin = position.copy();
    particles = new ArrayList&lt;Particle&gt;();
  }

  void addParticle(PVector pos) {
   particles.add(new Particle(pos));
  }

  void run() {
    for (int i = particles.size()-1; i &gt;= 0; i--) {
      Particle p = particles.get(i);
      p.run();
      if (p.isDead()) {
        particles.remove(i);
      }
    }
  }
}

class Particle {
  PVector position;
  PVector velocity;
  PVector acceleration;
  float lifespan;

  Particle(PVector l) {
    acceleration = new PVector(0, 0.05);
    velocity = new PVector(random(-1, 1), random(-2, 0));
    position = l.copy();
    lifespan = 255.0;
  }

  void run() {
    update();
    display();
  }

  void update() {
    velocity.add(acceleration);
    position.add(velocity);
    lifespan -= 1.0;
  }

  void display() {
    stroke(255, lifespan);
    fill(255, lifespan);
    ellipse(position.x, position.y, 8, 8);
  }

  boolean isDead() {
    if (lifespan &lt; 0.0) {
      return true;
    } else {
      return false;
    }
  }
}_
</code></pre>
]]></description>
   </item>
   <item>
      <title>pass a global variable to a class</title>
      <link>https://forum.processing.org/two/discussion/19187/pass-a-global-variable-to-a-class</link>
      <pubDate>Mon, 21 Nov 2016 11:30:28 +0000</pubDate>
      <dc:creator>digitalmartyn</dc:creator>
      <guid isPermaLink="false">19187@/two/discussions</guid>
      <description><![CDATA[<p>I have a particle system over a live video feed with an implementation of OpenCV OpticalFlow.</p>

<p>I need the particles to be affected by opticalflow values - i.e. move left and a right with the person in the video.</p>

<p>I can get the variable aveFlow.x each frame but can't run it through to each particle and change the vector x</p>

<p>full code:</p>

<pre><code>import gab.opencv.*;
import processing.video.*;
import java.awt.*;

//Movie video;
Capture video;
OpenCV opencv;

// DECLARE
ArrayList ballCollection;

float numBalls = 2;

void setup() {
  size(640, 480);
  video = new Capture(this, width/4, height/4);
  opencv = new OpenCV(this, width/4, height/4);
  opencv.loadCascade(OpenCV.CASCADE_FRONTALFACE);  

  //INITIALIZE
  ballCollection = new ArrayList();

  video.start();
}

void draw() {
  //background(0);
  //scale(2);
  opencv.loadImage(video);
  opencv.calculateOpticalFlow();

  image(video, 0, 0, width, height);

  //translate(video.width, 0);
  stroke(255, 0, 0);
  //opencv.drawOpticalFlow();

  PVector aveFlow = opencv.getAverageFlow();
  int flowScale = 100;
  //float optX = aveFlow.x;

  stroke(255);
  strokeWeight(2);
  //line(video.width/2, video.height/2, video.width/2 + aveFlow.x*flowScale, video.height/2 + aveFlow.y*flowScale);
  line(width/2, height/2, width/2 + aveFlow.x*flowScale, height/2 + aveFlow.y*flowScale);

  //numberofballs
  if (ballCollection.size()&lt;numBalls) {
    Ball myBall = new Ball(random(width), 0);
    ballCollection.add(myBall);
  }  

  //CALL FUNCTIONALITY
  for (int i = 0; i &lt; ballCollection.size(); i++) {
    Ball mb = (Ball) ballCollection.get(i);
    mb.run();
  }
}

//void movieEvent(Movie m) {
//  m.read();
//}

void captureEvent(Capture c) {
  c.read();
}

class Ball {

  //global variables
  float x=0;
  float y=0;
  //float speedX = random(-2, 2);
  float speedX = 0;

  float speedY = random(-2, 2);

  //float optY = 0;

  //constructor
  Ball(float _x, float _y) {
    x= _x;
    y= _y;
    //optX = _optX*50;
  }

  //functions
  void run() {
    if (y&lt;height) {
      display();
      move();
      //bounce();
      gravity();
      opticalFlow();
    }
  }

  void opticalFlow() {
    //speedX += aveFlow.x*flowScale;
  }

  void gravity() {
    speedY += 0.01;
  }

  void bounce() {
    if (x &gt; width ) {
      speedX *= -1;
    }
    if (x &lt; 0 ) {
      speedX *= -1;
    }
    if (y &gt; height ) {
      speedY *= -1;
    }
    if (y &lt; 0 ) {
      speedY *= -1;
    }
  }

  void move() {
    x += speedX;
    y += speedY;
  }

  void display() {
    ellipse (x, y, 20, 20);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Zooming in and out using the direction keys? / Changing color of text</title>
      <link>https://forum.processing.org/two/discussion/19076/zooming-in-and-out-using-the-direction-keys-changing-color-of-text</link>
      <pubDate>Wed, 16 Nov 2016 19:23:20 +0000</pubDate>
      <dc:creator>drewk94</dc:creator>
      <guid isPermaLink="false">19076@/two/discussions</guid>
      <description><![CDATA[<p>Hello! Really new to processing.. new to programming in general so bear with me. All I want to do is:</p>

<p>1) Change the color of the text
<br />
2) Zoom in and out using the directional keys (Up, down, left, right)</p>

<p>I can't manage to figure it out.. some help would be great. 
Thank you.</p>

<pre><code>TextGraphics tg;
PVector root = new PVector(random(1234), random(1234), random(1234)), //noise root
nSpeed = new PVector(random(-.02, .02), random(-.02, .02), random(-.02, .02));//noise speed;
ArrayList&lt;Particle&gt; particles = new ArrayList&lt;Particle&gt;();
int nbParticle = 6000;
int[] pgpx;//PGraphics' pixels array
float zoom = 100;//noise zoom level
Boolean noiseOn = true, hitMode = true;
import peasy.*;
PeasyCam cam;


void setup()
{
  size(1300, 800, P3D);
  cam = new PeasyCam(this, 800);
  cam.setMinimumDistance(50);
  cam.setMaximumDistance(1300);
  tg = new TextGraphics();
  strokeWeight(10);
  smooth();

}

void draw()
{ 
  background(0);
  lights();
  box(0);
  pushMatrix();
  box(0);
  popMatrix();


  for (int i = 0; i &lt; nbParticle; i++)
  {
    Particle p = particles.get(i);
    p.update();
  }
  root.add(nSpeed);//update noise


}


void createParticles()
{
  particles = new ArrayList&lt;Particle&gt;();
  //random particle disposition 
  while (particles.size () &lt; nbParticle)
  {
    Particle p = new Particle(particles.size ());
    particles.add(p);
  }
}

void mousePressed()
{
  root = new PVector(random(1234), random(1234));//reset noise root
  nSpeed = new PVector(random(-.02, .02), random(-.02, .02));//reset noise speed
}

void keyPressed()

  {
    switch(key)
    {
    case 'n'://noise toggle
      noiseOn = !noiseOn;
      break;
    case 'h'://hit toggle
      hitMode = !hitMode;
      if (!hitMode)
        for (Particle p : particles)
        {
          p.speed.mult(-1);
        }
      break;
    case ' '://ignore SPACE
    case ESC://ignore ESCAPE
    case ENTER://ignore ENTER
    case BACKSPACE://ignore BACKSPACE
      break;
    default://char input
      //tg.process("" + key);//RUN IN JAVA

      break;
    }
  }


class Particle
{
  final float SPEED_MIN = .12, SPEED_MAX = .25, h = 40;
  PVector pos, origin, speed;
  int rank, col = color(random(128, 255), random(128, 205), 90, 120);
  float n, nz;//noise
  Boolean stuck = false;//against a wall

  Particle(int p_rank)
  {
    rank = p_rank;
    init();
  }

  void init()
  {
    stuck = false;
    float theta = random(TWO_PI);
    speed = new PVector(cos(theta), sin(theta), -cos(theta));
    speed.mult(random(SPEED_MIN, SPEED_MAX) * (random(1)&lt;0?1:-1));
    Boolean done = false;
    while (!done)
    {
      pos = new PVector(random(width), random(height));
      if (green(pgpx[(int)pos.y * width + (int)pos.x]) &gt; 100)
      {
        pos.z = random(-h/2, h/2);
        origin = pos.get();
        done = true;
      }
    }
  }

  void update()
  {
    if (noiseOn &amp;&amp; !stuck)
    {
      n = noise(root.x + pos.x/zoom, root.y + pos.y/zoom, root.z + pos.z/zoom)*2*TWO_PI;
      nz = noise(root.x/10 + pos.x/zoom, root.y + pos.y/zoom, root.z + pos.z/zoom)*2*TWO_PI;
      speed.set(cos(n), sin(n), -cos(nz));
      speed.mult(SPEED_MAX);
    }

    if (!(stuck &amp;&amp; hitMode))
      pos.add(speed);

    if (green(pgpx[(int)pos.y * width + (int)pos.x]) &lt; 80)//particle outside the letter
    {
      stuck = hitMode;
      pos.sub(speed);
      if (!hitMode)
      {
        if (noiseOn)
        { 
          pos = origin.get();
        } else
        {      
          speed.x *= -1;
          speed.y *= -1;
        }
      }
    }
    if (pos.z &gt; h/2 || pos.z &lt; -h/2)
    {
      stuck = hitMode;
      pos.z = constrain(pos.z, -h/2, h/2);
      if (!hitMode)
      {
        if (noiseOn)
        {
          pos = origin.get();
        } else
        {
          speed.z *= -1;
        }
      }
    }

    stroke(map(pos.z, -h/2, h/2, 128, 255), map(pos.z, -h/2, h/2, 128, 205), 90, 120);
    point(pos.x-width/2, pos.y-height/2, pos.z);
  }
}

class TextGraphics
{  
  PGraphics pg;//buffer PG used to write the input char

  TextGraphics()
  {
    pg = createGraphics(width, height, P2D);
    process(new String("Nothing is ever complete."));//"Ï�")//initialize with a String
  }

  void process(String c)
  {
    pg.beginDraw();
    pg.translate(-width/2, -height/1.7);
    pg.background(0);
    pg.textSize(70);//500
    pg.fill(color(255, 255, 255));
    pg.textAlign(CENTER, CENTER);
    pg.text(c, width, height);
    pg.translate(width/2, height/1.7);
    pg.endDraw();

    pgpx = new int[width * height];
    pg.loadPixels();
    arrayCopy(pg.pixels, pgpx);
    pg.updatePixels();

    createParticles();
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to run Particles example in fullScreen();</title>
      <link>https://forum.processing.org/two/discussion/18982/how-to-run-particles-example-in-fullscreen</link>
      <pubDate>Fri, 11 Nov 2016 10:18:56 +0000</pubDate>
      <dc:creator>greentrancer</dc:creator>
      <guid isPermaLink="false">18982@/two/discussions</guid>
      <description><![CDATA[<p>Hello. So I was looking at the Particles (Demos &gt; Graphics) example from Processing 3.2.3 and I removed size(); and added fullScreen(); - after doing so, I cannot see anything on the screen anymore, only black background and no particles. Does anyone have any idea? Thanks.</p>
]]></description>
   </item>
   <item>
      <title>how to improve performance for particle systems</title>
      <link>https://forum.processing.org/two/discussion/18565/how-to-improve-performance-for-particle-systems</link>
      <pubDate>Sat, 15 Oct 2016 19:43:04 +0000</pubDate>
      <dc:creator>flowen</dc:creator>
      <guid isPermaLink="false">18565@/two/discussions</guid>
      <description><![CDATA[<p>dear creatives,</p>

<p>I'm building a particle system, based on Daniel Shiffman's code from nature of code. Drawing triangle vertices when distance is within the defined range. Quite fast I get massive fps drops, which i sort of expected as it's 3 loops within each other.</p>

<p>I've been briefly told about binned particle system, for which I could only find some old thread containing dead links. <a href="https://forum.libcinder.org/topic/kyle-mcdonald-s-binned-particle-system" target="_blank" rel="nofollow">https://forum.libcinder.org/topic/kyle-mcdonald-s-binned-particle-system</a></p>

<p>I wonder if there are other known techniques like this and if you know some resources or perhaps even a tutorial ;)</p>

<p>Thx in advance</p>
]]></description>
   </item>
   <item>
      <title>any tips to speed up sketch with 'high' number of particles?</title>
      <link>https://forum.processing.org/two/discussion/17434/any-tips-to-speed-up-sketch-with-high-number-of-particles</link>
      <pubDate>Wed, 06 Jul 2016 14:24:03 +0000</pubDate>
      <dc:creator>Xeronimo74</dc:creator>
      <guid isPermaLink="false">17434@/two/discussions</guid>
      <description><![CDATA[<p>I've got around 2800 particles (just calculating a couple of simple values and drawing them) but the sketch becomes quite slow (in Chrome and Firefox) ... I supposed that's to be expected? Or are there general tricks to speed something like this up?</p>
]]></description>
   </item>
   <item>
      <title>How to make particles go around an object instead of going through</title>
      <link>https://forum.processing.org/two/discussion/16893/how-to-make-particles-go-around-an-object-instead-of-going-through</link>
      <pubDate>Mon, 30 May 2016 07:59:16 +0000</pubDate>
      <dc:creator>PoYo</dc:creator>
      <guid isPermaLink="false">16893@/two/discussions</guid>
      <description><![CDATA[<p>I've been trying to do something with this project I have but failed always so far :) so decided to ask here :)</p>

<p>I want the particles to go around the ellipse from Rock class, not through it but around it, like a rock inside a river that water flows around it. Any suggestions ?</p>

<pre><code>int NUM_PARTICLES = 1000;
ParticleSystem p;
Rock r;
void setup()
{
  smooth();
  fullScreen(P2D);
  //size(700,700,P2D);
  //background(0);
  p = new ParticleSystem();
  r = new Rock();
}

void draw()
{
  background(0);
  p.update();
  p.render();
  r.rock();

}

float speed = 1;
class Particle
{
  PVector position, velocity;

  Particle()
  {
    position = new PVector(random(width),random(height));
    velocity = new PVector();
  }

  void update()
  {
    velocity.x = speed*(noise(position.y));
    velocity.y = speed*(noise(position.x));
    position.add(velocity);

    if(position.x&lt;0)position.x+=width;
    if(position.x&gt;width)position.x-=width;
    if(position.y&lt;0)position.y+=height;
    if(position.y&gt;height)position.y-=height;
  }

  void render()
  {
    stroke(0, 0, 255, 80);
    line(position.x,position.y,position.x-velocity.x,position.y-velocity.y);
  }
}

class ParticleSystem
{
  Particle[] particles;

  ParticleSystem()
  {
    particles = new Particle[NUM_PARTICLES];
    for(int i = 0; i &lt; NUM_PARTICLES; i++)
    {
      particles[i]= new Particle();
    }
  }

  void update()
  {
    for(int i = 0; i &lt; NUM_PARTICLES; i++)
    {
      particles[i].update();
    }
  }

  void render()
  {
    for(int i = 0; i &lt; NUM_PARTICLES; i++)
    {
      particles[i].render();
    }
  }
}
class Rock{

  void rock()
  {
  noFill();
  stroke(255);
  strokeWeight(4);
  ellipse(mouseX,mouseY,50,50);

}



}
</code></pre>
]]></description>
   </item>
   <item>
      <title>ArrayList of PVectors Setup and Display</title>
      <link>https://forum.processing.org/two/discussion/16830/arraylist-of-pvectors-setup-and-display</link>
      <pubDate>Wed, 25 May 2016 21:15:15 +0000</pubDate>
      <dc:creator>schehe</dc:creator>
      <guid isPermaLink="false">16830@/two/discussions</guid>
      <description><![CDATA[<p>Hi, 
I was wondering if anyone here can help me getting my head around PVectors. I am creating a visualization of points on Earth. For this I am creating an arrayList of PVectors, which get their data from a csv (Longitude, Latitute). My problem is the csv has over 88 000 lines and slows down the program when drawn in void draw() Therefore I wanted to initialize the PVectors in void createLocationPoints()) and only display them in draw with another funciton... For instance with giving the points a stroke weight. Can someone explain how I can display the function LocationVectors.add(new PVector(x, y, z)); in this example? I was thinking of something similar like Daniel Schiffmans simple particle example from the documentation but I can't quite get my head around it. Please be gentle, I am quite new to processing. Thanks a lot!</p>

<pre><code>import peasy.*;

PeasyCam cam;

//Radius Earth
float radius = 6371000/50000; //global scale

//Tables
Table dataTable;
Table locationTable;

//Data lists
FloatList AffordabilityIndex;
FloatList LongituteAI;
FloatList LatituteAI;
FloatList AltituteAI;

//Locations Lists
FloatList settlementPoint;
FloatList Longitute;
FloatList Latitute;
FloatList Altitute;

float x;
float y;
float z;

PVector LocationVector;
//PShape points;

ArrayList&lt;PVector&gt; LocationVectors;

void setup() {
  size(800, 800, P3D);
  smooth();
  dataTable = loadTable("dataTable.csv", "header");
  locationTable = loadTable("locationTable.csv", "header");

  LocationVectors = new ArrayList&lt;PVector&gt;();

  cam = new PeasyCam(this, 4000);
  cam.setMinimumDistance(250); //0
  cam.setMaximumDistance(500); //8000

  ////LOCATIONS
  ////create location lists
  Longitute = new FloatList();
  Latitute = new FloatList();
  Altitute = new FloatList();
  //Read and store CSV
  for (int i = 0; i &lt; locationTable.getRowCount(); i++) {
      TableRow rowLocationTable = locationTable.getRow(i);  
      Longitute.append(rowLocationTable.getFloat("Longitute")); 
      Latitute.append(rowLocationTable.getFloat("Latitute"));
      Altitute.append(rowLocationTable.getFloat("Altitute"));
    }


  //DATA
  //create data lists
  AffordabilityIndex = new FloatList();
  LongituteAI = new FloatList();
  LatituteAI = new FloatList();
  //Read and store CSV
  for (int i = 0; i &lt; dataTable.getRowCount(); i++) {
    TableRow rowDataTable = dataTable.getRow(i);
    AffordabilityIndex.append(rowDataTable.getFloat("Affordability Index")*1);
    LongituteAI.append(rowDataTable.getFloat("Longitute"));
    LatituteAI.append(rowDataTable.getFloat("Latitute"));
    //println(Longitute, Latitute, AffordabilityIndex);
  }

  createLocationPoints();

}

void draw() {

  background(255);
  shape(points);
  displayLocationPoints();

  //DRAW DATA

  AltituteAI = AffordabilityIndex;

  strokeWeight(4);
  stroke(0);
  beginShape(POINTS);

  for (int i = 0; i &lt; LongituteAI.size(); i++) {
    //Convert to Cartesian Coordinates
    //float a = pow( 1, 3);  // Sets 'a' to 1*1*1 = 1
    float f = 0; // flatening
    float lambda = atan(pow((1 - f), 2) * tan(radians(LatituteAI.get(i))));    // lambda

    float y = radius * cos(lambda) * cos(radians(LongituteAI.get(i))) + AltituteAI.get(i) * cos(radians(LatituteAI.get(i))) * cos(radians(LongituteAI.get(i))); //swaped x&amp;y
    float x = radius * cos(lambda) * sin(radians(LongituteAI.get(i))) + AltituteAI.get(i) * cos(radians(LatituteAI.get(i))) * sin(radians(LongituteAI.get(i)));
    float z = radius * sin(lambda) + AltituteAI.get(i) * sin(radians(LatituteAI.get(i)));

    vertex(x, y, z);
  }
  endShape();

  noStroke();
  sphere(radius*0.98);

}

void createLocationPoints(){
    //DRAW ALL LOCATIONS
  //strokeWeight(1);
  //stroke(0);
  //beginShape(POINTS);
   //points = createShape();
   //points.beginShape();

  for (int i = 0; i &lt; Longitute.size(); i++) {
    //Convert to Cartesian Coordinates
    //float a = pow( 1, 3);  // Sets 'a' to 1*1*1 = 1
    float f = 0; // flatening
    float lambda = atan(pow((1 - f), 2) * tan(radians(Latitute.get(i))));    // lambda

    float y = radius * cos(lambda) * cos(radians(Longitute.get(i))) + Altitute.get(i) * cos(radians(Latitute.get(i))) * cos(radians(Longitute.get(i))); //swaped x&amp;y
    float x = radius * cos(lambda) * sin(radians(Longitute.get(i))) + Altitute.get(i) * cos(radians(Latitute.get(i))) * sin(radians(Longitute.get(i)));
    float z = radius * sin(lambda) + Altitute.get(i) * sin(radians(Latitute.get(i)));

    vertex(x, y, z);

    LocationVector = new PVector(x, y, z);
    LocationVectors.add(new PVector(x, y, z));

  }

  //endShape();
  //points.endShape();
  println(LocationVectors);
} 

void displayLocationPoints(){
  strokeWeight(10);
  stroke(0);

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Code particles</title>
      <link>https://forum.processing.org/two/discussion/16093/code-particles</link>
      <pubDate>Mon, 18 Apr 2016 23:27:50 +0000</pubDate>
      <dc:creator>Pathy</dc:creator>
      <guid isPermaLink="false">16093@/two/discussions</guid>
      <description><![CDATA[<p>Hello . Does anyone have the particle code, which leave too many balls at the same time a certain point ?</p>
]]></description>
   </item>
   <item>
      <title>Particles moving (creating a word and expanding) using the position of the mouse</title>
      <link>https://forum.processing.org/two/discussion/15232/particles-moving-creating-a-word-and-expanding-using-the-position-of-the-mouse</link>
      <pubDate>Tue, 01 Mar 2016 18:28:07 +0000</pubDate>
      <dc:creator>derienkun</dc:creator>
      <guid isPermaLink="false">15232@/two/discussions</guid>
      <description><![CDATA[<p>Hi guys. Im quite new at this. I found this code that creates a number of particles which automatically expand and contracts forming a word, in this case the word is “real”. Now, what I would love it to do is to expand and contract not automatically and randomly, but using the position of the mouse. So, if the mouseY is down the screen all the particles are spread all over the canvas, but if the mouseY is up in the screen, all the particles contract and form the word “real”. If you could help me I would be eternally grateful.</p>

<p>Thanks!</p>

<p></p>

<pre>
<span>color</span> c = <span>color</span>(1);<span>//the secret colour</span>
<span>String</span> word = <span>&quot;real&quot;</span>;
<span>String</span> allwords =<span>&quot;real&quot;</span>;
<span>PVector</span> start  =<span>new</span> <span>PVector</span>(10, 60);
<span>int</span> tSize =500; <span>//Textsize</span>
<span>ArrayList</span>&lt;particle&gt; Points = <span>new</span> <span>ArrayList</span>&lt;particle&gt;();
<span>int</span> index=0;
<span>float</span> restZ=0;
<span>int</span> F = 0;
<span>float</span> CTime=150;<span>//number of frames between words</span>
<span>int</span> PNum =6000;<span>//number of particles</span>
<span>void</span> <span><b>setup</b></span>() {
&nbsp;&nbsp;<span>size</span>(1450, 850);
&nbsp;&nbsp;<span>frameRate</span>(100);
&nbsp;&nbsp;<span>background</span>(0);
&nbsp;&nbsp;<span>textSize</span>(tSize);
&nbsp;&nbsp;<span>fill</span>(0);
&nbsp;&nbsp;<span>text</span>(word, start.x, start.y+tSize); <span>//writing invisible text</span>
&nbsp;&nbsp;<span>loadPixels</span>(); <span>//saving all pixels of the sketch</span>
&nbsp;&nbsp;<span>for</span> (<span>int</span> i = 0; i &lt; PNum; i++) {<span>//creating the particles</span>
&nbsp;&nbsp;&nbsp;&nbsp;Points.<span>add</span>(<span>new</span> particle(<span>random</span>(<span>width</span>), <span>random</span>(<span>height</span>)));
&nbsp;&nbsp;}
}

<span>void</span> <span><b>draw</b></span>() {
&nbsp;&nbsp;<span>background</span>(0);
&nbsp;&nbsp;<span>int</span> Len = word.<span>length</span>();
&nbsp;&nbsp;<span>PVector</span> RealPix;
&nbsp;&nbsp;<span>if</span> (restZ==0) {<span>//when the timer for the word runs out</span>
&nbsp;&nbsp;&nbsp;&nbsp;restZ=CTime;
&nbsp;&nbsp;&nbsp;&nbsp;<span>for</span> (particle P : Points) {<span>//resetting particles and slowing them down</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;P.target=<span>false</span>;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;P.velocity.<span>mult</span>(1);
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;<span>String</span>[] Arr = allwords.<span>split</span>(<span>&quot; &quot;</span>);
&nbsp;&nbsp;&nbsp;&nbsp;word=Arr[F];<span>//getting the next word</span>
&nbsp;&nbsp;&nbsp;&nbsp;start.x&nbsp;=&nbsp;<span>int</span>(<span>random</span>(0, <span>width</span>-word.<span>length</span>()*tSize/1.45));
&nbsp;&nbsp;&nbsp;&nbsp;start.y&nbsp;=&nbsp;<span>int</span>(<span>random</span>(0, <span>height</span>-tSize*1.3));<span>//positioning text inside the window</span>
&nbsp;&nbsp;&nbsp;&nbsp;<span>fill</span>(c);
&nbsp;&nbsp;&nbsp;&nbsp;<span>text</span>(word, start.x, start.y+tSize);
&nbsp;&nbsp;&nbsp;&nbsp;<span>loadPixels</span>();
&nbsp;&nbsp;&nbsp;&nbsp;F++;
&nbsp;&nbsp;&nbsp;&nbsp;<span>if</span> (F&gt;=Arr.<span>length</span>) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;F=0;
&nbsp;&nbsp;&nbsp;&nbsp;};
&nbsp;&nbsp;}&nbsp;<span>else</span> <span>if</span> (restZ&lt;=1) {<span>//slowing down on the last 4 frames</span>
&nbsp;&nbsp;&nbsp;&nbsp;<span>for</span> (particle P : Points) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;P.velocity.<span>mult</span>(1.5);
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;}
&nbsp;&nbsp;restZ-=1;
&nbsp;&nbsp;<span>for</span> (<span>int</span> i = 0; i &lt; 13*PNum/(CTime-30); i++) {<span>//checking random points in the area of the text</span>
&nbsp;&nbsp;&nbsp;&nbsp;RealPix=&nbsp;&nbsp;<span>new</span> <span>PVector</span>(<span>int</span>(<span>random</span>(start.x, start.x+Len*tSize/1.45)), <span>int</span>(<span>random</span>(start.y, start.y+tSize*1.3)));
&nbsp;&nbsp;&nbsp;&nbsp;<span>int</span> pixNr =<span>int</span>(RealPix.y*<span>width</span> + RealPix.x);
&nbsp;&nbsp;&nbsp;&nbsp;<span>color</span> b= <span>pixels</span>[pixNr];
&nbsp;&nbsp;&nbsp;&nbsp;<span>if</span> ((c == b)&amp;&amp;(restZ&lt;CTime-20)&amp;&amp;(restZ&gt;=10)) {<span>//if the point is on text</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;particle&nbsp;Aktuell&nbsp;=&nbsp;Points.<span>get</span>(index);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>if</span> (Aktuell.target==<span>false</span>) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Aktuell.target=<span>true</span>;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>PVector</span> desired = <span>PVector</span>.<span>sub</span>(RealPix, Aktuell.location);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;desired.<span>div</span>(restZ);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Aktuell.velocity=&nbsp;desired;<span>//kicking the particle in the direction of the point</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;index++;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;index=index%PNum;
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;}
&nbsp;&nbsp;runP();<span>//simulating and drawing the particles</span>
}

<span>void</span> runP() {
&nbsp;&nbsp;<span>for</span> (particle P : Points) {
&nbsp;&nbsp;&nbsp;&nbsp;<span>stroke</span>(255, 255, 255, 128/<span>sqrt</span>(P.velocity.<span>mag</span>()+1));
&nbsp;&nbsp;&nbsp;&nbsp;P.location.<span>add</span>(P.velocity);
&nbsp;&nbsp;&nbsp;&nbsp;<span>line</span>(P.location.x, P.location.y, P.location.x+P.velocity.x, P.location.y+P.velocity.y);
&nbsp;&nbsp;}<span>//drawig particles as lines for a smoother look</span>
}

<span>class</span> particle {
&nbsp;&nbsp;<span>PVector</span> location;
&nbsp;&nbsp;<span>PVector</span> velocity;
&nbsp;&nbsp;<span>boolean</span> target=<span>false</span>;
&nbsp;&nbsp;particle(<span>float</span> x, <span>float</span> y) {
&nbsp;&nbsp;&nbsp;&nbsp;location&nbsp;=&nbsp;<span>new</span> <span>PVector</span>(x, y);
&nbsp;&nbsp;&nbsp;&nbsp;velocity&nbsp;=&nbsp;<span>new</span> <span>PVector</span>(0.0, 0.0);
&nbsp;&nbsp;}
}

</pre>

<p></p>
]]></description>
   </item>
   <item>
      <title>Create a particle explosion of an image</title>
      <link>https://forum.processing.org/two/discussion/13674/create-a-particle-explosion-of-an-image</link>
      <pubDate>Thu, 26 Nov 2015 22:08:56 +0000</pubDate>
      <dc:creator>CantSayIHave</dc:creator>
      <guid isPermaLink="false">13674@/two/discussions</guid>
      <description><![CDATA[<p>Hey, I'd like to make an explosion effect for a game I'm making. The image is about 20 pixels w/h so I'm not looking for anything huge.</p>

<p>I'd like to make it radiate outwards and fade from a central point, but I can't think of how to.</p>

<p>Any help is appreciated.</p>

<p>Thanks</p>
]]></description>
   </item>
   <item>
      <title>Gifs made up of Particles + Flock Behavior</title>
      <link>https://forum.processing.org/two/discussion/12580/gifs-made-up-of-particles-flock-behavior</link>
      <pubDate>Fri, 18 Sep 2015 18:08:49 +0000</pubDate>
      <dc:creator>amaier</dc:creator>
      <guid isPermaLink="false">12580@/two/discussions</guid>
      <description><![CDATA[<p>Hello! I've been creeping around the forums for about a month trying to see if I could answer this on my own... but I can't.</p>

<p>I want to create a gif that is made up of tiny particles. Like these wizards did: <a href="http://www.iamnop.com/particles/" target="_blank" rel="nofollow">http://www.iamnop.com/particles/</a>  ^:)^  (I know this isn't processing, but you get the idea)</p>

<p>But then I want each gif to interact with each other using Flocking behaviors, including having the mouse be a Predator.</p>

<p>Is this ridiculous?</p>

<p>I have been able to do bits and pieces of what I want... but I can't for the life of me figure out how to bring it together.  Creating gifs from particles seems impossible. :(</p>

<p>Any advice would be so greatly appreciated.</p>

<p>Thank you!
Allison</p>
]]></description>
   </item>
   <item>
      <title>Flying Particles 2D &amp; 3D (made with Processing, HD 720p)</title>
      <link>https://forum.processing.org/two/discussion/10625/flying-particles-2d-3d-made-with-processing-hd-720p</link>
      <pubDate>Sun, 03 May 2015 16:41:13 +0000</pubDate>
      <dc:creator>atoro</dc:creator>
      <guid isPermaLink="false">10625@/two/discussions</guid>
      <description><![CDATA[<p>(1) Flying Particles 2D (made with Processing)
<span class="VideoWrap"><span class="Video YouTube" id="youtube-bCERUcNaSsM"><span class="VideoPreview"><a href="http://youtube.com/watch?v=bCERUcNaSsM"><img src="http://img.youtube.com/vi/bCERUcNaSsM/0.jpg" width="640" height="385" border="0" /></a></span><span class="VideoPlayer"></span></span></span></p>

<p>(2) Flying Particles 2D (made with Processing)
<span class="VideoWrap"><span class="Video YouTube" id="youtube-rWAqEneXp0o"><span class="VideoPreview"><a href="http://youtube.com/watch?v=rWAqEneXp0o"><img src="http://img.youtube.com/vi/rWAqEneXp0o/0.jpg" width="640" height="385" border="0" /></a></span><span class="VideoPlayer"></span></span></span></p>

<p>(3) Flying Particles 3D (made with Processing)
<span class="VideoWrap"><span class="Video YouTube" id="youtube-kAeCjKpKj3I"><span class="VideoPreview"><a href="http://youtube.com/watch?v=kAeCjKpKj3I"><img src="http://img.youtube.com/vi/kAeCjKpKj3I/0.jpg" width="640" height="385" border="0" /></a></span><span class="VideoPlayer"></span></span></span></p>
]]></description>
   </item>
   <item>
      <title>Adding Particle Background</title>
      <link>https://forum.processing.org/two/discussion/10676/adding-particle-background</link>
      <pubDate>Wed, 06 May 2015 18:30:10 +0000</pubDate>
      <dc:creator>Shaker</dc:creator>
      <guid isPermaLink="false">10676@/two/discussions</guid>
      <description><![CDATA[<p>I am really new at processing but I am working on a code with a current particle system and want to add another system of particles as a background. How do I go about adding a second particle to an existing code without it effecting the current particle.</p>

<p>Any help at all would be greatly appreciated. I am trying to teach myself coding and just need to know the right direction to look.</p>

<p>Thanks,</p>
]]></description>
   </item>
   <item>
      <title>Flying Particles / Music Player (HD 720p)</title>
      <link>https://forum.processing.org/two/discussion/10780/flying-particles-music-player-hd-720p</link>
      <pubDate>Tue, 12 May 2015 19:22:22 +0000</pubDate>
      <dc:creator>atoro</dc:creator>
      <guid isPermaLink="false">10780@/two/discussions</guid>
      <description><![CDATA[<p>Made with Processing 
Flying Particles / Music Player (HD 720p) // gp 001 01 svsa
<span class="VideoWrap"><span class="Video YouTube" id="youtube-09j67sQ6WfQ"><span class="VideoPreview"><a href="http://youtube.com/watch?v=09j67sQ6WfQ"><img src="http://img.youtube.com/vi/09j67sQ6WfQ/0.jpg" width="640" height="385" border="0" /></a></span><span class="VideoPlayer"></span></span></span></p>
]]></description>
   </item>
   <item>
      <title>click on particle - loop over each?</title>
      <link>https://forum.processing.org/two/discussion/10549/click-on-particle-loop-over-each</link>
      <pubDate>Tue, 28 Apr 2015 01:16:30 +0000</pubDate>
      <dc:creator>argdev173</dc:creator>
      <guid isPermaLink="false">10549@/two/discussions</guid>
      <description><![CDATA[<p>Hi! I've a canvas with 400 aprox. elements (objects), each has a boolean state and i want to change that state by clicking on that object, i can achieve it by doing a dist from object x and y to mouse position. But looping over all the objects each time i click is a good choice? i think thats a perfomance flaw, i didnt try yet, but maybe in the future i want 1000 particles. The elements dont move, sorry for the english.</p>

<p>Thanks</p>
]]></description>
   </item>
   <item>
      <title>How to use particles</title>
      <link>https://forum.processing.org/two/discussion/10300/how-to-use-particles</link>
      <pubDate>Mon, 13 Apr 2015 23:31:18 +0000</pubDate>
      <dc:creator>RifleGirl</dc:creator>
      <guid isPermaLink="false">10300@/two/discussions</guid>
      <description><![CDATA[<p>So for a visualization of data I want a specific number of particles to move in a constrained area and then when the space bar is pressed move to another specific area and have the particles move in a different constrained space.</p>

<p>How would you do this and also change the number of particles in these constrained areas (go from 60 to 50).</p>
]]></description>
   </item>
   <item>
      <title>How to avoid particle teletransportation when deleting elements from a particles ArrayList</title>
      <link>https://forum.processing.org/two/discussion/9585/how-to-avoid-particle-teletransportation-when-deleting-elements-from-a-particles-arraylist</link>
      <pubDate>Thu, 26 Feb 2015 02:24:31 +0000</pubDate>
      <dc:creator>cifre</dc:creator>
      <guid isPermaLink="false">9585@/two/discussions</guid>
      <description><![CDATA[<pre><code>import peasy.*;
import processing.opengl.*;
import java.util.Iterator;

PeasyCam cam;

vectorField vectorfield;

ArrayList particles;
ArrayList&lt;ArrayList&gt; arrays = new ArrayList&lt;ArrayList&gt;();

void setup()
{
  size(800, 600, OPENGL);
  smooth();

  cam = new PeasyCam(this, 600/2, 600/2, 600/2, 700);

  vectorfield = new vectorField();
  particles = new ArrayList();

  for (int i = 0; i &lt; 5; i++) 
  {
    particles.add(new Particle(new PVector(random(0, 600), random(0, 600), random(0, 600)), random(2, 5), random(0.1f, 0.5f)));
    ArrayList&lt;PVector&gt; lines = new ArrayList&lt;PVector&gt;();
    arrays.add(lines);
  }
}

void draw()
{
  background(255);
  vectorfield.display();

  for (int i = 0; i &lt; particles.size (); i++) 
  {
    Particle p = (Particle) particles.get(i);

    ArrayList lines = (ArrayList) arrays.get(i);
    lines.add(new PVector(p.loc.x, p.loc.y, p.loc.z));

    p.follow(vectorfield);
    p.run();
  }

  for (int i = 0; i &lt; arrays.size (); i++)
  {
    ArrayList lines = (ArrayList) arrays.get(i);


    if (lines.size() &gt; 0)
    {
      for (int j=1; j &lt; lines.size (); j++) 
      {
        PVector a = (PVector) lines.get(j-1);
        PVector b = (PVector) lines.get(j);

        stroke(255, 0, 0);
        strokeWeight(1);
        line(a.x, a.y, a.z, b.x, b.y, b.z);
      }
    }
  }

  Iterator&lt;Particle&gt; it = particles.iterator();
  while (it.hasNext ()) 
  {
    Particle p = it.next();
    if (p.isDead()) 
    {
      it.remove();
    }
  }
}


class Particle 
{
  PVector loc;
  PVector vel;
  PVector acc;
  float r;
  float maxforce;    // Maximum steering force
  float maxspeed;    // Maximum speed

  Particle(PVector l, float ms, float mf) 
  {
    loc = l.get();
    r = 3.0f;
    maxspeed = ms;
    maxforce = mf;
    acc = new PVector(0, 0, 0);
    vel = new PVector(0, 0, 0);
  }

  public void run() 
  {
    render();
    update();
  }

  void follow(vectorField f) 
  {

    // Look ahead
    PVector ahead = vel.get();
    ahead.normalize(); 
    PVector lookup = PVector.add(loc, ahead);

    // What is the vector at that spot in the vector field?
    PVector desired = f.lookup(lookup);
    // Scale it up by maxspeed
    desired.mult(maxspeed);
    // Steering is desired minus velocity
    PVector steer = PVector.sub(desired, vel);
    steer.limit(maxforce);  // Limit to maximum steering force
    acc.add(steer);
  }

  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() 
  {
    stroke(0);
    strokeWeight(1);

    stroke(255, 0, 0);
    strokeWeight(5);
    pushMatrix();
    point(loc.x, loc.y, loc.z);
    popMatrix();
  }

  boolean isDead() 
  {
    if (loc.x &lt; -r) return true;
    if (loc.y &lt; -r) return true;
    if (loc.z &lt; -r) return true;
    if (loc.x &gt; 600+r) return true;
    if (loc.y &gt; 600+r) return true;
    if (loc.z &gt; 600+r) return true;
    else return false;
  }
}


class vectorField
{
  PVector[][][] field;
  int cols, rows, surf;

  int resolution;

  vectorField()
  {
    resolution = 50;

    cols = 600/resolution;
    rows = 600/resolution;
    surf = 600/resolution;

    field = new PVector[cols][rows][surf];
    init();
  }
  void init()
  {
    for (int i = 0; i &lt; cols; i++)
    {
      for (int j = 0; j &lt; rows; j++)
      {
        for (int k = 0; k &lt; surf; k++)
        {
         field[i][j][k] = new PVector(random(-100, 100), random(-100, 100), random(-100, 100));
        }
      }
    }
  }

  void display()
  {
    for (int i = 0; i &lt; cols; i++)
    {
      for (int j = 0; j &lt; rows; j++)
      {
        for (int k = 0; k &lt; surf; k++)
        {
          drawVector(field[i][j][k], i*resolution, j*resolution, k*resolution);
        }
      }
    }
  }

  void drawVector (PVector v, float x, float y, float z)
  {
    pushMatrix();
    translate(x, y, z);
    stroke(0,10);
    strokeWeight(1);
    line(0, 0, 0, v.x, v.y, v.z);
    popMatrix();
  }

  PVector lookup(PVector lookup) 
  {
    int i = (int) constrain(lookup.x/resolution, 0, cols-1);
    int j = (int) constrain(lookup.y/resolution, 0, rows-1);
    int k = (int) constrain(lookup.z/resolution, 0, surf-1);
    return field[i][j][k].get();
  }
}
</code></pre>

<p>Hello world! This is my first post in processing forum and I hope it won't be the last :)
My problem is that I have an ArrayList of particles and an ArrayList of each particles position, which I use to draw a line along the trajectory of the particles. When the particles leave the VectorField I kill them, and here comes the headache... I have particle_0, particle_1, particle_2, and particle_3, when I kill particle_2 particle_3 becomes particle_2, the last know position of particle_2 was before leaving the VectorField and beeing removed, but the new position of the new particle_2 is a completely different one so it just draws a straight line between the last know position and the new one... I can't get to figure this out, I hope someone out there has a solution for this! :)
Thanks in advanced</p>
]]></description>
   </item>
   <item>
      <title>PDF Export - Generative Typography - particles</title>
      <link>https://forum.processing.org/two/discussion/6708/pdf-export-generative-typography-particles</link>
      <pubDate>Sun, 10 Aug 2014 20:50:00 +0000</pubDate>
      <dc:creator>dachsdennis</dc:creator>
      <guid isPermaLink="false">6708@/two/discussions</guid>
      <description><![CDATA[<p>Hey everybody, i am totally new to processing and i was playing around with this generative Typography Tutorial. My Problem is that the pdf export that i tried to add to it won't work. Well, it just shows the regular Text in de PDF File but i want to have the particles. I guess that i am overlocking the class of particles somehow. Can anybody please help me out?</p>

<p>This is the Code which consists of two tabs.</p>

<p>FIRST TAB</p>

<p>import processing.pdf.*;</p>

<pre><code>boolean dosave=false;
int maxParticles = 1000; 
ArrayList &lt;Particle&gt; particles = new ArrayList &lt;Particle&gt; (); 
color BACKGROUND_COLOR = color(255);
color PGRAPHICS_COLOR = color(0);
float globalRotation;
PGraphics pg;

void setup() {
  size(1280, 700, P2D);
  smooth(16);
  pg = createGraphics(width, height, JAVA2D);
  pg.beginDraw();
  pg.textSize(200);
  pg.textAlign(CENTER, CENTER);
  pg.fill(PGRAPHICS_COLOR);
  pg.text("Test", pg.width/2, pg.height/2); 
  pg.endDraw();
  background(BACKGROUND_COLOR);
}

void draw() {

  if(dosave) {

   PGraphicsPDF pdf = (PGraphicsPDF)beginRaw(PDF, "pdf_complex_out.pdf"); 


    pdf.beginDraw();
    pdf.textSize(200);
    pdf.textAlign(CENTER, CENTER);
    pdf.fill(PGRAPHICS_COLOR);

    pdf.endDraw();
  }

  addRemoveParticles();
  // update and display each particle in the list
  for (Particle p : particles) {
    p.update();
    p.display();
  }

 if(dosave) {
    endRaw();
    }

}



void mousePressed() {
  particles.clear(); // remove all particles
  globalRotation = random(TWO_PI); // randomly set the global rotation/direction of the Particles
  }

void keyPressed() {
  if (key == 'd') {
    dosave=false;
  }
}

void addRemoveParticles() {
  // remove particles with no life left
  for (int i=particles.size()-1; i&gt;=0; i--) {
    Particle p = particles.get(i);
    if (p.life &lt;= 0) {
      particles.remove(i);
    }
  }
  // add particles until the maximum
  while (particles.size () &lt; maxParticles) {
    particles.add(new Particle());
  }

}
</code></pre>

<p>SECOND TAB</p>

<pre><code>class Particle {
  PVector loc;
  float life, lifeRate;

  Particle() {
    getPosition();
    life = random(0.9, 1.25);
    lifeRate = random(0.07, 0.08);
  }

  void update() {
    float angle = noise(loc.x * 0.01, loc.y * 0.01) * TWO_PI;
    PVector vel = PVector.fromAngle(angle + globalRotation);
    loc.add(vel);
    life -= lifeRate;
  }

  void display() {
    boolean special = random(1) &lt; 0.001;
    strokeWeight(special ? random(0.75, 3) : 0.75);
    stroke(0, special ? random(175, 255) : 65);
    point(loc.x, loc.y);
  }

  // get a random position inside the text
  void getPosition() {
    while (loc == null || !isInText (loc)) loc = new PVector(random(width), random(height));
  }

  // return if point is inside the text
  boolean isInText(PVector v) {
    return pg.get(int(v.x), int(v.y)) == PGRAPHICS_COLOR;
  }
}
</code></pre>
]]></description>
   </item>
   </channel>
</rss>