Howdy, Stranger!

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

  • Can u someone help me to draw this? (beziers)

    similar to the 2D editor above, here is a 3D Editor.

    the editor uses three steps:

    • you can enter points with the mouse, when you are ready, hit e to go to next step (you can go back to this step any time). You can edit the points and move them in x, y and z direction.

    • you can connect points to shapes (triangles are most common, rectangles and other shapes possible as well). End each single shape with hitting return/enter, then continue clicking with the mouse to make the next shape. You can define as much shapes as you want. All are based on the initial points.

    • hit x to export (using println()) to a full self running sketch

    Example usage:

    Typical example is a cube with 8 corners. You define the corners as points (step 1), you connect points to fore front (4 points), backside front, 4 walls (step 2), you export (step 3).

    Download:

    • Because of the complexity of the sketch (and the usage of multiple tabs) I posted it on github (and not here as the other sketches).

    name: vertexEditorForFill3Dc

    https://github.com/Kango/3DSketches

    Best, Chrisir ;-)

  • Can u someone help me to draw this? (beziers)

    here is yet another graphical Editor.

    This time the editor uses three steps:

    • you can enter points with the mouse, when you are ready, hit e to go to next step

    • you can connect points to shapes (triangles are most common, rectangles and other shapes possible as well). End each single shape with hitting return/enter, then continue clicking with the mouse to make the next shape. You can define as much shapes as you want. All are based on the initial points.

    • hit e to export (using println()) to a full self running sketch

    Example usage:

    Typical example is a cube with 8 corners. You define the corners as points (step 1), you connect points to fore front (4 points), backside front, 4 walls (step 2), you export (step 3).

    when I have time, I'll post in the new forum as well

    Chrisir ;-)

    // https://forum.processing.org/two/discussion/comment/124510/#Comment_124510 
    // https://en.wikipedia.org/wiki/Vertex_(computer_graphics)#Application_to_3D_models
    
    final String HELP1 = 
      "Click mouse to enter points."
      +"\nBackspace to delete last item."
      +"\nHit c to delete entire list." 
      +"\nHit e for connect mode." ;
    
    final String HELP2 = 
      "Click mouse to connect points."
      +"\nBackspace to delete last item."
      +"\nHit c to delete entire list." 
      +"\nHit Space bar: fill on/off." 
      +"\nHit p to go back to points mode"
      +"\nHit e to export." ;
    
    final int textBigSize = 19; 
    
    ArrayList<PVector> listPoints = new ArrayList();  
    ArrayList<OneShape> listShapes = new ArrayList();
    
    // current shape index for listShapes
    int currShape; 
    
    boolean showFill = true;  
    boolean flagExported = false; 
    
    //states 
    final int STATE_DRAW_POINTS = 0; // corners const  
    final int STATE_DRAW_SHAPES  = 1; // shapes const
    int state =  STATE_DRAW_POINTS; // current state 
    
    void setup() {
      size(1200, 888);
      background(111);
      listShapes.add(new OneShape());
    }
    
    void draw() {
    
      switch(state) {
    
      case STATE_DRAW_POINTS:
        drawForSTATE_DRAW_POINTS();
        break; 
    
      case STATE_DRAW_SHAPES:
        drawForSTATE_DRAW_SHAPES();
        break;
        //
      } //switch
      //
    } //func 
    
    // --------------------------------------------------------------------
    // called from draw() 
    
    void drawForSTATE_DRAW_POINTS() {
    
      background(111);
    
      // the list that has been entered 
      showlistPoints1();
      // show Instructions
      showInstructions(HELP1);
    
      // Mode Headline 
      textAlign(CENTER); 
      fill(255); 
      textSize(textBigSize); 
      text("Mode draw points (hit e to go to edges mode)", 
        width/2, 19);
      textAlign(LEFT);
      textSize(11);
    }
    
    void drawForSTATE_DRAW_SHAPES() {
      background(111);
      // the list that has been entered 
      showlistPoints1();
      // show Instructions
      showInstructions(HELP2);
    
      // on mouse over - effect 
      for (int i = 0; i < listPoints.size(); i++) {
        if (dist(mouseX, mouseY, listPoints.get(i).x, listPoints.get(i).y) < 20) {
          //
          stroke(255, 0, 0); 
          pointPVector(listPoints.get(i));
          break;
        }
      }
    
      // text curr shape  -------------------------------
      String a1=""; 
      for (int i : listShapes.get(currShape).indices) {
        a1 += str(i)+", ";
      }
      fill(255); 
      text("Current shape consists of corners # \nUse mouse to connect points\n"
        +a1
        +"\nHit enter to close current shape.", 
        width-210, 200); 
    
      // List of shapes : ---------------------------------
    
      for (OneShape os : listShapes) {
        // get edges of os 
        for (int i : os.indices) {
          a1 += str(i)+", ";
        }
        a1+="\n";
      }//for
      fill(255);
      String flagExportedText="";
    
      if (flagExported) 
        flagExportedText="(exported)\n";
      else flagExportedText="(not exported)\n";
    
      text(flagExportedText
        +"\nList of shapes :\n"
        +a1, 
        width-210, 300); 
    
      // lines for curr shapes -------------------------------------- 
    
      for (int i = 0; i < listShapes.get(currShape).indices.size()-1; i++) {
        stroke(0); 
        line( listPoints.get(listShapes.get(currShape).indices.get(i)) .x, 
          listPoints.get(listShapes.get(currShape).indices.get(i)) .y, 
          listPoints.get(listShapes.get(currShape).indices.get(i+1)) .x, 
          listPoints.get(listShapes.get(currShape).indices.get(i+1)) .y
          );
      }//for 
    
      // all Shapes
      for (OneShape os : listShapes) {
        os.show();
      }
    
      // Mode Headline 
      textAlign(CENTER); 
      fill(255); 
      textSize(textBigSize); 
      text("Mode draw edges (hit p to go to points mode)", 
        width/2, 19); 
      textAlign(LEFT);
      textSize(11);
    }
    
    // -----------------------------------------------------------
    // Inputs MOUSE
    
    void mousePressed () {
    
      switch(state) {
    
      case STATE_DRAW_POINTS : 
        PVector pv1 = new PVector(mouseX, mouseY); 
        listPoints.add(pv1); 
        flagExported = false; 
        break; 
    
      case STATE_DRAW_SHAPES : 
        for (int i=0; i<listPoints.size(); i++) {
          PVector pv = listPoints.get(i); 
    
          if (dist(mouseX, mouseY, pv.x, pv.y) < 20) {
            listShapes.get(currShape).indices.add ( i );
            flagExported = false; 
            return;
          }
        }//for
        break;
      } //switch
      //
    } //func
    
    // -----------------------------------------------------------
    // Inputs KEYBOARD 
    
    void keyPressed() {
      switch(state) {
    
      case STATE_DRAW_POINTS : 
        keyPressedForSTATE_DRAW_POINTS(); 
        break; 
    
      case STATE_DRAW_SHAPES : 
        keyPressedForSTATE_DRAW_SHAPES(); 
        break;
      }//switch
    }//func 
    
    void keyPressedForSTATE_DRAW_POINTS () {
      if (key=='c') {
        // delete all 
        listPoints.clear();
      } else if (key==BACKSPACE) {
        // delete last 
        if (listPoints.size()>0) {
          listPoints.remove(listPoints.size()-1);
        }
      } else if ( key=='e' ) {
        // toggle 
        state =  STATE_DRAW_SHAPES; // current state
      }
    }//func 
    
    void keyPressedForSTATE_DRAW_SHAPES () {
      if (key=='c') {
        // delete all indices in current shape
        listShapes.get(currShape).indices.clear();
      } else if (key==BACKSPACE) {
        // delete last 
        if (listShapes.get(currShape).indices.size()>0) {
          listShapes.get(currShape).indices.remove(listShapes.get(currShape).indices.size()-1);
        }
      } else if ( key==' ' ) {
        // toggle 
        showFill = !showFill;
      } else if ( key=='p' ) {
        state =  STATE_DRAW_POINTS; // set current state
      } else if (key==RETURN||key==ENTER) {
        listShapes.add(new OneShape());
        currShape++;
      } else if ( key=='e' ) {
        // export 
        export();
      }// else if
    }//func 
    
    //------------------------------------------------------------
    // Tools 
    
    void showInstructions(String localHelp) {
      fill(255); 
      text("Mouse: "
        +mouseX
        +","
        +mouseY
        +"\n\n" 
        + localHelp, 
        width-210, 19, 
        200, 900);
    }
    
    void export() {
      // export 
    
      flagExported = false; 
    
      println(   "\n// -------------------------------"); 
      println(   "\n// " +  dateTimeStamp() ); 
    
      // step 1: show list of points as array ----
    
      println(   "\nPVector[] listPVector = {");
    
      String as1="";
      for (PVector pv : listPoints) {
        as1+=
          "   new PVector("
          +pv.x
          +", "
          +pv.y
          +"),\n";
      }//for  
    
      if (as1.length()>0) {
        if (as1.charAt(as1.length()-1) == '\n' ) {
          as1 = as1.substring (0, as1.length()-1); 
          if (as1.charAt(as1.length()-1) == ',' )
            as1 = as1.substring (0, as1.length()-1);
        }
      }
    
      println(as1 + "\n    }; \n");
    
      // step 2: show list of shapes as array ----
    
      println("int[][] layout =  {");
    
      // all Shapes
      as1="";
      for (OneShape os : listShapes) {
        as1 += os.asString();
      }
    
      if (as1.length() > 0) {
        if (as1.charAt(as1.length()-1) == '\n' ) 
          as1 = as1.substring (0, as1.length()-1); 
        if (as1.charAt(as1.length()-1) == ',' )
          as1 = as1.substring (0, as1.length()-1);
      }
      println(as1 + "\n         };"); 
    
      // step 3: setup and draw ----
    
      println(   "\nvoid setup() {"); 
      println(   "  size(888, 888);"); 
      println(   "  background(111);"); 
      println(   "} //func"); 
      println(   ""); 
    
      println(   "void draw() {"); 
      println(   "  background(111);"); 
      println(   "  drawShape1();"); 
      println(   "} //func"); 
      println(   ""); 
    
      // step 4: function to use data  ----
    
      println(   "void drawShape1() {"); 
      println(   "  beginShape();" ); 
      println(   "  stroke(0); " ); 
      println(   "  fill( 255, 0, 0); " ); 
    
      println(   "  for (int i=0; i < layout.length; i++) {" ); 
      println(   "    beginShape();" ); 
      println(   "    for (int i2=0; i2 < layout[i].length; i2++) {" ); 
      println(   "      vertex( listPVector[  layout[i][i2]  ] .x, " ); 
      println(   "              listPVector[  layout[i][i2]   ] .y );" ); 
      println(   "    }//for" );
      println(   "    endShape(); " );
      println(   "  }//for\n" );
    
      println(   "  endShape(CLOSE); " ); 
      println(   "} //func"); 
      println(   "// -------------------------------");
    }
    
    void showlistPoints1() {
      //
      for (PVector pv : listPoints) {
        stroke(255); 
        pointPVector(pv);
      }
    }
    
    void pointPVector( PVector pv) {
      // 
      point  (pv.x, pv.y); 
    
      point  (pv.x, pv.y+1); 
      point  (pv.x+1, pv.y); 
    
      point  (pv.x, pv.y+2); 
      point  (pv.x+2, pv.y);
    }
    
    // ----------------------------------------------------------------------
    // Tools date and time
    
    String dateTimeStamp() {
      // short version 
      return getDate() + ", " + getTime();
    }
    
    String getDate() {
      return leadingZeros(year()) 
        + "/"+leadingZeros(month()) 
        + "/"+leadingZeros(day());
    }
    
    String getTime() {
      return leadingZeros(hour()) 
        + ":"+leadingZeros(minute()) 
        + ":"+leadingZeros(second());
    }
    
    String leadingZeros(int a) {
      String Buffer; 
      Buffer=nf(a, 2); 
      return(Buffer);
    }
    //
    
    // ===========================================================
    
    class OneShape {
    
      // one shape has a different number of points. The points are stored as indices for the list listPoints.
    
      ArrayList<Integer> indices = new ArrayList(); 
    
      // no constructor 
    
      void show() {
    
        beginShape(); 
        if (showFill)
          fill( 255, 0, 0, 66);
        else noFill(); 
        noStroke(); 
    
        // lines for curr edges 
        for (int i = 0; i < indices.size()-1; i++) {
          stroke(0); 
          vertex( listPoints.get(indices.get(i)) .x, 
            listPoints.get(indices.get(i)) .y);
        }//for
    
        endShape(CLOSE);
      }
    
      String asString() {
        // for export
    
        // empty?
        if (indices.size()<=0)
          return ""; // abort 
    
        String result = "  {"; 
        for (int i = 0; i < indices.size(); i++) {
          result +=  indices.get(i) + ", ";
        }
        return result+"},\n";
      }
      //
    } // class
    // 
    
  • Can u someone help me to draw this? (beziers)

    Similar to the program above, I made a shape / PShape editor, where you can draw by clicking the mouse and then export an entire sketch including the drawn PShape.

    Regards, Chrisir ;-)

    (the red cross is only decoration)

    final String HELP = 
      "Click mouse to draw vertex."
      +"\nBackspace to delete last item."
      +"\nHit c to delete entire list." 
      +"\nHit Space bar: fill on/off." 
      +"\nHit e to export." ;
    
    ArrayList<PVector> list = new ArrayList();  
    boolean showFill = false;  
    
    void setup() {
      size(888, 888);
      background(111);
    }
    
    void draw() {
      background(111);
      // example shape / optional 
      showCross(300, 300);
      // the list that has been entered 
      showList();
      // show Instructions
      showInstructions();
    }
    
    // ----------------------------------------------
    // Inputs 
    
    void mousePressed () {
      //println(
      //  "vertex("
      //  +mouseX
      //  +", "
      //  +mouseY
      //  +");");
      PVector pv = new PVector(mouseX, mouseY) ;
      list.add(pv);
    }
    
    void keyPressed() {
      if (key=='c') {
        // delete all 
        list.clear();
      } else if (key==BACKSPACE) {
        // delete last 
        if (list.size()>0) {
          list.remove(list.size()-1);
        }
      } else if ( key==' ' ) {
        // toggle 
        showFill = !showFill ;
      } else if ( key=='e' ) {
        // export 
        export();
      }// else if
    }//func 
    
    //------------------------------------------------------------
    // Tools 
    
    void showInstructions() {
      fill(255);
      text("Mouse: "
        +mouseX
        +","
        +mouseY
        +"\n\n" + HELP, 
        width-210, 19, 
        200, 900);
    }
    
    void export() {
      //
      println(   "\n// -------------------------------");
      println(   "\n//   " +  dateTimeStamp() ); 
      println(   "void setup() {");
      println(   "  size(888, 888);");
      println(   "  background(111);");
      println(   "} //func");
      println(   "");
    
      println(   "void draw() {");
      println(   "  background(111);");
      println(   "  drawShape1();");
      println(   "} //func");
      println(   "");
      println(   "void drawShape1() {"); 
      println(   "  beginShape();" ); 
      println(   "  stroke(0); " );
      println(   "  fill( 255, 0, 0); " );
      for (PVector pv : list) {
        println(
          "  vertex("
          +pv.x
          +", "
          +pv.y
          +");");
      }//for
      println(   "  endShape(CLOSE); " );
      println(   "} //func");
      println(   "// -------------------------------");
    }
    
    void showList() {
      beginShape();
      if (showFill) { 
        fill( 255, 0, 0);
      } else { 
        noFill();
      }
      noStroke();
      stroke(0); 
      for (PVector pv : list) {
        vertex(pv.x, pv.y);
      }
      endShape();
      //
      for (PVector pv : list) {
        pointPVector(pv);
      }
    }
    
    void pointPVector( PVector pv) {
      // 
      fill(0, 0, 255);
      stroke(255);
      point  (pv.x, pv.y);
    
      point  (pv.x, pv.y+1);
      point  (pv.x+1, pv.y);
    
      point  (pv.x, pv.y+2);
      point  (pv.x+2, pv.y);
    }
    
    // ----------------------------------------------------------------------
    // Tools date and time
    
    String dateTimeStamp() {
      // short version for file names
      return getDate() + ", " + getTime();
    }
    
    String getDate() {
      return leadingZeros(year()) 
        + "/"+leadingZeros(month()) 
        + "/"+leadingZeros(day());
    }
    
    String getTime() {
      return leadingZeros(hour()) 
        + ":"+leadingZeros(minute()) 
        + ":"+leadingZeros(second());
    }
    
    String leadingZeros(int a) {
      String Buffer;
      Buffer=nf(a, 2);
      return(Buffer);
    }
    
    //-----------------------------------------------------------------------
    // optional 
    
    void showCross(float x1, float y1) {
    
      // example shape / optional 
    
      pushMatrix(); 
    
      // the \ line ----------
      beginShape();
      fill( 255, 0, 0);
      noStroke();
      vertex(35, 27);
      vertex(48, 17);
      vertex(85, 80);
      vertex(85-13, 80+3);
      endShape(CLOSE);
    
      // the / line -------
    
      beginShape();
      fill( 255, 0, 0);
      vertex(35, 80);
      vertex(48, 87);
      vertex(85, 20);
      vertex(85-13, 20-3-2);
      endShape(CLOSE);
    
      popMatrix();
    }
    //
    
    • end of sketch

    Example for an exported sketch (resulting sketch):

    // -------------------------------
    
    //   2018/10/01, 15:05:26
    void setup() {
      size(888, 888);
      background(111);
    } //func
    
    void draw() {
      background(111);
      drawShape1();
    } //func
    
    void drawShape1() {
      beginShape();
      stroke(0); 
      fill( 255, 0, 0); 
      vertex(316.0, 321.0);
      vertex(429.0, 395.0);
      vertex(287.0, 516.0);
      endShape(CLOSE);
    } //func
    // -------------------------------
    
  • Can u someone help me to draw this? (beziers)

    there was a Bazier Tool but it hasn't been updated in 5 years and you can't install it in P3. source is in github, maybe it can be updated. https://github.com/drifkin/bezier-editor-tool

    alternatively, maybe Chrisir can make his code into a Tool.

  • Can u someone help me to draw this? (beziers)

    I extended my sketch

    Same principle

    but you can now add points BETWEEN existing points and you can also select GROUPS of points (button select) and then drag the entire group (button Drag)

    Chrisir ;-)

    // see https : // www.processing.org/tutorials/curves/
    // see https : // forum.processing.org/two/discussion/26216/can-someone-help-me-to-draw-this#latest
    // see https : // forum.processing.org/two/discussion/comment/123853/#Comment_123853
    
    final String helpText = 
      "BezierVertex-Editor: You can make a vertex here and use it in another program.\n\nThe 3 buttons on the right allow to change the mode.\nNormal Mode: You can click mouse to add new points,\n"
      +"drag and drop existing points to move them.\nRight mouse click to INSERT additional point between 2 existing points\n\n"
      +"Use Backspace to remove last entry (or all entries), use Delete key to remove highlighted point (click green point first),\n"
      +"\nNormal Mode has just been described. \nIn selection mode you can select a GROUP of points, \nin drag mode you can drag the entire group.\n\nEscape key to unselect all points. "
      +"\n\nSpace to export with println (to the direct window). \nThen you need to copy / paste the code from direct window to your target sketch.\n"
      +"For how to use the data see TARGET SKETCH at the end of the sketch which you need to make to a new sketch.\n\n(click x to hide/show this text)."; 
    
    ArrayList<PointMy> listPV = new ArrayList();
    
    // drag and drop 
    boolean hold=false; 
    int holding_i=-1;
    
    // help text on off 
    boolean textHelpIsOn = true; 
    
    // buttons
    Button[] buttons;
    
    String status="Normal Mode"; 
    int mode=0;
    
    PVector startPV=new PVector(0, 0); 
    
    // -----------------------------------------------------
    
    void setup() {
      size(840, 880);
      background(255);
    
      makeArrayList();   // just a test list, you can leave listPV as well empty
    
      makeButtons(); // buttons
    }// func 
    
    void draw() {
      background(255);
    
      switch(mode) {
      case 0:
        // standard mode 
        // drag and drop management 
        if (hold) {
          PointMy pm = listPV.get(holding_i);
          pm.p.x=mouseX;
          pm.p.y=mouseY;
        }
        break;
    
      case 1:
        // select mode
        if (hold) {
          // rect for show the rect 
          noFill();
          stroke(0); 
          rect(startPV.x, startPV.y, 
            mouseX-startPV.x, mouseY-startPV.y);
    
          // select points 
          for (int i = 0; i < listPV.size(); i++) {
            PointMy pm=listPV.get(i);
            if (pm.p.x>startPV.x&&
              pm.p.y>startPV.y&&
              pm.p.x<mouseX&&
              pm.p.y<mouseY) {
              pm.selected=true;
            }//if
            else {
              pm.selected=false;
            }//else
          }//for
        }//if
        break; 
    
      case 2: 
        // drag mode (for selection) 
        if (hold) {
          for (int i = 0; i < listPV.size(); i++) {
            PointMy pm=listPV.get(i);
            if (pm.selected) {
              pm.p.x+=mouseX-pmouseX;
              pm.p.y+=mouseY-pmouseY;
            }//if
          }//for
        }//if
        break;
    
      default:
        println("unknown mode in draw(): "+mode);
        exit(); 
        return;
      } // switch 
    
      // in ALL modes: 
    
      // show status
      fill(0);
      text(status, 5, height-4);
      stroke(0);
      line(0, height-21, 
        width, height-21);
    
      // show ArrayList
      showArrayList(); 
    
      // text help 
      if (textHelpIsOn) {
        fill(0) ;
        text(helpText, 17, 17);
      }
    
      // show Menu
      for (Button but : buttons) {
        but.update();
        but.display();
      }//for
      //
    }// func draw() 
    
    // -----------------------------------------------------
    
    void showArrayList() {
    
      // show the curve 
      noFill();
      stroke(0);
      beginShape();
      int i=0;
      if (listPV.size()>0) {
        curveVertexPVector(listPV.get(i).p);
        for ( i = 0; i < listPV.size(); i++) {
          curveVertexPVector(listPV.get(i).p);
        }
        i=listPV.size()-1;
        curveVertexPVector(listPV.get(i).p);
      }
      endShape();
    
      //show the points (additionally)
      noStroke();
      float rad=3;
      for ( i = 0; i < listPV.size(); i++) {
        PointMy pm = listPV.get(i);
        PVector pv=pm.p;
        // if we are close to the mouse, color green, else red
        if (dist(mouseX, mouseY, pv.x, pv.y)<11||pm.selected) {
          // near to mouse 
          fill( 0, 255, 0); // green
          rad=7;
        } else {
          // normal 
          fill(255, 0, 0);  // red
          rad=3;
        }
        ellipse(pv.x, pv.y, 
          rad, rad);
      }//for
    }//func
    
    // ----------------------------------------------------------
    // Tools 
    
    void makeArrayList() {
    
      // init
    
      int[] coords = {
        // alternating x and y value (which belong together: 0 and 1 is a pair, 2 and 3 is a pair....)
        40, 190, 
        110, 190, 
        140, 230, 
        60, 250, 
        50, 280
      };
    
      // read coords[]
      for (int i = 0; i < coords.length; i += 2) {
        listPV.add (  new PointMy ( new PVector(coords[i], coords[i + 1]+130), false ));
      }
    }//func 
    
    void curveVertexPVector(PVector pv) {
      // like curveVertex but gets a PVector as input  
      // (just an easy way to use vectors for curveVertex)
      curveVertex(pv.x, pv.y);
    }
    
    void makeButtons() {
      buttons = new Button[3];
      String[] buttonTexts={ "Normal", "Select", "Drag"   };
      if (buttons.length!=buttonTexts.length) {
        println("Arrays do not have the same length in setup()");
        exit();
        return;
      }
      int unit=29;
      for (int i = 0; i < buttons.length; i++) {
        Button newButton = new Button(
          buttonTexts[i], 
          width-80, i*unit+40, 
          74, unit-6, 
          i);
        buttons[i] = newButton;
      }
    }
    
    // ----------------------------------------------------------
    
    void keyPressed() {
    
      if (key==BACKSPACE) {
        if (listPV.size()>0)
          listPV.remove(listPV.size()-1);
      }
      // ----------------
      else if (key==' ') {
        // SPACE BAR
        String xval="float[] xValues = { ", 
          yval="float[] yValues = { ";
        for (int i = 0; i < listPV.size(); i++) {
          PVector pv=listPV.get(i).p;
          xval += str(pv.x)+",";
          yval += str(pv.y)+",";
        }//for
        println (xval+" };"); 
        println (yval+" };");
        println ("remove last comma");
      }// else if SPACE BAR
      //------------------------
      else if (key=='x') {
        textHelpIsOn = !textHelpIsOn;
      }//else if
      //----------------------------
      else if (key==DELETE) {
        for (int i = 0; i < listPV.size(); i++) {
          PointMy pm=listPV.get(i);
          if (dist(mouseX, mouseY, pm.p.x, pm.p.y)<11) {
            listPV.remove(i);
            return;
          }//if
        }//for
      }//else if
      //----------------------------
      else if (key==ESC) {
        key=0; // kill ESC
        for (int i = 0; i < listPV.size(); i++) {
          PointMy pm=listPV.get(i);
          pm.selected=false;
        }
      }
      //----------------------------
    }//func 
    
    void mousePressed() {
    
      // this applies in all modes !!! 
      if (mouseButton==LEFT) {
        // right screen border?
        if (mouseX>buttons[0].x) {
          if ( checkMouseOnMenu()) 
            return;
        }
      }
    
      switch(mode) {
    
      case 0:
        //  standard mode
        mousePressedForModeNormal();
        break;
    
      case 1:
        // Select 
        hold=true;
        startPV=new PVector (mouseX, mouseY); 
        break; 
    
      case 2: 
        // Drag selection
        hold=true;
        break;
    
      default:
        println("unknown mode in mousePressed: "+mode);
        exit(); 
        return;
      } // switch
    }
    
    void mousePressedForModeNormal() {
    
      if (mouseButton==LEFT) {
    
        // apply drag and drop
        for (int i = 0; i < listPV.size(); i++) {
          PVector pv=listPV.get(i).p;
          if (dist(mouseX, mouseY, pv.x, pv.y)<11) {
            hold=true; 
            holding_i=i;
            return;
          }
        }
    
        // no drag and drop, add point   
        listPV.add(new PointMy(new PVector(mouseX, mouseY), false));
      }//if
    
      // ---------------------------------------
    
      else if (mouseButton==RIGHT) {
    
        int result=-1; 
    
        float minDist = 10000; 
    
        println("here 4");
    
        // search pos
        for (int i = 0; i < listPV.size()-1; i++) {
          PVector pv1=listPV.get(i).p;
          PVector pv2=listPV.get(i+1).p;
    
          float dist= dist(mouseX, mouseY, (pv1.x+pv2.x)/2, (pv1.y+pv2.y)/2);
    
          if (dist<minDist&&dist<110) {
            result=i+1;
            minDist=dist;
          }//if
        }//for 
    
        // found something
        if (result>-1) {
          // no drag and drop, add point   
          listPV.add(result, new PointMy(new PVector(mouseX, mouseY), false));
        }
        //
      }//else if
    }//func 
    
    void mouseReleased() {
      // end drag and drop
      hold=false;
    }
    
    // -----------------------------
    
    boolean checkMouseOnMenu() {
      for (Button but : buttons) {
        but.press();
        if (but.pressed) {
          println(but.index);
          doCommand(but.index);
          return true; // Other buttons won't be pressed, just stop
        }
      }//for
      return false;
    }
    
    
    void doCommand(int cmd) {
      switch(cmd) {
      case 0:
        status="Normal Mode";
        mode=0;
        break; 
    
      case 1:
        status="Mode to select points (drag and drop mouse over the points)";
        mode=1;
        break; 
    
      case 2:
        status="Drag Mode (drag the group of points previously selected)";
        mode = 2; 
        break; 
    
      default:
        status="Error";
        mode=-1; // unknown
        println ("Error in doCommand: "+cmd); 
        exit();
        return;
      }//switch
    }//func 
    
    //============================================================================
    
    class Button {
    
      String btnText; 
    
      int x, y; // The x- and y-coordinates
      int sizeWidth, sizeHeight; // Dimension (width and height)
    
      //color baseGray; // Default gray value
      //color overGray; // Value when mouse is over the button
      //color pressGray; // Value when mouse is over and pressed
    
      boolean over = false; // True when the mouse is over
      boolean pressed = false; // True when the mouse is over and pressed
    
      int index;
    
      // constructor 
      Button(String text_, 
        int xp_, int yp_, 
        int sizeWidth_, int sizeHeight_, 
        int index_) {
    
        btnText=text_;
    
        x = xp_;
        y = yp_;
    
        sizeWidth = sizeWidth_;
        sizeHeight = sizeHeight_; 
    
        //baseGray = b_;
        //overGray = o_;
        //pressGray = p_;
    
        index=index_;
      } // constructor 
    
      // Updates the over field every frame
      void update() {
        if ((mouseX >= x) && (mouseX <= x + sizeWidth) &&
          (mouseY >= y) && (mouseY <= y + sizeHeight)) {
          over = true;
        } else {
          over = false;
        }
      }
    
      boolean press() {
        if (over) {
          pressed = true;
          return true;
        } else {
          pressed = false; 
          return false;
        }
      }
    
      void release() {
        pressed = false; // Set to false when the mouse is released
      }
    
      void display() {
    
        //if (pressed) {
        //  fill(pressGray);
        //} else if (over) {
        //  fill(overGray);
        //} else {
        //  fill(baseGray);
        //}
    
        // noFill(); 
        fill(111);
        noStroke(); 
        rect(x, y, 
          sizeWidth, sizeHeight);
    
        noFill(); 
        noStroke(); 
        if (mode==index)
          stroke(0, 225, 0);
        // else stroke(0);
        float dist = 2; 
        rect(x+dist, y+dist, 
          sizeWidth-dist-dist, sizeHeight-dist-dist);
    
        fill(255);  // green
        //  textAlign(CENTER); 
        // text(but.index, but.x+but.sizeWidth/2, 40);
        text(btnText, x+6, y+16);
        textAlign(LEFT);
      }
    }//class
    
    //============================================================================
    
    class PointMy {
      PVector p;
      boolean selected=false;
    
      PointMy( PVector p_, boolean selected_) {
        p=p_.copy();
        selected=selected_;
      }//constr
    }//class
    
    // ##############################################################
    //---------------------------------------------------------------
    
    // TARGET SKETCH 
    //
    //ArrayList<PVector> listPV = new ArrayList();
    
    //// YOUR DATA !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    //float[] xValues = { 40.0, 110.0, 140.0, 60.0, 50.0, 231.0 };
    //float[] yValues = { 90.0, 90.0, 130.0, 150.0, 180.0, 267.0 };
    //// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    
    //void setup() {
    //  size(840, 880);
    //  background(255);
    
    //  // read coords[]
    //  for (int i = 0; i < xValues.length; i += 1) {
    //    listPV.add ( new PVector(xValues[i], yValues[i]));
    //  }
    //}
    
    //// ---------------------------------------------------------------------
    
    //void draw() {
    //  // show the curve 
    //  noFill();
    //  stroke(0);
    //  beginShape();
    //  int i=0;
    //  if (listPV.size()>0) {
    //    curveVertexPVector(listPV.get(i));
    //    for ( i = 0; i < listPV.size(); i++) {
    //      curveVertexPVector(listPV.get(i));
    //    }
    //    i=listPV.size()-1;
    //    curveVertexPVector(listPV.get(i));
    //  }
    //  endShape();
    //}
    
    //void curveVertexPVector(PVector pv) {
    //  // like curveVertex but gets a PVector as input  
    //  // (just an easy way to use vectors for curveVertex)
    //  curveVertex(pv.x, pv.y);
    //}
    ////
    
  • Save frames of a video in a grid

    Hey,

    first, im really new to p5.js / processing. I just got a new book "creative coding in web", their is an example which will save frames of a video in a grid. My problem is, i dont get how the time measurement works, for me it seems to be really buggy. Everytime i run the sketch the result looks different. (Here is the example https://alpha.editor.p5js.org/generative-design/sketches/P_4_2_2_01)

    It would be nice if anyone could help me out.

  • Spanish cheatsheet for processing?

    it's literally two files copied from somewhere that's now defunct in order to make them easier to find.

    german wasn't listed. but feel free to translate.

    i don't have a pdf editor, that i know of, so don't expect updates. if i did, i'd fix the indenting...

  • How to send HTTP-PUT-request?

    just drag the java file into the pde editor and it should do the right thing

  • Can u someone help me to draw this? (beziers)

    @Chrisir -- have you ever thought about wrapping your bezier editor in a Tool? Kind of like a color picker?

  • Can u someone help me to draw this? (beziers)

    here is my bezier editor where you can draw and the sketch generates your code that you can use in the other sketch (your target sketch. Example below)

        // see https : // www.processing.org/tutorials/curves/
        // see https : // forum.processing.org/two/discussion/26216/can-someone-help-me-to-draw-this#latest
    
        final String helpText = 
          "BezierVertex-Editor: You can make a vertex here and use it in another program.\nYou can click mouse to add new points, drag and drop existing points to move them.\n"
          +"Backspace to remove last entry (or all entries), use Delete key to remove highlighted point (green point),\n"
          +"space to export with println (to the direct window). \nThen you need to copy / paste the code from direct window to your target sketch.\n(click x to hide/show this text)."; 
    
        ArrayList<PVector> listPV = new ArrayList();
    
        // drag and drop 
        boolean hold=false; 
        int holding_i=-1;
    
        // help text on off 
        boolean textHelpIsOn = true; 
    
        void setup() {
          size(840, 880);
          background(255);
          makeArrayList();
        }
    
        void draw() {
          background(255);
    
          // drag and drop management
          if (hold) {
            PVector pv = listPV.get(holding_i);
            pv.x=mouseX;
            pv.y=mouseY;
          }
    
          // show ArrayList
          showArrayList(); 
    
          // text help 
          if (textHelpIsOn) {
            fill(255, 0, 0) ;
            text(helpText, 17, 17);
          }
        }// func draw() 
    
        // -----------------------------------------------------
    
        void showArrayList() {
    
          // show the curve 
          noFill();
          stroke(0);
          beginShape();
          int i=0;
          if (listPV.size()>0) {
            curveVertexPVector(listPV.get(i));
            for ( i = 0; i < listPV.size(); i++) {
              curveVertexPVector(listPV.get(i));
            }
            i=listPV.size()-1;
            curveVertexPVector(listPV.get(i));
          }
          endShape();
    
          //show the points (additionally)
          noStroke();
          float rad=3;
          for ( i = 0; i < listPV.size(); i++) {
            PVector pv=listPV.get(i);
            // if we are close to the mouse, color green, else red
            if (dist(mouseX, mouseY, pv.x, pv.y)<11) {
              // near to mouse 
              fill( 0, 255, 0); // green
              rad=7;
            } else {
              // normal 
              fill(255, 0, 0);  // red
              rad=3;
            }
            ellipse(pv.x, pv.y, 
              rad, rad);
          }//for
        }//func
    
        // ----------------------------------------------------------
        // Tools 
    
        void makeArrayList() {
    
          // init
    
          int[] coords = {
            // alternating x and y value (which belong together: 0 and 1 is a pair, 2 and 3 is a pair....)
            40, 90, 110, 90, 140, 130, 60, 150, 50, 180
          };
    
          // read coords[]
          for (int i = 0; i < coords.length; i += 2) {
            listPV.add ( new PVector(coords[i], coords[i + 1]));
          }
        }//func 
    
        void curveVertexPVector(PVector pv) {
          // like curveVertex but gets a PVector as input  
          // (just an easy way to use vectors for curveVertex)
          curveVertex(pv.x, pv.y);
        }
    
        // ----------------------------------------------------------
    
        void keyPressed() {
    
          if (key==BACKSPACE) {
            if (listPV.size()>0)
              listPV.remove(listPV.size()-1);
          }
          // ----------------
          else if (key==' ') {
            // SPACE BAR
            String xval="float[] xValues = { ", 
              yval="float[] yValues = { ";
            for (int i = 0; i < listPV.size(); i++) {
              PVector pv=listPV.get(i);
              xval += str(pv.x)+",";
              yval += str(pv.y)+",";
            }//for
            println (xval+" };"); 
            println (yval+" };");
            println ("remove last comma");
          }// else if SPACE BAR
          //------------------------
          else if (key=='x') {
            textHelpIsOn = !textHelpIsOn;
          }//else if
          //----------------------------
          else if (key==DELETE) {
            for (int i = 0; i < listPV.size(); i++) {
              PVector pv=listPV.get(i);
              if (dist(mouseX, mouseY, pv.x, pv.y)<11) {
                listPV.remove(i);
                return;
              }//if
            }//for
          }//else if
          //----------------------------
          else if (key==ESC) {
            key=0;
          }
          //----------------------------
        }//func 
    
        void mousePressed() {
    
          // apply drag and drop
          for (int i = 0; i < listPV.size(); i++) {
            PVector pv=listPV.get(i);
            if (dist(mouseX, mouseY, pv.x, pv.y)<11) {
              hold=true; 
              holding_i=i;
              return;
            }
          }
    
          // no drag and drop, add point   
          listPV.add(new PVector(mouseX, mouseY));
        }
    
        void mouseReleased() {
          // end drag and drop
          hold=false;
        }
        //---------------------------------------------------------------
    
  • Resizing the iframe

    I'm trying to dynamically render the iframe from alpha p5 text editor in react

    render() { return(<iframe src = {src obtained from p5 text editor}></iframe>) }

    I need to adjust the size according to the size of the canvas inside. Thank you

  • Resizing the iframe

    Is there any way to adjust the iframe obtained from p5 alpha text editor so that its height and width equals the canvas inside?

  • How to compare two arrays

    pressing ctrl-t in the editor will indent your code nicely.

    nicely indented code is easier to read.

    code that's easier to read is easier to understand.

    code that's easier to understand is easier to debug.

  • Block editor for Processing

    Thank you @Bird!

    I played around with the editor today, trying to make a loading animation: https://app.code-it-studio.de/project/351

    Move the mouse around to change the number of ellipses. Things are getting complex pretty fast with P5, but it's fun to play with.

  • Code coloring for Processing in LaTeX listings package

    This is something I had up on this forum since last summer, but it was in a question thread so I thought I should share this here in the proper category as well.

    Current version: v1.2

    This LaTeX listings template will color your Processing code as you see them in the Processing editor. You can just post your code like you normally would using the listings package, and you will automatically get your code in the proper colors. Except one minor inconvenience, that I will explain here.

    For a function name that is the same as an already defined keyword (Such as "boolean" and "boolean()"), you have to use [escapechar = "char"] and \color{"color"}{"text"} to color them properly. Example:

    \begin{lstlisting}[escapechar = ?]
    boolean;
    ?\color{function}{boolean}?(1);
    \end{lstlisting}
    

    Copy and paste the below template if you want to use it. Alternatively, you can copy only the necessary parts. If in that case, note that \usepackage{listings} and \usepackage{color} is a must for this to work.

    Also note, I have licensed this work with CreativeCommons license CC-BY-SA, so please remember to give some credit to me ;)

    If you find any typos or any other errors, please tell me and I'll try to fix them as much as possible.

    Download version:
    http://www.mediafire.com/file/cw861uy156xftkv/article_listing_Processing_v1.2.tex
    GitHub Gist:
    https://gist.github.com/ebigunso/af355220e932f72d03289c576622aa29

    Full template below:

    \documentclass{article}
    
    \usepackage{graphicx}
    \usepackage{url}
    \usepackage{verbatim}
    \usepackage{listings}
    \usepackage{color}
    
    % Processing language definition template for LaTeX listings package v1.2
    %
    % Credits to ebigunso for creating this LaTeX listings language definition template for Processing
    % This template is licensed with CreativeCommons license CC-BY-SA 4.0
    % license info:
    % https://creativecommons.org/licenses/by-sa/4.0/legalcode
    
    %Define Colors
    \definecolor{black}{RGB}{0,0,0}
    \definecolor{gray}{RGB}{102,102,102}        %#666666
    \definecolor{function}{RGB}{0,102,153}      %#006699 lightblue
    \definecolor{lightgreen}{RGB}{102,153,0}    %#669900
    \definecolor{bluegreen}{RGB}{51,153,126}    %#33997e
    \definecolor{magenta}{RGB}{217,74,122}  %#d94a7a
    \definecolor{orange}{RGB}{226,102,26}       %#e2661a
    \definecolor{purple}{RGB}{125,71,147}       %#7d4793
    \definecolor{green}{RGB}{113,138,98}        %#718a62
    
    \lstdefinelanguage{Processing}{
      %keyword1&2&6
      morekeywords = [3]{abstract, break, class, continue, default, enum, extends, false, final, finally, implements, import, instanceof, interface, native, new, null, package, private, protected, public, static, strictfp, throws, transient, true, void, volatile, length, assert, case, return, super, this, throw},
      %keyword3
      morekeywords = [4]{catch, do, for, if, else, switch, synchronized, while, try},
      %keyword4
      morekeywords = [5]{width, height, pixelHight, displayHeight, displayWidth, focused, frameCount, frameRate, key, keyCode, keyPressed, mouseButton, mousePressed, mouseX, mouseY, pixels, pixelWidth, pmouseX, pmouseY},
      %keyword5
      morekeywords = [6]{Array, ArrayList, Boolean, Byte, BufferedReader, Character, Class, Double, Float, Integer, HashMap, PrintWriter, String, StringBuffer, StringBuilder, Thread, boolean, byte, char, color, double, float, int, long, short, FloatDict, FloatList, IntDict, IntList, JSONArray, JSONObject, PFont, PGraphics, PImage, PShader, PShape, PVector, StringDict, StringList, Table, TableRow, XML},
      %literal2
      morekeywords = [7]{ADD, ALIGN_CENTER, ALIGN_LEFT, ALIGN_RIGHT, ALPHA, ALPHA_MASK, ALT, AMBIENT, ARC, ARROW, ARGB, BACKSPACE, BASELINE, BEVEL, BLEND, BLUE_MASK, BLUR, BOTTOM, BOX, BURN, CENTER, CHATTER, CHORD, CLAMP, CLICK, CLOSE, CMYK, CODED, COMPLAINT, COMPOSITE, COMPONENT, CONCAVE_POLYGON, CONTROL, CONVEX_POLYGON, CORNER, CORNERS, CROSS, CUSTOM, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIAMETER, DIFFERENCE, DIFFUSE, DILATE, DIRECTIONAL, DISABLE_ACCURATE_2D, DISABLE_DEPTH_MASK, DISABLE_DEPTH_SORT, DISABLE_DEPTH_TEST, DISABLE_NATIVE_FONTS, DISABLE_OPENGL_ERRORS, DISABLE_PURE_STROKE, DISABLE_TEXTURE_MIPMAPS, DISABLE_TRANSFORM_CACHE, DISABLE_STROKE_PERSPECTIVE, DISABLED, DODGE, DOWN, DRAG, DXF, ELLIPSE, ENABLE_ACCURATE_2D, ENABLE_DEPTH_MASK, ENABLE_DEPTH_SORT, ENABLE_DEPTH_TEST, ENABLE_NATIVE_FONTS, ENABLE_OPENGL_ERRORS, ENABLE_PURE_STROKE, ENABLE_TEXTURE_MIPMAPS, ENABLE_TRANSFORM_CACHE, ENABLE_STROKE_PERSPECTIVE, ENTER, EPSILON, ERODE, ESC, EXCLUSION, EXIT, FX2D, GIF, GRAY, GREEN_MASK, GROUP, HALF, HALF_PI, HAND, HARD_LIGHT, HINT_COUNT, HSB, IMAGE, INVERT, JAVA2D, JPEG, LEFT, LIGHTEST, LINE, LINES, LINUX, MACOSX, MAX_FLOAT, MAX_INT, MIN_FOAT, MIN_INT, MITER, MODEL, MOVE, MULTIPLY, NORMAL, NORMALIZED, NO_DEPTH_TEST, NTSC, ONE, OPAQUE, OPEN, ORTHOGRAPHIC, OVERLAY, PAL, PDF, P2D, P3D, PERSPECTIVE, PI, PIE, PIXEL_CENTER, POINT, POINTS, POSTERIZE, PRESS, PROBLEM, PROJECT, QUAD, QUAD_STRIP, QUADS, QUARTER_PI, RAD_TO_DEG, RADIUS, RADIANS, RECT, RED_MASK, RELEASE, REPEAT, REPLACE, RETURN, RGB, RIGHT, ROUND, SCREEN, SECAM, SHAPE, SHIFT, SPAN, SPECULAR, SPHERE, SOFT_LIGHT, SQUARE, SUBTRACT, SVG, SVIDEO, TAB, TARGA, TAU, TEXT, TFF, THIRD_PI, THRESHOLD, TIFF, TOP, TRIANGLE, TRIANGLE_FAN, TRIANGLES, TRIANGLE_STRIP, TUNER, TWO, TWO_PI, UP, WAIT, WHITESPACE},
      %function1
      morekeywords = [8]{start, stop, breakShape, createPath, str, loadMatrix, parseBoolean, parseByte, parseChar, parseFloat, parseInt, saveFile, savePath, sketchFile, sketchPath, abs, acos, alpha, ambient, ambientLight, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginCamera, beginContour, beginRaw, beginRecord, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, binary, blend, blendColor, blendMode, blue, box, brightness, camera, ceil, clear, clip, color, colorMode, concat, constrain, copy, cos, createFont, createGraphics, createImage, createInput, createOutput, createReader, createShape, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, day, degrees, delay, directionalLight, displayDensity, dist, ellipse, ellipseMode, emissive, endCamera, endContour, endRaw, endRecord, endShape, exit, exp, expand, fill, filter, floor, frustum, fullScreen, get, green, hex, hint, hour, hue, image, imageMode, join, launch, lerp, lerpColor, lightFalloff, lights, lightSpecular, line, loadBytes, loadFont, loadImage, loadJSONArray, loadJSONObject, loadPixels, loadShader, loadShape, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, modelX, modelY, modelZ, month, nf, nfc, nfp, nfs, noClip, noCursor, noFill, noise, noiseDetail, noiseSeed, noLights, noLoop, norm, normal, noSmooth, noStroke, noTint, ortho, parseJSONArray, parseJSONObject, parseXML, perspective, list, pixelDnsity, point, pointLight, popMatrix, popStyle, pow, print, printArray, printCamera, println, printMatrix, printProjection, pushMatrix, pushStyle, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, requestImage, resetMatrix, resetShader, reverse, rotate, rotateX, rotateY, rotateZ, round, saturation, save, saveBytes, saveFrame, saveJSONArray, saveJSONObject, saveStream, saveStrings, saveTable, saveXML, scale, screenX, screenY, screenZ, second, selectFolder, selectInput, selectOutput, set, shader, shape, shapeMode, shearX, shearY, shininess, shorten, sin, size, smooth, sort, specular, sphere, sphereDetail, splice, split, splitTokens, spotLight, sq, sqrt, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textMode, textSize, texture, textureMode, textureWrap, textWidth, thread, tint, translate, triangle, trim, unbinary, unhex, updatePixels, vertex, year},
      %function2
      morekeywords = [9]{cache, readLine, close, flush, print, println, charAt, equals, indexOf, substring, toLowerCase, toUpperCase, getDouble, getLong, getColumnTitles, getColumnTypes, getColumnType, setDouble, setLong, add, clear, div, get, hasKey, keyArray, keys, mult, remove, set, size, sortKeys, sortKeysReverse, sortValues, sortValuesReverse, sub, valueArray, values, append, array, hasValue, max, min, mult, remove, reverse, shuffle, sort, sortReverse, increment, getBoolean, getFloat, getInt, getIntArray, getJSONArray, getJSONObject, getString, getStringArray, isNull, setBoolean, setFloat, setInt, setJSONArray, setJSONObject, setString, beginDraw, endDraw, blend, copy, filter, loadPixels, mask, resize, save, updatePixels, addChild, beginContour, beginShape, disableStyle, enableStyle, endContour, endShape, getChild, getChildCount, getVertex, getVertexCount, isVisible, resetMatrix, rotate, rotateX, rotateY, rotateZ, scae, setFill, setStroke, setVertex, setVisible, translate, angleBetween, cross, dist, dot, fromAngle, heading, lerp, limit, mag, magSq, normalize, randm2D, random3D, setMag, lower, upper, addColumn, addRow, clearRows, findRow, findRows, getColumnCount, getRow, getRowcount, getStringColumn, matchRow, matchRows, removeColumn, removeRow, removeTokens, rows, trim, getColumnTitle, format, getAttributeCount, getChildren, getContent, getNam, getParent, hasAttribute, hasChildren, listAttributes, listChildren, removeChild, setContent, setName, toString},
      %function4
      morekeywords = [10]{draw, keyReleased, keyTyped, mouseClicked, mouseDragged, mouseMoved, mouseReleased, mouseWheel, settings, setup},
      keywordstyle = [3]\color{bluegreen},
      keywordstyle = [4]\color{lightgreen},
      keywordstyle = [5]\color{magenta},
      keywordstyle = [6]\color{orange},
      keywordstyle = [7]\color{green},
      keywordstyle = [8]\color{function},
      keywordstyle = [9]\color{function},
      keywordstyle = [10]\color{function},
      sensitive = true,
      morecomment = [l][\color{gray}]{//},
      morecomment = [s][\color{gray}]{/*}{*/},
      morecomment = [s][\color{gray}]{/**}{*/},
      morestring = [b][\color{purple}]",
      morestring = [b][\color{purple}]'
    }
    \renewcommand{\ttdefault}{pcr}
    \lstset{
      language={Processing},
      basicstyle={\small\ttfamily},
      identifierstyle={\small},
      commentstyle={\small\itshape},
      keywordstyle={\small},
      ndkeywordstyle={\small},
      stringstyle={\small\ttfamily},
      frame={tb},
      breaklines=true,
      columns=[l]{fullflexible},
      numbers=left,
      xrightmargin=0em,
      xleftmargin=3em,
      numberstyle={\scriptsize},
      stepnumber=1,
      numbersep=1em,
      lineskip=-0.5ex,
    }
    
    % Use escapechar and \color{<color>}{<text>} to color function names properly, that is already defined as a different color keyword.
    %
    % \begin{lstlisting}[escapechar = ?]
    % boolean;
    % ?\color{function}{boolean}?(1);
    % \end{lstlisting}
    
    \title{}
    \author{}
    \date{}
    
    \begin{document}
    \maketitle
    \section{}
    
    \begin{thebibliography}{9}
    \end{thebibliography}
    \end{document}
    
  • Re: Pixels

    line("text", 10, 20.5)

    no such method...

    you can't draw half a pixel but you can fake half a black pixel, say, by making the whole pixel grey. this is called anti-aliasing and it's used to make things look smoother than is possible by colouring whole pixels.

    draw a line, save the image and examine it in a graphic editor and you'll see. (however, i don't think all render modes support this)

    https://www.quora.com/Why-is-anti-aliasing-required-in-games-Why-cant-the-graphics-be-developed-with-proper-edges

  • Eggs disappearing in mid-air as they are going down

    I don't know what happened to the other discussion I was writing a reply to. Some of what I wrote applies here too. Here's what I had:


    Well, your code has some problems.

    The biggest issue I see is a lack of nice formatting. Press Ctrl + t in the editor to automagically format your code.

    If you do that, then it should immediately become apparent that you are missing a stray closing brace. In fact, your Timer class is getting defined inside your Pan class! Add this closing brace in so your Pan class ends before your Timer class.

    The next issue I see is that you are loading the images inside the class definitions. Don't do this. To make sure that the images are only ever loaded once, put them inside the function that only ever runs once: setup().

    The display() method inside the normalEgg class has a loop in it. I have no idea why. You don't need a loop to draw the same image in the same place ten times. Just draw the image once?

    Anyway, actually looking at the collision method, it appears you have a pair of stray opening and closing braces in there that you don't need. Remove those.

    Looking at the collision method some more, we see that it looks fine! You are getting the distance from the center of the pan to the center of an egg. If that distance is less than some value, then there is a collision. That sounds good. There's no problem with it.

    But there is a problem. Your code has a bug. A bug happens when you have assumed your code does something that it dosen't actually do.

    This is a really sneaky bug too, and I suggest you take a minute here to try to find it yourself again before I clue you in to the problem.

    Last chance to solve it yourself. Here's a hint: Where is your pan? No really, where is your pan?

    The problem is that your code assumes your pan is at (pan.x, pan.y). But it isn't. It's drawn at (mouseX, 450), so where it appears to be has nothing to do with the x and y variables in the pan class! That is, even though the pan moves like you would like, if you use pan.x and pan.y as it's position, well, that position is always (0,0)!

    The best way to fix this is to modify the Pan class:

    class Pan {
      float x, y, r;
    
      Pan() {
        r = 30;
        x = mouseX;
        y = 450;
      }
    
      void display() {
        x = mouseX;
        image(pan, x, y);
      }
    }
    

    Now pan.x and pan.y are updated when they need to be, and the collision function should work properly. Try it! Does it?

  • what are the differences between setup() and settings()?

    From the current reference:

    The settings() function is new with Processing 3.0. It's not needed in most sketches. It's only useful when it's absolutely necessary to define the parameters to size() with a variable. Alternately, the settings() function is necessary when using Processing code outside of the Processing Development Environment (PDE). For example, when using the Eclipse code editor, it's necessary to use settings() to define the size() and smooth() values for a sketch..

    The settings() method runs before the sketch has been set up, so other Processing functions cannot be used at that point. For instance, do not use loadImage() inside settings(). The settings() method runs "passively" to set a few variables, compared to the setup() command that call commands in the Processing API.

    Settings is rarely used. One of the most common use cases for settings() is, as @kfrajer mentions, to establish dynamic width and height parameters for size(). If you try to do this in setup() you get an error.