Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

  • real time data program

    hey guys. in this time i need some help to optimize a system to pick shaders in real time (fragment shaders, and vertex shaders). This code is a mix that i recoleted in internet with code writing by myself.

    Theres a lot of problem and i need help:

    the idea of the program is that user can pick the shader in real time. there are two problems, first, i dont know how uploading the vertexShader, when i save it and reload it i need to click in another frag and then vertex upload.

    second, it seems very inestable.the window of shaders crash very often, specially when frame rate is lowest. I wondering how to fix that. maybe with thread(), but it dont know exactly how apply this method..

    If someone have time and wants to help, im sure that this code needs to be re writing. Thanks!

    ShaderWindow shaderWin;
    
    boolean recording = false;
    
    
    import netP5.*;
    import oscP5.*;
    
    OscP5 oscP5;
    NetAddress myRemoteLocation;
    
    import themidibus.*;
    MidiBus bus;
    MidiBus apc;
    float cc [] =new float [256];
    
    
    boolean record, load;
    double folderTime;
    File folderShader;
    float desmouse = 0.5;
    
    // BUFFERS-SHADERS
    
    String dirFolderShaders;
    String dirFolderShaders2;
    String dirFolderShadersvertex;
    
    PGraphics [] buffers = new PGraphics [4];
    PGraphics buffer;
    
    LoadShader loadshader;
    
    LoadShader loadshader2;
    LoadShader loadshaderVertex;
    
    ArrayList<ViewShader>vs = new ArrayList<ViewShader>();
    ViewShaderVertex ss;
    
    PShader sh, buffer1;
    float count;
    float angle = random(0, 0.005);
    
    int choiceSize =1;
    //int ww =  1920;
    //int h = 1080;
    
    void settings() {
      if (choiceSize==0) fullScreen(P3D, 2);
      if (choiceSize==1) size(1000, 1000, P3D);
      if (choiceSize==2) size(720, 1280, P3D);
    }
    
    void setup() {
    
      // BUFFERS-SHADERS
    
      dirFolderShaders = sketchPath("frag/");  //PUT SOME FRAGMENT IN THIS FOLDER
    
      dirFolderShadersvertex = sketchPath("vertex/"); PUT SOME VERTEX IN THIS FOLDER
    
      loadshader = new LoadShader(dirFolderShaders);
    
      loadshaderVertex = new LoadShader(dirFolderShadersvertex);
    
    
      for (int i = 0; i < buffers.length; i++) {
        buffers[i] = createGraphics(width, height, P3D);
      }
    
    
      ss = new ViewShaderVertex(loadshaderVertex.shadersPaths[1], loadshaderVertex, buffer);
      vs.add(new ViewShader(loadshader.shadersPaths[0], loadshader, buffer, ss));
    
      shaderWin = new ShaderWindow();
    }
    
    void draw() {
    
      background(0);
    
    
      for (ViewShader s : vs) {
        s.update();
      }
    
    
      if (folderShader.listFiles().length != loadshader.shadersNames.length) {
        loadshaderVertex.loadFolderShader();
      }
    
      if (folderShader.listFiles().length != loadshader.shadersNames.length) {
        loadshader.loadFolderShader();
      }
    
    
    
    
      buffers[0].beginDraw();
      buffers[0].background(0);
      buffers[0].translate(width/2, height/2);
    
    
      buffers[0].sphere(100);
      buffers[0].endDraw();
    
      image(buffers[0],0,0);
    }
    
    
    
    // LOAD SHADER CLASS
    
    class LoadShader {
    
      String dirFolderShaders;
    
      String[] shadersNames;
      String[] shadersPaths;
    
      LoadShader(String _dirFolderShaders) {
        dirFolderShaders= _dirFolderShaders;
        loadFolderShader();
      }
    
      void loadFolderShader() {
        load = true;
        folderShader = new File(dirFolderShaders);
        File files[] = folderShader.listFiles();
        shadersNames = new String[files.length];
        shadersPaths = new String[files.length];
        for (int i = 0; i < files.length; i++) {
          shadersNames[i] = split(files[i].getName(), ".")[0];
          shadersPaths[i] = files[i].getAbsolutePath();
          //println(shadersNames[i]);
        }
        load = false;
      }
    }
    
    class ViewShader {
    
      boolean reload, error, loaded;
      File fileShader;
    
      long timeModi;
      long timeModis;
      String src;
    
      PShader shader;
      PShader shader1;
      PShader shader2;
      float a;
      LoadShader loadshader;
      ViewShaderVertex ss;
      PGraphics b;
    
      ViewShader(String _src, LoadShader _loadshader, PGraphics _b) {
        src = _src;
        fileShader = new File(src);
        openShader(fileShader);
        //shader1 = loadShader("blur.glsl", "bloomVert.glsl");
        //shader2 = loadShader("blur_vertical.glsl", "bloomVert.glsl");
        loadshader = _loadshader;
        b = _b;
      }
    
      ViewShader(String _src, LoadShader _loadshader, PGraphics _b, ViewShaderVertex _s) {
        ss = _s;
    
        //shader = loadShader("test2.glsl", "defaultVertex2.glsl");
        //shader1 = loadShader("blur.glsl", "bloomVert.glsl");
        //shader2 = loadShader("blur_vertical.glsl", "bloomVert.glsl");
    
        src = _src;
        fileShader = new File(src);
        openShader(fileShader);
        loadshader = _loadshader;
        b = _b;
      }
    
    
      void update() {
        if (reload) {      
          openShader(fileShader);
          reload = false;
        }
        if (shader != null) {
    
          //float p = map(cc[15], 0, 1, 0, 1);
          //float amt = map(cc[16], 0, 1, 1, 50);
          //float  h = map(cc[48], 0, 1, 0, 0.1);
          // //float  h = map(cc[14], 0, 1, 0, 0.5);
    
    
          shader.set("u_time", random(10));
    
          //shader1.set("u_time", angle);
          //shader2.set("u_time", angle);
    
          //shader.set("var2", p);
          //shader.set("amt", amt);
    
          //shader1.set("var2", p);
          //shader2.set("var2", p);
    
    
          if (fileShader.lastModified() != timeModi) {
            openShader(fileShader);
          }
        }
      }
    
    
      void newShader(String _srcc) {
        src = _srcc;
        fileShader = new File(src);
        reload = true;
        openShader(fileShader);
      }
    
      void openShader(File file) {
        if (file != null) {
          fileShader = file;
          timeModi = fileShader.lastModified();  
          try {
            shader = loadShader(file.getAbsolutePath(), ss.fileShader.getAbsolutePath());
    
            buffers[0].shader(shader);
    
    
            println(file.getAbsolutePath());
            error = false;
            loaded = true;
          }
          catch (RuntimeException e) {
            if (error == false) {
              error = true;
              // String time = nf(str(hour()),2) + ":" + nf(str(minute()),2) + ":" + nf(str(second()),2);
              println("\n");
              // println("At", time, "loadShader() returned the following error: \n");
              println("loadShader() returned the following error: \n");
              e.printStackTrace();
            }
            loaded = false;
          }
        }
      }
    }
    
    public class ShaderWindow extends PApplet {
    
      ShaderWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      boolean mover;
    
      void settings() {
        size(600, 800, P2D);
      }
    
      void setup() {
        this.frameRate(30);
      }
    
    
      void draw() {
    
        background(25);
    
    
        for (int i = 0; i < vs.size(); i++) {
          ViewShader sss = vs.get(i);
          selector(i*100, 16, 100, width-16, sss, sss.loadshader, this);
        }
    
        ViewShaderVertex s = ss;  
        selector2(400, 16, 100, width-16, s, ss.loadshader, this);
    
      }
    
      void selector(float xx, float yy, float ww, float hh, ViewShader vs, LoadShader loadshader, PApplet p) {
        p.fill(150);
        p.noStroke();
        p.rectMode(CORNER);
    
        int cant = loadshader.shadersNames.length;
        p.rect(xx, yy+cant*16, ww, hh-cant*16);
        for (int i = 0; i < cant; i++) {
          boolean sobre = false;
          if (p.mouseX >= xx && p.mouseX < xx+ww && p.mouseY >= yy+i*16 && p.mouseY < yy+(i+1)*16) {
            sobre = true;
          }
          if (sobre) {
            p.fill(125);
          } else {
            p.fill(100, 50);
          }
          boolean selec = vs.src.equals(loadshader.shadersPaths[i]);
          if (p.mousePressed && sobre && !selec) {
            vs.newShader(loadshader.shadersPaths[i]);
          }
    
          if (selec) {
            p.fill(100);
            if (vs.error) {
              p.fill(200, 10, 10);
            }
          }
    
          p.rect(xx, yy+i*16, ww, 16);
          p.textAlign(LEFT, TOP);
          p.fill(250);
          if (i < loadshader.shadersNames.length && !load)
            text(loadshader.shadersNames[i], xx+5, yy+i*16);
        }
      }
    
      void selector2(float xx, float yy, float ww, float hh, ViewShaderVertex vs, LoadShader loadshader, PApplet p) {
        p.fill(150);
        p.noStroke();
        p.rectMode(CORNER);
    
        int cant = loadshader.shadersNames.length;
        p.rect(xx, yy+cant*16, ww, hh-cant*16);
        for (int i = 0; i < cant; i++) {
          boolean sobre = false;
          if (p.mouseX >= xx && p.mouseX < xx+ww && p.mouseY >= yy+i*16 && p.mouseY < yy+(i+1)*16) {
            sobre = true;
          }
          if (sobre) {
            p.fill(125);
          } else {
            p.fill(100, 50);
          }
          boolean selec = ss.src.equals(loadshader.shadersPaths[i]);
          if (p.mousePressed && sobre && !selec) {
            vs.newShader(loadshader.shadersPaths[i]);
          }
    
          if (selec) {
            p.fill(100);
            if (vs.error) {
              p.fill(200, 10, 10);
            }
          }
    
          p.rect(xx, yy+i*16, ww, 16);
          p.textAlign(LEFT, TOP);
          p.fill(250);
          if (i < loadshader.shadersNames.length && !load)
            p.text(loadshader.shadersNames[i], xx+5, yy+i*16);
        }
      }
    }
    
    class ViewShaderVertex {
    
      boolean reload, error, loaded;
      File fileShader;
      long timeModi;
      String src;
      String src2;
    
      PShader shader;
    
      float a;
      LoadShader loadshader;
      ViewShader ss;
    
      ViewShaderVertex(String _src, LoadShader _loadshader, PGraphics b) {
    
        src = _src;
        fileShader = new File(src);
        openShader(fileShader);
    
        loadshader = _loadshader;
      }
    
    
    
      void update() {
        if (reload) {      
          openShader(fileShader);
          reload = false;
        }
        if (shader != null) {
    
          if (fileShader.lastModified() != timeModi) {
            openShader(fileShader);
    
          }
        }
      }
    
    
      void newShader(String src) {
        this.src = src;
        fileShader = new File(src);
        reload = true;
        openShader(fileShader);
      }
    
      void openShader(File file) {
    
        if (file != null) {
          fileShader = file;
          timeModi = fileShader.lastModified();
    
          try {
                    for (ViewShader s : vs) {
              s.update();
            }
            //shader = loadShader("test.glsl", file.getAbsolutePath());
            shader.setVertexShader(file.getAbsolutePath());
            buffers[0].shader(shader);
    
            println(file.getAbsolutePath());
            error = false;
            loaded = true;
          }
          catch (RuntimeException e) {
            if (error == false) {
              error = true;
              // String time = nf(str(hour()),2) + ":" + nf(str(minute()),2) + ":" + nf(str(second()),2);
              println("\n");
              // println("At", time, "loadShader() returned the following error: \n");
              println("loadShader() returned the following error: \n");
              e.printStackTrace();
            }
            loaded = false;
          }
        }
      }
    }
    
  • multiple window - clone main window

    solved, if someone is interested, here the code:

    PWindow win;
    PGraphics pg;
    
    public void settings() {
      size(640, 480);
    }
    
    void setup() { 
      win = new PWindow();
      pg = createGraphics(width, height);
      println(width, height);
    }
    
    void draw() {
      pg.beginDraw();
      pg.background(255, 0, 0);
      pg.fill(255);
      pg.rect(10, 10, abs(sin(frameCount*.02)*width), 10);
      pg.endDraw();
      image(pg, 0, 0, width, height);
      win.setPG(pg);
    }
    
    void mousePressed() {
      println("mousePressed in primary window");
    }  
    
    class PWindow extends PApplet {
      PGraphics pg1;
    
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      void settings() {
        size(320, 240);
      }
    
      void setup() {
        background(150);
        pg1 = createGraphics(width, height);
        println(width, height);
      }
    
      void setPG(PGraphics pg1) {
        pg1.beginDraw();
        this.pg1=pg1;
        pg1.endDraw();
      }
    
      void draw() {
        image(pg1, 0, 0, width, height);
      }
    
      void mousePressed() {
        println("mousePressed in secondary window");
      }
    }
    
  • multiple window - clone main window

    i try to use a PGraphi but it not clone the main window, any suggestion?

    PWindow win;
    PGraphics pg;
    
    public void settings() {
      size(320, 240);
    }
    
    void setup() { 
      win = new PWindow();
      pg = createGraphics(width, height);
    }
    
    void draw() {
      pg.beginDraw();
      pg.background(255, 0, 0);
      pg.fill(255);
      pg.rect(10, 10, frameCount, 10);
      win.draw(pg);
      pg.endDraw();
      image(pg, 0, 0);
      //win.draw();
    }
    
    void mousePressed() {
      println("mousePressed in primary window");
    }
    class PWindow extends PApplet {
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      void settings() {
        size(500, 200);
      }
    
      void setup() {
        background(150);
      }
    
      void draw(PGraphics pg) {
        image(pg, 0, 0, width, height);
      }
    
      void mousePressed() {
        println("mousePressed in secondary window");
      }
    }
    
  • multiple window - clone main window

    hi to all!

    i use processing as my principal instrument to do visual live set, and i've the necessity to clone the main window to another to control what is rendering in that moment!

    for now i'm using this code:

    class PWindow extends PApplet {
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      void settings() {
        size(500, 200);
      }
    
      void setup() {
        background(150);
      }
    
      void draw() {
        //here i want to clone the main window
      }
    
      void mousePressed() {
        println("mousePressed in secondary window");
      }
    }
    
    
    PWindow win;
    
    public void settings() {
      size(320, 240);
    }
    
    void setup() { 
      win = new PWindow();
    }
    
    void draw() {
      background(255, 0, 0);
      fill(255);
      rect(10, 10, frameCount, 10);
    }
    
    void mousePressed() {
      println("mousePressed in primary window");
    }  
    

    is possible do what i ask starting with this?

    thank to everyone!!

  • Send value to a object

    this doesn't make too much sense - at least to me:

    Every Sphere on the screen represent an Obj when i click on that ellipse, i want change with a slider the "total" value for this Obj.

    When you want the ellipses to symbolize your objects, why then additionally put in objects??

    Either ellipses / Spheres OR obj.

    This

    this is really bad:

        for (Sphere currentSphere : s) {
          if (currentSphere.over) {
    
            for (Obj o : obj) {
              o.printt();
              cID = currentSphere.id;
            }
    

    it takes a lot of processor time to check for each sphere ALL objects!!!

    A nested for loop only makes sense when you have a structure like a grid where each line has many cells.

    New version

    New version without obj but with:

    • slider takes the value from clicked ellipse!!!

    Chrisir ;-)

    import controlP5.*;
    
    ArrayList<Sphere> s;
    
    PWindow controller;
    
    int cID=-1;  
    
    // ------------------------------------------------------------
    
    void settings() {
      size(500, 500, P3D);
    }
    
    void setup() {
      controller = new PWindow();
    
      s = new ArrayList<Sphere>();
    
      // add one sphere (optional)
      float size1 = 50; 
      Sphere newSphere = new Sphere(
        new PVector(random(size1, width-size1), random(size1, height-size1)), 
        255, 
        size1, 
        0); 
      s.add(newSphere);
    }
    
    void draw() {
      background(0);
    
      for (Sphere ss : s) {   
        ss.display();
        ss.isOver(mouseX, mouseY);
      }
    }
    
    // ------------------------------------------------------------
    // Inputs 
    
    void mousePressed() {
    
      if (mouseButton==RIGHT) { 
        s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()));
        return; // leave here
      }
    
      //reset 
      cID=-1; 
    
      if (mouseButton==LEFT) {
        for (Sphere currentSphere : s) {
          if (currentSphere.over) {
            currentSphere.isClick = true;
            cID = currentSphere.id;
            float currentSize = s.get(cID).size; 
            controller.cp5.getController("vertices").setValue(currentSize);
          } else {
            currentSphere.isClick = false;
          }
        }//for
      }//if
      //
    } //func 
    
    // ===========================================================
    
    class Sphere {
    
      color c; 
      float size;
      float x, y;
      PVector p = new PVector(0, 0);
      boolean over = false;
      boolean isClick = false;
      int id;
      int initialValue = 50;
    
      //constr 
      Sphere(PVector _pos, 
        color _color, 
        float _size, 
        int _id) {
        // 
        p=_pos.copy();
        c = _color;
        size = _size;
        id = _id;
      }//constr
    
      void display() {
        fill(c);
        ellipseMode(RADIUS);
        ellipse(p.x, p.y, 
          size, size);
      }
    
      boolean isOver(float px, float py) {
        float d = dist(px, py, p.x, p.y);
        if (d < size) {
          over = true;
          c = 150;
          if (isClick) 
            c = 25; // color
          return true;
        } else {
          over = false;
          c = 255;
          if (isClick) 
            c = 25; // color
          return false;
        }
      }//func
    }//class
    
    // ===========================================================
    
    public class PWindow extends PApplet {  
    
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      ControlP5 cp5;
    
      void settings() {
        size(500, 250, P2D);
      }
    
      void setup() {
        cp5 = new ControlP5(this);
        background(0);
    
        cp5.addSlider("vertices")
          .setPosition(25, 50)
          .setSize(200, 20)
          .setRange(0, 50);
      }
    
      void draw() {
        background(0);
    
        if (cID>-1) {
          fill(255);
          stroke(255);
          textSize(13);
          text(cID, width/2, 150);
        }
      }
    
      void vertices(int c) {
    
        if (cID==-1) 
          return; 
    
        Sphere s1 = s.get(cID); 
        s1.size = c;
        println("a slider event. ");
      }
      //
    } //class 
    //
    
  • Send value to a object

    Oh, im in a new trouble... In fact this piece of code is a reduction of a bigger program. What i really want is a "interface" to control another object. Now, we change the Sphere.size with a slider. but what i want to change when a Sphere.isclick is the size of another Obj...

    i try this, but it doesnt work. I try others variations without a result. I think you can help appying your cID logic...

    I thinks that is a really easy way.. Every Sphere on the screen represent an Obj when i click on that ellipse, i want change with a slider the "total" value for this Obj.

    (in the real code, the variable "total" represent the detail of a sphere)

    import controlP5.*;
    
    ArrayList<Sphere> s;
    ArrayList<Obj> obj;
    
    PWindow controller;
    int cID=-1;  
    
    void settings() {
      size(500, 500, P3D);
    }
    
    void setup() {
      controller = new PWindow();
    
      s = new ArrayList<Sphere>();
      obj = new ArrayList<Obj>();
    
      // add one sphere (optional)
      float size1 = 50; 
      Sphere newSphere = new Sphere(
        new PVector(random(size1, width-size1), random(size1, height-size1)), 
        255, 
        size1, 
        0); 
      s.add(newSphere);
    }
    
    void draw() {
      background(0);
      for (Sphere ss : s) {   
        ss.display();
        ss.isOver(mouseX, mouseY);
      }
    
      println(obj.size());
    }
    
    
    
    void mousePressed() {
      if (mouseButton==RIGHT) { 
        s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()));
        obj.add(new Obj(int(random(50)), s.size()));
        return; // leave here
      }
    
      //reset 
      cID=-1; 
    
      if (mouseButton==LEFT) {
    
    
    
    
        for (Sphere currentSphere : s) {
          if (currentSphere.over) {
    
            for (Obj o : obj) {
              o.printt();
              cID = currentSphere.id;
            }
    
            currentSphere.isClick = true;
            cID = currentSphere.id;
          } else {
            currentSphere.isClick = false;
          }
        }
      }
    }
    
    // ===========================================================
    
    class Sphere {
    
      color c; 
      float size;
      float x, y;
      PVector p = new PVector(0, 0);
      boolean over = false;
      boolean isClick = false;
      int id;
      int initialValue = 50;
    
      Sphere(PVector pos, 
        color _color, 
        float _size, 
        int _id) {
        // 
        p=pos.copy();
        c = _color;
        size = _size;
        id = _id;
      }//constr
    
      void display() {
        fill(c);  
        ellipse(p.x, p.y, 
          size, size);
      }
    
      boolean isOver(float px, float py) {
    
        ellipseMode(RADIUS);
    
        float d = dist(px, py, p.x, p.y);
        if (d < size) {
          over = true;
          c = 150;
          if (isClick) 
            c = 25; // color
          return true;
        } else {
          over = false;
          c = 255;
          if (isClick) 
            c = 25; // color
          return false;
        }
      }//func
    }//class
    
    // ===========================================================
    
    class Obj {
      int total;
      int id;
      Obj(int _total, int _id) {
        total = _total;
        id = _id;
      }
    
      void printt() {
        println(total);
      }
    }
    
    public class PWindow extends PApplet {  
    
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      ControlP5 cp5;
    
      int vertices = 50;
      float ss;
    
    
      Slider abc;
    
    
      void settings() {
        size(500, 250, P2D);
      }
    
      void setup() {
        cp5 = new ControlP5(this);
        background(0);
    
        cp5.addSlider("vertices")
          .setPosition(25, 50)
          .setSize(200, 20)
          .setRange(0, 50)
          ;
      }
    
      void draw() {
        background(0);
    
        if (cID>-1) {
          fill(255);
          stroke(255);
          textSize(13);
          text(cID, width/2, 150);
        }
      }
    
      void vertices(int c) {
    
        if (cID==-1) 
          return; 
    
        Obj o = obj.get(cID); 
        o.total = c;
        println("a slider event. ");
      }
    }//class 
    //
    
  • Send value to a object

    Also, instead of reading the slider throughout, it's better to use slider event

    see

    http://www.sojamo.de/libraries/controlP5/examples/controllers/ControlP5slider/ControlP5slider.pde

    Using size as ID

    here you had

          s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()+1));
    

    (s.size()+1)

    better

     s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()));
    

    s.size()

    New version

    (lots of other changes too)

    import controlP5.*;
    
    ArrayList<Sphere> s;
    PWindow controller;
    int cID=-1;  
    
    void settings() {
      size(500, 500, P3D);
    }
    
    void setup() {
      controller = new PWindow();
    
      s = new ArrayList<Sphere>();
    
      // add one sphere (optional)
      float size1 = 50; 
      Sphere newSphere = new Sphere(
        new PVector(random(size1, width-size1), random(size1, height-size1)), 
        255, 
        size1, 
        0); 
      s.add(newSphere);
    }
    
    void draw() {
      background(0);
      for (Sphere s : s) {
        s.display();
        s.isOver(mouseX, mouseY);
      }
    }
    
    //void select() {
    //  for (Sphere currentSphere : s) {
    //    if (currentSphere.isClick) {
    //      // println(currentSphere.id, "HOLA");
    //      currentSphere.c = 25; // color
    //      // println("");
    //    }
    //  }
    //}
    
    void mousePressed() {
      if (mouseButton==RIGHT) { 
        s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()));
        return; // leave here
      }
    
      //reset 
      cID=-1; 
    
      if (mouseButton==LEFT) {
        for (Sphere currentSphere : s) {
          if (currentSphere.over) {
            currentSphere.isClick = true;
            cID = currentSphere.id;
          } else {
            currentSphere.isClick = false;
          }
        }
      }
    }
    
    // ===========================================================
    
    class Sphere {
    
      color c; 
      float size;
      float x, y;
      PVector p = new PVector(0, 0);
      boolean over = false;
      boolean isClick = false;
      int id;
      int initialValue = 50;
    
      Sphere(PVector pos, 
        color _color, 
        float _size, 
        int _id) {
        // 
        p=pos.copy();
        c = _color;
        size = _size;
        id = _id;
      }//constr
    
      void display() {
        fill(c);  
        ellipse(p.x, p.y, 
          size, size);
      }
    
      boolean isOver(float px, float py) {
    
        ellipseMode(RADIUS);
    
        float d = dist(px, py, p.x, p.y);
        if (d < size) {
          over = true;
          c = 150;
          if (isClick) 
            c = 25; // color
          return true;
        } else {
          over = false;
          c = 255;
          if (isClick) 
            c = 25; // color
          return false;
        }
      }//func
    }//class
    
    // ===========================================================
    
    public class PWindow extends PApplet {  
    
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      ControlP5 cp5;
    
      int vertices = 50;
      float ss;
    
    
      Slider abc;
    
    
      void settings() {
        size(500, 250, P2D);
      }
    
      void setup() {
        cp5 = new ControlP5(this);
        background(0);
    
        cp5.addSlider("vertices")
          .setPosition(25, 50)
          .setSize(200, 20)
          .setRange(0, 50)
          ;
      }
    
      void draw() {
        background(0);
    
        if (cID>-1) {
          fill(255);
          stroke(255);
          textSize(13);
          text(cID, width/2, 150);
        }
      }
    
      void vertices(float c) {
    
        if (cID==-1) 
          return; 
    
        Sphere obj = s.get(cID); 
        obj.size = c;
        println("a slider event. ");
      }
    }//class 
    //
    
  • Send value to a object

    Hello everybody. I`ve a problem:

    I`ve a array of ellipse Objects. Every object has his variable of size in the constructor. In a second screen, via controlP5, a slider that change the size of every ellipse. What i want is change the size of an ellipse object when isClicked is true, and in that particular object, and store that value. But i cant, and i dont know exaclty why. I think that when i change the size in the constructor every object take the same value.

    here the code, sorry for my very bad english, hope you understand:

    (in resume: click the object, change it value, store the value. click in another object, and change it value (different of object 1)…etc.)

    import controlP5.*;
    
    ArrayList<Sphere>s;
    PWindow controller;
    
    
    void settings() {
      size(500, 500, P3D);
    }
    
    
    void setup() {
      controller = new PWindow();
    
      s = new ArrayList<Sphere>();
      s.add(new Sphere(new PVector(random(width), random(height)), 255, 50, 0));
    }
    
    void draw() {
      background(0);
      pushMatrix();
      select();
    
      for (Sphere s : s) {
        s.display();
        s.isOver(mouseX, mouseY);
      }
      popMatrix();
    }
    
    void select() {
      for (Sphere s : s) {
        if (s.isClick) {
          println(s.id, "HOLA");
          s.c = 25;
          println("");
        }
      }
    }
    
    void mousePressed() {
    
      if (mouseButton==RIGHT) s.add(new Sphere(new PVector(mouseX, mouseY), 255, 50, s.size()+1));
    
      for (Sphere s : s) {
        if (mouseButton==LEFT && s.over) {
          s.isClick = true;
        } else {
          s.isClick = false;
        }
      }
    }
    
    class Sphere {
    
      float c, size;
      float x, y;
      ArrayList<PVector> p = new ArrayList<PVector>();
      boolean over = false;
      boolean isClick = false;
      int id;
      int initialValue = 50;
    
      Sphere(PVector pos, float _color, float _size, int _id) {
        p.add(pos);
        c = _color;
        size = _size;
        id = _id;
      }
    
      void display() {
        for (PVector pos : p) {
          pushMatrix();
          translate(pos.x, pos.y);
          fill(c);  
          ellipse(0, 0, size, size);
          popMatrix();
        }
      }
    
      boolean isOver(float px, float py) {
        ellipseMode(RADIUS);
        for (PVector pos : p) {
          float d = dist(px, py, pos.x, pos.y);
          if (d < size) {
            over = true;
            c = 150;
            return true;
          } else {
            over = false;
            c = 255;
            return false;
          }
        }
        return false;
      }
    }
    public class PWindow extends PApplet {  
    
      PWindow() {
        super();
        PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
      }
    
      ControlP5 cp5;
    
      int vertices = 50;
      float ss;
    
    
      Slider abc;
    
    
      void settings() {
        size(500, 250, P2D);
      }
    
      void setup() {
        cp5 = new ControlP5(this);
        background(0);
    
    
        cp5.addSlider("vertices")
          .setPosition(25, 50)
          .setSize(200, 20)
          .setRange(0, 50)
          ;
      }
    
      void draw() {
        background(0);
    
        for (int i = s.size()-1; i >= 0; i--) {
          Sphere obj = s.get(i); 
          ss = vertices;
    
          if (obj.isClick==true) {
            fill(255);
            stroke(255);
            textSize(13);
            text(i, width/2, 150);
            println(i);
            obj.size = vertices;
          }
        }
      }
    
    }
    
  • How to use Grafica objects/methods in an independent window generated by G4P GUI builder

    Hi @FRV!

    Here is an example that displays two plots in two separate windows. I hope it helps you!

    /*
      Based on
      https://gist.github.com/atduskgreg/666e46c8408e2a33b09a
      https://forum.processing.org/two/discussion/12319/using-papplet-runsketch-to-create-multiple-windows-in-a-ps3-sketch
    */
    
    import grafica.*;
    
    GPlot plot1;
    GPlot plot2;
    
    void settings() {
      size(450, 300);
    }
    
    void setup() {
      // Start a new Processing applet
      MyPApplet newApplet = new MyPApplet();
      String[] args = {newApplet.getClass().getSimpleName()};
      PApplet.runSketch(args, newApplet);
    
      // Prepare the points for the first plot
      int nPoints = 100;
      GPointsArray points = new GPointsArray(nPoints);
    
      for (int i = 0; i < nPoints; i++) {
        points.add(i, 10*noise(0.1*i));
      }
    
      // Create the first plot
      plot1 = new GPlot(this);
    
      // Set the plot title and the axis labels
      plot1.setTitleText("Plot 1 in main Processing applet");
      plot1.getXAxis().setAxisLabelText("x axis");
      plot1.getYAxis().setAxisLabelText("y axis");
    
      // Add the points
      plot1.setPoints(points);
    
      // Activate the zooming and panning
      plot1.activateZooming();
      plot1.activatePanning();
    }
    
    void draw() {
      // Draw the first plot
      background(255);
      plot1.defaultDraw();
    }     
    
    
    public class MyPApplet extends PApplet {
    
      public void settings() {
        size(450, 300);
      }
    
      public void setup() {
        // Prepare the points for the second plot
        int nPoints = 100;
        GPointsArray points = new GPointsArray(nPoints);
    
        for (int i = 0; i < nPoints; i++) {
          points.add(i, 10*noise(0.1*i));
        }
    
        // Create the second plot ("this" reffers to the newApplet instance)
        plot2 = new GPlot(this);
    
        // Set the plot title and the axis labels
        plot2.setTitleText("Plot 2 in newApplet");
        plot2.getXAxis().setAxisLabelText("x axis");
        plot2.getYAxis().setAxisLabelText("y axis");
    
        // Add the points
        plot2.setPoints(points);
    
        // Activate the zooming and panning
        plot2.activateZooming();
        plot2.activatePanning();
      }
    
      public void draw() {
        // Draw the second plot
        background(255);
        plot2.defaultDraw();
      }
    }
    
  • stream video on second monitor

    Try this. It works in my machine: Win 10. If you set the display to zero, it takes both screens. If you set it to 1, it loads in one screen. If 2 is selected, it is loaded in the other screen.

    Kf

    import processing.video.*;
    
    PApplet projector0;
    PApplet projector1;
    
    void settings() {
      size(300, 300);
    }
    
    void setup() {
      smooth(4);
      noLoop();
      stroke(-1);
    
      projector0 = new ProjectorSketch();
      projector1 = new ProjectorSketch();
    
      runSketch(new String[] {  "--display=1", "--present", "--sketch-path=" + sketchPath(), "Projector" }, projector0);
    }
    
    void draw() {
      background(150);
    }
    
    
    
    class ProjectorSketchX extends PApplet {
    
      color bc;
    
      void settings() {
        size(600, 400);
      }
    
      void setup() {
        bc=color(150, 150, 0);
      }
    
      void draw() {
        background(bc);
      }
    }
    
    public class ProjectorSketch extends PApplet {
      Movie movie;
    
      public void settings() {
        //size(displayWidth, displayHeight, JAVA2D);
        size(400, 600);
      }
    
      public void setup() {
        stroke(#FFFF00);
        movie = new Movie(this, dataPath("transit.mov"));
        movie.loop();
      }
    
      public void draw() {
    
        image(movie, 0, 0, width, height);
      }
    
    
      public void movieEvent(Movie m) {
        m.read();
      }
    }
    

    Keyword: kf_keyword mainSketch, runSketch, multiple windows, multiple PApplets, main function

  • Per-pixel collision with arrays

    No line errors specified as it runs but then crashes? i guess. The console shows:

    The sketch path is not set. java.lang.RuntimeException: Files must be loaded inside setup() or after it has been called. at processing.core.PApplet.createInputRaw(PApplet.java:7030) at processing.core.PApplet.createInput(PApplet.java:7002) at processing.core.PApplet.loadBytes(PApplet.java:7292) at processing.core.PApplet.loadImage(PApplet.java:5428) at processing.core.PApplet.loadImage(PApplet.java:5350) at aPIXELCOLLISIONS.(aPIXELCOLLISIONS.java:23) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at processing.core.PApplet.runSketch(PApplet.java:10691) at processing.core.PApplet.main(PApplet.java:10467) The sketch path is not set. java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at processing.core.PApplet.runSketch(PApplet.java:10697) at processing.core.PApplet.main(PApplet.java:10467) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at processing.core.PApplet.runSketch(PApplet.java:10691) ... 1 more

    etc

  • stream video on second monitor

    Hi All, i would be able to stream two video on two different monitor, at the same time. So far this is the code i written to stream one on the secondary monitor, but is not working:

    import processing.video.*;
    
    final PApplet projector0 = new ProjectorSketch();
    final PApplet projector1 = new ProjectorSketch();
    
    void setup() {
      size(300, 300, JAVA2D);
      smooth(4);
      noLoop();
      stroke(-1);
    
      runSketch(new String[] { "--display=1", "--present",  "--sketch-path=" + sketchPath(), "Projector" }, projector0);
    
    }
    
    void draw() {
      background(0);
    }
    
    
    class ProjectorSketch extends PApplet {
      Movie movie;
    
    
     void setup() {
    
       stroke(#FFFF00);
       movie = new Movie(this, "transit.mov");
      movie.loop();
    
       }
    
    
      public void settings() {
        size(displayWidth, displayHeight, JAVA2D);
    
      }
    
      void draw() {
    
      image(movie, 0, 0, width, height);
      }
    }
    
    public void movieEvent(Movie m) {
      m.read();
    }
    
  • with second applet, strange errors about createGraphics
    PGraphics canvas;
    
    void setup() {
      size(400, 400, P3D);
      canvas = createGraphics(400, 400, P3D);
    
      String[] args = {"YourSketchNameHere"};
      SecondApplet sa = new SecondApplet();
      PApplet.runSketch(args, sa);
    }
    
    void draw() {
    
      canvas.beginDraw();
      canvas.background(127);
      canvas.lights();
      canvas.translate(width/2, height/2);
      canvas.rotateX(frameCount * 0.01);
      canvas.rotateY(frameCount * 0.01);  
      canvas.box(150);
      canvas.endDraw();
      image(canvas, 0, 0);
    }     
    
    public class SecondApplet extends PApplet {
    
      public void settings() {
        size(200, 100,P3D);
      }
      public void draw() {
        background(255);
        fill(0);
        ellipse(100, 50, 10, 10);
      }
    }
    

    With that code I get "createGraphics() requires size to use P3D or P2D" (paraphrasing)

    Or if I try to create an instance of a Syphon window, for example, I get null pointer.

    What's the deal? My goal is to create a 2-window app with Syphon output from one window and a P5 control setup on the other.

  • java cannot run processing, quits with the following error: Error: Could not find or load main class

    If you create a simple sketch in the PDE and then export it from there, you will see that you need other jar files. This is important specially when you are working with the P2D renderer.


    Have you tried using processing-java to create your executable?


    Before running the command, we need to implement the following changes:

    • Class names start with upper case as in Test and not test.
    • As a mention above, OpenGL requires extra libs. For the time being, drop the P2D parameter in your size(). After all, this is just a demo to show how to run it using javac.
    • Your main should look like this (From HappyCoding @KevinWorkman):

      public static void main(String[]args){
          String[] processingArgs = {"Test"};
          Test mySketch = new Test();
          PApplet.runSketch(processingArgs, mySketch);
      }
      

    Now you execute:

    javac -cp ".;C:\Users\C\Downloads\downloaded_installers\P3\current\processing\core\library\core.jar" Test.java
    
    java -cp ".;C:\Users\C\Downloads\downloaded_installers\P3\current\processing\core\library\core.jar" Test
    

    Note that if you execute javac -help you will see some other convenient arguments Notice in Windows you use ; while in Linux you would use :

    This should get you started.

    Kf


    Relevant posts:

    http://happycoding.io/tutorials/java/processing-in-java
    https://github.com/processing/processing/wiki/Command-Line
    https://forum.processing.org/two/discussion/7375/how-to-compile-a-sketch-to-java
    https://forum.processing.org/two/discussion/23924/handling-command-line-arguments-in-a-sketch
    https://www.programcreek.com/2014/01/compile-and-run-java-in-command-line-with-external-jars/

    https://rishisoftwareblog.wordpress.com/2013/02/12/compiling-and-executing-a-processing-sketch-as-a-java-class/

    https://forum.processing.org/two/discussion/21204/using-launch4j-jarmatey-with-processing
    http://launch4j.sourceforge.net/
    https://github.com/processing/processing/tree/master/java/application/launch4j

  • Using Java 9 (jre-9.0.4) in Processing (3.3.7)

    Well, I'm happy PDE's pre-processor "eliminates" this whole "complicated" block: \m/

    import processing.core.*;
    
    class MyPApplet extends PApplet {
      public static void main(String[] args) {
        runSketch(platformNames, new PApplet());
      }
    }
    

    That thing is what makes Java worse for beginners than Python! 3:-O
    Remove that outta sight and Java can finally be used for teaching beginners as well! :>

  • Using Java 9 (jre-9.0.4) in Processing (3.3.7)

    Hello everybody,

    we are using a .jar library in our processing (3.3.7) sketch, which is based on java9. Is there a way to direkt the processing sketch to java9?

    Thanks in advance, for any kind of suggestions!

    This is the error:

    java.lang.UnsupportedClassVersionError: ________________ has been compiled by a more recent version of the Java Runtime (class file version 53.0), this version of the Java Runtime only recognizes class file versions up to 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.getDeclaredConstructors0(Native Method)
        at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
        at java.lang.Class.getConstructor0(Class.java:3075)
        at java.lang.Class.getDeclaredConstructor(Class.java:2178)
        at processing.core.PApplet.runSketch(PApplet.java:10691)
        at processing.core.PApplet.main(PApplet.java:10467)
    This version of Processing only supports libraries and JAR files compiled for Java 1.6 or earlier.
    A library used by this sketch was compiled for Java 1.7 or later, 
    and needs to be recompiled to be compatible with Java 1.6.
    
  • ArrayList - ConcurrentModificationException

    hey, im trying to add Objects into an arrayList that is a part of a class, from a second Papplet,(when the user click the mouse, add a new Obj). But it doesnt work properly, an concurrent modification exception is crashing the sketch:

    here the code:

    the main scene 3D

    System s;
    PWindow w;
    void settings() {
      s = new System();
      size(500, 500, P3D);
    
    }
    
    void setup() {
      background(0);
      s = new System();
      w = new PWindow();
    }
    
    void draw() {
      background(0);
      pushMatrix();
      translate(width/2, height/2);
      s.run();
      popMatrix();
    }
    
    class System {
      ArrayList<Obj>o;
      System() {
        o = new ArrayList<Obj>();
      }
    
      void addObj(float x, float z) {
        o.add(new Obj(new PVector(x, 0, z)));
      }
    
    
      void run() {
        for (Obj obj : o) {
          obj.display();
        }
      }
    
    }
    
    class Obj {
    
      PVector pos;
    
      Obj(PVector o) {
        pos = o.get();
      }
    
      void display() {
        pushMatrix();
        translate(pos.x, pos.y, pos.z);
        sphere(100);
        popMatrix();
      }
    }
    

    the second Papplet , when the user click the screen, add a new Obj

        class PWindow extends PApplet {
    
          PWindow() {
            super();
            PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
          }
    
    
          void settings() {
            size(500, 500, P2D);
          }
    
          void setup() {
          }
    
          void draw() {
            for(Obj o : s.o){
            ellipse(o.pos.x, o.pos.z, 20, 20);
            }
          }
    
          void mousePressed(){
          s.addObj(mouseX,mouseY);
          }
    
    
        }
    
  • Null Pointer Exception in Eclipse using JUnit and Comparator

    Thanks Kevin. That really helped me out.

    It is a little silly but I've been learning about JUnit in my Java class and I wanted to see if I could use it in my processing projects. It's not that practical in most cases but I like having the option.

    Here is the working code I came up with if anyone ends up doing something similar:

    package graham.wilfred.pixelsort;
    
    import static org.junit.Assert.assertEquals;
    import java.util.Comparator;
    import org.junit.jupiter.api.AfterEach;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.DisplayName;
    import org.junit.jupiter.api.Test;
    import processing.core.PApplet;
    
    public class AlphaComparatorTest {
    
        PApplet app;
        Comparator<Integer> instance;
    
        @BeforeEach
        public void before() {
            app = new PApplet();
            String[] args = { "graham.wilfred.pixelsort.AlphaComparatorTest" };
            PApplet.runSketch(args, app);
            instance = new AlphaComparator(app);;
        }
    
        @Test
        @DisplayName("AlphaComparator -- Equal Alpha Value Test")
        void equalAlpha() {
            int testColor1, testColor2;
            for (int i = 0; i <= 255; i++) {
                testColor1 = app.color(i, i);
                testColor2 = app.color(255 - i, i);
                assertEquals(instance.compare(testColor1, testColor2), 0);
            }
        }
    
        @AfterEach
        public void after() {
            app.stop();
        }
    
    }
    

    And the Comparator:

    package graham.wilfred.pixelsort;
    
    import java.util.Comparator;
    import processing.core.PApplet;
    
    public class AlphaComparator implements Comparator<Integer> {
    
        PApplet parent;
    
        public AlphaComparator(PApplet p) {
            parent = p;
        }
    
        public int compare(Integer o1, Integer o2) {
            Float b1 = parent.alpha(o1);
            Float b2 = parent.alpha(o2);
            return b1.compareTo(b2);
        }
    
    }
    
  • Mouse focus with multiple windows

    Focus only in current active window which you activate by clicking within the sketch window. Check the demo below. I added some other things that you don't need btw.

    This demo creates a master window and three slave windows which are randomly placed within your display. Click any of the slave windows.

    Kf

    //REFERENCE: https://github.com/processing/processing/issues/1700
    //REFERENCE: https://forum.processing.org/two/discussion/4712/window-location
    //REFERENCE: https://github.com/processing/processing/wiki/Library-Basics
    
    
    import java.awt.*;
    
    final int UNKNOWN=-1;
    
    int ctr=100;
    int currentWindow=UNKNOWN;
    
    
    void setup() {
      size(300, 100);
      fill(144);
      textAlign(CENTER,CENTER);
    
    
      createSketch(ctr++, "Slave Sketch");
      createSketch(ctr++, "Slave Sketch");
      createSketch(ctr++, "Slave Sketch");
    }
    
    
    
    void draw() {
    
      background(0);
      textSize(24);
      text("MASTER\n"+currentWindow,width/2,height/4);
    
       textSize(10);
      text("Click on any window",width/2,height*0.75);
    }  
    
    
    void createSketch(int handle, String name) {
    
      String[] args ={this.toString()};  //Need to attach current name which is stripped by the new sketch 
      String[] newArgs = {name, str(handle)};
      SecondApplet sa = new SecondApplet();
      PApplet.runSketch(concat(args, newArgs), sa);
    }
    
    void mousePressed(){
      currentWindow=UNKNOWN;
    }
    
    
    public class SecondApplet extends PApplet {
    
      String cname;
      int handle;
    
      public void settings() {
        size(200, 300);
      }
      public void setup() {
        println(args);
        cname=args[0];
        handle=int(args[1]);
        getSurface().setTitle(cname+":"+handle);
    
    
        noFill();
    
        registerMethod("pre", this);
      }
    
      void pre() {
        //Frame needs to exist before you call this method
        getSurface().setLocation((int)random(width, displayWidth-width), (int)random(height, displayHeight-height)); 
        unregisterMethod("pre", this);
      }
    
      public void draw() {
        if (focused==true) {
    
          background(0);
          fill(random(255), random(255), random(255));
          ellipse(width/2, height/2, 50, 50);
          currentWindow=handle;
        } else {
    
          background(255);
          fill(0);
          ellipse(100, 50, 10, 10);
    
          //This is done to save unnecessary calls to draw.
          //Recovers when sketch re-gains focus.
          //Only applies to this demonstration.
          noLoop();
        }
      }
    
      void mousePressed() {
    
        //Recover draw's continuous updates
        loop();
    
        //This next doesn't need to be done here as it is handle by the Window object. 
        //However, not doing this shows that you will have inconsistent nehavior 
        //between the mouse event, the focus action and the draw() method. In other
        //words, it seems that draw is not able to see the that focus was gained on time
        focused=true;
      }
    }
    
  • launch() won't launch my compiled processing sketch

    From the example I provided in my most recent link, I did this:

    launch(sketchPath("")+"runSketch.bat");

    This assumes the bat file is in your sketch folder. Within the bat file you should do this:

    cd d:\\folder\\containing\\exec\file
    mySketch.exe
    

    Does this work for you?

    Kf