Пример #1
0
  public void WRITE() {
    if (writeEnable == false) return;

    myPort.write("h");

    myPort.write(PApplet.parseInt(PitchP.value() * 100));
    myPort.write(PApplet.parseInt(RollP.value() * 100));
    myPort.write(PApplet.parseInt(YawP.value() * 100));

    myPort.write(PApplet.parseInt(PitchD.value() * 100));
    myPort.write(PApplet.parseInt(RollD.value() * 100));
    myPort.write(PApplet.parseInt(YawD.value() * 100));

    myPort.write(PApplet.parseInt(PitchPWR.value()));
    myPort.write(PApplet.parseInt(RollPWR.value()));
    myPort.write(PApplet.parseInt(YawPWR.value()));

    myPort.write(RCcontrol);
    myPort.write(YawRCon);

    myPort.write(PApplet.parseInt(RollCal.value() * 10 + 100));
    // println (RollCal.value());
    // println (int (RollCal.value()*10+100));

    readStatus = "Write OK";
  }
Пример #2
0
    public void addPlant(int type, int mouseX, int mouseY) {
      if (mouseX <= left || mouseX >= right || mouseY <= top || mouseY >= bottom) return;
      println(mouseX, mouseY);
      int colIndex = floor((mouseX - left) / wSpacing);
      int rowIndex = floor((mouseY - top) / hSpacing);

      int x = PApplet.parseInt(left + colIndex * wSpacing);
      int y = PApplet.parseInt(top + rowIndex * hSpacing);
      if (plants[colIndex][rowIndex] == null) plants[colIndex][rowIndex] = new Plant(type, x, y);
    }
Пример #3
0
  public static String[] parseSketchSmooth(String code, boolean fussy) {
    String[] matches = PApplet.match(scrubComments(code), SMOOTH_REGEX);

    if (matches != null) {
      boolean badSmooth = false;

      if (PApplet.parseInt(matches[1], -1) == -1) {
        badSmooth = true;
      }

      if (badSmooth && fussy) {
        // found a reference to smooth, but it didn't seem to contain numbers
        final String message =
            "The smooth level of this applet could not automatically\n"
                + "be determined from your code. Use only a numeric\n"
                + "value (not variables) for the smooth() command.\n"
                + "See the smooth() reference for an explanation.";
        //				Messages.showWarning("Could not find smooth level", message, null);
        showWarning("Could not find smooth level", message);
        //        new Exception().printStackTrace(System.out);
        return null;
      }

      return matches;
    }
    return new String[] {null, null}; // not an error, just empty
  }
Пример #4
0
 public void InitSerial(float portValue) {
   // initialize the serial port selected in the listBox
   println(
       "initializing serial "
           + PApplet.parseInt(portValue)
           + " in serial.list()"); // for debugging
   // grab the name of the serial port
   String portPos = Serial.list()[PApplet.parseInt(portValue)];
   // initialize the port
   serial = new Serial(this, portPos, 115200);
   // read bytes into a buffer until you get a linefeed (ASCII 10):
   serial.bufferUntil('\n');
   println("done init serial");
   // initialized com port flag
   init_com = 1;
 }
Пример #5
0
  // \u30c7\u30fc\u30bf\u53d6\u5f97
  public void getAllData() {

    // xively\u304b\u3089\u306e\u30c7\u30fc\u30bf\u53d6\u5f97
    String lines[] = getDataFromXively(URL, MY_KEY);

    // \u53d6\u5f97\u3057\u305f\u30c7\u30fc\u30bf\u3092\u30ea\u30b9\u30c8\u306b\u683c\u7d0d
    dotLists = new ArrayList<ArrayList<dotObj>>();

    // \u30c1\u30e3\u30f3\u30cd\u30eb\u306e\u53d6\u5f97
    int max_channel = 0;
    int min_channel = 9999;
    for (int i = 0; i < lines.length; i++) {
      String data[] = split(lines[i], ',');
      int theChannel = PApplet.parseInt(data[0]);
      if (min_channel > theChannel) {
        min_channel = theChannel;
      }
      if (max_channel < theChannel) {
        max_channel = theChannel;
      }
    }

    // \u5168\u30c1\u30e3\u30f3\u30cd\u30eb\u306e\u30c7\u30fc\u30bf\u3092\u53d6\u5f97\u3057\u3001\u30ea\u30b9\u30c8\u306b\u683c\u7d0d
    for (int channel = min_channel; channel <= max_channel; channel++) {
      ArrayList<dotObj> dotList = getDataList(lines, channel);
      dotLists.add(dotList);
    }
  }
Пример #6
0
  // \u30c7\u30fc\u30bf\u3092\u30ea\u30b9\u30c8\u306b\u683c\u7d0d\u3057\u3066\u53d6\u5f97
  public ArrayList<dotObj> getDataList(String[] lines, int targetChannel) {

    ArrayList<dotObj> retList = new ArrayList<dotObj>();

    // \u5168\u30c7\u30fc\u30bf\u3092\u53c2\u7167\u3057\u3066\u5fc5\u8981\u306a\u60c5\u5831\u3092\u53d6\u308a\u51fa\u3059
    int index = 0;
    for (int i = 0; i < lines.length; i++) {
      // ','\u3067\u533a\u5207\u308a\u914d\u5217\u306b\u683c\u7d0d
      String data[] = split(lines[i], ',');
      // channel, date, valuse
      // \u306e\u9806\u3067\u30c7\u30fc\u30bf\u304c\u683c\u7d0d\u3055\u308c\u3066\u3044\u308b
      int channel = PApplet.parseInt(data[0]); // \u30c1\u30e3\u30f3\u30cd\u30eb
      String timeStamp = data[1]; // \u65e5\u4ed8
      float val = PApplet.parseFloat(data[2]); // \u5024

      if (channel == targetChannel) {
        // println("channel: " + channel);
        // println("date   : " + timeStamp);
        // println("val    : " + val);

        // \u53d6\u5f97\u3057\u305f\u30c7\u30fc\u30bf\u3092\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u306b\u30bb\u30c3\u30c8\u3057\u3001\u914d\u5217\u306b\u683c\u7d0d
        float m = map(val, -0.5f, 0.5f, height / 4, height);
        dotObj theObj = new dotObj(index * width / 70, m, 0);
        theObj.channel = channel;
        theObj.timeStamp = timeStamp;
        theObj.val = val;
        retList.add(theObj);

        index++;
      }
    }

    return retList;
  }
 public void gameOver() { // trigger game over
   this.screen = 2; // sets screen to game over
   noStroke();
   noLoop();
   fill(255, 0, 0);
   rect(0, height / 8, width, height / 8 * 6);
   stroke(255);
   this.shooterlist[0] = null; // removes active ball
   String[] scores = loadStrings("scores.txt"); // loads high score from text file
   if (PApplet.parseInt(scores[0])
       < this.score) { // checks if current score is greater than high score
     scores[0] = "" + this.score + ""; // makes string
     saveStrings("data/scores.txt", scores); // saves to the scores.txt in data folder
   }
   fill(255);
   textSize(30);
   textAlign(CENTER, TOP);
   text("Game Over", width / 2, height / 8);
   textSize(20);
   text("Your Score\n" + this.score, 60, height / 8 * 2);
   text("High Score\n" + scores[0], width - (60 * width / 320), height / 8 * 2);
   fill(255, 0, 0);
   button = new Button(width / 2, 50, width / 4, height / 8 * 6, "Play Again", 18);
   button.display();
 }
Пример #8
0
  public void controlEvent(ControlEvent theEvent) {
    // PulldownMenu is if type ControlGroup.
    // A controlEvent will be triggered from within the ControlGroup.
    // therefore you need to check the originator of the Event with
    // if (theEvent.isGroup())
    // to avoid an error message from controlP5.
    if (theEvent.isGroup()) {
      if (theEvent.group().name() == "ruleChoiceList") {
        //    println(theEvent.group().value()+" from "+theEvent.group());
        selectedRule = PApplet.parseInt(theEvent.group().value());
        // has to be here for the controlp5 library
      }
    } else if (theEvent.isController()) {
      //    println(theEvent.controller().value()+" from "+theEvent.controller());
    }

    //  switch(theEvent.controller().id()) {
    //    case(1):
    //    myColorRect = (int)(theEvent.controller().value());
    //    break;
    //    case(2):
    //    myColorBackground = (int)(theEvent.controller().value());
    //    break;
    //    case(3):
    //    println(theEvent.controller().stringValue());
    //    break;
    //  }

  }
  public void setup() {
    size(1000, 1000);
    background(255);

    // presets
    int rows = 12;
    int cols = 12;
    float outerRadius = width / cols;

    // randomly generated
    int pointCount;
    int steps;
    float innerRadius;
    float innerRadiusRatio;
    float outerRadiusRatio;
    float shadeRatio;
    float rotationRatio;

    translate(outerRadius / 2, outerRadius / 2);
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
        pointCount = PApplet.parseInt(random(5, 15));
        steps = PApplet.parseInt(random(3, 20));
        innerRadius = outerRadius * random(0.3f, 0.9f);
        innerRadiusRatio = innerRadius / steps;
        outerRadiusRatio = outerRadius / steps;

        float randColor = random(225, 255);
        shadeRatio = randColor / steps;
        rotationRatio = random(90, 200) / steps;

        pushMatrix();
        translate(outerRadius * j, outerRadius * i);
        for (int k = 0; k < steps; k++) {
          float shade = shadeRatio * k;
          fill(shade);
          stroke(randColor - shade, 100);
          pushMatrix();
          scale(0.4f);
          rotate(rotationRatio * k * PI / 180);
          star(pointCount, outerRadius - outerRadiusRatio * k, innerRadius - innerRadiusRatio * k);
          popMatrix();
        }
        popMatrix();
      }
    }
  }
  public void mousePressed() {
    if (mouseButton == LEFT) {

      int xX = PApplet.parseInt(mouseX) / cellSize;
      int yY = PApplet.parseInt(mouseY) / cellSize;
      //    fill(255);
      //    textSize(12);
      //    text( xX + " " + yY, mouseX, mouseY);
      grid[xX][yY].pressed();
    }
    if (mouseButton == RIGHT) {
      starttime = millis();
      if (play == true) {
        play = false;
      } else {
        play = true;
      }
    }
  }
Пример #11
0
  private static boolean hasBadSize(SurfaceInfo surfaceInfo) {
    String width = getPrivateSurfaceInfoField(surfaceInfo, "width", String.class);
    String height = getPrivateSurfaceInfoField(surfaceInfo, "height", String.class);

    if (width == null || height == null) {
      return true;
    }

    if (!width.equals("displayWidth")
        && !width.equals("displayHeight")
        && PApplet.parseInt(width, -1) == -1) {
      return true;
    }
    if (!height.equals("displayWidth")
        && !height.equals("displayHeight")
        && PApplet.parseInt(height, -1) == -1) {
      return true;
    }
    return false;
  }
Пример #12
0
  static public Font getFont(String attr) {
    boolean replace = false;
    String value = get(attr);
    if (value == null) {
      //System.out.println("reset 1");
      value = getDefault(attr);
      replace = true;
    }

    String[] pieces = PApplet.split(value, ',');
    if (pieces.length != 3) {
      value = getDefault(attr);
      //System.out.println("reset 2 for " + attr);
      pieces = PApplet.split(value, ',');
      //PApplet.println(pieces);
      replace = true;
    }

    String name = pieces[0];
    int style = Font.PLAIN;  // equals zero
    if (pieces[1].indexOf("bold") != -1) {
      style |= Font.BOLD;
    }
    if (pieces[1].indexOf("italic") != -1) {
      style |= Font.ITALIC;
    }
    int size = PApplet.parseInt(pieces[2], 12);
    Font font = new Font(name, style, size);

    // replace bad font with the default
    if (replace) {
      set(attr, value);
    }

    return font;
  }
Пример #13
0
  public void draw() {
    background(0);
    // Strings composition
    textFont(createFont("Arial bold", 24));
    fill(c_red);
    stroke(255);
    text("OpenWheels GUI V1.0", 20, 30);
    textSize(16);
    // textAlign(CENTER);
    fill(c_azure);
    text("Acc_RAW:  " + Acc_RAW, 150, 65);
    AccSlider.setValue(Acc_RAW);
    text("Gyro_RAW: " + Gyro_RAW, 150, 90);
    GyroSlider.setValue(Gyro_RAW);
    text("Acc_Angle:  " + Acc_Angle + "\u00b0", 150, 115);
    text("Gyro_Rate: " + Gyro_Rate + "\u00b0/sec", 150, 140);
    text("Drive: " + Drive, 150, 165);
    text("Steer: " + Steer, 150, 190);
    text("BatLevel: " + nf(BatLevel, 1, 1) + "V", 150, 215);
    text("Status: " + statusFlag, 150, 240);
    graphGauge();
    graphGrid();

    // call the function that plot the angular of acc, with few screen settings
    graphRoll(PApplet.parseFloat(Acc_Angle), VideoBuffer2, c_red); // xPos, YPos, YSpan
    // call the function that plot the estimate angular, with few screen settings
    graphRoll(Angle, VideoBuffer1, c_yellow); // xPos, YPos, YSpan

    // call arduino for data every timePolling [msec]
    int timePolling = 50; // 50msec=20Hz
    time1 = millis();
    if (init_com == 1) {
      while (serial.available() > 0) processSerialData();
      if ((time1 - time2) > timePolling) {
        if (requestPID == true) {
          serial.write('E');
          requestPID = false;
        } else if (writePID == true) {
          int P = PApplet.parseInt(conf_KP.value());
          int I = PApplet.parseInt(conf_KI.value());
          int D = PApplet.parseInt(conf_KD.value());
          char data[] = {0, 0, 0, 0, 0};
          data[0] = 'W';
          data[1] = PApplet.parseChar(P);
          data[2] = PApplet.parseChar(I);
          data[3] = PApplet.parseChar(D);
          data[4] = ' ';
          String str = new String(data);
          serial.write(str);
          println(str);
          // println(" P=" + P + " I=" + I + " D=" + D);
          writePID = false;
        }
        // else if (RUN==true ) {serial.write('A');}
        else {
          serial.write('A');
        }
        time2 = time1;
      }
    }
  }
Пример #14
0
/*      */   public int getInt(String name, int defaultValue)
/*      */   {
/*  925 */     String value = getString(name);
/*  926 */     return value == null ? defaultValue : PApplet.parseInt(value, defaultValue);
/*      */   }
Пример #15
0
  /**
   * Part of the MessageConsumer interface, this is called
   * whenever a piece (usually a line) of error message is spewed
   * out from the compiler. The errors are parsed for their contents
   * and line number, which is then reported back to Editor.
   */
  public void message(String s) {
    int i;

    System.out.println("**************[ROBOTIS]***********************************");
    // remove the build path so people only see the filename
    // can't use replaceAll() because the path may have characters in it which
    // have meaning in a regular expression.
    if (!verbose) {
      while ((i = s.indexOf(buildPath + File.separator)) != -1) {
        s = s.substring(0, i) + s.substring(i + (buildPath + File.separator).length());
      }
    }
  
    // look for error line, which contains file name, line number,
    // and at least the first line of the error message
    String errorFormat = "([\\w\\d_]+.\\w+):(\\d+):\\s*error:\\s*(.*)\\s*";
    String[] pieces = PApplet.match(s, errorFormat);

//    if (pieces != null && exception == null) {
//      exception = sketch.placeException(pieces[3], pieces[1], PApplet.parseInt(pieces[2]) - 1);
//      if (exception != null) exception.hideStackTrace();
//    }
    
    if (pieces != null) {
      String error = pieces[3], msg = "";
      
      if (pieces[3].trim().equals("SPI.h: No such file or directory")) {
        error = _("Please import the SPI library from the Sketch > Import Library menu.");
        msg = _("\nAs of Arduino 0019, the Ethernet library depends on the SPI library." +
              "\nYou appear to be using it or another library that depends on the SPI library.\n\n");
      }
      
      if (pieces[3].trim().equals("'BYTE' was not declared in this scope")) {
        error = _("The 'BYTE' keyword is no longer supported.");
        msg = _("\nAs of Arduino 1.0, the 'BYTE' keyword is no longer supported." +
              "\nPlease use Serial.write() instead.\n\n");
      }
      
      if (pieces[3].trim().equals("no matching function for call to 'Server::Server(int)'")) {
        error = _("The Server class has been renamed EthernetServer.");
        msg = _("\nAs of Arduino 1.0, the Server class in the Ethernet library " +
              "has been renamed to EthernetServer.\n\n");
      }
      
      if (pieces[3].trim().equals("no matching function for call to 'Client::Client(byte [4], int)'")) {
        error = _("The Client class has been renamed EthernetClient.");
        msg = _("\nAs of Arduino 1.0, the Client class in the Ethernet library " +
              "has been renamed to EthernetClient.\n\n");
      }
      
      if (pieces[3].trim().equals("'Udp' was not declared in this scope")) {
        error = _("The Udp class has been renamed EthernetUdp.");
        msg = _("\nAs of Arduino 1.0, the Udp class in the Ethernet library " +
              "has been renamed to EthernetUdp.\n\n");
      }
      
      if (pieces[3].trim().equals("'class TwoWire' has no member named 'send'")) {
        error = _("Wire.send() has been renamed Wire.write().");
        msg = _("\nAs of Arduino 1.0, the Wire.send() function was renamed " +
              "to Wire.write() for consistency with other libraries.\n\n");
      }
      
      if (pieces[3].trim().equals("'class TwoWire' has no member named 'receive'")) {
        error = _("Wire.receive() has been renamed Wire.read().");
        msg = _("\nAs of Arduino 1.0, the Wire.receive() function was renamed " +
              "to Wire.read() for consistency with other libraries.\n\n");
      }

      if (pieces[3].trim().equals("'Mouse' was not declared in this scope")) {
        error = _("'Mouse' only supported on the Arduino Leonardo");
        //msg = _("\nThe 'Mouse' class is only supported on the Arduino Leonardo.\n\n");
      }
      
      if (pieces[3].trim().equals("'Keyboard' was not declared in this scope")) {
        error = _("'Keyboard' only supported on the Arduino Leonardo");
        //msg = _("\nThe 'Keyboard' class is only supported on the Arduino Leonardo.\n\n");
      }
      
      RunnerException e = null;
      if (!sketchIsCompiled) {
        // Place errors when compiling the sketch, but never while compiling libraries
        // or the core.  The user's sketch might contain the same filename!
        e = sketch.placeException(error, pieces[1], PApplet.parseInt(pieces[2]) - 1);
      }

      // replace full file path with the name of the sketch tab (unless we're
      // in verbose mode, in which case don't modify the compiler output)
      if (e != null && !verbose) {
        SketchCode code = sketch.getCode(e.getCodeIndex());
        String fileName = (code.isExtension("ino") || code.isExtension("pde")) ? code.getPrettyName() : code.getFileName();
        int lineNum = e.getCodeLine() + 1;
        s = fileName + ":" + lineNum + ": error: " + pieces[3] + msg;        
      }
            
      if (exception == null && e != null) {
        exception = e;
        exception.hideStackTrace();
      }      
    }
    
    System.err.print(s);
  }
Пример #16
0
 /** @param defaultValue the default value of the attribute */
 public int getIntContent(int defaultValue) {
   return PApplet.parseInt(node.getTextContent(), defaultValue);
 }
  public void draw() {
    // background(33,22,223);
    background(0);
    scale(.45f, .45f);
    smooth(4);

    /////////////
    // rightline
    /////////////
    int test;
    pushMatrix();
    translate(
        offsety + width,
        offsetx - height + 250 - 30); // divide the with by the height of the original photo
    rotate(PI / 3);

    for (int i = 1; i < 6; i++) {
      //  if (int(random(1,filecount))%i == 0) {
      test = PApplet.parseInt(random(1, filecount));
      println(test);
      // println(filecount);
      smooth(4);

      image(img[PApplet.parseInt(random(1, filecount))], 250, 250);
      image(img[PApplet.parseInt(random(1, filecount))], offsetx * i + 250, 250);
      //    }
    }
    popMatrix();

    /////////////
    // leftline
    /////////////
    // int test;
    pushMatrix();
    translate(-90, offsetx + height + 550); // divide the with by the height of the original photo
    rotate(-PI / 3);

    for (int i = 1; i < 6; i++) {
      //  if (int(random(1,filecount))%i == 0) {
      // println(filecount);
      smooth(4);
      image(img[PApplet.parseInt(random(1, filecount))], 250, 250);
      image(img[PApplet.parseInt(random(1, filecount))], offsetx * i + 250, 250);
      //    }
    }
    popMatrix();

    /////////////
    // bottomline
    /////////////

    pushMatrix();
    for (int i = 1; i < 6; i++) {
      smooth(4);
      image(img[PApplet.parseInt(random(1, filecount))], 250, 2 * height - 310 + 250);
      image(img[PApplet.parseInt(random(1, filecount))], offsetx * i + 250, 2 * height - 310 + 250);
    }
    popMatrix();

    pushMatrix();
    smooth(4);
    xint = mouseX;
    yint = mouseY;

    println(xint);
    println(yint);

    // tri.beginDraw();
    // tri.scale(2.2, 2.2);
    // tri.translate(3,6);
    // tri.noStroke();

    scale(2.2f, 2.2f);
    translate(3, 6);
    noStroke();

    stroke(0);
    // stroke(33,22,223);
    strokeWeight(30);
    line(88, 655, 450, 18);
    line(450, 18, 815, 655);
    line(815, 655, 88, 655);
    // tri.endDraw();

    popMatrix();
  }
Пример #18
0
  public void setup() {
    minim = new Minim(this);
    size(winWidth, winHeight, OPENGL);
    background(bGround);
    sm = new SceneManager(minim);
    rulesChecker = new RulesChecker();

    controlP5 = new ControlP5(this);
    // ruleChoiceList = controlP5.addDropdownList("ruleChoiceList",850,100,100,100);
    // customize(ruleChoiceList);
    selectedRule = 0;
    selectedCamera = 0;
    gl = ((PGraphicsOpenGL) g).gl;

    picker = new Picker(this);
    oscP5 = new OscP5(this, port);
    // TODO(sanjeet): Change the address
    interfaceAddr = new NetAddress("127.0.0.1", port);

    noStroke();
    lines = loadStrings("fileFriedrich.txt"); // Hardcoded input file name
    String[] tokens = split(lines[0], " ");
    if (tokens.length != 1) {
      println("Incorrect file format for number of cameras");
      return;
    }
    int numOfCams = PApplet.parseInt(tokens[0]);
    for (int i = 1; i < numOfCams + 1; i++) {

      tokens = split(lines[i], " ");
      float[] matrix = new float[16];
      for (int j = 0; j < tokens.length; j++) {
        matrix[j] = PApplet.parseFloat(tokens[j]);
      }

      cameras.add(new Cam(FloatBuffer.wrap(matrix))); // add all the cameras
    }

    tokens = split(lines[1 + numOfCams], " ");
    if (tokens.length != 1) {
      println("Incorrect file format for number of characters");
      return;
    }
    int numOfChars = PApplet.parseInt(tokens[0]);
    for (int i = 2 + numOfCams; i < lines.length; i++) {
      tokens = split(lines[i], " ");
      float[] matrix = new float[16];
      for (int j = 0; j < tokens.length; j++) {
        matrix[j] = PApplet.parseFloat(tokens[j]);
      }

      characters.add(new Character(FloatBuffer.wrap(matrix))); // add all the characters
    }

    characters.get(0).col = color(255, 255, 0);
    characters.get(1).col = color(255, 0, 255);

    timeline = new Timeline(sm);
    // add initial tick to the begining of the timeline
    timeline.addTick(cameras.get(0));

    debug = new Debug(controlP5);

    // title, start, end, initVal, xpos, ypos, width, height
    // controlP5.addSlider("Timeline", 0,120,0,100,winHeight-50,winWidth-200,30);

  }
Пример #19
0
  /**
   * Parse a chunk of code and extract the size() command and its contents. Also goes after
   * fullScreen(), smooth(), and noSmooth().
   *
   * @param code The code from the main tab in the sketch
   * @param fussy true if it should show an error message if bad size()
   * @return null if there was an error, otherwise an array (might contain some/all nulls)
   */
  public static SurfaceInfo parseSketchSizeCustom(String code, boolean fussy)
      throws SketchException {
    // This matches against any uses of the size() function, whether numbers
    // or variables or whatever. This way, no warning is shown if size() isn't
    // actually used in the applet, which is the case especially for anyone
    // who is cutting/pasting from the reference.

    //    String scrubbed = scrubComments(sketch.getCode(0).getProgram());
    //    String[] matches = PApplet.match(scrubbed, SIZE_REGEX);
    //    String[] matches = PApplet.match(scrubComments(code), SIZE_REGEX);

    /*
    1. no size() or fullScreen() method at all
       will use the non-overridden settings() method in PApplet
    2. size() or fullScreen() found inside setup() (static mode sketch or otherwise)
       make sure that it uses numbers (or displayWidth/Height), copy into settings
    3. size() or fullScreen() already in settings()
       don't mess with the sketch, don't insert any defaults
    really only need to deal with situation #2.. nothing to be done for 1 and 3
    */
    // if static mode sketch, all we need is regex
    // easy proxy for static in this case is whether [^\s]void\s is present

    String uncommented = scrubComments(code);

    Mode mode = parseMode(uncommented);

    String searchArea = null;

    switch (mode) {
      case JAVA:
        // it's up to the user
        searchArea = null;
        break;
      case ACTIVE:
        // active mode, limit scope to setup

        // Find setup() in global scope
        MatchResult setupMatch = findInCurrentScope(VOID_SETUP_REGEX, uncommented);
        if (setupMatch != null) {
          int start = uncommented.indexOf("{", setupMatch.end());
          if (start >= 0) {
            // Find a closing brace
            MatchResult match = findInCurrentScope(CLOSING_BRACE, uncommented, start);
            if (match != null) {
              searchArea = uncommented.substring(start + 1, match.end() - 1);
            } else {
              throw new SketchException("Found a { that's missing a matching }", false);
            }
          }
        }
        break;
      case STATIC:
        // static mode, look everywhere
        searchArea = uncommented;
        break;
    }

    if (searchArea == null) {
      return new SurfaceInfo();
    }

    StringList extraStatements = new StringList();

    // First look for noSmooth() or smooth(N) so we can hoist it into settings.
    String[] smoothContents = matchMethod("smooth", searchArea);
    if (smoothContents != null) {
      extraStatements.append(smoothContents[0]);
    }
    String[] noContents = matchMethod("noSmooth", searchArea);
    if (noContents != null) {
      if (extraStatements.size() != 0) {
        throw new SketchException("smooth() and noSmooth() cannot be used in the same sketch");
      } else {
        extraStatements.append(noContents[0]);
      }
    }
    String[] pixelDensityContents = matchMethod("pixelDensity", searchArea);
    if (pixelDensityContents != null) {
      extraStatements.append(pixelDensityContents[0]);
    } else {
      pixelDensityContents = matchDensityMess(searchArea);
      if (pixelDensityContents != null) {
        extraStatements.append(pixelDensityContents[0]);
      }
    }

    String[] sizeContents = matchMethod("size", searchArea);
    String[] fullContents = matchMethod("fullScreen", searchArea);
    // First check and make sure they aren't both being used, otherwise it'll
    // throw a confusing state exception error that one "can't be used here".
    if (sizeContents != null && fullContents != null) {
      throw new SketchException("size() and fullScreen() cannot be used in the same sketch", false);
    }

    // Get everything inside the parens for the size() method
    // String[] contents = PApplet.match(searchArea, SIZE_CONTENTS_REGEX);
    if (sizeContents != null) {
      StringList args = breakCommas(sizeContents[1]);
      SurfaceInfo info = new SurfaceInfo();
      //      info.statement = sizeContents[0];
      info.addStatement(sizeContents[0]);
      //			info.width = args.get(0).trim();
      //			info.height = args.get(1).trim();
      //			info.renderer = (args.size() >= 3) ? args.get(2).trim() : null;
      //			info.path = (args.size() >= 4) ? args.get(3).trim() : null;
      setPrivateSurfaceInfoField(info, "width", (args.size() >= 1) ? args.get(0).trim() : null);
      setPrivateSurfaceInfoField(info, "height", (args.size() >= 2) ? args.get(1).trim() : null);
      setPrivateSurfaceInfoField(info, "renderer", (args.size() >= 3) ? args.get(2).trim() : null);
      setPrivateSurfaceInfoField(info, "path", (args.size() >= 4) ? args.get(3).trim() : null);

      // Trying to remember why we wanted to allow people to use displayWidth
      // as the height or displayHeight as the width, but maybe it's for
      // making a square sketch window? Not going to

      //			if (info.hasOldSyntax()) {
      if (hasOldSyntax(info)) {
        //        return null;
        throw new SketchException("Please update your code to continue.", false);
      }

      //			if (info.hasBadSize() && fussy) {
      if (hasBadSize(info) && fussy) {
        // found a reference to size, but it didn't seem to contain numbers
        final String message =
            "The size of this sketch could not be determined from your code.\n"
                + "Use only numbers (not variables) for the size() command.\n"
                + "Read the size() reference for more details.";
        //				Messages.showWarning("Could not find sketch size", message, null);
        showWarning("Could not find sketch size", message);
        //        new Exception().printStackTrace(System.out);
        //        return null;
        throw new SketchException("Please fix the size() line to continue.", false);
      }

      info.addStatements(extraStatements);
      //			info.checkEmpty();
      invokePrivateSurfaceInfoMethod(info, "checkEmpty", null);
      return info;
      // return new String[] { contents[0], width, height, renderer, path };
    }
    // if no size() found, check for fullScreen()
    // contents = PApplet.match(searchArea, FULL_SCREEN_CONTENTS_REGEX);
    if (fullContents != null) {
      SurfaceInfo info = new SurfaceInfo();
      //      info.statement = fullContents[0];
      info.addStatement(fullContents[0]);
      StringList args = breakCommas(fullContents[1]);
      if (args.size() > 0) { // might have no args
        String args0 = args.get(0).trim();
        if (args.size() == 1) {
          // could be either fullScreen(1) or fullScreen(P2D), figure out which
          if (args0.equals("SPAN") || PApplet.parseInt(args0, -1) != -1) {
            // it's the display parameter, not the renderer
            //						info.display = args0;
            setPrivateSurfaceInfoField(info, "display", args0);
          } else {
            //						info.renderer = args0;
            setPrivateSurfaceInfoField(info, "renderer", args0);
          }
        } else if (args.size() == 2) {
          //					info.renderer = args0;
          //					info.display = args.get(1).trim();
          setPrivateSurfaceInfoField(info, "renderer", args0);
          setPrivateSurfaceInfoField(info, "display", args.get(1).trim());
        } else {
          throw new SketchException("That's too many parameters for fullScreen()");
        }
      }
      //			info.width = "displayWidth";
      //			info.height = "displayHeight";
      setPrivateSurfaceInfoField(info, "width", "displayWidth");
      setPrivateSurfaceInfoField(info, "height", "displayHeight");
      //      if (extraStatements.size() != 0) {
      //        info.statement += extraStatements.join(" ");
      //      }
      info.addStatements(extraStatements);
      //			info.checkEmpty();
      invokePrivateSurfaceInfoMethod(info, "checkEmpty", null);

      return info;
    }

    // Lint is telling me that this statement is never true... but I beg to differ
    if (sizeContents == null && fullContents == null) {
      /*
       * Default to fullscreen
       *
       * This isn't in Processing's implementation, but for some reason the prior version
       * of APDE also defaulted to fullscreen, so include this to keep it the same
       *
       * Plus, it makes more sense to default to fullscreen - who wants a 100 x 100 sketch
       * display area on a mobile device?
       */

      SurfaceInfo info = new SurfaceInfo();

      info.addStatement("fullScreen();");

      setPrivateSurfaceInfoField(info, "width", "displayWidth");
      setPrivateSurfaceInfoField(info, "height", "displayHeight");

      info.addStatements(extraStatements);
      invokePrivateSurfaceInfoMethod(info, "checkEmpty", null);

      return info;
    }

    // Made it this far, but no size() or fullScreen(), and still
    // need to pull out the noSmooth() and smooth(N) methods.
    if (extraStatements.size() != 0) {
      SurfaceInfo info = new SurfaceInfo();
      //      info.statement = extraStatements.join(" ");
      info.addStatements(extraStatements);
      return info;
    }

    // not an error, just no size() specified
    // return new String[] { null, null, null, null, null };
    return new SurfaceInfo();
  }
Пример #20
0
  /**
   * Parse a chunk of code and extract the size() command and its contents. Also goes after
   * fullScreen(), smooth(), and noSmooth().
   *
   * @param code The code from the main tab in the sketch
   * @param fussy true if it should show an error message if bad size()
   * @return null if there was an error, otherwise an array (might contain some/all nulls)
   */
  public static SurfaceInfo parseSketchSize(String code, boolean fussy) throws SketchException {
    // This matches against any uses of the size() function, whether numbers
    // or variables or whatever. This way, no warning is shown if size() isn't
    // actually used in the applet, which is the case especially for anyone
    // who is cutting/pasting from the reference.

    //    String scrubbed = scrubComments(sketch.getCode(0).getProgram());
    //    String[] matches = PApplet.match(scrubbed, SIZE_REGEX);
    //    String[] matches = PApplet.match(scrubComments(code), SIZE_REGEX);

    /*
    1. no size() or fullScreen() method at all
       will use the non-overridden settings() method in PApplet
    2. size() or fullScreen() found inside setup() (static mode sketch or otherwise)
       make sure that it uses numbers (or displayWidth/Height), copy into settings
    3. size() or fullScreen() already in settings()
       don't mess with the sketch, don't insert any defaults

    really only need to deal with situation #2.. nothing to be done for 1 and 3
    */
    // if static mode sketch, all we need is regex
    // easy proxy for static in this case is whether [^\s]void\s is present

    String searchArea = scrubComments(code);
    String[] setupMatch = PApplet.match(searchArea, VOID_SETUP_REGEX);
    if (setupMatch != null) {
      String found = setupMatch[0];
      int start = searchArea.indexOf(found) + found.length();
      int openBrace = searchArea.indexOf("{", start);
      char[] c = searchArea.toCharArray();
      int depth = 0;
      int closeBrace = -1;
      StringBuilder sb = new StringBuilder();
      for (int i = openBrace; i < c.length; i++) {
        if (c[i] == '{') {
          depth++;
        } else if (c[i] == '}') {
          depth--;
          if (depth == 0) {
            closeBrace = ++i;
            break;
          }
        } else {
          sb.append(c[i]);
        }
      }
      if (closeBrace == -1) {
        throw new SketchException("Found a { that's missing a matching }", false);
        //        return null;
      }
      searchArea = sb.toString();
    }

    StringList extraStatements = new StringList();

    // First look for noSmooth() or smooth(N) so we can hoist it into settings.
    String[] smoothContents = matchMethod("smooth", searchArea);
    if (smoothContents != null) {
      extraStatements.append(smoothContents[0]);
    }
    String[] noContents = matchMethod("noSmooth", searchArea);
    if (noContents != null) {
      if (extraStatements.size() != 0) {
        throw new SketchException("smooth() and noSmooth() cannot be used in the same sketch");
      } else {
        extraStatements.append(noContents[0]);
      }
    }
    String[] pixelDensityContents = matchMethod("pixelDensity", searchArea);
    if (pixelDensityContents != null) {
      extraStatements.append(pixelDensityContents[0]);
    }

    String[] sizeContents = matchMethod("size", searchArea);
    String[] fullContents = matchMethod("fullScreen", searchArea);
    // First check and make sure they aren't both being used, otherwise it'll
    // throw a confusing state exception error that one "can't be used here".
    if (sizeContents != null && fullContents != null) {
      throw new SketchException("size() and fullScreen() cannot be used in the same sketch", false);
    }

    // Get everything inside the parens for the size() method
    // String[] contents = PApplet.match(searchArea, SIZE_CONTENTS_REGEX);
    if (sizeContents != null) {
      StringList args = breakCommas(sizeContents[1]);
      SurfaceInfo info = new SurfaceInfo();
      info.statement = sizeContents[0];
      info.width = args.get(0).trim();
      info.height = args.get(1).trim();
      info.renderer = (args.size() >= 3) ? args.get(2).trim() : null;
      info.path = (args.size() >= 4) ? args.get(3).trim() : null;

      // Trying to remember why we wanted to allow people to use displayWidth
      // as the height or displayHeight as the width, but maybe it's for
      // making a square sketch window? Not going to

      if (info.hasOldSyntax()) {
        //        return null;
        throw new SketchException("Please update your code to continue.", false);
      }

      if (info.hasBadSize() && fussy) {
        // found a reference to size, but it didn't seem to contain numbers
        final String message =
            "The size of this sketch could not be determined from your code.\n"
                + "Use only numbers (not variables) for the size() command.\n"
                + "Read the size() reference for more details.";
        Base.showWarning("Could not find sketch size", message, null);
        //        new Exception().printStackTrace(System.out);
        //        return null;
        throw new SketchException("Please fix the size() line to continue.", false);
      }

      if (extraStatements.size() != 0) {
        info.statement += extraStatements.join(" ");
      }
      info.checkEmpty();
      return info;
      // return new String[] { contents[0], width, height, renderer, path };
    }
    // if no size() found, check for fullScreen()
    // contents = PApplet.match(searchArea, FULL_SCREEN_CONTENTS_REGEX);
    if (fullContents != null) {
      SurfaceInfo info = new SurfaceInfo();
      info.statement = fullContents[0];
      StringList args = breakCommas(fullContents[1]);
      if (args.size() > 0) { // might have no args
        String args0 = args.get(0).trim();
        if (args.size() == 1) {
          // could be either fullScreen(1) or fullScreen(P2D), figure out which
          if (args0.equals("SPAN") || PApplet.parseInt(args0, -1) != -1) {
            // it's the display parameter, not the renderer
            info.display = args0;
          } else {
            info.renderer = args0;
          }
        } else if (args.size() == 2) {
          info.renderer = args0;
          info.display = args.get(1).trim();
        } else {
          throw new SketchException("That's too many parameters for fullScreen()");
        }
      }
      info.width = "displayWidth";
      info.height = "displayHeight";
      if (extraStatements.size() != 0) {
        info.statement += extraStatements.join(" ");
      }
      info.checkEmpty();
      return info;
    }

    // Made it this far, but no size() or fullScreen(), and still
    // need to pull out the noSmooth() and smooth(N) methods.
    if (extraStatements.size() != 0) {
      SurfaceInfo info = new SurfaceInfo();
      info.statement = extraStatements.join(" ");
      return info;
    }

    // not an error, just no size() specified
    // return new String[] { null, null, null, null, null };
    return new SurfaceInfo();
  }