Exemplo n.º 1
0
 /**
  * Adding key support. up and down arrows can be used to scroll listbox or dropdownList,up and
  * down, use shift+up/down for faster scrolling, use alt+up/down to jump to the top or bottom.
  *
  * @exclude {@inheritDoc}
  */
 @ControlP5.Invisible
 public void keyEvent(final KeyEvent theEvent) {
   super.keyEvent(theEvent);
   float x = getAbsolutePosition().x;
   float y = getAbsolutePosition().y;
   boolean b =
       (getWindow().mouseX > x
           && getWindow().mouseX < (x + _myWidth)
           && getWindow().mouseY > (y - getBarHeight())
           && getWindow().mouseY < y + _myOriginalBackgroundHeight);
   if (b && isOpen()) {
     float step = (1.0f / (float) items.size());
     if (cp5.isShiftDown()) {
       step *= 10;
     } else if (cp5.isAltDown()) {
       step = 1;
     }
     if (theEvent.getAction() == KeyEvent.PRESSED) {
       switch (theEvent.getKeyCode()) {
         case (PApplet.UP):
           _myScrollbar.setValue(PApplet.constrain(_myScrollbar.getValue() + step, 0, 1));
           break;
         case (PApplet.DOWN):
           _myScrollbar.setValue(PApplet.constrain(_myScrollbar.getValue() - step, 0, 1));
           break;
       }
     }
   }
 }
Exemplo n.º 2
0
  /*
  	Perform Simulation
  */
  public void simulate(float dt) {
    // Accelerate angular speed
    float requiredSpeed = targetAngularSpeed - angularSpeed;
    float angularAccel = requiredSpeed / dt;
    angularAccel = PApplet.constrain(angularAccel, -maxAngularAccel, maxAngularAccel);

    // Limit Angular speed
    angularSpeed += angularAccel * dt;
    angularSpeed = PApplet.constrain(angularSpeed, -maxAngularSpeed, maxAngularSpeed);

    // Orientation Simulation
    orientation += angularSpeed * dt;

    // Position simulation
    PVector worldRequiredSpeed = targetSpeed.get();
    worldRequiredSpeed.rotate(orientation);
    worldRequiredSpeed.sub(speed);

    // PVector worldRequiredSpeed = worldTargetSpeed.get();
    float dSpeed = worldRequiredSpeed.mag();
    float dAcell = dSpeed / dt;
    float dForce = Math.min(dAcell * getMass(), motorForce);

    worldRequiredSpeed.normalize();
    worldRequiredSpeed.mult(dForce);
    force.add(worldRequiredSpeed);

    super.simulate(dt);
  }
Exemplo n.º 3
0
 public void setValue(float val) {
   float oldValue = value;
   value = PApplet.constrain(val, min, max);
   if (useReflection) {
     if (useMethod) {
       try {
         method.invoke(fieldObj, value);
       } catch (Exception e) {
         e.printStackTrace();
       }
     } else {
       try {
         field.setFloat(fieldObj, value);
       } catch (Exception e) {
         // Try setting the String value.
         String s = getStringValueForNumber(value);
         try {
           field.set(fieldObj, s);
         } catch (Exception e2) {
           e.printStackTrace();
           e2.printStackTrace();
         }
       }
     }
   }
   updateString();
 }
Exemplo n.º 4
0
  /**
   * Retrieves the data associated with a given audio frame.
   *
   * @param inpFrameIdx Index of the desired audio frame.
   * @return Array of float values representing the data for this audio frame.
   */
  private float[] rtrvAudioFrameData(int inpFrameIdx) {
    float[] rtnFrameData = new float[_frameDataCntNbr];

    inpFrameIdx = PApplet.constrain(inpFrameIdx, 0, _audioFrameCnt - 1);

    for (int bufferIdx = 0; bufferIdx < _frameDataCntNbr; bufferIdx++) {
      rtnFrameData[bufferIdx] = _musicData[inpFrameIdx][bufferIdx];
    }

    return rtnFrameData;
  }
Exemplo n.º 5
0
 /**
  * Calculate a force to push particle away from repeller
  *
  * @param ptcl the Particle to push
  * @return PVector direction
  */
 public PVector pushParticle(Particle ptcl) {
   PVector dir = PVector.sub(getLoc(), ptcl.getLoc()); // Calculate direction of
   // force
   float d = dir.mag(); // Distance between objects
   dir.normalize(); // Normalize vector (distance doesn't matter here, we
   // just want this vector for direction)
   d = PApplet.constrain(d, 5, 100); // Keep distance within a reasonable
   // range
   float force = -1 * G / (d * d); // Repelling force is inversely
   // proportional to distance
   dir.mult(force); // Get force vector --> magnitude * direction
   return dir;
 }
Exemplo n.º 6
0
 /*
  * (non-Javadoc)
  *
  * @see controlP5.Controller#updateInternalEvents(processing.core.PApplet)
  */
 public void updateInternalEvents(PApplet theApplet) {
   if (isMousePressed && !ControlP5.keyHandler.isAltDown) {
     if (isActive) {
       float c =
           (_myDragDirection == HORIZONTAL)
               ? _myControlWindow.mouseX - _myControlWindow.pmouseX
               : _myControlWindow.mouseY - _myControlWindow.pmouseY;
       currentValue += (c) / resolution;
       if (isLimited) {
         currentValue = PApplet.constrain(currentValue, 0, 1);
       }
       setInternalValue(currentValue);
     }
   }
 }
Exemplo n.º 7
0
  public void setY(float setY) {
    y = PApplet.constrain(setY - h / 2, minY, maxY);

    // mapping eventuell noch logarithmisch? - mŸsste stimmen

    // calc cameraTarget
    p5.cam_eyetargetpos.z =
        PApplet.map(
            y + h,
            p5.timeChooser.y + p5.timeChooser.h,
            p5.timeChooser.y,
            (p5.height / 2.0f) / PApplet.tan(PConstants.PI * 30.0f / 180.0f),
            -p5.timeline.timelineLength
                + (p5.height / 2.0f) / PApplet.tan(PConstants.PI * 30.0f / 180.0f));

    // System.out.println("set Y: " + p5.cam_eyetargetpos.z + " " + (p5.timeChooser.y +
    // p5.timeChooser.h) + " " + (p5.timeChooser.y) + " " + ((p5.height / 2.0f) /
    // p5.tan(PConstants.PI * 30.0f / 180.0f)) + " " + (p5.timeline.timelineLength + (p5.height /
    // 2.0f) / p5.tan(PConstants.PI * 30.0f / 180.0f)));
  }
Exemplo n.º 8
0
  public Level(String filename, PixelPie pie) {
    XML file = pie.app.loadXML(filename);

    // Get level properties, if any.
    if (file.getChild("properties") != null) {
      properties = new StringDict();
      for (XML child : file.getChild("properties").getChildren("property")) {
        properties.set(child.getString("name"), child.getString("value"));
      }
    }

    // Get tile dimensions.
    tileWidth = file.getInt("tilewidth");
    tileHeight = file.getInt("tileheight");

    // Get Row and Column count.
    levelColumns = file.getInt("width");
    levelRows = file.getInt("height");

    // Get level dimensions.
    levelWidth = levelColumns * tileWidth;
    levelHeight = levelRows * tileHeight;

    // Get tileSets.
    tileSets = file.getChildren("tileset");

    // Get objects.
    objects = file.getChildren("objectgroup");

    // Get scripts.
    scripts = new HashMap<String, Script>();
    for (XML objectType : objects) {
      String objectName = objectType.getString("name");

      // Check type of object.
      if (objectName.substring(0, 1).equals("(")) {

        // Break up name into parts.
        String[] nameParts = PApplet.split(objectName, " ");

        // If script.
        if (nameParts[0].equals("(script)")) {

          // Grab script name.
          String name = nameParts[1];

          // Initialize coordinates array (if any).
          IntDict scriptCoords = new IntDict();

          // Check for objects in script layer. Get coordinates from these objects.
          if (objectType.getChild("object") != null) {
            for (XML coordObj : objectType.getChildren("object")) {

              // Check if object has a name, if not, skip it.
              if (coordObj.getString("name") == null) {
                pie.log.printlg("Script coordinate container does not have a name. Ignoring.");
                continue;
              }

              // Figure out object type.
              int coordType = 0;
              if (coordObj.hasChildren()) {
                coordType = (coordObj.getChild("polyline") != null) ? 2 : 1;
              }

              // Process coordinates depending on object type.
              switch (coordType) {

                  // If rectangle, take top-left corner.
                case 0:
                  scriptCoords.set(
                      coordObj.getString("name"),
                      PixelPie.coordToArray(coordObj.getInt("x"), coordObj.getInt("y"), this));
                  break;

                  // If ellipse, take center.
                case 1:
                  scriptCoords.set(
                      coordObj.getString("name"),
                      PixelPie.coordToArray(
                          coordObj.getInt("x") + coordObj.getInt("width") / 2,
                          coordObj.getInt("y") + coordObj.getInt("height") / 2,
                          this));
                  break;

                  // If poly line, record each point.
                case 2:
                  String[] coordsArray =
                      PApplet.split(coordObj.getChild("polyline").getString("points"), " ");
                  int startX = Integer.parseInt(objectType.getChild("object").getString("x"));
                  int startY = Integer.parseInt(objectType.getChild("object").getString("y"));
                  for (int i = 0; i < coordsArray.length; i++) {
                    scriptCoords.set(
                        coordObj.getString("name") + "_" + PApplet.nf(i, 2),
                        PixelPie.coordToArray(
                            startX + Integer.parseInt(PApplet.split(coordsArray[i], ",")[0]),
                            startY + Integer.parseInt(PApplet.split(coordsArray[i], ",")[1]),
                            this));
                  }
                  break;
              }
            }
          } else {
            scriptCoords = null;
          }

          // Get the total amount of frames.
          int endFrame = 0;
          for (XML obj : objectType.getChild("properties").getChildren("property")) {
            endFrame = PApplet.max(endFrame, PixelPie.getScriptFrame(obj.getString("name")));
          }

          // Create the scriptAction container "children".
          HashMap<String, ScriptAction[]> children = new HashMap<String, ScriptAction[]>();

          // Create the script object.
          Script Script = new Script(endFrame, scriptCoords, children, pie);
          scripts.put(name, Script);

          // Create scriptAction temporary container. This one uses a HashMap so we can dynamically
          // add scriptActions to it.
          HashMap<String, ArrayList<ScriptAction>> scriptTemp =
              new HashMap<String, ArrayList<ScriptAction>>();

          // Add scriptActions to the temporary container.
          for (XML obj : objectType.getChild("properties").getChildren("property")) {
            String frame = PApplet.str(PixelPie.getScriptFrame(obj.getString("name")));

            // Create scriptAction object from parameters.
            String[] actionArray = PApplet.split(obj.getString("value"), "(");
            String params = actionArray[1].substring(0, actionArray[1].length() - 1);
            ScriptAction action = null;
            // try {action = (scriptAction) Class.forName(app.getClass().getName() + "$script_" +
            // actionArray[0]).getDeclaredConstructors()[0].newInstance(new Object[]{app, params,
            // Script});}
            try {
              action =
                  (ScriptAction)
                      Class.forName(pie.app.getClass().getName() + "$script_" + actionArray[0])
                          .getDeclaredConstructors()[0]
                          .newInstance(new Object[] {pie.app});
              action.setup(params, Script);
            } catch (Exception e) {
              pie.log.printlg(e);
            }

            // Check whether there is an entry in the scriptTemp array.
            if (scriptTemp.get(frame) != null) {
              scriptTemp.get(frame).add(action);
            } else {
              // Initiate Arraylist.
              scriptTemp.put(frame, new ArrayList<ScriptAction>());
              scriptTemp.get(frame).add(action);
            }
          }

          // Turn over contents of temporary container to "children" array.
          for (@SuppressWarnings("rawtypes") Map.Entry entry : scriptTemp.entrySet()) {
            ScriptAction[] tempActions = new ScriptAction[scriptTemp.get(entry.getKey()).size()];
            for (int i = 0; i < scriptTemp.get(entry.getKey()).size(); i++) {
              tempActions[i] = scriptTemp.get(entry.getKey()).get(i);
            }
            children.put(entry.getKey().toString(), tempActions);
          }
        }
      }
    }

    // Load level layers.
    XML[] layers = file.getChildren("layer");

    // Count number of background and level layers.
    for (int i = 0; i < layers.length; i++) {
      if (layers[i].getString("name").substring(0, 4).equals("(bg)")) {
        backgroundLayers++;
      } else {
        levelLayers++;
      }
    }

    // Initiate arrays.
    background = new int[backgroundLayers][levelColumns * levelRows];
    levelMap = new int[levelLayers][levelColumns * levelRows];
    bgScroll = new float[backgroundLayers];

    // Process each layer.
    int currentLayer = 0;
    int bgCurrentLayer = 0;
    for (int i = 0; i < layers.length; i++) {

      // If it's a background layer...
      if (layers[i].getString("name").substring(0, 4).equals("(bg)")) {

        // Get properties.
        HashMap<String, String> prop = new HashMap<String, String>();
        for (XML property : layers[i].getChild("properties").getChildren("property")) {
          prop.put(property.getString("name"), property.getString("value"));
        }

        // Process the scroll rate.
        bgScroll[bgCurrentLayer] =
            PApplet.constrain(Float.parseFloat(PixelPie.getProp(prop, "scroll")), 0, 1);

        // Process each background tile.
        XML[] tiles = layers[i].getChild("data").getChildren("tile");
        for (int k = 0; k < tiles.length; k++) {
          background[bgCurrentLayer][k] = tiles[k].getInt("gid");
        }

        // Increase background layer counter.
        bgCurrentLayer++;
      }

      // Else, load layer as normal.
      else {
        // Load each tile.
        XML[] tiles = layers[i].getChild("data").getChildren("tile");
        for (int k = 0; k < tiles.length; k++) {
          levelMap[currentLayer][k] = tiles[k].getInt("gid");
        }
        currentLayer++;
      }
    }
  }
Exemplo n.º 9
0
 public void value(float value) {
   this.value = (constrain) ? PApplet.constrain(value, this.min, this.max) : value;
 }
Exemplo n.º 10
0
 public float value() {
   return (constrain) ? PApplet.constrain(this.value, this.min, this.max) : this.value;
 }
Exemplo n.º 11
0
  /** All GUI components are registered for mouseEvents */
  public void mouseEvent(MouseEvent event) {
    if (!visible || !enabled || !available) return;

    calcTransformedOrigin(winApp.mouseX, winApp.mouseY);

    int spot = whichHotSpot(ox, oy);

    // If over the track then see if we are over the thumb
    if (spot >= 9) {
      if (isOverThumb(ox, oy)) spot = 10;
      else spot = -1; // Over empty track so ignore
    }
    if (spot != currSpot) {
      currSpot = spot;
      bufferInvalid = true;
    }

    if (currSpot >= 0 || focusIsWith == this) cursorIsOver = this;
    else if (cursorIsOver == this) cursorIsOver = null;

    switch (event.getID()) {
      case MouseEvent.MOUSE_PRESSED:
        if (focusIsWith != this && currSpot >= 0 && z > focusObjectZ()) {
          dragging = false;
          last_ox = ox;
          last_oy = oy;
          takeFocus();
        }
        break;
      case MouseEvent.MOUSE_CLICKED:
        if (focusIsWith == this) {
          switch (currSpot) {
            case 1:
              value -= 0.1f;
              if (value < 0) value = 0;
              bufferInvalid = true;
              fireEvent(this, GEvent.CHANGED);
              break;
            case 2:
              value += 0.1f;
              if (value + filler > 1.0) value = 1 - filler;
              bufferInvalid = true;
              fireEvent(this, GEvent.CHANGED);
              break;
          }
          dragging = false;
          loseFocus(parent);
        }
        break;
      case MouseEvent.MOUSE_RELEASED:
        if (focusIsWith == this && dragging) {
          loseFocus(parent);
          dragging = false;
          isValueChanging = false;
          bufferInvalid = true;
        }
        break;
      case MouseEvent.MOUSE_DRAGGED:
        if (focusIsWith == this) {
          float movement = ox - last_ox;
          last_ox = ox;
          float deltaV = movement / (width - 32);
          value += deltaV;
          value = PApplet.constrain(value, 0, 1.0f - filler);
          isValueChanging = true;
          bufferInvalid = true;
          dragging = true;
          fireEvent(this, GEvent.CHANGED);
        }
        break;
    }
  }