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

    Finally got a chance to try this, thanks again for the knowledge GoToLoop! Well, I added this to the surface call, but the PDF output is still at the initial size set in the size command.

    size(100,100, PDF, 'pdfOutput.pdf')
    this.surface.setResizable(True)
    this.surface.setSize(5760, 5760)
    

    Sorry if this is obvious, still a Processing newbie.

    THANKS again for any additional info! :D

  • how resize sketch without recompile
    final int W=640;
    
    
    void settings() {
      size(W, 360);
    }
    
    void setup() {
    
      surface.setResizable(true);
      noLoop();
    }
    
    void draw() {
      background(random(50, 200));
    }
    
    void mouseReleased() {
      surface.setSize((int)random(0.20*W, W), height);
    }
    

    Kf

  • Surface doesn't work in Python mode

    Thanks for the info GoToLoop! I was wondering if this works when using the PDF renderer? I'm outputting large PDF files from processing and would like to dynamically set the PDF size after I've done some calculations on the input files. I'm getting the following error when I try to include the frame.setResizable(True). I'm using Processing 3.3.6 btw.

    AttributeError: 'NoneType' object has no attribute 'surface'

    Thanks in advance for any info you might have!

  • 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));
    }
    
  • Converting Java code to Python

    I wonder if you 1st was able to transpile back the ".java" sketch as a ".pde" in order to run it under Java Mode? :-?

    • Like removing the statement w/ the package keyword.
    • The public class DepthOfField_Demo extends PApplet { statement & its corresponding closing curly brace.
    • And of course, the whole public static void main(String args[]) { code block. #:-S

    That whole code is æsthetically messy. But here's what I've come w/ as a ".pde" file w/o changing the original ".java" 1 much: :P

    "Depth_of_Field.pde":

    // 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
    
    import static java.util.Locale.ENGLISH;
    
    import com.jogamp.opengl.GL2;
    
    import peasy.PeasyCam;
    
    import com.thomasdiewald.pixelflow.java.DwPixelFlow;
    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;
    
    static final String POSITION = "position: (%7.3f, %7.3f, %7.3f)\n";
    static final String ROTATION = "rotation: (%7.3f, %7.3f, %7.3f)\n";
    static final String LOOK_AT  = "look-at:  (%7.3f, %7.3f, %7.3f)\n";
    static final String DISTANCE = "distance: (%7.3f)\n";
    
    static final String FPS = "   [fps %6.2f]";
    
    boolean start_fullscreen = false;
    
    int viewport_w = 1000;
    int viewport_h = 600;
    int viewport_x = 200;
    int viewport_y = 0;
    
    // camera control
    PeasyCam peasycam;
    
    // library context
    DwPixelFlow context;
    
    PShape shp_scene;
    
    PGraphics3D pg_render;
    PGraphics3D pg_dof;
    PGraphics3D pg_tmp;
    
    DepthOfField dof;
    DwScreenSpaceGeometryBuffer geombuffer;
    
    DwMagnifier magnifier;
    
    boolean apply_dof = true;
    
    void settings() {
      if (!start_fullscreen)  size(viewport_w, viewport_h, P3D);
      else {
        fullScreen(P3D);
        viewport_w = displayWidth;
        viewport_h = displayHeight;
        viewport_x = 0;
        viewport_y = 0;
      }
    
      noSmooth();
    }
    
    void setup() {
      surface.setResizable(true);
      surface.setLocation(viewport_x, viewport_y);
    
      // camera
      peasycam = new PeasyCam(this, -4.083, -6.096, 7.000, 1300);
      peasycam.setRotations(1.085, -0.477, 2.910);
    
      // main library context
      context = new DwPixelFlow(this);
      context.print();
      context.printGL();
    
      // callback for scene display (used in GBAA)
      DwSceneDisplay scene_display = new DwSceneDisplay() {  
        @ Override public void display(PGraphics3D canvas) {
          displayScene(canvas);
        }
      };
    
      geombuffer = new DwScreenSpaceGeometryBuffer(context, scene_display);
    
      dof = new DepthOfField(context);
    
      int mag_h = height/3;
      magnifier = new DwMagnifier(this, 4, 0, height - mag_h, mag_h, mag_h);
    
      frameRate(1000);
    }
    
    void draw() {
      resizeScreen();
      displaySceneWrap(pg_render);
      DwFilter.get(context).gamma.apply(pg_render, pg_render);
    
      int mult_blur = 30;
    
      if (apply_dof) {
        geombuffer.update(pg_render);
    
        DwFilter.get(context).gaussblur.apply(geombuffer.pg_geom, geombuffer.pg_geom, 
          pg_tmp, (int) Math.pow(mult_blur, 0.33));
    
        //      dof.param.focus     = map(mouseX, 0, width, 0, 1);
        dof.param.focus_pos = new float[]{0.5, 0.5};
        dof.param.focus_pos[0] = map(mouseX+0.5, 0, width, 0, 1);
        dof.param.focus_pos[1] = map(mouseY+0.5, 0, height, 1, 0);
        dof.param.mult_blur = mult_blur;
        dof.apply(pg_render, pg_dof, geombuffer);
    
        DwFilter.get(context).copy.apply(pg_dof, pg_render);
      }
    
      magnifier.apply(pg_render, mouseX, mouseY);
      magnifier.displayTool();
    
      DwUtils.beginScreen2D(g);
      //    peasycam.beginHUD();
      {
        blendMode(REPLACE);
        clear();
        image(pg_render, 0, 0);
        //      image(geombuffer.pg_geom, 0, 0);
    
        magnifier.display(g, 0, height-magnifier.h);
    
        blendMode(BLEND);
    
        pushMatrix();
        float cursor_s = 10;
    
        float fpx = dof.param.focus_pos[0] * width;
        float fpy = (1.0 - dof.param.focus_pos[1]) * height;
    
        blendMode(EXCLUSION);
        translate(fpx, fpy);
        strokeWeight(1);
        stroke(255, 200);
        line(-cursor_s, 0, +cursor_s, 0);
        line(0, -cursor_s, 0, +cursor_s);
        blendMode(BLEND);
        popMatrix();
      }
      //    peasycam.endHUD();
      DwUtils.endScreen2D(g);
    
      String txt_fps = String.format(getClass().getName() + FPS, frameRate);
      surface.setTitle(txt_fps);
    }
    
    void keyReleased() {
      if (keyCode == 'C') printCam();
      else if (key == ' ') apply_dof = !apply_dof;
    }
    
    boolean resizeScreen() { // dynamically resize render-targets
      final boolean[] resized = { false };
    
      pg_render = DwUtils.changeTextureSize(this, pg_render, width, height, 8, resized);
      pg_dof    = DwUtils.changeTextureSize(this, pg_dof, width, height, 0, resized);
      pg_tmp    = DwUtils.changeTextureSize(this, pg_tmp, width, height, 0, resized, 
        GL2.GL_RGBA16F, GL2.GL_RGBA, GL2.GL_FLOAT);
    
      //    geombuffer.resize(width, height)
    
      if (resized[0]) {
        // nothing here
      }
    
      peasycam.feed();
      perspective(60 * DEG_TO_RAD, width/(float)height, 2, 6000);
    
      return resized[0];
    }
    
    void displaySceneWrap(PGraphics3D canvas) {
      canvas.beginDraw();
      DwUtils.copyMatrices((PGraphics3D) this.g, canvas);
    
      canvas.blendMode(PConstants.BLEND);
      canvas.background(2);
      displayScene(canvas);
      canvas.endDraw();
    }
    
    void displayScene(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(255, 255);
        canvas.pgl.clearColor(1, 1, 1, 6000);
        canvas.pgl.clear(PGL.COLOR_BUFFER_BIT);
      }
    
      sceneShape(canvas);
    }
    
    void sceneShape(PGraphics3D canvas) {
      if (shp_scene != null) {
        canvas.shape(shp_scene);
        return;
      }
    
      shp_scene = createShape(GROUP);
    
      int num_boxes = 50;
      int num_spheres = 50;
      float bb_size = 800;
      float xmin = -bb_size;
      float xmax = +bb_size;
      float ymin = -bb_size;
      float ymax = +bb_size;
      float zmin =  0;
      float zmax = +bb_size;
    
      colorMode(HSB, 360, 1, 1);
      randomSeed(0);
    
      for (int i = 0; i < num_boxes; i++) {
        float px = random(xmin, xmax);
        float py = random(ymin, ymax);
        float sx = random(200) + 10;
        float sy = random(200) + 10;
        float sz = random(zmin, zmax);
    
        float off = 45;
        float base = 0;
        float hsb_h = base + random(-off, off);
        float hsb_s = 1;
        float hsb_b = random(0.1, 1.0);
        int shading = color(hsb_h, hsb_s, hsb_b);
    
        PShape shp_box = createShape(BOX, sx, sy, sz);
        shp_box.setFill(true);
        shp_box.setStroke(false);
        shp_box.setFill(shading);
        shp_box.translate(px, py, sz*.5);
        shp_scene.addChild(shp_box);
      }
    
      DwCube cube_smooth = new DwCube(4);
      DwCube cube_facets = new DwCube(2);
    
      for (int i = 0; i < num_spheres; i++) {
        float px = random(xmin, xmax);
        float py = random(ymin, ymax);
        float pz = random(zmin, zmax);
        float rr = random(50) + 50;
        boolean facets = true;//(i%2 == 0);
    
        float off = 20;
        float base = 225;
        float hsb_h = base + random(-off, off);
        float hsb_s = 1;
        float hsb_b = random(0.1, 1.0);
        int shading = color(hsb_h, hsb_s, hsb_b);
    
        PShape shp_sphere = createShape(PShape.GEOMETRY);
        if (facets) {
          DwMeshUtils.createPolyhedronShape(shp_sphere, cube_facets, 1, 4, false);
        } else {
          DwMeshUtils.createPolyhedronShape(shp_sphere, cube_smooth, 1, 4, true);
        }
    
        shp_sphere.setStroke(!true);
        shp_sphere.setStroke(color(0));
        shp_sphere.setStrokeWeight(0.01 / rr);
        shp_sphere.setFill(true);
        shp_sphere.setFill(shading);
        shp_sphere.resetMatrix();
        shp_sphere.scale(rr);
        shp_sphere.translate(px, py, pz);
        shp_scene.addChild(shp_sphere);
      }
    
      colorMode(RGB, 255, 255, 255);
    
      PShape shp_rect = createShape(RECT, -1000, -1000, 2000, 2000);
      shp_rect.setStroke(false);
      shp_rect.setFill(true);
      shp_rect.setFill(color(255));
    
      shp_scene.addChild(shp_rect);
    }
    
    PShape createGridXY(int lines, float s) {
      PShape shp_gridxy = createShape();
      shp_gridxy.beginShape(LINES);
      shp_gridxy.stroke(0);
      shp_gridxy.strokeWeight(1);
      float d = lines*s;
    
      for (int i = 0; i <= lines; i++) {
        shp_gridxy.vertex(-d, -i*s, 0); 
        shp_gridxy.vertex(d, -i*s, 0);
        shp_gridxy.vertex(-d, +i*s, 0); 
        shp_gridxy.vertex(d, +i*s, 0);
    
        shp_gridxy.vertex(-i*s, -d, 0); 
        shp_gridxy.vertex(-i*s, d, 0);
        shp_gridxy.vertex(+i*s, -d, 0); 
        shp_gridxy.vertex(+i*s, d, 0);
      }
    
      shp_gridxy.endShape();
      return shp_gridxy;
    }
    
    void printCam() {
      float[] pos = peasycam.getPosition();
      float[] rot = peasycam.getRotations();
      float[] lat = peasycam.getLookAt();
      float   dis = (float) peasycam.getDistance();
    
      System.out.printf(ENGLISH, POSITION, pos[0], pos[1], pos[2]);
      System.out.printf(ENGLISH, ROTATION, rot[0], rot[1], rot[2]);
      System.out.printf(ENGLISH, LOOK_AT, lat[0], lat[1], lat[2]);
      System.out.printf(ENGLISH, DISTANCE, dis);
    }
    
  • event when I change size

    Thxs for sharing @quark. Here is my example.

    Kf

    //REFERENCE: https://forum.processing.org/one/topic/detect-resize.html
    //REFERENCE: https://github.com/processing/processing/wiki/Library-Basics
    //REFERENCE: https://github.com/processing/processing/wiki/Window-Size-and-Full-Screen
    
    
    
    
    int w, h;
    String ws = "";
    PGraphics pg;
    
    void setup() {
      size(400, 360);
      w = width;
      h = height;
      surface.setResizable(true);
      registerMethod("pre", this);
    
      refreshPG();
    }
    
    void pre() {
      if (w != width || h != height) {
        // Sketch window has resized
        w = width;
        h = height;
        ws = "Size = " +w + " x " + h + " pixels";
        // Do what you need to do here
        refreshPG();
      }
    }
    
    void draw() {
      background(200, 200, 255);
      fill(0);
      text(ws, 30, 30);
      image(pg,width/3,height/3);
    }
    
    
    void refreshPG() {
      int ww=int(w/3.0);
      int hh=int(h/3.0);
    
      println("REFRESH ", ww, hh);
      pg=createGraphics(ww, hh, JAVA2D);
      pg.beginDraw();
      pg.background(random(100, 200));
      pg.endDraw();
    }
    
  • event when I change size

    Processing does not generate an event when the window is resized so you have to detect the change yourself. This code demonstrates how to do this.

    NOTE: the pre() is a special method that will be executed immediately before each call to draw() because we have registered it.

    int w, h;
    String ws = "";
    
    void setup() {
      size(400, 360);
      w = width;
      h = height;
      surface.setResizable(true);
      registerMethod("pre", this);
    }
    
    void pre() {
      if (w != width || h != height) {
        // Sketch window has resized
        w = width;
        h = height;
        ws = "Size = " +w + " x " + h + " pixels";
        // Do what you need to do here
      }
    }
    
    void draw() {
      background(200, 200, 255);
      fill(0);
      text(ws, 30, 30);
    }
    
  • event when I change size

    Hi friends,

    I'm using surface.setResizable(true); to can adapt the size of my window, it runs perfectly. I'm asking if there is an way to catch this event when I change the size with my mouse. I need to change the size of my PGraphics inside my sketch. Is it possible ?

  • Shadertoy shader not rendering until screen window is resized if surface.setResizable(true)

    I'm trying to figure out DwShadertoy's implementation of Shadertoy shaders, however there are two big issues I've ran into. The first is that the window won't render until it is resized when setResizable is true. The second is the mouse Y cords are not mapped correctly. MouseY seems to be shifted 2/3rds of the screen down. Trying to compensate for the shift doesn't seem to have any effect.

    See the example script "WetStone" included in pixelflow for reference.

     if(mousePressed){
          toy.set_iMouse(mouseX, height-1-mouseY, mouseX, height-1-mouseY);
        }
    

    This is the default in all the example scripts and I'm trying to figure out why that is and why it doesn't work.

    /**
     * 
     * PixelFlow | Copyright (C) 2017 Thomas Diewald - www.thomasdiewald.com
     * 
     * https://github.com/diwi/PixelFlow.git
     * 
     * A Processing/Java library for high performance GPU-Computing.
     * MIT License: https://opensource.org/licenses/MIT
     * 
     */
    
    
    
    import com.thomasdiewald.pixelflow.java.DwPixelFlow;
    import com.thomasdiewald.pixelflow.java.imageprocessing.DwShadertoy;
    
    
      //
      // Shadertoy Demo:   https://www.shadertoy.com/view/ldSSzV
      // Shadertoy Author: https://www.shadertoy.com/user/TDM
      //
    
      DwPixelFlow context;
      DwShadertoy toy;
    
      public void settings() {
        size(1280, 720, P2D);
        smooth(0);
      }
    
      public void setup() {
        surface.setResizable(true);
    
        context = new DwPixelFlow(this);
        context.print();
        context.printGL();
    
        toy = new DwShadertoy(context, "data/WetStone.frag");
    
        frameRate(60);
      }
    
    
      public void draw() {
        if(mousePressed){
          toy.set_iMouse(mouseX, height-1-mouseY, mouseX, height-1-mouseY);
        }
    
        toy.apply(g);
    
        String txt_fps = String.format(getClass().getSimpleName()+ "   [size %d/%d]   [frame %d]   [fps %6.2f]", width, height, frameCount, frameRate);
        surface.setTitle(txt_fps);
      }
    
  • How to port shaders from shaderfog, shadertoy to Processing?

    Doing some searching I found there used to be a library called GL Graphics http://glgraphics.sourceforge.net/, but it was last updated in 2011. Is there anything like that which exists for processing 3? It looks like pixel flow might have some of that capability but I'm getting a lot of bugs. For example, if surface.setResizable(true);, nothing will be rendered until the window is resized. And the mouse cordinates are wrong on the y axis, only having effect on the bottom 1/4 or so of the screen. Also, not sure how to pass values for custom variables into the shader.

  • Disable maximize button?

    with size() being called in settings(),

    surface.setResizable(false); does nothing in setup(); It does nullpointerexception in settings() after size();

    frame.setResizable(false) also doesn't work.

    void setup() {
      size(400, 300, removeFrameBorder());
    
      frameRate(60);
      smooth(8);
      stroke(#00FFFF);
      strokeWeight(1.5);
      textSize(32);
    }
    
    void draw() {
      background(0300);
    
      fill(#FF0000);
      text(frameCount, width - 100, 40);
    
      fill(#0000FF);
      translate(frameCount % width, height >> 1);
      sphere(96);
    }
    
    String removeFrameBorder() {
      if (!isGL()) {
        frame.removeNotify();
        frame.setUndecorated(true);
        frame.addNotify();
      }
    
      return P3D;
    }
    

    this code from your link doesn't work because isGL doesn't work in processing3, also size needs to be in settings()

  • Disable maximize button?

    Not tested, but try:

    surface.setResizable(false);

    after calling size. Or try GoTo's first post here: https://forum.processing.org/two/discussion/3013/are-undecorated-frames-dead-with-processing-2-x

    Is there an index of all the built in processing hooks

    The reference only documents the basic functions that can be accessed by the common users of the Processing library, keeping in mind Processing is directed to a public with less experience in Programming with the concept to engage them into programming. It is my understanding they don't intend to document all the built-in functionalities. These other functions are found mostly by checking previous posts or browsing the source code available in GitHub.

    Kf

  • Disable maximize button?

    I want a fixed window size, I don't want the maximize button to make the window full screen.

    setResizable does nothing. Calling size() every frame breaks sketch.

  • Creating a Big Background Image That a Player Can Navigate and the Camera Follows Them

    Thank you, I will look at the code you provided me and I will try to implement it. I'm currently in school (where imgur is blocked) so I can't really upload them anywhere so, if you could provide me with your email, I could send them to you. Also here is my Jerry class.

            class Jerry {
    
    
    
              int x;
    
              int y;
    
              int speedX;
    
              int speedY;
    
              int w;
    
              int h;
    
    
    
              Jerry (int jx, int jy, int jW, int jH) {
    
                x = jx;
    
                y = jy;
    
                speedX = 0;
    
                speedY = 0;
    
                w = jW;
    
                h = jH;
    
              }
    
    
    
              // Displays each frame depending on what direction it is facing.
    
              void display () {
    
                image(jerryWalking[currentFrame], x, y, w, h);
    
                if (speedX == speed) {
    
                  currentDirection = "right";
    
                  if (walking) {
    
                    if (millis ()- timeSinceLastFrame >= frameSpeed) {
    
                      timeSinceLastFrame = millis();
    
                      currentFrame++;
    
                      if (currentFrame == jerryFrames) {
    
                        currentFrame =0;
    
                      }
    
                    }
    
                  }
    
                }
    
                if (speedX == -1 *speed) {
    
                  currentDirection = "left";
    
                  if (walking) {
    
                    if (millis ()- timeSinceLastFrame >= frameSpeed) {
    
                      timeSinceLastFrame = millis();
    
                      currentFrame++;
    
                      if (currentFrame == jerryFrames) {
    
                        currentFrame =0;
    
                      }
    
                    }
    
                  }
    
                }
    
                if (speedY == speed) {
    
                  currentDirection = "down";
    
                  if (walking) {
    
                    if (millis ()- timeSinceLastFrame >= frameSpeed) {
    
                      timeSinceLastFrame = millis();
    
                      currentFrame++;
    
                      if (currentFrame == jerryFrames) {
    
                        currentFrame =0;
    
                      }
    
                    }
    
                  }
    
                }
    
                if (speedY == -1 * speed) {
    
                  currentDirection = "up";
    
                  if (walking) {
    
                    if (millis ()- timeSinceLastFrame >= frameSpeed) {
    
                      timeSinceLastFrame = millis();
    
                      currentFrame++;
    
                      if (currentFrame == jerryFrames) {
    
                        currentFrame =0;
    
                      }
    
                    }
    
                  }
    
                }
    
              }
    
    
    
              // Allows the sprite to walk.
    
              void update () {
    
                if (left) {
    
                  speedX = -1 * speed;
    
                }
    
                if (right) {
    
                  speedX = speed;
    
                }
    
                if (!left && !right) {
    
                  speedX = 0;
    
                }
    
                if (left && right) {
    
                  speedX = 0;
    
                }
    
                if (up) {
    
                  speedY = -1 * speed;
    
                }
    
                if (down) {
    
                  speedY = speed;
    
                }
    
                if (!down && !up) {
    
                  speedY = 0;
    
                }
    
                if (down && up) {
    
                  speedY = 0;
    
                }
    
                if (left && up) {
    
                  speedY = 0;
    
                }
    
                if (right && up) {
    
                  speedY = 0;
    
                }
    
                if (right && down) {
    
                  speedY = 0;
    
                }
    
                if (left && down) {
    
                  speedY = 0;
    
                }
    
                x+=0;
    
                y+=0;
    
              }
    
            }
    

    I currently have an image as my background , its not a tile map. It seems to be working fine. Thanks again. This is my updated code, if you know of any way that I can send you the images please let me know ASAP.

            import gifAnimation.*;
    
    
    
            PImage [] jerryWalking;
    
            PImage [] allFireFrames;
    
            Gif fire;
    
            PImage bg;
    
            int jerryFrames = 4;
    
            String currentDirection = "right";
    
            Boolean left, right, up, down ;
    
            int currentFrame = 0;
    
            Boolean walking = false;
    
            int speed = 2;
    
            int frameSpeed = 200;
    
            float timeSinceLastFrame;
    
            int bottomBorder = 250;
    
            int topBorder = 1;
    
            int scene = 1;
    
            int bgX =-1669;
    
            int bgY = -522;
    
            int scrollSpeed = 4;
    
            int offsetX = 0;
    
            int offsetY = 0;
    
            boolean isOut;
    
            Jerry j = new Jerry(200, 200, 32, 32);
    
            Border b;
    
    
    
            // Loads the animation frames for your character.
    
            void loadAssets () {
    
              jerryWalking = new PImage[jerryFrames];
    
              for ( int i = 0; i<jerryFrames; i++) {
    
                jerryWalking[i]=loadImage("jerry_"+currentDirection+(i+1)+".png");
    
              }
    
            }
    
    
    
            void setup () {
    
              //surface.setResizable(true);
    
              frameRate(60);
    
              size (500, 500);
    
              left = false;
    
              right = false;
    
              down = false;
    
              up = false;
    
              timeSinceLastFrame = millis();
    
              allFireFrames = Gif.getPImages(this, "fire.gif");
    
              bg = loadImage("map.png");
    
              fire = new Gif(this, "fire.gif");
    
              fire.play();
    
            }
    
            void draw () {
    
              frameRate(30);
    
              background(0);
    
              image(bg, bgX, bgY);
    
              b = new Border(283-offsetX,35-offsetY,196,400);
    
              image(fire, width/2-offsetX-65, height/2-offsetY-30);
    
              image(fire, width/2-offsetX-65, height/2-offsetY+90);
    
              loadAssets();
    
              // Barrabas
    
              j.display();
    
              j.update();
    
              // Border prototype
    
              isOut = b.checkIfOut(j.x+32,j.y);
    
              b.display();
    
              b.keepJin();
    
              println(bgX, bgY);
    
              fill(255);
    
              println(b.wb,b.hb);
    
              println(mouseX,mouseY);
    
              println(isOut);
    
    
    
            }
    
    
    
            //Movement
    
            void keyPressed () {
    
              switch(keyCode) {
    
              case 37:
    
                left = true;
    
                currentDirection = "left";
    
                walking = true;
    
                bgX += scrollSpeed;
    
                offsetX -= scrollSpeed;
    
                break;
    
              case 39:
    
                right = true;
    
                currentDirection = "right";
    
                walking = true;
    
                bgX -= scrollSpeed;
    
                offsetX += scrollSpeed;
    
                break;
    
              case 38:
    
                up = true;
    
                currentDirection = "up";
    
                walking = true;
    
                bgY+= scrollSpeed;
    
                offsetY -= scrollSpeed;
    
                break;
    
              case 40:
    
                currentDirection = "down";
    
                down = true;
    
                walking = true;
    
                bgY -= scrollSpeed;
    
                offsetY += scrollSpeed;
    
                break;
    
              }
    
            }
    
    
    
            void keyReleased () {
    
              switch(keyCode) {
    
              case 37:
    
                left = false;
    
                currentDirection = "left";
    
                walking = false;
    
                break;
    
              case 39:
    
                right = false;
    
                currentDirection = "right";
    
                walking = false;
    
                break;
    
              case 38:
    
                up = false;
    
                currentDirection = "up";
    
                walking = false;
    
                break;
    
              case 40:
    
                down = false;
    
                currentDirection = "down";
    
                walking = false;
    
                break;
    
              case 70:
    
                scrollSpeed--;
    
                break;
    
              case 71:
    
                scrollSpeed++;
    
                break;
    
              }
    
            }
    

    BORDER CLASS :

            class Border {
    
    
    
              int x;
    
              int y;
    
              int w;
    
              int h;
    
              int wb;
    
              int hb;
    
    
    
              Border(int bx, int by, int bw, int bh) {
    
                x = bx;
    
                y = by;
    
                w = bw;
    
                h = bh;
    
                wb = x+w;
    
                hb = y+h;
    
              }
    
    
    
              void display () {
    
                noStroke();
    
                fill(255);
    
                rect(x, y, w, h);
    
              }
    
    
    
              boolean checkIfOut (int mx, int my) {
    
                if ( mx>x && mx<wb && my>y && my<hb) {
    
                  return true;
    
                } else {
    
                  return false;
    
                }
    
              }
    
    
    
              void keepJin () {
    
                if (isOut == true) {
    
                  j.x = x-32;
    
                  scrollSpeed = 0;
    
                }
    
                if (isOut == false) {
    
                scrollSpeed = 4;
    
                }
    
              }
    
            } // end of Border Class
    
  • Creating a Big Background Image That a Player Can Navigate and the Camera Follows Them

    I made an example where I create an internal image (map) artificially and then the player runs over it

    then the map is treated via a viewPort

    solution for right and left ONLY

    // https : // forum.processing.org/two/discussion/26491/creating-a-big-background-image-that-a-player-can-navigate-and-the-camera-follows-them#latest
    // 27/2/2018
    
    PImage [] jerryWalking;
    
    PGraphics bg;
    
    int jerryFrames = 4;
    String currentDirection = "right";
    Boolean left, right, up, down ;
    int currentFrame = 0;
    Boolean walking = false;
    int speed = 2;
    int frameSpeed = 200;
    float timeSinceLastFrame;
    int bottomBorder = 250;
    int topBorder = 1;
    int scene = 1;
    
    Jerry j = new Jerry();//(200, 200, 32, 32);
    
    float viewPortX, viewPortY;
    
    //-----------------------------------------------------------------
    
    void setup () {
    
      size(800, 800); 
    
      surface.setResizable(true);
      left = false;
      right = false;
      down = false;
      up = false;
      timeSinceLastFrame = millis();
    
      // bg = loadImage("scene1.png");
    
      //if(bg==null) {
      if (true) {
        bg= createGraphics(5000, 5000);
        bg.beginDraw();
        bg.background(100);
        bg.stroke(255);
        for (int x=0; x < bg.width; x+=50) {
          for (int y=0; y < bg.height; y+=50) {
            bg.fill(random(255));
            bg.rect(x, y, 50, 50);
          }
        }// end of for
        bg.endDraw();
      }//if
    
      loadAssets();
    }//func 
    
    void draw () {
      //  surface.setSize(bg.width, bg.height);
    
      image(bg, viewPortX, viewPortY);
    
      j.display();
      j.update();
    
      print(j.x);
      print(",");
      println(j.y);
      // left 1094
      // right 1118
    
      // manage viewPort -----------------
    
    
      if (j.x<60) // player 
        viewPortX+=5;
    
      // checks X  
      if (viewPortX > bg.width-width)
        viewPortX=bg.width-width;
    
      if (viewPortX < width-bg.width)
        viewPortX=width-bg.width;
    
      if (viewPortX < -bg.width+width)
        viewPortX=-bg.width+width;
    
      if (viewPortX > 0)
        viewPortX=0;
    }
    
    //-----------------------------------------------------------------------
    
    void loadAssets () {
      jerryWalking = new PImage[jerryFrames];
      for ( int i = 0; i<jerryFrames; i++) {
        jerryWalking[i]=loadImage("jerry_"+currentDirection+(i+1)+".png");
      }
    }
    
    // --------------------------------------------------------------------
    
    void keyPressed () {
      switch(keyCode) {
      case 37:
        left = true;
        currentDirection = "left";
        walking = true;
        break;
      case 39:
        right = true;
        currentDirection = "right";
        walking = true;
        break;
      case 38:
        up = true;
        currentDirection = "up";
        walking = true;
        break;
      case 40:
        currentDirection = "down";
        down = true;
        walking = true;
        break;
      }
    }
    
    void keyReleased () {
      switch(keyCode) {
      case 37:
        left = false;
        currentDirection = "left";
        walking = false;
        break;
      case 39:
        right = false;
        currentDirection = "right";
        walking = false;
        break;
      case 38:
        up = false;
        currentDirection = "up";
        walking = false;
        break;
      case 40:
        down = false;
        currentDirection = "down";
        walking = false;
        break;
      case 70:
        speed--;
        break;
      case 71:
        speed++;
        break;
      }
    }
    
    // ================================================================
    
    class Jerry {
    
      float x=110, 
        y=110;
    
      void display() {
        ellipse(x, y, 13, 14);
      }
    
      void update() {
        if (right) {
    
          if (viewPortX <= width-bg.width) {
            viewPortX=width-bg.width;
            x+=4;
          } else {
            if (j.x>width-60) // player 
              viewPortX-=5;
            else 
            x+=4;
          }
        }//right 
    
        if (left) {
          if (viewPortX >= 0) {
            viewPortX=0;
            x-=4;
          } else {
            if (j.x<60) // player 
              viewPortX+=5;
            else 
            x-=4;
          }
        }//left 
    
    
        if (up)
          y-=4;
    
        if (down)
          y+=4;
    
        //-----------------
        // checks
    
        if (x>width-7)
          x=width-7;
    
        if (x<7)
          x=7;
      }
    }//class 
    //
    
  • How can I resize my sketch when using ControlP5 Buttons.

    I'm very new to processing so please excuse my lack of proper terminology. When I open this sketch and move my mouse over the buttons they highlight and work as expected. When I make the screen much larger all appears ok except when I move my mouse over the buttons they no longer highlight and work unless I move my mouse to what appears to be the old unscaled location of the buttons. Any Idea how to fix this?

    Roger.

    This is my code. Hope I'm posting it right.

    import controlP5.*;
    ControlP5 cp5;
    
    PFont font1;
    
    void setup() {
    
      size(500, 500);
      surface.setResizable(true);
    
      font1 = createFont("Ravie", 20, true);   
    
      cp5 = new ControlP5(this);
      cp5.addButton("button1")
        .setCaptionLabel("Button 1")
        .setPosition(100, 200)
        .setSize(125, 50)
        .setColorBackground(0)
        .setFont(font1)
        ;
      cp5.addButton("button2")
        .setCaptionLabel("Button2")
        .setPosition(100, 350)
        .setSize(125, 50)
        .setColorBackground(0)
        .setFont(font1)
        ;
    }
    
    
    void draw() {
    
      scale( width/500.0, height/500.0);
    
      background(0);
    }
    
  • Creating a Big Background Image That a Player Can Navigate and the Camera Follows Them

    So I'm trying to create an RPG game for my Computer Science class and I want to make the camera follow my sprite around the canvas and have one big background image that only shows a portion on the canvas and as the user moves it goes to a new part of the image. Essentially creating the map for my game which the player can navigate.

    Kind of like this but in 2D:

    Currently, I am drawing each scene after the player passes the edge and resizing the canvas to fit the image. This isn't too good because it displaces the window and the user has to keep moving it in order to see the full map. Please help.

    This is the code I have so far:

        PImage [] jerryWalking;
        PImage bg;
        int jerryFrames = 4;
        String currentDirection = "right";
        Boolean left, right, up, down ;
        int currentFrame = 0;
        Boolean walking = false;
        int speed = 2;
        int frameSpeed = 200;
        float timeSinceLastFrame;
        int bottomBorder = 250;
        int topBorder = 1;
        int scene = 1;
        Jerry j = new Jerry(200, 200, 32, 32);
    
        void loadAssets () {
          jerryWalking = new PImage[jerryFrames];
          for ( int i = 0; i<jerryFrames; i++) {
            jerryWalking[i]=loadImage("jerry_"+currentDirection+(i+1)+".png");
          }
        }
    
        void setup () {
          surface.setResizable(true);
          left = false;
          right = false;
          down = false;
          up = false;
          timeSinceLastFrame = millis();
          bg = loadImage("scene1.png");
        }
        void draw () {
          surface.setSize(bg.width, bg.height);
          image(bg, 0, 0);
          loadAssets();
          j.display();
          j.update();
          println(j.x);
          println();
          println(j.y);
          // left 1094
          // right 1118
        }
    
    
        void keyPressed () {
          switch(keyCode) {
          case 37:
            left = true;
            currentDirection = "left";
            walking = true;
            break;
          case 39:
            right = true;
            currentDirection = "right";
            walking = true;
            break;
          case 38:
            up = true;
            currentDirection = "up";
            walking = true;
            break;
          case 40:
            currentDirection = "down";
            down = true;
            walking = true;
            break;
          }
        }
    
        void keyReleased () {
          switch(keyCode) {
          case 37:
            left = false;
            currentDirection = "left";
            walking = false;
            break;
          case 39:
            right = false;
            currentDirection = "right";
            walking = false;
            break;
          case 38:
            up = false;
            currentDirection = "up";
            walking = false;
            break;
          case 40:
            down = false;
            currentDirection = "down";
            walking = false;
            break;
          case 70:
            speed--;
            break;
          case 71:
            speed++;
            break;
          }
        }
    
  • Problems with Kim Asendorf's code for Pixel Sorting

    Whenever I substantiate the code, I get the problem "NullPointerException" at the "surface.setSize(img.width, img.height);" line and it says "Could not find a method to load image.jpg". What could be the problem

    int mode = 1;
    
    // image path is relative to sketch directory
    PImage img;
    String imgFileName = "MyImage";
    String fileType = "png";
    
    int loops = 1;
    
    // threshold values to determine sorting start and end pixels
    int blackValue = -16000000;
    int brightnessValue = 60;
    int whiteValue = -13000000;
    
    int row = 0;
    int column = 0;
    
    boolean saved = false;
    
    void setup() {
      img = loadImage(imgFileName+"."+fileType);
    
      // use only numbers (not variables) for the size() command, Processing 3
      size(1, 1);
    
      // allow resize and update surface to image dimensions
      surface.setResizable(true);
      surface.setSize(img.width, img.height);
    
      // load image onto surface - scale to the available width,height for display
      image(img, 0, 0, width, height);
    }
    
    
    void draw() {
    
      // loop through columns
      while(column < img.width-1) {
        println("Sorting Column " + column);
        img.loadPixels(); 
        sortColumn();
        column++;
        img.updatePixels();
      }
    
      // loop through rows
      while(row < img.height-1) {
        println("Sorting Row " + column);
        img.loadPixels(); 
        sortRow();
        row++;
        img.updatePixels();
      }
    
      // load updated image onto surface and scale to fit the display width,height
      image(img, 0, 0, width, height);
    
      if(!saved && frameCount >= loops) {
    
        // save img
        img.save(imgFileName+"_"+mode+".png");
    
        saved = true;
        println("Saved "+frameCount+" Frame(s)");
    
        // exiting here can interrupt file save, wait for user to trigger exit
        println("Click or press any key to exit...");
      }
    }
    
    void keyPressed() {
      if(saved)
      {
        System.exit(0);
      }
    }
    
    void mouseClicked() {
      if(saved)
      {
        System.exit(0);
      }
    }
    
    void sortRow() {
      // current row
      int y = row;
    
      // where to start sorting
      int x = 0;
    
      // where to stop sorting
      int xend = 0;
    
      while(xend < img.width-1) {
        switch(mode) {
          case 0:
            x = getFirstNotBlackX(x, y);
            xend = getNextBlackX(x, y);
            break;
          case 1:
            x = getFirstBrightX(x, y);
            xend = getNextDarkX(x, y);
            break;
          case 2:
            x = getFirstNotWhiteX(x, y);
            xend = getNextWhiteX(x, y);
            break;
          default:
            break;
        }
    
        if(x < 0) break;
    
        int sortLength = xend-x;
    
        color[] unsorted = new color[sortLength];
        color[] sorted = new color[sortLength];
    
        for(int i=0; i<sortLength; i++) {
          unsorted[i] = img.pixels[x + i + y * img.width];
        }
    
        sorted = sort(unsorted);
    
        for(int i=0; i<sortLength; i++) {
          img.pixels[x + i + y * img.width] = sorted[i];      
        }
    
        x = xend+1;
      }
    }
    
    
    void sortColumn() {
      // current column
      int x = column;
    
      // where to start sorting
      int y = 0;
    
      // where to stop sorting
      int yend = 0;
    
      while(yend < img.height-1) {
        switch(mode) {
          case 0:
            y = getFirstNotBlackY(x, y);
            yend = getNextBlackY(x, y);
            break;
          case 1:
            y = getFirstBrightY(x, y);
            yend = getNextDarkY(x, y);
            break;
          case 2:
            y = getFirstNotWhiteY(x, y);
            yend = getNextWhiteY(x, y);
            break;
          default:
            break;
        }
    
        if(y < 0) break;
    
        int sortLength = yend-y;
    
        color[] unsorted = new color[sortLength];
        color[] sorted = new color[sortLength];
    
        for(int i=0; i<sortLength; i++) {
          unsorted[i] = img.pixels[x + (y+i) * img.width];
        }
    
        sorted = sort(unsorted);
    
        for(int i=0; i<sortLength; i++) {
          img.pixels[x + (y+i) * img.width] = sorted[i];
        }
    
        y = yend+1;
      }
    }
    
    
    // black x
    int getFirstNotBlackX(int x, int y) {
    
      while(img.pixels[x + y * img.width] < blackValue) {
        x++;
        if(x >= img.width) 
          return -1;
      }
    
      return x;
    }
    
    int getNextBlackX(int x, int y) {
      x++;
    
      while(img.pixels[x + y * img.width] > blackValue) {
        x++;
        if(x >= img.width) 
          return img.width-1;
      }
    
      return x-1;
    }
    
    // brightness x
    int getFirstBrightX(int x, int y) {
    
      while(brightness(img.pixels[x + y * img.width]) < brightnessValue) {
        x++;
        if(x >= img.width)
          return -1;
      }
    
      return x;
    }
    
    int getNextDarkX(int _x, int _y) {
      int x = _x+1;
      int y = _y;
    
      while(brightness(img.pixels[x + y * img.width]) > brightnessValue) {
        x++;
        if(x >= img.width) return img.width-1;
      }
      return x-1;
    }
    
    // white x
    int getFirstNotWhiteX(int x, int y) {
    
      while(img.pixels[x + y * img.width] > whiteValue) {
        x++;
        if(x >= img.width) 
          return -1;
      }
      return x;
    }
    
    int getNextWhiteX(int x, int y) {
      x++;
    
      while(img.pixels[x + y * img.width] < whiteValue) {
        x++;
        if(x >= img.width) 
          return img.width-1;
      }
      return x-1;
    }
    
    
    // black y
    int getFirstNotBlackY(int x, int y) {
    
      if(y < img.height) {
        while(img.pixels[x + y * img.width] < blackValue) {
          y++;
          if(y >= img.height)
            return -1;
        }
      }
    
      return y;
    }
    
    int getNextBlackY(int x, int y) {
      y++;
    
      if(y < img.height) {
        while(img.pixels[x + y * img.width] > blackValue) {
          y++;
          if(y >= img.height)
            return img.height-1;
        }
      }
    
      return y-1;
    }
    
    // brightness y
    int getFirstBrightY(int x, int y) {
    
      if(y < img.height) {
        while(brightness(img.pixels[x + y * img.width]) < brightnessValue) {
          y++;
          if(y >= img.height)
            return -1;
        }
      }
    
      return y;
    }
    
    int getNextDarkY(int x, int y) {
      y++;
    
      if(y < img.height) {
        while(brightness(img.pixels[x + y * img.width]) > brightnessValue) {
          y++;
          if(y >= img.height)
            return img.height-1;
        }
      }
      return y-1;
    }
    
    // white y
    int getFirstNotWhiteY(int x, int y) {
    
      if(y < img.height) {
        while(img.pixels[x + y * img.width] > whiteValue) {
          y++;
          if(y >= img.height)
            return -1;
        }
      }
    
      return y;
    }
    
    int getNextWhiteY(int x, int y) {
      y++;
    
      if(y < img.height) {
        while(img.pixels[x + y * img.width] < whiteValue) {
          y++;
          if(y >= img.height) 
            return img.height-1;
        }
      }
    
      return y-1;
    }
    
  • Processing Works Perfectly Local but Cursor Incorrect Position Online

    Hello,

    My file works perfectly local when I run it in Processing, however, when I upload this to my website the cursor on the animation is around 500px from my cursor. Please see here:

    https://ts133842-container.zoeysite.com/

    The size of the frame matches the size against size(). My code is below.

    Particle p = new Particle();
    
    final int LIGHT_FORCE_RATIO = 70;  
    final int  LIGHT_DISTANCE= 70 * 50;  
    final int  BORDER = 100;  
    float baseRed, baseGreen, baseBlue;  
    float baseRedAdd, baseGreenAdd, baseBlueAdd;  
    final float RED_ADD = 3.2;   
    final float GREEN_ADD = 1.7;  
    final float BLUE_ADD = 4.3;  
    float boxX, boxY;
    float widthSize = width;
    
    int rectWidth = 915;
    int rectHeight = 197;
    
    
    //PImage img;
    
    void setup() {
      background(0);
      size(1840, 400);
     // surface.setResizable(true);
      noCursor();
      //img = loadImage("flowtoy.jpg");
      baseRed = 0;
      baseRedAdd = RED_ADD;
    
      baseGreen = 0;
      baseGreenAdd = GREEN_ADD;
    
      baseBlue = 0;
      baseBlueAdd = BLUE_ADD;
    
      boxX = width/2;
      boxY = height/2;
    }
    
    void draw() {
      //image(img, 400, 100, img.width/2, img.height/2);
      if (mouseX>boxX-rectWidth && mouseX<boxX+rectWidth &&
        mouseY>boxY-rectHeight && mouseY<boxY+rectHeight) {
    
        //saveFrame("output/LightDrawing_####.png");
    
        baseRed += baseRedAdd;
        baseGreen += baseGreenAdd;
        baseBlue += baseBlueAdd;
    
        colorOutCheck();
    
        p.move(mouseX, mouseY);
    
    
        int tRed = (int)baseRed;
        int tGreen = (int)baseGreen;
        int tBlue = (int)baseBlue;
    
        tRed *= tRed;
        tGreen *= tGreen;
        tBlue *= tBlue;
    
    
        loadPixels();
    
        int left = max(0, p.x - BORDER);
        int right = min(width, p.x + BORDER);
        int top = max(0, p.y - BORDER);
        int bottom = min(height, p.y + BORDER);
    
    
        for (int y = top; y < bottom; y++) {
          for (int x = left; x < right; x++) {
            int pixelIndex = x + y * width;
    
            int r = pixels[pixelIndex] >>16 & 0xFF;
            int g = pixels[pixelIndex] >> 8 & 0xFF;
            int b = pixels[pixelIndex] & 0xFF;
    
    
            int dx = x - p.x;
            int dy = y - p.y;
            int distance = (dx *dx ) + (dy* dy);  
    
    
            if (distance < LIGHT_DISTANCE) {
              int fixFistance = distance * LIGHT_FORCE_RATIO;
    
              if (fixFistance == 0) {
                fixFistance = 1;
              }   
              r = r + tRed / fixFistance;
              g = g + tGreen / fixFistance;
              b = b + tBlue / fixFistance;
            }
            pixels[x + y * width] = color(r, g, b);
          }
        }
    
         updatePixels();
      } else { 
        setup();
      }
    
      //updatePixels();
    }
    
    
    void colorOutCheck() {
      if (baseRed < 10) {
        baseRed = 10;
        baseRedAdd *= -1;
      } else if (baseRed > 255) {
        baseRed = 255;
        baseRedAdd *= -1;
      }
    
      if (baseGreen < 10) {
        baseGreen = 10;
        baseGreenAdd *= -1;
      } else if (baseGreen > 255) {
        baseGreen = 255;
        baseGreenAdd *= -1;
      }
    
      if (baseBlue < 10) {
        baseBlue = 10;
        baseBlueAdd *= -1;
      } else if (baseBlue > 255) {
        baseBlue = 255;
        baseBlueAdd *= -1;
      }
    }
    
    void mousePressed()
    {
      setup();
    }
    
    class Particle {
      int x, y;        
      float vx, vy;    
      //float slowLevel;
    
    
      Particle() {
        x = (int)3;
        y = (int)2;
     //   slowLevel = random(100) + 1;
      }
    
      void move(float targetX, float targetY) {
        vx = (targetX - x) ;
        vy = (targetY - y) ;
    
        x = (int)(x + vx);
        y = (int)(y + vy);
      }
    }
    

    Is anything immediately obvious? Thank you.

  • Unable to Get Background Image Working Online

    Hey guys. I have added a background image to my code which shows fine when I run this in Processing 3.3.6, however, when I host this on my website I get the following error in the console log before the background goes grey:

    Screenshot at Feb 17 13-38-30

    dc_theme_assets_6336.js?v=1518869301:286 Uncaught Error using image in background(): PImage not loaded.

    I don't really understand why this would be any different. I don't have much luck when searching online for this particular error in relation to my issue, so I'm wondering if anyone could share any insight?

    Please see my full code below. The background image 'bannerbg.jpg' on line 20. Thanks so much.

    Particle p = new Particle();
    
    final int LIGHT_FORCE_RATIO = 70;  
    final int  LIGHT_DISTANCE= 70 * 50;  
    final int  BORDER = 100;  
    float baseRed, baseGreen, baseBlue;  
    float baseRedAdd, baseGreenAdd, baseBlueAdd;  
    final float RED_ADD = 3.2;   
    final float GREEN_ADD = 1.7;  
    final float BLUE_ADD = 4.3;  
    float boxX, boxY;
    float widthSize = width;
    
    int rectWidth = 915;
    int rectHeight = 197;
    
    PImage img;
    
    void setup() {
    img = loadImage("https://"+"s3.amazonaws.com/zcom-media/sites/a0iE000000QK9yZIAT/media/mediamanager/bannerbg.jpg");
    
      background(img);
      size(1840, 400);
     // surface.setResizable(true);
      noCursor();
      //img = loadImage("flowtoy.jpg");
      baseRed = 0;
      baseRedAdd = RED_ADD;
    
      baseGreen = 0;
      baseGreenAdd = GREEN_ADD;
    
      baseBlue = 0;
      baseBlueAdd = BLUE_ADD;
    
      boxX = width/2;
      boxY = height/2;
    
    }
    
    void draw() {
      //image(img, 400, 100, img.width/2, img.height/2);
      if (mouseX>boxX-rectWidth && mouseX<boxX+rectWidth &&
        mouseY>boxY-rectHeight && mouseY<boxY+rectHeight) {
    
        //saveFrame("output/LightDrawing_####.png");
    
        baseRed += baseRedAdd;
        baseGreen += baseGreenAdd;
        baseBlue += baseBlueAdd;
    
        colorOutCheck();
    
        p.move(mouseX, mouseY);
    
    
        int tRed = (int)baseRed;
        int tGreen = (int)baseGreen;
        int tBlue = (int)baseBlue;
    
        tRed *= tRed;
        tGreen *= tGreen;
        tBlue *= tBlue;
    
    
        loadPixels();
    
        int left = max(0, p.x - BORDER);
        int right = min(width, p.x + BORDER);
        int top = max(0, p.y - BORDER);
        int bottom = min(height, p.y + BORDER);
    
    
        for (int y = top; y < bottom; y++) {
          for (int x = left; x < right; x++) {
            int pixelIndex = x + y * width;
    
            int r = pixels[pixelIndex] >>16 & 0xFF;
            int g = pixels[pixelIndex] >> 8 & 0xFF;
            int b = pixels[pixelIndex] & 0xFF;
    
    
            int dx = x - p.x;
            int dy = y - p.y;
            int distance = (dx *dx ) + (dy* dy);  
    
    
            if (distance < LIGHT_DISTANCE) {
              int fixFistance = distance * LIGHT_FORCE_RATIO;
    
              if (fixFistance == 0) {
                fixFistance = 1;
              }   
              r = r + tRed / fixFistance;
              g = g + tGreen / fixFistance;
              b = b + tBlue / fixFistance;
            }
            pixels[x + y * width] = color(r, g, b);
          }
        }
    
         updatePixels();
      } else { 
        setup();
      }
    
      //updatePixels();
    }
    
    
    void colorOutCheck() {
      if (baseRed < 10) {
        baseRed = 10;
        baseRedAdd *= -1;
      } else if (baseRed > 255) {
        baseRed = 255;
        baseRedAdd *= -1;
      }
    
      if (baseGreen < 10) {
        baseGreen = 10;
        baseGreenAdd *= -1;
      } else if (baseGreen > 255) {
        baseGreen = 255;
        baseGreenAdd *= -1;
      }
    
      if (baseBlue < 10) {
        baseBlue = 10;
        baseBlueAdd *= -1;
      } else if (baseBlue > 255) {
        baseBlue = 255;
        baseBlueAdd *= -1;
      }
    }
    
    void mousePressed()
    {
      setup();
    }
    
    class Particle {
      int x, y;        
      float vx, vy;    
      //float slowLevel;
    
    
      Particle() {
        x = (int)3;
        y = (int)2;
     //   slowLevel = random(100) + 1;
      }
    
      void move(float targetX, float targetY) {
        vx = (targetX - x) ;
        vy = (targetY - y) ;
    
        x = (int)(x + vx);
        y = (int)(y + vy);
      }
    }