Howdy, Stranger!

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

  • Surface doesn't work in Python mode

    @pxlmnkeee, any PApplet public member not yet available in globals():

    for k, v in enumerate(globals().items()): print k, v
    exit()
    

    Can be accessed by prefixing them w/ this.. :-B

    You can see in my 1st reply example, I can access the non-globals() member getSurface() either w/ this.getSurface() or this.surface. :ar!

    Also, you can import any Processing classes not yet available in globals() via from package.name import class.

    For example, we can import the non-globals() class IntList like this: :bz
    https://Processing.org/reference/IntList.html

    from processing.data import IntList
    print dir(IntList)
    exit()
    

    Or even something more "obscure" like the PGL class: >-)
    https://GitHub.com/processing/processing/blob/master/core/src/processing/opengl/PGL.java

    from processing.opengl import PGL
    print dir(PGL)
    exit()
    
  • Converting Java code to Python

    Hi @solub! It took a long time, but I've just finished refactoring "Depth_of_Field.pde". #:-S

    Now that I've reorganized this sketch, I'm ready to convert it to a ".pyde" file. :)>-

    Just w8 a lil' more. Stay w/ the latest ".pde" file for now: :-\"

    /**
     * Depth of Field (DoF) (1.20)
     * Thomas Diewald (diwi) (2017-Oct-07)
    
     * GitHub.com/diwi/PixelFlow/blob/master/examples/Miscellaneous/
     * DepthOfField_Demo/DepthOfField_Demo.java
    
     * Refactor by GoToLoop (v1.4.2) (2018-May-18) (PDE v3.3.5)
     * Forum.Processing.org/two/discussion/27905/converting-java-code-to-python#Item_18
     */
    
    import com.thomasdiewald.pixelflow.java.DwPixelFlow;
    import com.thomasdiewald.pixelflow.java.geometry.DwIndexedFaceSetAble;
    import com.thomasdiewald.pixelflow.java.geometry.DwCube;
    import com.thomasdiewald.pixelflow.java.geometry.DwMeshUtils;
    import com.thomasdiewald.pixelflow.java.imageprocessing.filter.DepthOfField;
    import com.thomasdiewald.pixelflow.java.imageprocessing.filter.DwFilter;
    import com.thomasdiewald.pixelflow.java.render.skylight.DwSceneDisplay;
    import com.thomasdiewald.pixelflow.java.render.skylight.DwScreenSpaceGeometryBuffer;
    import com.thomasdiewald.pixelflow.java.utils.DwMagnifier;
    import com.thomasdiewald.pixelflow.java.utils.DwUtils;
    
    import peasy.PeasyCam;
    
    import com.jogamp.opengl.GL2;
    
    import static java.util.Locale.ENGLISH;
    import java.util.Formatter;
    
    final Formatter formatter = new Formatter(ENGLISH);
    
    static final String POSITION = "position: (%8.2f, %8.2f, %8.2f)\n";
    static final String ROTATION = "rotation: (%8.2f, %8.2f, %8.2f)\n";
    static final String LOOK__AT = "look-at:  (%8.2f, %8.2f, %8.2f)\n";
    static final String DISTANCE = "distance: (%8.2f)\n";
    
    final String TITLE = getClass().getName() + "   [fps %6.2f]";
    
    static final int BB_SIZE = 800, BB_OFFSET = BB_SIZE >> 2;
    static final int BB_TOTAL = BB_SIZE + BB_OFFSET;
    static final int BB_COORD = -BB_TOTAL, BB_DIAM = BB_TOTAL << 1;
    
    static final int XMIN = -BB_SIZE, XMAX = BB_SIZE;
    static final int YMIN = -BB_SIZE, YMAX = BB_SIZE;
    static final int ZMIN = 0, ZMAX = BB_SIZE;
    
    static final int BOX_DIAM = BB_OFFSET + BB_OFFSET/20;
    static final int SPH_MIN_D = BB_OFFSET >> 2, SPH_MAX_D = BB_OFFSET >> 1;
    
    static final int BOXES = 50, SPHERES = 50;
    
    static final int CROSS_S = 10, ZFAR = 6000;
    static final int MULT_BLUR = 30, BLUR_POW = (int) pow(MULT_BLUR, 1/3.0);
    static final float RAD60 = 60*DEG_TO_RAD, FPS = 60;
    
    static final color BASE_COL = 0x80FFFFFF, CROSS_COL = 0xd0FFFFFF;
    
    static final long SEED = 0;
    static final boolean FIXED_SEED = false;
    
    static final boolean FULLSCREEN = false, RESIZABLE = false;
    boolean apply_dof = false, alt_render = false;
    
    final boolean[] resized = new boolean[1];
    
    final DwIndexedFaceSetAble cube_smooth = new DwCube(4), cube_facets = new DwCube(2);
    
    PGraphics3D pg_render, pg_dof, pg_tmp;
    PShape shp_scene;
    
    PeasyCam peasy;
    
    DwPixelFlow context;
    DwFilter dw_filter;
    DepthOfField dof;
    DwScreenSpaceGeometryBuffer geombuffer;
    DwMagnifier magnifier;
    
    void settings() {
      if (FULLSCREEN) fullScreen(P3D);
      else size(displayWidth*9/10, displayHeight*9/10, P3D);
      noSmooth();
    }
    
    void setup() {
      frameRate(FPS);
      cursor(CROSS);
    
      if (RESIZABLE)  getSurface().setResizable(true);
      getSurface().setLocation(displayWidth - width >> 1, 8);
    
      peasy = new PeasyCam(this, -4.083, -6.096, 7, 2000);
      peasy.setRotations(1.085, -.477, 2.91);
    
      dw_filter = DwFilter.get(context = new DwPixelFlow(this));
      context.print();
      context.printGL();
    
      dof = new DepthOfField(context);
      dof.param.mult_blur = MULT_BLUR;
    
      final DwSceneDisplay scene_display = new DwSceneDisplay() {  
        @ Override final public void display(final PGraphics3D canvas) {
          displayScene(canvas);
        }
      };
    
      geombuffer = new DwScreenSpaceGeometryBuffer(context, scene_display);
    
      final int mag_h = height/3;
      magnifier = new DwMagnifier(this, 4, 0, height - mag_h, mag_h, mag_h);
    }
    
    void draw() {
      final PGraphics canv = getGraphics();
      final DepthOfField.Param param = dof.param;
    
      setTitle();
      resizeScreen();
      displaySceneWrap(pg_render, canv);
      dw_filter.gamma.apply(pg_render, pg_render);
    
      if (apply_dof)  applyDoF(param);
      renderScene(param, canv);
    }
    
    void keyPressed() {
      final int k = keyCode;
    
      if (k == ENTER | k == RETURN)  shp_scene = null;
      else if (k == 'C' | k == CONTROL)  printCam();
      else if (k == 'P' | k == BACKSPACE)  looping ^= true;
      else if (k == ' ')  apply_dof ^= true;
      else if (k == SHIFT)  alt_render ^= true;
    }
    
    void applyDoF(final DepthOfField.Param param) {
      final PGraphicsOpenGL geom = geombuffer.pg_geom;
      dw_filter.gaussblur.apply(geom, geom, pg_tmp, BLUR_POW);
    
      param.focus_pos[0] = map(mouseX + .5, 0, width, 00, 1);
      param.focus_pos[1] = map(mouseY + .5, 0, height, 1, 0);
      dof.apply(pg_render, pg_dof, geombuffer);
    
      dw_filter.copy.apply(pg_dof, pg_render);
    }
    
    void renderScene(final DepthOfField.Param param, final PGraphics canv) {
      final PGraphics pg = alt_render? geombuffer.pg_geom : pg_render;
    
      magnifier.apply(pg, mouseX, mouseY);
      magnifier.displayTool();
    
      DwUtils.beginScreen2D(canv);
      //peasy.beginHUD();
    
      blendMode(REPLACE);
      image(pg, 0, 0);
      magnifier.display(pg, 0, height - magnifier.h);
    
      final float fpx = param.focus_pos[0] * width;
      final float fpy = (1 - param.focus_pos[1]) * height;
    
      blendMode(EXCLUSION);
      strokeCap(PROJECT);
      stroke(CROSS_COL);
      line(fpx - CROSS_S, fpy, fpx + CROSS_S, fpy);
      line(fpx, fpy - CROSS_S, fpx, fpy + CROSS_S);
      blendMode(BLEND);
    
      //peasy.endHUD();
      DwUtils.endScreen2D(canv);
    }
    
    boolean resizeScreen() { // dynamically resize render-targets
      final int w = width, h = height;
    
      perspective(RAD60, (float) w/h, 2, ZFAR);
      peasy.feed();
    
      boolean happened = resized[0] = false;
      pg_render = DwUtils.changeTextureSize(this, pg_render, w, h, 8, resized);
      happened |= resized[0];
    
      resized[0] = false;
      pg_dof = DwUtils.changeTextureSize(this, pg_dof, w, h, 0, resized);
      happened |= resized[0];
    
      resized[0] = false;
      pg_tmp = DwUtils.changeTextureSize(this, pg_tmp, w, h, 0, resized, 
        GL2.GL_RGBA16F, GL2.GL_RGBA, GL2.GL_FLOAT);
    
      geombuffer.update(pg_render);
      return happened | resized[0];
    }
    
    void displaySceneWrap(final PGraphics3D canvas, final PGraphics canv) {
      DwUtils.copyMatrices((PGraphicsOpenGL) canv, canvas);
      canvas.beginDraw();
      canvas.background(2);
      displayScene(canvas);
      canvas.endDraw();
    }
    
    void displayScene(final PGraphics3D canvas) {
      canvas.directionalLight(255, 255, 255, 200, 600, 400);
      canvas.directionalLight(255, 255, 255, -200, -600, -400);
      canvas.ambientLight(64, 64, 64);
    
      if (canvas == geombuffer.pg_geom) {
        canvas.background(-1);
        canvas.pgl.clearColor(1, 1, 1, ZFAR);
        canvas.pgl.clear(PGL.COLOR_BUFFER_BIT);
      }
    
      if (shp_scene == null)  shp_scene = makeShape();
      canvas.shape(shp_scene);
    }
    
    PShape makeShape() {
      final PShape scene = createShape(GROUP);
    
      pushStyle();
      colorMode(HSB, 360, 1, 1);
      noStroke();
    
      if (FIXED_SEED)  randomSeed(SEED);
    
      for (int i = 0; i < BOXES; ++i) {
        final float px = random(XMIN, XMAX), py = random(YMIN, YMAX);
        final float sx = random(BOX_DIAM, BOX_DIAM), sy = random(BOX_DIAM, BOX_DIAM);
        final float sz = random(ZMIN, ZMAX);
    
        fill(random(-45, 45), 1, random(.1, 1));
        final PShape shp_box = createShape(BOX, sx, sy, sz);
        shp_box.translate(px, py, sz*.5);
        scene.addChild(shp_box);
      }
    
      for (int i = 0; i < SPHERES; ++i) {
        final float px = random(XMIN, XMAX), py = random(YMIN, YMAX);
        final float pz = random(ZMIN, ZMAX), rr = random(SPH_MIN_D, SPH_MAX_D);
    
        fill(random(205, 245), 1, random(.1, 1));
        final PShape shp_sphere = createShape(PShape.GEOMETRY);
        shp_sphere.scale(rr);
        shp_sphere.translate(px, py, pz);
        scene.addChild(shp_sphere);
    
        if ((i&1) == 0)
          DwMeshUtils.createPolyhedronShape(shp_sphere, cube_facets, 1, 4, false);
        else
          DwMeshUtils.createPolyhedronShape(shp_sphere, cube_smooth, 1, 4, true);
      }
    
      fill(BASE_COL);
      scene.addChild(createShape(RECT, BB_COORD, BB_COORD, BB_DIAM, BB_DIAM));
    
      popStyle();
      return scene;
    }
    
    static final void clearFormatter(final Formatter f) {
      ((StringBuilder) f.out()).setLength(0);
    }
    
    void setTitle() {
      clearFormatter(formatter);
      getSurface().setTitle(formatter.format(TITLE, frameRate).toString());
    }
    
    void printCam() {
      final float[] pos = peasy.getPosition();
      final float[] rot = peasy.getRotations();
      final float[] lat = peasy.getLookAt();
      final double  dis = peasy.getDistance();
    
      clearFormatter(formatter);
    
      println(formatter.
        format(POSITION, pos[0], pos[1], pos[2]).
        format(ROTATION, rot[0], rot[1], rot[2]).
        format(LOOK__AT, lat[0], lat[1], lat[2]).
        format(DISTANCE, dis));
    }
    
  • Disable maximize button?

    Thanks kfrajer, but that only seems to work with the default renderer, not P2D or P3D.

    import processing.awt.PSurfaceAWT.SmoothCanvas;
    import com.sun.awt.AWTUtilities;
    import javax.swing.JFrame;
    import javax.swing.JRootPane;
    
    JFrame jframe;
    
    static final JFrame getJFrame(final PSurface surf) {
      return (JFrame) ((SmoothCanvas) surf.getNative()).getFrame();
    }
    
    
    
    void setup() {
      size(500, 500,P3D);
      //size(500, 500);
      jframe = getJFrame(getSurface());
    }
    
    int i = 0;
    void draw(){
      background(i);
      i++;
      if (i>255) i=0;
    }
    

    That works but only with the default renderer.

    It errors,

    No library found for processing.awt.PSurfaceAWT

    No library found for com.sun.aw

    Also I couldn't any hooks for the window being resized, like onResize() or something similar. Is there an index of all the built in processing hooks (like void mouseMoved()) i couldn't find such a list in the reference.

  • Countdown Class library for Java, JS & Python

    Java Mode Version:

    https://Gist.GitHub.com/GoToLoop/ea4db8a8622e27541213da3c9a43ca21

    "CountdownClass.pde":

    /** 
     * Countdown Class (v1.2.5)
     * GoToLoop (2017/Aug/26)
     *
     * Forum.Processing.org/two/discussion/27733/
     * countdown-class-library-for-java-js-python
     *
     * Forum.Processing.org/two/discussion/23846/
     * time-delay-in-python-mode#Item_11
     *
     * Gist.GitHub.com/GoToLoop/ea4db8a8622e27541213da3c9a43ca21
     */
    
    import gotoloop.countdown.Countdown;
    
    static final float SECS = 7.5;
    static final int WAIT_TIME = (int) (SECS * 1000);
    
    static final String AWAIT = "Awaiting " + SECS;
    static final String END = "Countdown Finished";
    
    static final color WAITING_BG = PImage.BLUE_MASK | PImage.ALPHA_MASK;
    static final color DONE_BG = PImage.RED_MASK | PImage.ALPHA_MASK;
    
    final Countdown countdown = new Countdown(WAIT_TIME);
    
    void setup() {
      size(300, 180);
      smooth(3);
      frameRate(60);
    
      colorMode(RGB);
      fill(#FFFF00);
    
      textSize(0100);
      textAlign(CENTER, CENTER);
    
      final int m = millis(), t = m + WAIT_TIME;
      countdown.start();
      println(m, t, t - m, TAB, countdown);
    }
    
    void draw() {
      getSurface().setTitle(countdown.done? END : AWAIT);
      background(countdown.done? DONE_BG : WAITING_BG);
    
      final String txt = millis() + "\n" + frameCount;
      text(txt, width>>1, height>>1);
    }
    

    "Countdown.java":

    /** 
     * Countdown Class (v1.2.5)
     * GoToLoop (2017/Aug/26)
     *
     * https://Forum.Processing.org/two/discussion/27733/
     * countdown-class-library-for-java-js-python
     *
     * https://Forum.Processing.org/two/discussion/23846/
     * time-delay-in-python-mode#Item_11
     *
     * https://Gist.GitHub.com/GoToLoop/ea4db8a8622e27541213da3c9a43ca21
     */
    
    package gotoloop.countdown;
    
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class Countdown {
      protected static final Timer t = new Timer("Countdown");
    
      public TimerTask task;
      public int delay;
      public volatile boolean done = true;
    
      public Countdown() {
      }
    
      public Countdown(final int waitTime) { // milliseconds
        delay = Math.abs(waitTime);
      }
    
      @Override public String toString() {
        return "Delay: " + delay + "  -  Done: " + done;
      }
    
      public Countdown start() {
        if (task != null)  task.cancel();
        done = false;
        t.schedule(task = new Timeout(), delay);
        return this;
      }
    
      protected class Timeout extends TimerTask {
        @Override public void run() {
          done = true;
        }
      }
    }
    
  • Paste and Copy text

    Hello,

    here you can get text data from the Win 10 clipboard inside your running sketch (you paste into the variable a1)

    use space bar for ctrl-v (does run in P2D, not in P3D afaik)

    Chrisir

    // https: // forum.processing.org/two/discussion/27473/paste-and-copy-text#latest
    // https: // forum.processing.org/two/discussion/17270/why-this-getx-method-is-missing-in-processing-3-1-1
    
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.UnsupportedFlavorException;
    
    String a1=""; 
    
    void setup() {
      size(660, 660);
      a1 = GetTextFromClipboard();
    }
    
    void draw() {
      //
      background(0); 
      textAlign(CENTER);
      text("Hit space bar to paste from clipboard (Win 10, processing 3.3.7)", width/2, 26);
      text(a1, width/2, 66);
    }
    
    // --------------------------------------------------------------
    
    void keyPressed() {
      if (key==' ') {
        a1 = GetTextFromClipboard ();
      }
    }
    
    String GetTextFromClipboard () {
      String text = (String) GetFromClipboard(DataFlavor.stringFlavor);
    
      if (text==null) 
        return "";
    
      return text;
    }
    
    Object GetFromClipboard (DataFlavor flavor) {
    
      Clipboard clipboard = getJFrame(getSurface()).getToolkit().getSystemClipboard();
    
      Transferable contents = clipboard.getContents(null);
      Object object = null; // the potential result 
    
      if (contents != null && contents.isDataFlavorSupported(flavor)) {
        try
        {
          object = contents.getTransferData(flavor);
          println ("Clipboard.GetFromClipboard() >> Object transferred from clipboard.");
        }
    
        catch (UnsupportedFlavorException e1) // Unlikely but we must catch it
        {
          println("Clipboard.GetFromClipboard() >> Unsupported flavor: " + e1);
          e1.printStackTrace();
        }
    
        catch (java.io.IOException e2)
        {
          println("Clipboard.GetFromClipboard() >> Unavailable data: " + e2);
          e2.printStackTrace() ;
        }
      }
    
      return object;
    } 
    
    static final javax.swing.JFrame getJFrame(final PSurface surf) {
      return
        (javax.swing.JFrame)
        ((processing.awt.PSurfaceAWT.SmoothCanvas)
        surf.getNative()).getFrame();
    }
    //
    
  • WindowJS - cross-mode alert(), confirm(), prompt() & other JS API for Java

    this works, I needed the class in test tab

    in the 2nd tab Inputs.java I had to comment out the package

    // package iadt.creative;
    

    I also receive huge bunch of warnings but it runs now in 2D

    /**
    
     https : // forum.processing.org/two/discussion/comment/119754#Comment_119754
    
    
     * Keyboard Input Library
     * Andrew Errity v0.2 (2015-Oct-01)
     * GoToLoop v1.0.2 (2015-Oct-22)
     *
     * https://Forum.Processing.org/two/discussion/13175/
     * do-whille-is-not-working-how-it-suppose-to#Item_12
     *
     * https://GitHub.com/aerrity/Inputs/blob/master/src/Inputs.java
     * https://Gist.GitHub.com/GoToLoop/bba0c288aaeeb5ef9bb1
     */
    
    //import iadt.creative.Inputs.*;
    
    
    Inputs in1 = new Inputs();   // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    
    void setup() {
      getSurface().setVisible(false);
    
      byte age;
      do {
        while ((age = in1.readByte("Enter your age:")) < 0);  //!!!!
        println("Your age is:", age);
      } while (in1.readBoolean("Again?"));     // !!!!!
    
      exit();
    }
    
    //
    
  • 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;
      }
    }
    
  • fullscreen() span on 2 displays in Ubuntu unity

    Ah, the fun of Unity! :-) Easy way would be to switch to a different window manager for this - Unity isn't great for full screen displays, particularly with multiple monitors. It doesn't seem possible to get it to respond to setting the size bigger than the screen size, despite allowing you to do this manually.

    Bit of Googling suggests the ability to hack the Unity settings with CCSM to make two monitors appear as one. You'll also find lots of problems with other software and this too!

    You might be able to get access to the native JOGL window (getSurface().getNative()) and move it around, but that's going to take some digging - just tried a few simple things and couldn't get it to work.

  • Add WindowListener / Listen to window changing state

    getSurface.setResizable(false);

    alas, this is the default for the canvas (Windows OS here) so my maximize button is disabled. Now, would removing the top frame of your window solve the problem? I mean, removing the top bar where the min/max and close button are located?

    Kf

  • How to draw a rect() in a Thread

    https://Forum.Processing.org/two/discussion/15473/readme-how-to-format-code-and-text

    /**
     * Threaded PGraphics (v1.1.1)
     * GoToLoop (2018/Jan/03)
     *
     * Forum.Processing.org/two/discussion/25799/
     * how-to-draw-a-rect-in-a-thread#Item_2
     */
    
    static final float FPS = 10;
    final Layer layer = new Layer();
    
    void setup() {
      size(250, 200);
      smooth(3);
      frameRate(FPS);
    
      colorMode(RGB);
      imageMode(CORNER);
    
      layer.start();
      while (layer.pg == null || layer.pg.height != height)  delay(1);
    }
    
    void draw() {
      getSurface().setTitle("Frames: " + frameCount);
      background((color) random(#000000));
      image(layer.pg, 0, 0);
    }
    
    class Layer extends Thread {
      static final short INTERVAL = 1*1000, TXT_SIZE = 40;
      static final float BOLD = 2.5;
      static final color BORDER = 0, TXT_COLOR = -1;
    
      PGraphics pg;
    
      void run() {
        initDisplay();
        displayLoop();
      }
    
      void initDisplay() {
        pg = createGraphics(width, height, JAVA2D);
        pg.beginDraw();
    
        pg.smooth(3);
        pg.colorMode(RGB);
        pg.rectMode(CENTER);
    
        pg.strokeWeight(BOLD);
        pg.stroke(BORDER);
    
        pg.textSize(TXT_SIZE);
        pg.textAlign(CENTER, CENTER);
    
        pg.endDraw();
      }
    
      void displayLoop() {
        final int cx = pg.width>>1, cy = pg.height>>1;
    
        for (int frames = 1;; delay(INTERVAL), ++frames) {
          pg.beginDraw();
    
          pg.clear();
          pg.fill((color) random(#000000));
          pg.rect(cx, cy, cx, cy);
    
          pg.fill(TXT_COLOR);
          pg.text(frames, cx, cy);
    
          pg.endDraw();
        }
      }
    }
    
  • Processing with mouse click

    @GoToLoop yes ofcourse you're right, my bad.

        static final boolean JAVA = 1/2 != 1/2.;  //why 1/2 and static
        static final color[] PALETTE = { #FF0000, #008000, #0000FF }; //this is hex
        int idx;   //what other word would you use here
    
        void setup() {
          size(300, 200);
          noLoop();
          colorMode(RGB);
        }
    
        void draw() {
          final color c = PALETTE[idx]; //so [] means it's an array right?
          background(c);
          if (JAVA)  getSurface().setTitle("Color: " + idx + "  -  #" + hex(c, 6)); //Could you explain what happens here precisely?
        }
    
        void mousePressed() {
          keyPressed();
        }
    
        void keyPressed() {
          idx = (idx + 1) % PALETTE.length; //and here as well.
          redraw();
        }
    

    It's quite a lot as you can see, I'm really in the beginning of processing. I have a lot discover, so if you think I should be able to figure some lines out myself, I understand that. But I hope you can help me understand this, because I think this a very nice and small program.

  • How to go back to original colour using IF statements?

    https://Processing.org/reference/modulo.html
    https://OpenProcessing.org/sketch/473642

    /** 
     * Palette Cycle (v1.0)
     * GoToLoop (2017/Nov/11)
     *
     * Forum.Processing.org/two/discussion/24960/
     * how-to-go-back-to-original-colour-using-if-statements#Item_1
     *
     * Forum.Processing.org/two/discussion/24988/processing-with-mouse-click
     *
     * OpenProcessing.org/sketch/473642
     */
    
    static final boolean JAVA = 1/2 != 1/2.;
    static final color[] PALETTE = { #FF0000, #008000, #0000FF };
    int idx;
    
    void setup() {
      size(300, 200);
      noLoop();
      colorMode(RGB);
    }
    
    void draw() {
      final color c = PALETTE[idx];
      background(c);
      if (JAVA)  getSurface().setTitle("Color: " + idx + "  -  #" + hex(c, 6));
    }
    
    void mousePressed() {
      keyPressed();
    }
    
    void keyPressed() {
      idx = (idx + 1) % PALETTE.length;
      redraw();
    }
    
  • Why isn't initializing ArrayList size working?

    Anyways, here's my made-up sketch, attempting to guess how yours works: 3:-O

    vectors.tsv:

    endptsFrom  endptsTo
    tCenter;tCenter pW;pE
    pW;pE   tCenter;tCenter
    tCenter;tCenter pN;pS
    (pS.x, pW.y, -5)    (tWidth.x, -tHalf.y)
    pN;pS   tCenter;tCenter
    

    QuasiPVecParser.pde:

    /**
     * QuasiPVecParser (v1.0.1)
     * GoToLoop (2017-Oct-17)
     *
     * Forum.Processing.org/two/discussion/24562/
     * why-isn-t-initializing-arraylist-size-working#Item_31
     */
    
    import java.util.Arrays;
    import java.util.Map;
    
    static final String FILENAME = "vectors", EXT = ".tsv";
    
    PVecEndPointsPair[] vecPairs;
    Table t;
    
    void setup() {
      size(400, 300);
      smooth(3);
      noLoop();
      frameRate(60.0);
      strokeWeight(2.5);
    
      getSurface().setResizable(true);
    
      t = loadTable(FILENAME + EXT, "header");
      keyPressed();
      printArray(vecPairs);
    }
    
    void draw() {
      clear();
    
      for (final PVecEndPointsPair pair : vecPairs) {
        final PVector[] begins = pair.from, ends = pair.to;
        final int len = min(begins.length, ends.length);
    
        for (int i = 0; i < len; ++i) {
          final PVector from = begins[i], to = ends[i];
          stroke((color) random(#000000));
          line(from.x, from.y, to.x, to.y);
        }
      }
    }
    
    void keyPressed() {
      vecPairs = createPVecCoordPairsFromTable(t);
      redraw = true;
    }
    
    void mousePressed() {
      keyPressed();
    }
    
    PVecEndPointsPair[] createPVecCoordPairsFromTable(final Table t) {
      final int rows = t.getRowCount();
      final PVecEndPointsPair[] coords = new PVecEndPointsPair[rows];
      final PVecParser parser = new PVecParser();
    
      for (int i = 0; i < rows; ++i) {
        final TableRow tr = t.getRow(i);
        final PVector[] from = parser.parseVecs(tr.getString(0));
        final PVector[] to = parser.parseVecs(tr.getString(1));
    
        coords[i] = new PVecEndPointsPair(from, to);
      }
    
      return coords;
    }
    
    class PVecEndPointsPair {
      final PVector[] from, to;
    
      PVecEndPointsPair(final PVector[] begins, final PVector[] ends) {
        from = begins;
        to = ends;
      }
    
      @ Override String toString() {
        return "\nFrom: " + Arrays.toString(from)
          + "\nTo:   " + Arrays.toString(to);
      }
    }
    
    class PVecParser {
      static final String TOKENS = ",()" + WHITESPACE;
    
      final PVector VEC_NULL = new PVector(Float.NaN, Float.NaN, Float.NaN);
    
      final PVector[] coords = {
        new PVector(width>>1, height>>1), // tCenter
        new PVector(width>>2, height>>2), // tHalf
        new PVector(width, height>>2), // tWidth
        new PVector(width>>2, height), // tHeight
        new PVector(width>>1, 0), // pN
        new PVector(width>>1, height), // pS
        new PVector(0, height>>1), // pW
        new PVector(width, height>>1), // pE
        new PVector(0, 0), // vNW
        new PVector(width, 0), // vNE
        new PVector(0, height), // vSW
        new PVector(width, height) // vSE
      };
    
      final String[] QUASI_ENUMS = {
        "tCenter", "tHalf", "tWidth", "tHeight", 
        "pN", "pS", "pW", "pE", 
        "vNW", "vNE", "vSW", "vSE"
      };
    
      final Map<String, PVector> vecEnums =
        new HashMap<String, PVector>(1 + QUASI_ENUMS.length, 1.0);
    
      PVecParser() {
        int idx = 0;
        for (final String q : QUASI_ENUMS)  vecEnums.put(q, coords[idx++]);
      }
    
      PVector[] parseVecs(final String s) {
        final String[] splits = split(s, ';');
        final int len = splits.length;
        final PVector[] vecs = new PVector[len];
    
        for (int i = 0; i < len; ++i) {
          final String[] tokens = splitTokens(splits[i], TOKENS);
          final int tokLen = tokens.length;
    
          if (tokLen == 1) {
            vecs[i] = vecEnums.getOrDefault(tokens[0], VEC_NULL).get();
            continue;
          }
    
          final float[] xyz = new float[tokLen];
          for (int j = 0; j < tokLen; xyz[j] = parseCoord(tokens[j++]));
    
          vecs[i] = new PVector().set(xyz);
        }
    
        return vecs;
      }
    
      float parseCoord(String s) {
        float f = float(s);
        if (f == f)  return f;
    
        final float neg = s.charAt(0) == '-'? -1.0 : 1.0;
        if (neg < 0.0)  s = s.substring(1);
    
        final String[] tokens = split(s, '.');
        final PVector vec = vecEnums.getOrDefault(tokens[0], VEC_NULL);
    
        switch (tokens[1].charAt(0)) {
        case 'x':
          return vec.x * neg;
        case 'y':
          return vec.y * neg;
        case 'z':
          return vec.z * neg;
        }
    
        return f * neg;
      }
    }
    
  • Descending curve function?

    An alternative approach using a class to generate next opacity value: $-)
    Online version: https://OpenProcessing.org/sketch/450448

    /** 
     * AlphaStepGen (v1.0)
     * GoToLoop (2017/Sep/20)
     *
     * Forum.Processing.org/two/discussion/24193/descending-curve-function#Item_2
     * OpenProcessing.org/sketch/450448
     */
    
    static final boolean JS = 1/2 == 1/2.;
    final AlphaStep opaque = new AlphaStep();
    
    void setup() {
      size(800, 600);
      smooth(3);
      frameRate(5);
    
      colorMode(RGB);
      ellipseMode(CENTER);
    
      strokeWeight(2.5);
      stroke(0);
    
      println(opaque.steps);
    }
    
    void draw() {
      background(-1);
      fill(255, 0, 0, opaque.nextAlpha());
      ellipse(width>>1, height>>1, width>>1, height>>1);
    
      if (JS)  return;
    
      String info = "Frame: " + frameCount + "  -  Alpha: " + opaque.toString();
      getSurface().setTitle(info);
    }
    
    class AlphaStep {
      static final int STEP = 5;
      float opacity = 255;
      final float[] steps = new float[1 + (int)opacity];
    
      AlphaStep() {
        for (int opac = (int)opacity, i = steps.length; i-- > 0; 
          steps[opac - i] = STEP * norm(i, opac, 0));
      }
    
      color nextAlpha() {
        return round(opacity -= steps[round(opacity)]);
      }
    
      String toString() {
        return nf(opaque.opacity, 0, 2);
      }
    }
    
  • Time delay in python mode?

    https://Gist.GitHub.com/GoToLoop/ea4db8a8622e27541213da3c9a43ca21

    CountdownClass.pde:

    /** 
     * Countdown Class (v1.2.5)
     * GoToLoop (2017/Aug/26)
     *
     * Forum.Processing.org/two/discussion/27733/
     * countdown-class-library-for-java-js-python
     *
     * Forum.Processing.org/two/discussion/23846/
     * time-delay-in-python-mode#Item_11
     *
     * Gist.GitHub.com/GoToLoop/ea4db8a8622e27541213da3c9a43ca21
     */
    
    import gotoloop.countdown.Countdown;
    
    static final float SECS = 7.5;
    static final int WAIT_TIME = (int) (SECS * 1000);
    
    static final String AWAIT = "Awaiting " + SECS;
    static final String END = "Countdown Finished";
    
    static final color WAITING_BG = PImage.BLUE_MASK | PImage.ALPHA_MASK;
    static final color DONE_BG = PImage.RED_MASK | PImage.ALPHA_MASK;
    
    final Countdown countdown = new Countdown(WAIT_TIME);
    
    void setup() {
      size(300, 180);
      smooth(3);
      frameRate(60);
    
      colorMode(RGB);
      fill(#FFFF00);
    
      textSize(0100);
      textAlign(CENTER, CENTER);
    
      final int m = millis(), t = m + WAIT_TIME;
      countdown.start();
      println(m, t, t - m, TAB, countdown);
    }
    
    void draw() {
      getSurface().setTitle(countdown.done? END : AWAIT);
      background(countdown.done? DONE_BG : WAITING_BG);
    
      final String txt = millis() + "\n" + frameCount;
      text(txt, width>>1, height>>1);
    }
    

    Countdown.java:

    /** 
     * Countdown Class (v1.2.5)
     * GoToLoop (2017/Aug/26)
     *
     * https://Forum.Processing.org/two/discussion/27733/
     * countdown-class-library-for-java-js-python
     *
     * https://Forum.Processing.org/two/discussion/23846/
     * time-delay-in-python-mode#Item_11
     *
     * https://Gist.GitHub.com/GoToLoop/ea4db8a8622e27541213da3c9a43ca21
     */
    
    package gotoloop.countdown;
    
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class Countdown {
      protected static final Timer t = new Timer("Countdown");
    
      public TimerTask task;
      public int delay;
      public volatile boolean done = true;
    
      public Countdown() {
      }
    
      public Countdown(final int waitTime) { // milliseconds
        delay = Math.abs(waitTime);
      }
    
      @Override public String toString() {
        return "Delay: " + delay + "  -  Done: " + done;
      }
    
      public Countdown start() {
        if (task != null)  task.cancel();
        done = false;
        t.schedule(task = new Timeout(), delay);
        return this;
      }
    
      protected class Timeout extends TimerTask {
        @Override public void run() {
          done = true;
        }
      }
    }
    
  • Referencing to mainApp(PApplet) instead of "this"

    Java's keyword this is always of the datatype of the class block it was typed in.
    Let's say your class is called MyGif:

    import gifAnimation.Gif;
    
    class MyGif {
      Gif myAnimation;
    
      MyGif(String myFile) {
        myAnimation = new Gif(this, myFile);
      }
    }
    

    That won't compile b/c Gif's constructor demands that its 1st parameter to be of datatype PApplet.
    But that this is of datatype MyGif instead. #-o

    There are many approaches to workaround it. And you've already found out 1 as SketchName.this. :ar!

    But the simplest 1 is to instantiate such libraries in the main sketch; and then pass it as an argument for the target class: *-:)

    /** 
     * MyGifAnim (v1.0)
     * GoToLoop (2017/Jul/14)
     *
     * Forum.Processing.org/two/discussion/23440/
     * referencing-to-mainapp-papplet-instead-of-this#Item_3
     */
    
    import gifAnimation.Gif;
    
    MyGif gif;
    
    void setup() {
      smooth(3);
      frameRate(60);
      imageMode(CENTER);
    
      gif = new MyGif(new Gif(this, "anim.gif"));
      getSurface().setSize(gif.myAnimation.width, gif.myAnimation.height);
    }
    
    void draw() {
      background(-1);
      image(gif.myAnimation, width>>1, height>>1);
    }
    
    class MyGif {
      Gif myAnimation;
    
      MyGif(Gif gif) {
        myAnimation = gif;
        gif.loop();
      }
    }
    
  • Resizing a Movie - Possible Bug?
    /** 
     * Efficient Movie Resize (v1.0)
     * GoToLoop (2017/Jul/10)
     *
     * Forum.Processing.org/two/discussion/23389/
     * resizing-a-movie-possible-bug#Item_4
     */
    
    import processing.video.Movie;
    PImage frame;
    
    static final String FN = "test", EXT = ".mov";
    static final int SCALE = 4, DELAY = 5, SMOOTH = 3, FPS = 10;
    
    void setup() {
      smooth(SMOOTH);
      initVideo();
    }
    
    void draw() {
      background(frame);
    }
    
    void movieEvent(final Movie m) {
      m.read();
      final PImage img = m.get();
      img.resize(img.width/SCALE, img.height/SCALE);
      frame = img;
    }
    
    void initVideo() {
      final Movie vid = new Movie(this, FN + EXT);
      vid.loop();
      while (vid.height == 0)  delay(DELAY);
      getSurface().setSize(vid.width/SCALE, vid.height/SCALE);
      frameRate(FPS + vid.frameRate);
    }
    
  • Dynamically controlled particle system with Toxiclibs
    • Glad you've finally made it. Congrats! <:-P
    • But I'm puzzled why a chain of else if {} would work while switch () { case: } wouldn't! :-/
    • Then I've decided to refactor the whole code. #:-S
    • Given I can't have any inputs from OSC, I can only use mouse for such task here. 8-|
    • Maybe it will for ya this time if you run the refactored sketch I hope. O:-)

    /**
     * Attraction2D + OSC (v1.2.3)
     * Copyright © 2010 Karsten Schmidt
     * Mods Narner & GoToLoop (2017-Jun-14)
     *
     * GNU.org/licenses/lgpl-2.1.html
     *
     * forum.Processing.org/two/discussion/22940/
     * dynamically-controlled-particle-system-with-toxiclibs#Item_12
     */
    
    import toxi.geom.Vec2D;
    import toxi.geom.Rect;
    
    import toxi.physics2d.VerletPhysics2D;
    import toxi.physics2d.VerletParticle2D;
    
    import toxi.physics2d.behaviors.ConstantForceBehavior2D;
    import toxi.physics2d.behaviors.AttractionBehavior2D;
    
    import oscP5.OscP5;
    import oscP5.OscMessage;
    
    static final boolean MOUSE = true;
    static final float STRENGTH = .9, DRAGGING = .05, GRAVITY = .15;
    static final int PARTICLES = 600, DIAM = 5, AREA = 250;
    static final int SMOOTH = 2, FPS = 60, PORT = 6000;
    
    int oscGesture = -1;
    color bg = #008000;
    
    final VerletPhysics2D physics = new VerletPhysics2D();
    
    final AttractionBehavior2D attractor =
      new AttractionBehavior2D(new Vec2D(), AREA, 0);
    
    final StringBuilder sb = new StringBuilder(30);
    
    void setup() {
      size(680, 382, FX2D);
      smooth(SMOOTH);
      frameRate(FPS);
    
      colorMode(RGB);
      blendMode(REPLACE);
    
      stroke(-1);
      strokeWeight(DIAM);
    
      physics.particles.ensureCapacity(PARTICLES);
      ((ArrayList<?>) physics.behaviors).ensureCapacity(PARTICLES + 2);
    
      physics.setWorldBounds(new Rect(0, 0, width, height)).setDrag(DRAGGING);
      physics.addBehavior(new ConstantForceBehavior2D(new Vec2D(0, GRAVITY)));
      physics.addBehavior(attractor);
    
      new OscP5(this, PORT);
      registerMethod("pre", this);
    }
    
    void pre() {
      Vec2D v = Vec2D.randomVector().scaleSelf(DIAM).addSelf(width>>1, DIAM<<2);
      VerletParticle2D p = new VerletParticle2D(v);
    
      physics.addParticle(p)
        .addBehavior(new AttractionBehavior2D(p, DIAM<<2, -1.2, .01));
    
      if (physics.particles.size() == PARTICLES)  unregisterMethod("pre", this);
    }
    
    void draw() {
      processChosenGesture(oscGesture);
      //processChosenGesture((int) random(20));
    
      background(bg);
      for (final Vec2D p : physics.update().particles)  point(p.x, p.y);
    
      displayInfoTitle()
    }
    
    void mousePressed() {
      if (MOUSE) {
        attractor.getAttractor().set(mouseX, mouseY);
        attractor.setStrength(STRENGTH);
        bg = #800000;
      }
    }
    
    void mouseDragged() {
      if (MOUSE)  attractor.getAttractor().set(mouseX, mouseY);
    }
    
    void mouseReleased() {
      if (MOUSE)  disableGestureAttraction();
    }
    
    void oscEvent(final OscMessage msg) {
      oscGesture = msg.get(0).intValue();
      println("Received gesture was:", oscGesture);
    }
    
    void displayInfoTitle() {
      sb.setLength(0);
    
      sb.append("Particles: ").append(physics.particles.size())
        .append("  -  FPS: ").append(round(frameRate));
    
      getSurface().setTitle(sb.toString());
    }
    
    void processChosenGesture(final int gesture) {
      if (gesture < 0)  return;
    
      oscGesture = -1;
      println("Gesture to process is:", gesture);
    
      switch (gesture) {
      case 0:
        activateGestureAttraction(); 
        break;
      case 1:
        setRandomPositionForAttractor(); 
        break;
      case 2:
        disableGestureAttraction();
      }
    }
    
    void activateGestureAttraction() {
      attractor.getAttractor().set(width>>1, height>>1);
      attractor.setStrength(STRENGTH);
      bg = #FF0000;
    }
    
    void setRandomPositionForAttractor() {
      attractor.getAttractor()
        .set(random(DIAM, width - DIAM), random(DIAM, height - DIAM));
    }
    
    void disableGestureAttraction() {
      attractor.setStrength(0);
      bg = #0000FF;
    }
    
  • Making a "Generator of Art" initial problems

    This is not the solution, but it shows a dynamic sketch: Mouse the mouse and click to set v5. Can you explain what do you want the lines to do? To originated at the center of the screen and extend to the corner of your sketch?

    Kf

    import processing.awt.PSurfaceAWT.SmoothCanvas;
    import com.sun.awt.AWTUtilities;
    
    import javax.swing.JFrame;
    import javax.swing.JRootPane;
    
    
    JFrame jframe;
    
    
    PVector v1;
    PVector v2;
    PVector v3;
    PVector v4;
    PVector v5;
    
    float a;
    float b;
    float c;
    float d;
    
    PVector m;
    
    
    
    void setup() {
      size(500, 500);
      jframe = getJFrame(getSurface());
    
      jframe.removeNotify();
      jframe.setUndecorated(true);
      jframe.addNotify();
    
      rectMode(CENTER);
    
      m=new PVector();
      v1 = new PVector(m.x, m.y);
      v2 = new PVector(width - m.x, m.y); 
      v3 = new PVector(1, height - 1);
      v4 = new PVector(width - m.x, height - m.y);
      v5 = new PVector(random(width*0.5), random(width*0.5));
    
      a = PVector.angleBetween(v1, v5);
      b = PVector.angleBetween(v2, v5);
      c = PVector.angleBetween(v3, v5);
      d = PVector.angleBetween(v4, v5);
    }
    void draw() {
      background(150);
    
    
      for (int i = 10; i >= 0; i--) {
        if (i%2 == 0 )
          fill(0);
        else fill(255);
    
        if (v5.x <= 250 && v5.y <=250)
          rect(v5.x+10*i, v5.y+10*i, i*50, i*50);
        if (v5.x >= 500 && v5.y >= 500)
          rect(v5.x-10*i, v5.y-10*i, i*50, i*50);
      }
    
    
      m.set(mouseX, mouseY);
      v1.set(m.x, m.y);
      v2.set(width - m.x, m.y); 
      v3.set(m.x, height - m.y);
      v4.set(width - m.x, height - m.y);
      //v5.set((width*0.5), (width*0.5));
    
      a = PVector.angleBetween(v1, v5);
      b = PVector.angleBetween(v2, v5);
      c = PVector.angleBetween(v3, v5);
      d = PVector.angleBetween(v4, v5);
    
    
    
      line(v1.x, v1.y, v5.x, v5.y);
      line(v2.x, v2.y, v5.x, v5.y);
      line(v3.x, v3.y, v5.x, v5.y);
      line(v4.x, v4.y, v5.x, v5.y);
      println(degrees(a));
      println(degrees(b));
      println(degrees(c));
      println(degrees(d));
      println(v5.x);
    }
    
    void mouseReleased() {
    
      v5.set(random(width*0.5), random(width*0.5));
    }
    
    
    static final JFrame getJFrame(final PSurface surf) {
      return (JFrame) ((SmoothCanvas) surf.getNative()).getFrame();
    }