<?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 #performance - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/feed.rss?Tag=%23performance</link>
      <pubDate>Sun, 08 Aug 2021 17:50:54 +0000</pubDate>
         <description>Tagged with #performance - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/tagged%23performance/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>Video Delay : Ed Tannenbaum, Recollections</title>
      <link>https://forum.processing.org/two/discussion/28108/video-delay-ed-tannenbaum-recollections</link>
      <pubDate>Thu, 30 Aug 2018 22:14:13 +0000</pubDate>
      <dc:creator>Adrien</dc:creator>
      <guid isPermaLink="false">28108@/two/discussions</guid>
      <description><![CDATA[<p>Hi,</p>

<p>I try to create something like this :<a rel="nofollow" href="https://www.youtube.com/watch?v=YBKkVpRxUfs"> https://www.youtube.com/watch?v=YBKkVpRxUfs</a>, using a kinect.
At the moment I made some test with something like this :</p>

<pre><code>class User {
  PGraphics pgBodyBg; 
  PImage bodyImg; 
  float colorIndexCounter; 
  int id; 
  ArrayList&lt;DelayImg&gt; bodyImageList = new ArrayList&lt;DelayImg&gt;();
  PGraphics pgTotal; 
  DelayImg[] buffer;

  User(int i) {
    colorIndexCounter=random(10); 
    pgTotal=createGraphics(512, 424);  
    pgTotal.beginDraw(); 
    pgTotal.background(0, 0); 
    pgTotal.endDraw(); 
    buffer=new DelayImg[50];
  }


  void delayEffect() {
    fillBuffer(); 
    changeColor(); 
    display();
  }

  void fillBuffer() {
    PImage bi= bodyImg.copy(); 
    DelayImg di=new DelayImg(bi); 
    for (int i = buffer.length-1; i &gt; 0; i--) {
      buffer[i] = buffer[i-1];
    }
    buffer[0]=di;
  }



  void changeColor() {
    pgTotal.beginDraw(); 
    pgTotal.clear(); 
    pgTotal.pushStyle(); 
    for (int j=buffer.length-1; j&gt;=0; j--) { 
      if (buffer[j]!=null) buffer[j].changeColor(pgTotal);
    }
    pgTotal.popStyle();
    pgTotal.endDraw();
  }

  void display() {
    image(pgTotal, 0, 0);
  }
}



class DelayImg {
  PImage img; 
  float alf=255; 
  PShape shape; 
  PGraphics pgBg; 
  int partSize=200; 
  DelayImg(PImage _img) {
    img=_img; 
    img.filter(THRESHOLD); 
    pgBg=createGraphics(512, 424);
  }

  void display(PGraphics pg) {
    pg.tint(255, alf); 
    pg.image(img, 0, 0); 
    if (alf&gt;0)alf-=0.5;
    else alf=0;
  }

  void changeColor(PGraphics pg) {
    pgBg.beginDraw(); 
    pgBg.background(random(255), random(255), random(255));  
     pgBg.mask(img);
    pgBg.endDraw();
    pg.image(pgBg, 0, 0);
  }
}
</code></pre>

<p>bodyImg is update each frame, coming from kinect.</p>

<p>I want to be able to change the color everytime, that why pgTotal is clear every frame and display fresh new images, but the way I do it is very slow (10 fps).
Do you have any suggestion, different kind of algorithm to improve frameRate? I try to use some vertex and textures aswell, but no real improvement...</p>

<p>Thanks for your help!</p>

<p>A.</p>
]]></description>
   </item>
   <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>2d Metaball sketch running super slow in Python mode</title>
      <link>https://forum.processing.org/two/discussion/27651/2d-metaball-sketch-running-super-slow-in-python-mode</link>
      <pubDate>Mon, 02 Apr 2018 20:27:28 +0000</pubDate>
      <dc:creator>solub</dc:creator>
      <guid isPermaLink="false">27651@/two/discussions</guid>
      <description><![CDATA[<p>Hi guys,</p>

<p>I made several Python versions of 2d metaball sketches I found here on the forum or on the CodingTrain Github.</p>

<p>Problem: It runs super slow (&lt;1fps !) while all Java versions run very smoothly (60fps).</p>

<p>Questions:</p>

<ul>
<li><p>Why such a difference in the framerates ?</p></li>
<li><p>Is is possible to improve the Python code or am i for ever doomed for having chosen Python mode over Java mode ?</p></li>
</ul>

<p><strong>original JAVA code</strong></p>

<p>main tab:</p>

<pre><code>Blob[] blobs = new Blob[10];

void setup() {
  size(640, 360);
  colorMode(HSB);
  for (int i = 0; i &lt; blobs.length; i++) {
    blobs[i] = new Blob(random(width), random(height));
  }
}

void draw() {
  background(51);


  println(frameRate);

  loadPixels();
  for (int x = 0; x &lt; width; x++) {
    for (int y = 0; y &lt; height; y++) {
      int index = x + y * width;
      float sum = 0;
      for (Blob b : blobs) {
        float d = dist(x, y, b.pos.x, b.pos.y);
        sum += 10 * b.r / d;
      }
      pixels[index] = color(sum, 255, 255);
    }
  }

  updatePixels();

  for (Blob b : blobs) {
    b.update();
    //b.show();
  }
}
</code></pre>

<p>blob class</p>

<pre><code>class Blob {
  PVector pos;
  float r;
  PVector vel;

  Blob(float x, float y) {
    pos = new PVector(x, y);
    vel = PVector.random2D();
    vel.mult(random(2, 5));
    r = random(120, 400);
  }

  void update() {
    pos.add(vel); 
    if (pos.x &gt; width || pos.x &lt; 0) {
      vel.x *= -1;
    }
    if (pos.y &gt; height || pos.y &lt; 0) {
      vel.y *= -1;
    }
  }

  void show() {
    noFill();
    stroke(0);
    strokeWeight(4);
    ellipse(pos.x, pos.y, r*2, r*2);
  }
}
</code></pre>

<p><strong>PYTHON code</strong></p>

<pre><code>liste = []

def setup():
    size(640, 360, FX2D)
    colorMode(HSB)
    [liste.append(Blob(random(width), random(height))) for e in range(10)]

def draw():
    loadPixels()
    for x in range(width):
        for y in range(height):
            index = x + y * width
            sum = 0
            for e in liste:
                d = dist(x, y, e.pos.x, e.pos.y)
                try:
                    sum += 10 * e.r / d
                except ZeroDivisionError:
                    return 1
            pixels[index] = color(sum, 255, 255)
    updatePixels()

    for e in liste:
        e.update()

class Blob(object):
    def __init__(self, x, y):
        self.pos = PVector(x, y)
        self.velocity = PVector.random2D()
        self.velocity.mult(random(2, 5))
        self.r = random(120, 400)

    def update(self):
        self.pos.add(self.velocity)

        if self.pos.x &gt; width or self.pos.x &lt; 0:
            self.velocity.x *= -1
        if self.pos.y &gt; height or self.pos.y &lt; 0:
            self.velocity.y *= -1
</code></pre>
]]></description>
   </item>
   <item>
      <title>Camera / video image slow</title>
      <link>https://forum.processing.org/two/discussion/14403/camera-video-image-slow</link>
      <pubDate>Mon, 11 Jan 2016 23:06:07 +0000</pubDate>
      <dc:creator>mcfetrmatt</dc:creator>
      <guid isPermaLink="false">14403@/two/discussions</guid>
      <description><![CDATA[<p>Hi there, I am looking into accessing the camera built into my laptop and have that feed back into Processing. I have downloaded the Video library and copied the code from the <a rel="nofollow" href="https://processing.org/reference/libraries/video/Capture.html">Capture Class</a> and when I run it I get 90 cameras listed and the processing window (the camera video feed) runs really slow, almost one frame a second. The image also has a green tint and I can only access the front camera. I have a i7 model of the new Surface Pro 4.</p>

<p>Any feedback appreciated,</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/423/TFPMCCLEQ7M4.JPG" alt="ScreenGrab" title="ScreenGrab" /></p>
]]></description>
   </item>
   <item>
      <title>How to get more FPS ?</title>
      <link>https://forum.processing.org/two/discussion/26732/how-to-get-more-fps</link>
      <pubDate>Fri, 09 Mar 2018 13:17:05 +0000</pubDate>
      <dc:creator>GeorgeJava</dc:creator>
      <guid isPermaLink="false">26732@/two/discussions</guid>
      <description><![CDATA[<p>How to GET more FPS ???
I dont know how to make program better :/ can you help me ?</p>

<pre><code>PImage light, screen, bg, lightImage, mask;
PGraphics pg, lightMask;
int up, down, right, left;
float x, y, speed = 1;
color randomColor;
float camX=0, camY=0;
float  Ox1, Ox2, Oy1, Oy2;
int globalMX, globalMY;
void setup() {
  size(480, 270, P3D);
  frameRate(60);
  background(0);
  bg = loadImage( "https://" + "ichef.bbci.co.uk/images/ic/480xn/p01lckx1.jpg"  );
  lightImage = loadImage( "https://" + "i.stack.imgur.com/NaD6F.png" );
  bg.resize(width, height);
  light = bg.copy();
  lightMask = createGraphics(width, height);
  randomColor = color(random(256), random(256), random(256));
  bullets = new ArrayList&lt;Bullet&gt;();
  reloadLights();
  x = width/2;
  y = height/2;
}
void draw() {  
  background(0);
  imageMode(CORNER);
  image(bg, 0, 0);
  screen = get(0, 0, width, height);
  fill(0,125);
  noStroke();
  rectMode(CENTER);
  rect(x, y, width, height);
  reloadLights();
  screen.mask(lightMask);

  image(screen, x-width/2,y-height/2);
  fill(255, 255, 0);
  textAlign(LEFT, TOP);
  textSize(39);
  text(int(frameRate) + " FPS", 5, 5);
  ellipse(globalMX,globalMY,20,20);
  x += (right - left) * speed;
  y += (down - up) * speed;
  Ox1=camX-width+x;
  Ox2=camX+x;
  Oy1=camY-y;
  Oy2=camY+height-y;
  ortho(Ox1, Ox2, Oy1, Oy2);
}
void reloadLights() {
  pg = lightMask;
  pg.beginDraw();
  pg.background(0);
  pg.blendMode(ADD);
  pg.translate(-x+width/2,-y+height/2);
  for (int i = bullets.size()-1; i &gt;= 0; i--) {
    Bullet bullet = bullets.get(i);
    drawLight(bullet.x, bullet.y, bullet.r);
    println(bullet.x + "  " + bullet.y);
  }
  pg.endDraw();
}
void drawLight(int xL, int yL, int rL) {
 // pushMatrix();
  pg.imageMode(CENTER);
  pg.image(lightImage, xL,yL, rL, rL);
  //popMatrix();
}

void mousePressed() {
  bullets.add( new Bullet(globalMX, globalMY, 50));
  reloadLights();
}
ArrayList&lt;Bullet&gt; bullets;
class Bullet {
  int x, y, r;
  public Bullet(int x_, int y_, int r_) {
    x = x_;
    y = y_;
    r = r_;
  }
}
void keyPressed() {
  if (key == 'a' || key == 'A') {
    left = 1;
  }
  if (key == 'd' || key == 'D') {
    right = 1;
  }
  if (key == 'w' || key == 'W') {
    up = 1;
  }
  if (key == 's' || key == 'S') {
    down = 1;
  }
}
void keyReleased() {
  if (key == 'a' || key == 'A') {
    left = 0;
  }
  if (key == 'd' || key == 'D') {
    right = 0;
  }
  if (key == 'w' || key=='W') {
    up = 0;
  }
  if (key == 's' || key == 'S') {
    down = 0;
  }
}
void mouseMoved() {
  globalMX=mouseX+int(x)-(width/2);
  globalMY=mouseY+int(y)-(height/2);
}
</code></pre>

<p><img src="https://forum.processing.org/two/uploads/imageupload/983/IDX6EFN48V0B.png" alt="screenshot" title="screenshot" /></p>
]]></description>
   </item>
   <item>
      <title>Basic questions about reducing CPU usage when drawing pictures</title>
      <link>https://forum.processing.org/two/discussion/26304/basic-questions-about-reducing-cpu-usage-when-drawing-pictures</link>
      <pubDate>Sat, 10 Feb 2018 23:20:27 +0000</pubDate>
      <dc:creator>delsey</dc:creator>
      <guid isPermaLink="false">26304@/two/discussions</guid>
      <description><![CDATA[<p>Hello, I wrote a program for choosing colors for an LED-Strip. It works quite good, but it seems to be using quite alot of CPU. (30% CPU, i5 7600k <a href="/two/profile/4">@4</a>.6ghz)</p>

<p>I know that this usage is due to my program constantly loading pictures:</p>

<p>Setup method:</p>

<pre><code>      fade = loadImage("fade.jpg");
      red = loadImage("red.jpg");
      green = loadImage("green.jpg");
      blue = loadImage("blue.jpg");
      plus = loadImage("plus.jpg");
      minus = loadImage("minus.jpg");
</code></pre>

<p>Draw-Method:</p>

<pre><code>      image(fade, 1, 241, boxsize-1, boxsize-1);
      image(red, 82, 241, boxsize-2, boxsize-1);
      image(green, 161, 241, boxsize-1, boxsize-1);
      image(blue, 241, 241, boxsize-1, boxsize-1);
      image(plus, 401, 241, boxsize-1, boxsize-1);
      image(minus, 481, 241, boxsize-1, boxsize-1);
</code></pre>

<p>Can someone help me to adapt it?
How do I load the pictures without consantly having to draw them? It would be enough to draw them once when the program starts.</p>
]]></description>
   </item>
   <item>
      <title>Basic cpu question</title>
      <link>https://forum.processing.org/two/discussion/26187/basic-cpu-question</link>
      <pubDate>Wed, 31 Jan 2018 07:08:52 +0000</pubDate>
      <dc:creator>matthieu</dc:creator>
      <guid isPermaLink="false">26187@/two/discussions</guid>
      <description><![CDATA[<p>What is the most cpu difficult :
<code>float x = 9/2.0;</code>
or
<code>float x = 9*0.5;</code></p>
]]></description>
   </item>
   <item>
      <title>100% CPU utilisation when playing multiple videos using the video library</title>
      <link>https://forum.processing.org/two/discussion/14329/100-cpu-utilisation-when-playing-multiple-videos-using-the-video-library</link>
      <pubDate>Fri, 08 Jan 2016 01:14:24 +0000</pubDate>
      <dc:creator>alzxul</dc:creator>
      <guid isPermaLink="false">14329@/two/discussions</guid>
      <description><![CDATA[<p>Hi,</p>

<p>I'm trying to play some movies and sound in a processing sketch; there are 10 movies and 1 sound file - all the movies are fairly small [&lt;=5MB]; I create them in setup and call .play() on them, and then in draw() I use image() on them, and I also use movieEvent() function to call .read() on them; whenever I run this the videos lag and my CPU spikes to 100%</p>

<p>Surely playing 10 concurrent movies isn't that onerous?</p>

<p>Does anyone have any ideas for how to improve the performance or can tell me if I'm doing something wrong or missing something?</p>

<p>Any help would be much appreciated, thanks</p>

<p>Thanks</p>
]]></description>
   </item>
   <item>
      <title>How do I reduce lag for many operations?</title>
      <link>https://forum.processing.org/two/discussion/25592/how-do-i-reduce-lag-for-many-operations</link>
      <pubDate>Sat, 16 Dec 2017 03:25:12 +0000</pubDate>
      <dc:creator>kellen</dc:creator>
      <guid isPermaLink="false">25592@/two/discussions</guid>
      <description><![CDATA[<p>Hello, I am making a program with many particles that refer to each other and it is getting quite laggy. It is for every particle trying to calculate the distance to every other particle for gravity. So the more particles I add the lag increases exponentially. Any tips on how to reduce lag?</p>
]]></description>
   </item>
   <item>
      <title>How to improve sketch performance</title>
      <link>https://forum.processing.org/two/discussion/25617/how-to-improve-sketch-performance</link>
      <pubDate>Mon, 18 Dec 2017 10:11:04 +0000</pubDate>
      <dc:creator>dehyde</dc:creator>
      <guid isPermaLink="false">25617@/two/discussions</guid>
      <description><![CDATA[<p>I have a sketch that's using a few long arrays and image processing.</p>

<p>Is there a way to make openGL render the sketch, or any other simple "trick" to improve performance?</p>

<p><img src="" alt="" /><img src="https://forum.processing.org/two/uploads/imageupload/342/SAGP6AEML8HV.png" alt="Screenshot_13" title="Screenshot_13" /></p>
]]></description>
   </item>
   <item>
      <title>Image processing on Android - poor permormance.</title>
      <link>https://forum.processing.org/two/discussion/25510/image-processing-on-android-poor-permormance</link>
      <pubDate>Mon, 11 Dec 2017 09:05:05 +0000</pubDate>
      <dc:creator>Rakerson</dc:creator>
      <guid isPermaLink="false">25510@/two/discussions</guid>
      <description><![CDATA[<p>Hi there !</p>

<p>I have made simple code which is performing a blue filter. It adds some value to R value and substract something from GB values in two for() loops. It works great on PC but on mobile the performance is really slow. You can see the stuttering on the screen below. Ofc. changing the size of capture image helps but it is not a solution I am looking. How can you improve the performance, what's the best way to do image proccesing on mobile ?</p>

<p>Code:</p>

<pre><code>import ketai.camera.*;

PImage prev;
float threshold = 60;

color currentColor;
color lastColor;

float r1 = 0;
float g1 = 0;
float b1 = 0;

KetaiCamera cam;
void setup() {
  orientation(LANDSCAPE);
  imageMode(CENTER);
  cam = new KetaiCamera(this, 320, 240, 24);
  prev = createImage(320, 240, RGB);
  cam.start();
}

void onCameraPreviewEvent(){
  cam.read();
}

void draw() {
    image(prev, width/2, height/2);
    cam.loadPixels();
    prev.loadPixels();
    loadPixels();

    for (int y = 0; y &lt; cam.height; y++ ) 
  {
    for (int x = 0; x &lt; cam.width; x++ ) 
    {
      int loc = x + y * cam.width; 
      currentColor = cam.pixels[loc]; //current values, taken from cam
      lastColor = prev.pixels[loc];

      float r1 = red(currentColor);
      float g1 = green(currentColor);
      float b1 = blue(currentColor);

      //pixels[loc] = color(r1+30,g1-35,b1-35);
      //float r2 = red(lastColor);
      //float g2 = green(lastColor);
      //float b2 = blue(lastColor);

       prev.pixels[loc] = color(r1-40,g1-40,b1+40);
      //prev.pixels[loc] = lerpColor(lastColor, currentColor, 0.9);

    }
  }
    prev.updatePixels();
    //image(prev, width/2, height/2);
    updatePixels();
  }
</code></pre>

<p><img src="" alt="" /><img src="https://forum.processing.org/two/uploads/imageupload/667/4V1HGE0NCTLR.JPG" alt="filtr" title="filtr" /></p>
]]></description>
   </item>
   <item>
      <title>PGraphics and Android : very slow, even with simple sketch</title>
      <link>https://forum.processing.org/two/discussion/25550/pgraphics-and-android-very-slow-even-with-simple-sketch</link>
      <pubDate>Wed, 13 Dec 2017 08:33:01 +0000</pubDate>
      <dc:creator>Adrien</dc:creator>
      <guid isPermaLink="false">25550@/two/discussions</guid>
      <description><![CDATA[<p>Hi,</p>

<p>When I'm running this very simple sketch on a Samsung tab A (2016), frameRate is around 8fps, even with a very simple sketch as this one :</p>

<pre><code>PGraphics pg; 
void setup() {
  size(displayWidth, displayHeight, P2D); 
  pg=createGraphics(width, height);
}

void draw() {
  println("fps : ", frameRate); 
  pg.beginDraw(); 
  pg.stroke(0); 
  pg.ellipse(width/2, height/2, 300, 300); 
  pg.endDraw(); 
  image(pg, 0, 0, width, height);
}
</code></pre>

<p>I tried different render (Default one, P2D, P3D, JAVA2D, OPENGL...), but still.</p>

<p>Do you have any idea where it come from (I have 2 times "OpenGL error 1280 at bot beginDraw(): invalid enum", aswell..) or how to manage things differently? I really need to draw on différent layer, because one has to be refhresh every frame and the other no...</p>

<p>Thanks for your help,</p>

<p>A.</p>
]]></description>
   </item>
   <item>
      <title>blend() and filter() significantly slow down 1080p Video FPS to 7; Any solutions?</title>
      <link>https://forum.processing.org/two/discussion/23072/blend-and-filter-significantly-slow-down-1080p-video-fps-to-7-any-solutions</link>
      <pubDate>Thu, 15 Jun 2017 06:03:24 +0000</pubDate>
      <dc:creator>SpPank</dc:creator>
      <guid isPermaLink="false">23072@/two/discussions</guid>
      <description><![CDATA[<p>//hey, I'm probably not doing this right
//is it cause I'm using the context of PGraphics and PImage mixed up??
//IM GETTING 7 FPS W/ I7 7700K AND 1070 sli
//CPU AND GPU ARE NOT BEING PUSHED
///NEED HELP!!!!</p>

<p>import java.util.ArrayList;
import KinectPV2.KJoint;
import KinectPV2.*;</p>

<p>KinectPV2 kinect;</p>

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

<p>Movie coral;
PGraphics feedback;</p>

<p>void setup() {
  fullScreen(P2D, 2);
  feedback = createGraphics(1920,1080,P2D);
  background(0);
  //blendMode(ADD);</p>

<p>//Video stuff
  coral = new Movie(this, "CoralReef.mp4");
  coral.loop();</p>

<p>//Kinect stuff
  kinect = new KinectPV2(this);
  kinect.enableBodyTrackImg(true);
  kinect.enableSkeletonDepthMap(true);
  kinect.init();
}</p>

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

<p>PImage kinectSil;</p>

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

<p>kinectSil = kinect.getBodyTrackImage();</p>

<p>kinectSil.filter(INVERT);
  kinectSil.loadPixels();
  for (int i = 0; i &lt; kinectSil.pixels.length; i++) {
    if (kinectSil.pixels[i] == color(0)) {
      kinectSil.pixels[i] = color(0, 0);
    } else {
      kinectSil.pixels[i] = color(255,255);
    }
  }
  kinectSil.updatePixels();</p>

<p>feedback.beginDraw();
  feedback.image(kinectSil,0,0,1920,1080);
  feedback.blend(coral, 0, 0, coral.width, coral.height, 0, 0, coral.width, coral.height, MULTIPLY);
  feedback.filter(THRESHOLD);
  feedback.endDraw();
  tint(255,10);
  image(coral,0,0,width,height);
  blend(feedback,0,0,feedback.width,feedback.height, 0, 0, width, height, LIGHTEST);
  fill(45);
  rect(0,0,150,54);
  textSize(30);
  fill(255);
  text(frameRate, 20,40);
}</p>
]]></description>
   </item>
   <item>
      <title>Having fps problems each time I use sprites (images).</title>
      <link>https://forum.processing.org/two/discussion/24874/having-fps-problems-each-time-i-use-sprites-images</link>
      <pubDate>Sun, 05 Nov 2017 06:00:15 +0000</pubDate>
      <dc:creator>chuckopo</dc:creator>
      <guid isPermaLink="false">24874@/two/discussions</guid>
      <description><![CDATA[<p>For my game I started using simply figures for testing. Now that I had that working, I implemented sprites using images, but my fps starts going down quickly. I can not figure out how to fix this issue.</p>
]]></description>
   </item>
   <item>
      <title>How to avoid lag when using parallax effect in fullscreen ?</title>
      <link>https://forum.processing.org/two/discussion/24740/how-to-avoid-lag-when-using-parallax-effect-in-fullscreen</link>
      <pubDate>Wed, 25 Oct 2017 19:40:06 +0000</pubDate>
      <dc:creator>Néon</dc:creator>
      <guid isPermaLink="false">24740@/two/discussions</guid>
      <description><![CDATA[<p>Hi,</p>

<p>I'm making a 2D game with, hopefully, side-scrolling. Following a discussion with Chrisir, I'm posting my lag issue here with a MCVE. I run the following code and when I add the parallax function in fullscreen, I get intense lag. When I run it at 960x540, its fine. My code is far from perfect at this stage so if you see anything to improve, please let me know.</p>

<pre><code>//I wont use all of these for this MCVE, 
//but its usually what I import for Box2d and collisions.
import shiffman.box2d.*;
import org.jbox2d.common.*;
import org.jbox2d.dynamics.joints.*;
import org.jbox2d.collision.shapes.*;
import org.jbox2d.collision.shapes.Shape;
import org.jbox2d.common.*;
import org.jbox2d.dynamics.*;
import org.jbox2d.dynamics.contacts.*;

// A reference to our box2d world
Box2DProcessing box2d;

//Declaring my hero
Hero hero;

PImage img;
PVector vBG;

void setup() {
  //fullScreen();
  size(960, 540);

  // Initialize box2d physics and create the world
  box2d = new Box2DProcessing(this);
  box2d.createWorld();

  // We are setting a custom gravity
  box2d.setGravity(0, -0.0005);

  //Initializing hero
  hero = new Hero(88, 88, 20);

  img = loadImage("Starsinthesky.jpg");

  vBG = new PVector(0, 0);
}

void draw() {

  imageMode(CORNER);
  parallaxe(img, vBG, hero.velocity().x); 

  // Thru time
  box2d.step();

  //Show and move Hero
  hero.display();
  hero.mover();
  hero.boundary(); //This is what I call to limit the range of my here

}
</code></pre>

<p>Here is the parallax function :</p>

<pre><code>void parallaxe(PImage img, PVector pos, float vit) {
  pos.sub(vit, 0, 0); 

  if(pos.x &lt; width-img.width) {
    image(img, pos.x+img.width, pos.y);
  }

  if(pos.x &gt; 0) {
    image(img, pos.x-img.width, pos.y);
  }

  if(pos.x &lt; -img.width) {
    pos.x = width;
  }

  if (pos.x &gt; width) {
    pos.x = width-img.width;
  }

  image(img, pos.x, pos.y);
}
</code></pre>

<p>And here is my movable hero class :</p>

<pre><code>class Hero {
  Body body;
  float r;

  Hero(float x, float y, float r_) {
    r = r_;
    // This function puts the hero in the Box2d world
    makeBody(x, y, r);
    body.setUserData(this);
  }

  void display() {
    Vec2 pos = box2d.getBodyPixelCoord(body);
    pushMatrix();
    translate(pos.x, pos.y);
    fill(0, 44, 188);
    noStroke();
    ellipse(0, 0, r*2, r*2);
    popMatrix();
  }

  void mover() {
    Vec2 move = new Vec2(0, 0);
    Vec2 pos = body.getWorldCenter();

    if ((keyPressed == true) &amp;&amp; ((key == 'w') || (key == 'W'))) {
      move.y += 100;
    }
    if ((keyPressed == true) &amp;&amp; ((key == 's') || (key == 'S'))) {
      move.y -= 100;
    }
    if ((keyPressed == true) &amp;&amp; ((key == 'a') || (key == 'A'))) {
      move.x -= 100;
    }
    if ((keyPressed == true) &amp;&amp; ((key == 'd') || (key == 'D'))) {
      move.x += 100;
    }
    body.applyForce(move, pos);
  }

  Vec2 velocity() {
    return body.getLinearVelocity();
  }

  //Here is the method that would limit the movement of my hero if it worked.
  //Box2d coordinate system is in the middle of the screen.
  void boundary() {
    Vec2 pos = box2d.getBodyPixelCoord(body);
    if (pos.x &lt; r) {
    pos.x = r;
    }
    if (pos.x &gt; width-r) {
    pos.x = width-r;
    }
    if (pos.y &lt; r) {
    pos.y = r;
    }
    if (pos.y &gt; height-r) {
    pos.y = height-r;
    }
  }  

  // Here's our function that adds the particle to the Box2D world
  void makeBody(float x, float y, float r) {
    // Define a body
    BodyDef bd = new BodyDef();
    // Set its position
    bd.position = box2d.coordPixelsToWorld(x, y);
    bd.type = BodyType.DYNAMIC;
    body = box2d.createBody(bd);

    // Make the body's shape a circle
    CircleShape cs = new CircleShape();
    cs.m_radius = box2d.scalarPixelsToWorld(r);

    FixtureDef fd = new FixtureDef();
    fd.shape = cs;
    // Parameters that affect physics
    fd.density = 1;
    fd.friction = 0.01;
    fd.restitution = 0.3;

    // Attach fixture to body
    body.createFixture(fd);    
  }

}
</code></pre>

<p>I hope you won't mind that it uses Box2D, its part of the game I make. I'm not sure if this is a lag factor. At the moment, I have no guess as to what causes this. Any hint is welcomed.</p>
]]></description>
   </item>
   <item>
      <title>Multidimensional arrays and java?</title>
      <link>https://forum.processing.org/two/discussion/24613/multidimensional-arrays-and-java</link>
      <pubDate>Wed, 18 Oct 2017 00:27:03 +0000</pubDate>
      <dc:creator>shawnlau</dc:creator>
      <guid isPermaLink="false">24613@/two/discussions</guid>
      <description><![CDATA[<p>I'm working on a paint program that will be able to handle larger images ( 4800 x 6000) pixels.  In order to mix pixels properly, I've found I need to either use a floating point array or an array with the integer r,g,b, values of the pixels shifted 16. Using just integers, there is a little clipping each time that is lost and they start adding up into weird hue shifts.  Though tests, I've found no difference in performance between using the floating point array and the integer shifted array-at least on the java machine. So I use the float because its clearer.</p>

<p>But I have found a major difference in performance between using a multidimensional array and 3 one dimension arrays.</p>

<p>I had been allocating the array as such:</p>

<p><code>float floatArray = new float[4800 * 6000][3];</code></p>

<p>That little line of code took about 5-10 seconds to allocate on my Windows 7, i7 processor with 16gb ram.</p>

<p>But writing it as this takes only milliseconds to allocate:</p>

<pre><code>float floatArrayR = new float[4800 * 6000];
float floatArrayG = new float[4800 * 6000];
float floatArrayB = new float[4800 * 6000];
</code></pre>

<p>I remember reading many years ago that different os's handle multidimensional arrays differently and one should not assume how the members are ordered. I can't imagine how the java virtual machine handles multidimensional arrays to make them so much slower than one dimension arrays. Allocation time from 5-10 seconds to milliseconds? Whats going on there? The multidimensional array also slowed garbage collection so much it was performance issue. Not so with the one dimension array.</p>
]]></description>
   </item>
   <item>
      <title>KetaiCamera extremely slow when compiled from Android Studio</title>
      <link>https://forum.processing.org/two/discussion/24240/ketaicamera-extremely-slow-when-compiled-from-android-studio</link>
      <pubDate>Sun, 24 Sep 2017 16:10:28 +0000</pubDate>
      <dc:creator>surumadurum</dc:creator>
      <guid isPermaLink="false">24240@/two/discussions</guid>
      <description><![CDATA[<p>I face an odd behaviour when I compile my sketch from within Android Studio (what I have to to because I am using a JNI library dependency):</p>

<p>The same app (namely the CameraGettingStarted example sketch from Ketai library examples) has about 15FPS when I compile from the processing app and only about 3-4 FPS when I use Android Studio.</p>

<p>I just imported the temporary build folder into Android Studio, so basically everything (manifest, build.gradle etc.) is untouched.</p>

<p>Does anyone have an idea???</p>
]]></description>
   </item>
   <item>
      <title>p5.js code feedback/critique</title>
      <link>https://forum.processing.org/two/discussion/24211/p5-js-code-feedback-critique</link>
      <pubDate>Thu, 21 Sep 2017 22:30:59 +0000</pubDate>
      <dc:creator>xna</dc:creator>
      <guid isPermaLink="false">24211@/two/discussions</guid>
      <description><![CDATA[<p>I made this <a rel="nofollow" href="https://mxa.github.io/tinykeys/">keyboard</a> and <a rel="nofollow" href="https://github.com/mxa/tinykeys/blob/master/sketch.js">Source</a> and is not particulary fast, but kind of works. In order to avoid retriggering when you hold down a key,  I make an array for the triggered notes, make a copy of that array and then delete the original array and fill it again with the new keys. I then check if the newly triggered keys are also in the previously triggered array and if, so don't play them.</p>

<p>Is there a way to optimize the performance of this and make it work on desktops without touch?</p>

<p>Any hints greatly appreciated.</p>

<pre><code>var keyboard,       //image of the keyboard
    kbdcopy,        //resized image of the keyboard (visible)
    keycolormap,    //colormap of the keys (hidden)
    imageRatio,     //ratio of the image h/w    
    keyboardWidth,  
    //keyboardHeight,
    keysdown = new Array(),
    previouskeysdown = new Array(),
    scaleFactor = 1;    //scaling factor of the image

const FOLDER = 'keys/', EXT = '.wav',
      INDEX_START = 53, INDEX_END = 79,
      INDEX_TOTAL = 1 + INDEX_END - INDEX_START,
      sounds = Array(INDEX_TOTAL);

//sounds.playMode(restart); // for some reason this throws an error even though it's in the sound.p5,js reference

function preload() {
    for (let i = 0; i &lt; INDEX_TOTAL; ++i){
        sounds[i] = loadSound(FOLDER + (i + INDEX_START) + EXT);
    }
    keyboard=loadImage("keyboard.png", img =&gt; kbdcopy = img.get());
    keycolormap=loadImage("keycolormap.png");
}

function setup()   {
    var myCanvas = createCanvas(windowWidth, windowHeight);
    myCanvas.parent("keyboard");
    colorMode(RGB, 255);
    imageRatio = keyboard.height/keyboard.width;
    //print("imageRatio: "+imageRatio);
    windowResized();
  }

function draw() {
    background(255);
    image(kbdcopy,0,0);
    textSize(17);
    fill(150);
    text("TinyKeys v.0.13 Max Neupert, 2017",10,kbdcopy.height+25);
//    text("touches: "+touches.length,10,kbdcopy.height+45);
//    text("keysdown: ",10,kbdcopy.height+65);
//    for (var i=0;i&lt;keysdown.length;i++){
//        text(keysdown[i]+",",100+(i*26),kbdcopy.height+65);
//    }
//        text("previouskeysdown: ",10,kbdcopy.height+85);
//    for (var i=0;i&lt;previouskeysdown.length;i++){
//        text(previouskeysdown[i]+",",160+(i*26),kbdcopy.height+85);
//    }
    touching();
    playing();
    muting();
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight);
    if (windowWidth &lt; keyboard.width){
        kbdcopy = keyboard.get();
        kbdcopy.resize(windowWidth,0);
        keyboardWidth = windowWidth;
        //keyboardHeight = keyboardWidth*imageRatio;
        scaleFactor = keyboardWidth/keyboard.width;
        //print("new scaleFactor: "+scaleFactor);
        }
}

// INTERACTION AND SOUND PLAYING

function touchStarted(){}  //an empty function to stop the default behavior of panning screen

// TOUCH
function touching(){
    var note;
    //var midi;
    fill(255,100,50,100);
    noStroke();
    previouskeysdown = [];
    arrayCopy(keysdown,previouskeysdown); //copy old array
    keysdown = []; //delete old array
    for (let i = 0; i &lt; touches.length; i++) {
        ellipse(touches[i].x, touches[i].y, 85)
        note=keycolormap.get(touches[i].x/scaleFactor,touches[i].y/scaleFactor); //get the color in the hidden image
        note=((red(note))/5);
        //midi = note+52
        note = note-1;
        if (note&gt;-1){
            keysdown.push(note);
        }
    }
    if (touches.length==0){
         keysdown = [];
        }
}

function playing(){
    var note;
    for (let i = 0; i &lt;keysdown.length; i++){
            note=keysdown[i];
                if (previouskeysdown.includes(keysdown[i])){ //check if the key was previosly touched
                    // well, if so, don't trigger again then (empty if clause...)
                }
                else{
                    sounds[note].setVolume(0.5);
                    sounds[note].play(); // if it is a new touch, well then play.
                } 

    }
}
function muting(){
    var note;
    for (let i = 0; i &lt;previouskeysdown.length; i++){
            note=previouskeysdown[i];
                if (previouskeysdown.includes(keysdown[i])){ //check if the key was previosly touched
                    // well, if so, then keep it playing (empty if clause...)
                }
                else{
                    sounds[note].fade(0,0.1);
                    sounds[note].stop(0.1); // if it is not touched any more, then stop.
                } 

    }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>How long does textAlign take</title>
      <link>https://forum.processing.org/two/discussion/24063/how-long-does-textalign-take</link>
      <pubDate>Fri, 08 Sep 2017 13:43:53 +0000</pubDate>
      <dc:creator>schotsl</dc:creator>
      <guid isPermaLink="false">24063@/two/discussions</guid>
      <description><![CDATA[<p>Quick question, does the <code>textAlign</code> function take just as long manually calculating what the position should be with for instance <code>textDecent</code> or is the text Align function not as efficient?</p>
]]></description>
   </item>
   <item>
      <title>To anyone experiencing low frame rates when using image() many times</title>
      <link>https://forum.processing.org/two/discussion/23957/to-anyone-experiencing-low-frame-rates-when-using-image-many-times</link>
      <pubDate>Tue, 29 Aug 2017 01:43:45 +0000</pubDate>
      <dc:creator>MadScience2728</dc:creator>
      <guid isPermaLink="false">23957@/two/discussions</guid>
      <description><![CDATA[<p>Greetings,</p>

<p>I had a very big problem in an app I'm developing. So far I've only used it JAVA Mode, and my framerates where about 20-30 fps, so on a tablet the sketch would never work. I've googled to my best ability but couldn't find a solution.</p>

<p>The game is a word game, and has an 9*11 grid of letter tiles (plus the background). Each one of these is a pre-loaded PImage of 55x55px.
If I remove the image() function in the tiles display() method, the problem went away.</p>

<p>So my question was how in the world do I display that many images without problem? A game like Minecraft can display thousands of images, in higher pixel dimensions, in 3D, and at high framerates. Why couldn't I?</p>

<p>I reduced the code to the problem below (image file below too if you want to test). Right before I was about to post on this forum to get help, I tried taking the size to display parameters out of the image() call. And it worked. The on-the-fly display size of the image was taking up way too much CPU.</p>

<p>If you're having this same problem, hopefully your problem is the same, and you can fix it easily like I have. Modifications:</p>

<p>Add this in setup:
<code>tile.resize(round(full_tile), round(full_tile));</code></p>

<p>Change this in draw:
<code>image(tile, grid[x][y].x, grid[x][y].y);</code></p>

<p>And that is it! Hope this helps!</p>

<pre><code>PImage tile;

float full_tile;
float three_quarter_tile;
float half_tile;
float quarter_tile;
float eighth_tile;

PVector grid_tile_dims;
PVector[][] grid;
PVector grid_corner;



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

  tile = loadImage("tile.png");

  full_tile = height/12;
  three_quarter_tile = full_tile * 0.75;
  half_tile = full_tile * 0.5;
  quarter_tile = full_tile * 0.25;
  eighth_tile = full_tile * 0.125;

  grid_tile_dims = new PVector(11, 9);
  grid = new PVector[int(grid_tile_dims.x)][int(grid_tile_dims.y)]; 
  float grid_step = eighth_tile;
  grid_corner = new PVector(width - (half_tile + ((height - ((grid_tile_dims.y * full_tile) + ((grid_tile_dims.y - 1) * grid_step)))/2)), quarter_tile + ((height - ((grid_tile_dims.y * full_tile) + ((grid_tile_dims.y -1) * grid_step)))/2));


  for   (int y = 0; y &lt; int(grid_tile_dims.y); y++)
  {
    for (int x = 0; x &lt; int(grid_tile_dims.x); x++)
    {
      float sep = 0;
      if (x % 2 != 0.0) sep = half_tile;
      grid[x][y] = new PVector(grid_corner.x - ((full_tile + grid_step) * x), sep + grid_corner.y + ((full_tile + grid_step) * y));
    }
  }
}


void draw()
{
  background(255);

  for (int y = 0; y &lt; int(grid_tile_dims.y); y++)
  {
    for (int x = 0; x &lt; int(grid_tile_dims.x); x++)
    {
      if(!mousePressed) image(tile, grid[x][y].x, grid[x][y].y, full_tile, full_tile);
    }
  }

  fill(0);
  textAlign(LEFT, TOP);
  textSize(height/32);
  text(int(frameRate), 2, 2);
}
</code></pre>

<p><img src="" alt="" /></p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/560/MU31HCOGKGEK.png" alt="tile" title="tile" /></p>
]]></description>
   </item>
   <item>
      <title>Why is my game lagging so much? HELP!</title>
      <link>https://forum.processing.org/two/discussion/23917/why-is-my-game-lagging-so-much-help</link>
      <pubDate>Thu, 24 Aug 2017 17:30:29 +0000</pubDate>
      <dc:creator>HOSTL</dc:creator>
      <guid isPermaLink="false">23917@/two/discussions</guid>
      <description><![CDATA[<p>Hi! I have been working on an RTS game lately and it has been lagging A LOT. I only started development 3 days ago. (It can't be my PC, because it can play Overwatch) Anyways, here is my code (It is objective oriented so there will be lots of classes before the main code):</p>

<pre><code>class SelectionMenu {
  PImage buildingSprite;
  boolean placing;
  boolean bought;
  boolean setMouseCoordinateToXY;
  int buildingX;
  int buildingY;

  void display() {
    //Background
    stroke(155, 0, 0);
    strokeWeight(4);
    fill(0, 0, 0, 175);

    rect(0, 500, 1280, 220, 20);

    //Tower Selection
  }

  void update() {
    if (mousePressed == true &amp;&amp; bought == false &amp;&amp; mouseY &lt; 500) {
      placing = true;
    }
    if (placing == true) {
      image(loadImage("bank.png"), mouseX, mouseY);
      if (mousePressed == true) {
        if (setMouseCoordinateToXY == false) {
          buildingX = mouseX;
          buildingY = mouseY;
        }
        gameBuildings.add(new Building(1, mouseX, mouseY));
      }
    }
  }
}



class Troop extends GameObject {
  PImage troopSprite;

  Troop(int type_) {
    type_ = type;
  }
}



class Building extends GameObject {
  PImage buildingSprite;

  Building(int type_, int x_, int y_) {
    type = type_;
    x = x_;
    y = y_;
  }

  void display() {
    image(buildingSprite, x + cameraX, y + cameraY);
  }

  void update() {
    //Selects buildingSprite
    if (type == 1) {
      buildingSprite = loadImage("bank.png");
    }

    //BANK
    if (type == 1) {
      money += .25;
    }
  }
}



class MusicHandler extends GameObject {
  boolean bgm1playing;
  boolean bgm2playing;
  boolean bgm3playing;
  int timer;

  void update() {
    text(timer, 100, 100);

    //Updates timer
    timer++;

    //Does stuff
    if (bgm1playing == false &amp;&amp; bgm2playing == false &amp;&amp; bgm3playing == false) {
      bgm1.play();
      bgm1playing = true;
      if (timer &gt; 300) {
        bgm2playing = true;
        bgm1playing = false;
      }
    }
    if (bgm2playing == true) {
      bgm2.play();
      if (timer &gt; 500) {
        bgm3playing = true;
        bgm2playing = false;
      }
    }
    if (bgm3playing == true) {
      bgm3.play();
      if (bgm3.duration() &gt; 10) {
        bgm1playing = false;
        bgm2playing = false;
        bgm3playing = false;
      }
    }
  }
}



class CameraController {
  void update() {
    if ((keys['w']) || (keys['W'])) {
      cameraY += 15;
    }
    if ((keys['a']) || (keys['A'])) {
      cameraX += 15;
    }
    if ((keys['s']) || (keys['S'])) {
      cameraY -= 15;
    }
    if ((keys['d']) || (keys['D'])) {
      cameraX -= 15;
    }
  }
}



class GameObject {
  boolean grounded;
  float x;
  float y;
  float w;
  float h;
  int type;

  void display() {}
  void update() {}
}



import processing.sound.*;

final static ArrayList&lt;Building&gt; gameBuildings = new ArrayList();
final static ArrayList&lt;Troop&gt; gameTroops = new ArrayList();

boolean keys[] = new boolean[128];

SoundFile bgm1;
SoundFile bgm2;
SoundFile bgm3;

SelectionMenu selectionMenu = new SelectionMenu();

MusicHandler mHandler = new MusicHandler();

CameraController camera = new CameraController();

PImage background;

double money;

int cameraX;
int cameraY;

void setup() {
  fullScreen();

  bgm1 = new SoundFile(this, "bgm1.mp3");
  bgm2 = new SoundFile(this, "bgm2.mp3");
  bgm3 = new SoundFile(this, "bgm3.mp3");

  background = loadImage("background.png");
}

void draw() {
  background(0, 120, 0);

  camera.update();

  for (int i = -5120; i &lt; 5120; i += 1280) {
    for (int a = -2880; a &lt; 2880; a += 720) {
      image(background, i + cameraX, a + cameraY);
    }
  }

  for (int i = 0; i &lt; gameBuildings.size(); i++) {
    Building bObj = gameBuildings.get(i);
    bObj.update();
    bObj.display();
  }

  selectionMenu.display();
  selectionMenu.update();

  fill(0, 255, 0);
  text("$" + money, 10, 10);
}

void keyPressed() {
  keys[key] = true;
}

void keyReleased() {
  keys[key] = false;
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Less CPU intensive way to scan pixels</title>
      <link>https://forum.processing.org/two/discussion/23592/less-cpu-intensive-way-to-scan-pixels</link>
      <pubDate>Wed, 26 Jul 2017 23:03:33 +0000</pubDate>
      <dc:creator>TimShaw</dc:creator>
      <guid isPermaLink="false">23592@/two/discussions</guid>
      <description><![CDATA[<p>Hi -</p>

<p>I am scanning an image line by line and outputting the greyscale of each pixel to Pure Data via OSC, all of it is working ok but it seems super intensive for the computer, the fans are on full speed and sometimes Processing crashes a few minutes in.</p>

<p>Is there anything I can do to make this code less intensive? Might be missing something obvious?</p>

<p>It could be because of the frameRate, and if so are there any suggestions of other ways of doing this? So that I can still run the scanning pretty fast</p>

<p>Thanks in advance for any help</p>

<pre><code>import oscP5.*;
import netP5.*;

NetAddress remote;
OscP5 oscP5;
//int incomingOSCData;
// int sendTestData;
// String msgType;

PImage img;
int x, y, s, r;

void setup() {
  size(500, 500);
  oscP5 = new OscP5(this,12000);
  remote = new NetAddress("127.0.0.1",3000);
  s = 10;
  stroke(255);
  reset();
  frameRate(200);
  img = loadImage("10.jpg");
  background(0);
  img.loadPixels();
}

void reset(){
  background(0);
  x = 0;
  y = 0;
  OscMessage msg = new OscMessage("/sync");
  msg.add(1);
  oscP5.send(msg,remote);
}

void draw() {
  if(x&gt;=width){ y+=s; x=0; }
  if(y&gt;=height) reset();
  delay(100);
  int loc = x + y*img.width;
  noStroke();
  color c = img.pixels[loc];
  // int alpha = (c &gt;&gt; 24) &amp; 0xFF;
  int red   = (c &gt;&gt; 16) &amp; 0xFF;
  int green = (c &gt;&gt; 8)  &amp; 0xFF;
  int blue  =  c        &amp; 0xFF;
  int gray = ((red + green + blue) / 3);
  // println(alpha + " " + red + " " + green + " " + blue);
  fill(c);
  rect(x++,y,4,4);
  // println(gray);
  OscMessage msg = new OscMessage("/grayscale");
  msg.add(gray);
  oscP5.send(msg,remote);
}
</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>Performance and Memory Issues</title>
      <link>https://forum.processing.org/two/discussion/23111/performance-and-memory-issues</link>
      <pubDate>Sun, 18 Jun 2017 07:51:37 +0000</pubDate>
      <dc:creator>Bhargav</dc:creator>
      <guid isPermaLink="false">23111@/two/discussions</guid>
      <description><![CDATA[<p>I am using latest version of processing on raspberry pi 3 latest updated OS.  TO give you overview of my project includes using dynamically loading of some images for display and which are dynamically fetched while the program is running. And it uses GPIO pins and captures pictures from a webcam. My program starts with auto run. Code and functionality wise everything is working well to my project but I think its not using the full resources available on Pi and working slow. If it can use more resources of Pi it might run faster but i dont know how to work on it</p>

<p>In the scenario the startup time is takes about 45seconds to 60seconds(a minute) until it completely load the program and starts running. As the program is still loading i cant even show loading symbol on the screen as the pi is loading processing and he program it self.</p>

<p>Also the task manager shows that the memory is used between 400MB to 600MB out of 923MB(total) while the processing code alone is running. Also at the same time the CPU usage is also less the 55% shown in task manager's live display.</p>

<p>And If i leave my program keep running and dont do anything after sometime the raspberry Pi system hangs and I have to forcefully  swtich off the power.</p>

<p>Need to how can i make processing on Raspberry Pi make use of more RAM memory and CPU available to it.</p>

<p>I also went into raspi-config and from advance setting to GL Drivers ann enabled the GL Full KMS option. Then I added into 256MB for GPU memory. But it doesnt help much. Can't see any effective results while the code is running.</p>
]]></description>
   </item>
   <item>
      <title>Faster way of drawing a byte to the screen ?</title>
      <link>https://forum.processing.org/two/discussion/22978/faster-way-of-drawing-a-byte-to-the-screen</link>
      <pubDate>Wed, 07 Jun 2017 18:52:24 +0000</pubDate>
      <dc:creator>aephx</dc:creator>
      <guid isPermaLink="false">22978@/two/discussions</guid>
      <description><![CDATA[<p>Hey guys!
I've made a Program that basically emulates a 256x192 (monochrome)screen in processing.
The byte-array, in which i store the pixel-data, has 6kb.  (8pixel per byte, to a total of 6144bytes). 
1 drawing cycle of the screen (if every pixel is a 1==white) takes the Program around 6 seconds.</p>

<p>So my question is, is there a faster way of drawing a byte to the screen than my approach?</p>

<p>Code of the drawing "algorithm":</p>

<p><code>for (int I=0; I&lt;6144; I++){
    int x,y = I/32;
    for(int X=0; X&lt;32; X++) {
      x = X*8;
      // checks if the bit is == 1 and then draws the point
      if ( (DataIn[I] &amp; 0x01) &gt; 0) point(x,y);
      if ( (DataIn[I] &amp; 0x02) &gt; 0) point(x+1,y);
      if ( (DataIn[I] &amp; 0x04) &gt; 0) point(x+2,y);
      if ( (DataIn[I] &amp; 0x08) &gt; 0) point(x+3,y);
      if ( (DataIn[I] &amp; 0x10) &gt; 0) point(x+4,y);
      if ( (DataIn[I] &amp; 0x20) &gt; 0) point(x+5,y);
      if ( (DataIn[I] &amp; 0x40) &gt; 0) point(x+6,y);
      if ( (DataIn[I] &amp; 0x80) &gt; 0) point(x+7,y);
    }
  }</code></p>

<p>also sorry about my bad english</p>
]]></description>
   </item>
   <item>
      <title>Optimize my Conway Game of Life in Quil in Clojure</title>
      <link>https://forum.processing.org/two/discussion/22937/optimize-my-conway-game-of-life-in-quil-in-clojure</link>
      <pubDate>Mon, 05 Jun 2017 11:47:13 +0000</pubDate>
      <dc:creator>Aljones15</dc:creator>
      <guid isPermaLink="false">22937@/two/discussions</guid>
      <description><![CDATA[<p>Ok so in clojure REPL (time (conway-state cells)) returns about 0.43 milliseconds more than fast enough for 15 FPS. However the actual draw loop seems to be really lagging on drawing my rects. code below:``</p>

<pre><code>  1(ns hello-quil.core                                                                                                  
  2                                                                                                                     
  3 (:require [quil.core :as q]                                                                                         
  4            [quil.middleware :as m]                                                                                  
  5            [clojure.core.reducers :as r]))                                                                          
  6                                                                                                                     
  7(def scaler 10.0)                                                                                                    
  8(defstruct cell :index :alive :x :y)                                                                                 
  9(defn scale-w [] (Math/floor (/ 640 scaler) ))                                                                       
 10(defn scale-h [] (Math/floor (/ 360 scaler) ))                                                                       
 11                                                                                                                     
 12                                                                                                                     
 13(defn scaledCoord [coord] (if (= coord 0) coord (* scaler coord)))                                                   
 14                                                                                                                     
 15(def initState                                                                                                       
 16  ; the initial state                                                                                                
 17  (map-indexed                                                                                                       
 18    (fn [index num]                                                                                                  
 19      (struct cell index (rand-int 2) (scaledCoord (mod index (scale-w)))                                            
 20        (scaledCoord(Math/floor (/ index (scale-w))))))                                                              
 21    (range 0 (* (scale-w) (scale-h))))                                                                               
 22)                                                                                                                    
 23                                                                                                                     
 24(defn setup []                                                                                                       
 25  ; Set frame rate to 30 frames per second.                                                                          
 26  (q/frame-rate 15)                                                                                                  
 27  ; Set color mode to HSB (HSV) instead of default RGB.                                                              
 28  (q/color-mode :hsb)                                                                                                
 29  ; setup function returns initial state. It contains                                                                
 30  {:cells (into [] initState)}                                                                                       
 31)                                                                                                                    
 32                                                                                                                     
 33(defn getNeighbor [x y cells]                                                                                        
 34  ; gets the neigbor or return a random alive if no neighbor                                                         
 35  (let [result (into [] (r/filter (fn [c] (and (= x (:x c)) (= y (:y c)))) cells))]                                  
 36  (if (empty? result) (rand-int 2) (:alive (first result))))                                                         
 37)                                                                                                                    
 38                                                                                                                     
 39                                                                                                                     
 40(defn getNeighbors [c cells]                                                                                         
 41  ; get neighbors in 8 directions                                                                                    
 42  (let [x (:x c) y (:y c) left (- x scaler) right (+ x scaler) up (+ y scaler) down (- y scaler)]                    
 43    (map                                                                                                             
 44      (fn [[newX newY]](getNeighbor newX newY cells))                                                                
 45      [[right y] [left y] [right up] [left up] [x up] [x down] [right down] [left down]]))                           
 46)                                                                                                                    
 47                                                                                                                     
 48                                                                                                                     
 49(defmulti cell-state                                                                                                 
 50  ; takes a vector of neighbors and sums them                                                                        
 51  (fn [c cells] (reduce + cells))                                                                                    
 52)                                                                                                                    
 53; if there are 2 the cell stays the same                                                                             
 54(defmethod cell-state 2 [c cells] c)                                                                                 
 55; if there are 3 neighbors we reproduce 1                                                                            
 56(defmethod cell-state 3 [c _] (assoc c :alive 1))                                                                    
 57; everything else it dies                                                                                            
 58(defmethod cell-state :default [c _] (assoc c :alive 0))                                                             
 59                                                                                                                      60(defn update-cell [cells]                                                                                            
 61  ; curried func that takes the state, then return a mappable func                                                   
 62  (fn [c] (let [neighbors (getNeighbors c cells)]                                                                    
 63    (cell-state c neighbors)))                                                                                       
 64)                                                                                                                    
 65                                                                                                                     
 66(defn conway-state [cells]                                                                                           
 67  ; update conway's game of life                                                                                     
 68  (map (update-cell cells) cells)                                                                                    
 69)                                                                                                                    
 70                                                                                                                     
 71(defn update-state [state]                                                                                           
 72  ; Update sketch state by changing circle color and position.                                                       
 73  {:cells (conway-state (:cells state))}                                                                             
 74)                                                                                                                    
 75                                                                                                                     
 76(defn getFill [alive]                                                                                                
 77  (if (&gt; alive 0) 255 0)                                                                                             
 78)                                                                                                                    
 79                                                                                                                     
 80(defn draw-cell [c]                                                                                                  
 81  (q/with-fill [(getFill (:alive c))] (q/rect (:x c) (:y c) scaler scaler))                                          
 82)                                                                                                                    
 83                                                                                                                     
 84(defn draw-state [state]                                                                                             
 85  ; Clear the sketch by filling it with light-grey color.                                                            
 86  (q/background 240)                                                                                                 
 87  ; Calculate x and y coordinates of the cell and the color.                                                         
 88  (doseq [cell (:cells state) ]                                                                                      
 89    (draw-cell cell))                                                                                                
 90)            
91                                                                                                                     
 92(q/defsketch hello-quil                                                                                              
 93  :title "Basic Conway Game of Life"                                                                                 
 94  :size [640 360]                                                                                                    
 95  ; setup function called only once, during sketch initialization.                                                   
 96  :setup setup                                                                                                       
 97  ; update-state is called on each iteration before draw-state.                                                      
 98  :update update-state                                                                                               
 99  :draw draw-state                                                                                                   
100  :features [:keep-on-top]                                                                                           
101  ; This sketch uses functional-mode middleware.                                                                     
102  ; Check quil wiki for more info about middlewares and particularly                                                 
103  ; fun-mode.                                                                                                        
104  :middleware [m/fun-mode])                 
</code></pre>
]]></description>
   </item>
   <item>
      <title>Sketch running slow</title>
      <link>https://forum.processing.org/two/discussion/22201/sketch-running-slow</link>
      <pubDate>Tue, 25 Apr 2017 16:53:39 +0000</pubDate>
      <dc:creator>Sjors</dc:creator>
      <guid isPermaLink="false">22201@/two/discussions</guid>
      <description><![CDATA[<p>So I made this little game with pictures (they are hosted online so anyone can run this script) on my computer it runs fine but when I move to a device with lower specs it starts to drop to like 5fps how would I solve this? also when running this code it could look clitchy since I didn't keep aspect ratios in mind when making it.</p>

<p>EDIT: I made the stupid mistake of not mentioning that when I when I said "a lower spec system" I meant an andriod phone</p>

<pre><code>ArrayList &lt;Bullet&gt; bullets;
int background_y;

PImage background;
PImage player;
PImage enemy;
PImage bullet;

int bullet_traveling;
int bullet_timer1;
int bullet_timer2;
int bullet_shot;
int bullet_side;
int bullet_x;
int bullet_y;

int enemy_health;
int enemy_x;
int enemy_y;

int player_x;
int player_y;

void setup() {
  fullScreen();
  frameRate(60);
  bullets = new ArrayList();

  background = loadImage("https://" + "s21.postimg.org/oubg978af/background.png");
  player = loadImage("https://" + "s13.postimg.org/hy84r98mv/player.png");
  bullet = loadImage("https://" + "s23.postimg.org/45ev766kr/bullet.png");
  enemy = loadImage("https://" + "s27.postimg.org/6njql63gz/enemy.png");

  bullet.resize(bullet.width/3, bullet.height/3);
  background.resize(width, height);

  player_y = height/4*3;
  player_x = width/2;
}

void draw() {
  background();
  for (Bullet temp : bullets) temp.update();
  bullet_enemy();
  player();
  enemy();

  if (mousePressed) {
    if (bullet_timer1 == 0) {
      bullet_timer1 = 1;
      bullet_timer2 = millis();
    }
    if (millis() - bullet_timer2 &gt;= 200) {
      bullet_timer1 = 0;
      if (bullet_side == 1) {
        Bullet temp = new Bullet(player_x+55, player_y);
        bullets.add(temp);
        bullet_side = 0;
      } else {
        Bullet temp = new Bullet(player_x-55, player_y); 
        bullets.add(temp);
        bullet_side = 1;
      }
    }
  }
}

void background() {
  image(background, 0, background_y);
  image(background, 0, background_y-height);
  background_y += 1;
  if (background_y &gt;= height) background_y = 0;
}

void enemy() {
  if (enemy_health == 0) {
    enemy_health = 1;
    enemy_y = -enemy.width/2;
    enemy_x = int(random(enemy.width/2, width-enemy.width/2));
  }
  if (enemy_y-enemy.width/2 &gt;= height) {
    enemy_health = 0;
  }
  enemy_y += 3;

  image(enemy, enemy_x-enemy.width/2, enemy_y-enemy.height/2);
}

void player() {
  if (mousePressed &amp;&amp; player_x &lt; mouseX) player_x = player_x + 12;
  if (mousePressed &amp;&amp; player_x &gt; mouseX) player_x = player_x - 12;
  image(player, -player.width/2+player_x, -player.height/2+player_y);
}

void bullet_enemy() {
  if (player_x &lt;= enemy_x+100 &amp;&amp; player_x &gt;= enemy_x-100 || bullet_traveling == 1) {
    bullet_traveling = 1;
    if (bullet_shot == 0) {
      bullet_x = enemy_x;
      bullet_y = enemy_y;
      bullet_shot = 1;
    }
    rect(bullet_x, bullet_y, 10, 10);
    bullet_y = bullet_y + 30 ;
  }

  if (bullet_x &lt;= player_x+player.width/2 &amp;&amp; bullet_x &gt;= player_x-player.width/2 &amp;&amp; bullet_y &gt;= player_y) {
    bullet_traveling = 0;
    bullet_shot = 0;
  }
}

class Bullet {
  float x;
  float y;
  float speed;

  Bullet(float tx, float ty) {
    x = tx;
    y = ty;
  }

  void update() {
    image(bullet, -bullet.width/2+x, -bullet.height/2+y);
    y -= 25;
    if (x &lt;= enemy_x+enemy.width/2 &amp;&amp; x &gt;= enemy_x-enemy.width/2 &amp;&amp; y &lt;= enemy_y) {
      x = -10000;
      enemy_health = 0;
    }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Rendering using P2D on an EC2 instance?</title>
      <link>https://forum.processing.org/two/discussion/22111/rendering-using-p2d-on-an-ec2-instance</link>
      <pubDate>Thu, 20 Apr 2017 16:49:21 +0000</pubDate>
      <dc:creator>thomas_capogreco</dc:creator>
      <guid isPermaLink="false">22111@/two/discussions</guid>
      <description><![CDATA[<p>I am using a recursive trig function to make super high definition symmetrical spiral shapes that morph into one another, but because of the computation involved, it is very slow: ~6 hours for a minute of footage (1440 frames) on my mbp.</p>

<p>The P2D renderer doesn't make it go that much faster on my computer, but I thought there might be a way to make use of a GPU instance on EC2 via OpenGL?</p>

<p>Thanks to one of Daniel Shiffman's tutorials, I managed to get a sketch running on EC2 and exporting .png files using the default renderer - would I just be better off getting a compute instance and using the default renderer? I was curious so I hired a larger compute instance, but it rendered the frames only very slightly faster than the free tier instance.</p>

<p>Any advice / pointers / resources wrt rendering headless on EC2 would be amazing!!</p>
]]></description>
   </item>
   <item>
      <title>Slowdown when looping through IntList()'s</title>
      <link>https://forum.processing.org/two/discussion/21700/slowdown-when-looping-through-intlist-s</link>
      <pubDate>Thu, 30 Mar 2017 10:57:42 +0000</pubDate>
      <dc:creator>gonadgranny</dc:creator>
      <guid isPermaLink="false">21700@/two/discussions</guid>
      <description><![CDATA[<p>Hi folks!
I have been using IntList() to store an arbitrary amount of mouse coordinates. i chose intlist because it does not require the size to be declared in the beginning.
I have been looping over these points to draw a graph using the following code:</p>

<pre><code>void drawgraph(){
  //draw the visual rep of the positional points
  int buffer =  10;
  stroke(0);
  fill(255);
  rectMode(CORNER);
  rect(0,height - graphHeight,width,graphHeight +20);
  if(posX.size() &gt; 1){
    for(int i = 0; i &lt; posX.size() -1; i++){
    float a = map(posX.get(i),maxleft,maxright,height-buffer, height - (graphHeight -buffer));
    float b = map(posX.get(i+1),maxleft,maxright,height-buffer, height - (graphHeight -buffer));
    float a1 = map(posY.get(i),maxup,maxdown,height - (graphHeight -buffer), height-buffer);
    float b1 = map(posY.get(i+1),maxup,maxdown,height - (graphHeight -buffer), height-buffer);

      stroke(#00D3ED);//xgraph
      strokeWeight(1);
      line((i+xLen),a,(i+xLen),b);
      stroke(#F534BE);//ygraph
      strokeWeight(1);
      line((i+xLen),a1,(i+xLen),b1);

    }
  }
}
</code></pre>

<p>This works fine but it does seem to use a lot of CPU. the longer the list gets(and subsequently has to be displayed) the more of the cpu its hogging) I want to incorporate a third data steam into the mix and when i do its grinds to a halt.
Is there a better way for me to accomplish this? I have been looking into using Pgraphics to speed things up which works great for static graphics but gets a bit complicated when things are relatively dynamic. Anly help would be much appreciated. Thanks, Danny.</p>
]]></description>
   </item>
   </channel>
</rss>