示例#1
0
  public void report(ContactConstraint[] constraints) {
    if (m_listener == null) {
      return;
    }

    for (int i = 0; i < m_contactCount; ++i) {
      Contact c = m_contacts[i];
      ContactConstraint cc = constraints[i];
      ContactResult cr = new ContactResult();
      cr.shape1 = c.getShape1();
      cr.shape2 = c.getShape2();
      Body b1 = cr.shape1.getBody();
      int manifoldCount = c.getManifoldCount();
      List<Manifold> manifolds = c.getManifolds();
      for (int j = 0; j < manifoldCount; ++j) {
        Manifold manifold = manifolds.get(j);
        cr.normal.set(manifold.normal);
        for (int k = 0; k < manifold.pointCount; ++k) {
          ManifoldPoint point = manifold.points[k];
          ContactConstraintPoint ccp = cc.points[k];
          cr.position = XForm.mul(b1.getXForm(), point.localPoint1);

          // TOI constraint results are not stored, so get
          // the result from the constraint.
          cr.normalImpulse = ccp.normalImpulse;
          cr.tangentImpulse = ccp.tangentImpulse;
          cr.id = new ContactID(point.id);

          m_listener.result(cr);
        }
      }
    }
  }
示例#2
0
文件: Bodies.java 项目: watbe/ftg
  /**
   * Checks if player collides with a character. Uses the onDeath() function for effects.
   *
   * @param game - the game
   */
  public void characterCollision(Game game) {

    Player player = game.player;

    if (timerStart) {
      timer += 0.1;
      if (timer > 1) {
        player.hit = false;
      }
      if (timer > 5) {
        timerStart = false;
        player.immune = false;
        timer = 0;
      }
    }

    for (int i = 0; i < this.size(); i++) {

      Body character = this.get(i);

      if (Math.abs(player.xPos - character.xPos) < (player.size + character.size) / 2
          && Math.abs(player.yPos - character.yPos) < (player.size + character.size) / 2) {

        character.onDeath();
      }
    }
  }
示例#3
0
  /**
   * Deliveres notification to the user that an email has been dropped. Typically due to size
   * restriction
   *
   * @param account
   * @param messageNumber
   * @param message
   * @throws Exception
   */
  public void saveMessageDroppedNotification(
      Account account, int messageNumber, Message message, int reportedSize) throws Exception {
    MessageParser parser = new MessageParser();

    Email email = new Email();
    email.setSubject(
        "Your email"); // ReceiverUtilsTools.subSubject(parser.parseMsgSubject(message),
                       // subjectSize));
    email.setFrom(parser.parseMsgAddress(message, "FROM", false));
    email.setTo(ReceiverUtilsTools.subAddress(parser.parseMsgAddress(message, "TO", true)));
    email.setCc(ReceiverUtilsTools.subAddress(parser.parseMsgAddress(message, "CC", true)));
    email.setBcc(ReceiverUtilsTools.subAddress(parser.parseMsgAddress(message, "BCC", true)));
    email.setMaildate(ReceiverUtilsTools.dateToStr(message.getSentDate()));
    email.setStatus("0");
    email.setUserId(account.getUser_id());
    email.setMessage_type("EMAIL");

    Body body = new Body();

    String droppedMessage =
        getEmailDroppedMessage(account, getMessageDate(message), reportedSize, email.getFrom());

    body.setData(droppedMessage.getBytes());
    email.setBodySize(droppedMessage.length());

    int saveStatus = DALDominator.newSaveMail(account, email, body);

    if (log.isDebugEnabled())
      log.debug(
          String.format(
              "[%s] msgNum=%d, saving completed for dropped message with status %s",
              account.getName(), messageNumber, saveStatus));
  }
示例#4
0
  @Override
  public void see(Implementation implementation, Signature sig, Body body, Declaration tail) {
    // initialize graph
    currentFlowGraph = new SimpleGraph<Block>();
    flowGraphs.put(implementation, currentFlowGraph);

    // get blocks by name
    blocksByName = new HashMap<String, Block>();
    Block b = body.getBlocks();
    while (b != null) {
      blocksByName.put(b.getName(), b);
      currentFlowGraph.node(b);
      b = b.getTail();
    }

    // build graph
    body.eval(this);

    // check for reachability
    seenBlocks = new HashSet<Block>();
    b = body.getBlocks();
    if (b == null) return;
    dfs(b);
    while (b != null) {
      if (!seenBlocks.contains(b))
        Err.warning("" + b.loc() + ": Block " + b.getName() + " is unreachable.");
      b = b.getTail();
    }

    if (tail != null) tail.eval(this);
  }
示例#5
0
  public void run(ArrayList<Creature> creatures) {
    loc = bodyCopy.loc;
    vel = bodyCopy.vel;
    acc = bodyCopy.acc;

    decision.setMove(true);
    decision.setMoveTogheterNeigh(true);

    bodyCopy.addNearCreatures(creatures);
    bodyCopy.removeNearCreatures();
    bodyCopy.addNeighbord(creatures);
    bodyCopy.removeNeighbord();

    setNearCreatures(bodyCopy);
    setNeighbords(bodyCopy);
    setArrayNearDecisions();
    setArrayNeighbordsDecisions();

    action();

    /*
     * bodyCopy.run(creatures);
     *
     * beHunted(creatures); if (isPredator && hungry < 3) { isHunting =
     * true; } else { isHunting = false; } //
     * println(relativeness(creatures,4));
     */
  }
 public PDFDocument() {
   mHeader = new Header();
   mBody = new Body();
   mBody.setByteOffsetStart(mHeader.getPDFStringSize());
   mBody.setObjectNumberStart(0);
   mCRT = new CrossReferenceTable();
   mTrailer = new Trailer();
 }
示例#7
0
 public final void end() {
   final Iterator<Body> i = mBodies.iterator();
   while (i.hasNext()) {
     final Body body = i.next();
     if (!body.isStopped()) {
       body.stop();
     }
     i.remove();
   }
 }
示例#8
0
 /**
  * Performs the work that is required to construct any sort of <tt>UnitGraph</tt>.
  *
  * @param body The body of the method for which to construct a control flow graph.
  */
 protected UnitGraph(Body body) {
   this.body = body;
   unitChain = body.getUnits();
   method = body.getMethod();
   if (Options.v().verbose())
     G.v()
         .out
         .println(
             "[" + method.getName() + "]     Constructing " + this.getClass().getName() + "...");
 }
示例#9
0
 public final void write(final String data) {
   final Iterator<Body> i = mBodies.iterator();
   while (i.hasNext()) {
     final Body body = i.next();
     if (body.isStopped()) {
       i.remove();
     } else {
       body.writeEventData(data);
     }
   }
 }
示例#10
0
  /** Prints the given <code>JimpleBody</code> to the specified <code>PrintWriter</code>. */
  private void printLocalsInBody(Body body, UnitPrinter up) {
    // Print out local variables
    {
      Map typeToLocals = new DeterministicHashMap(body.getLocalCount() * 2 + 1, 0.7f);

      // Collect locals
      {
        Iterator localIt = body.getLocals().iterator();

        while (localIt.hasNext()) {
          Local local = (Local) localIt.next();

          List localList;

          Type t = local.getType();

          if (typeToLocals.containsKey(t)) localList = (List) typeToLocals.get(t);
          else {
            localList = new ArrayList();
            typeToLocals.put(t, localList);
          }

          localList.add(local);
        }
      }

      // Print locals
      {
        Iterator typeIt = typeToLocals.keySet().iterator();

        while (typeIt.hasNext()) {
          Type type = (Type) typeIt.next();

          List localList = (List) typeToLocals.get(type);
          Object[] locals = localList.toArray();
          up.type(type);
          up.literal(" ");

          for (int k = 0; k < locals.length; k++) {
            if (k != 0) up.literal(", ");

            up.local((Local) locals[k]);
          }

          up.literal(";");
          up.newline();
        }
      }

      if (!typeToLocals.isEmpty()) {
        up.newline();
      }
    }
  }
示例#11
0
  public void collide() {
    // Update awake contacts.
    for (Contact c = m_world.m_contactList; c != null; c = c.getNext()) {
      final Body body1 = c.getShape1().getBody();
      final Body body2 = c.getShape2().getBody();
      if (body1.isSleeping() && body2.isSleeping()) {
        continue;
      }

      c.update(m_world.m_contactListener);
    }
  }
示例#12
0
  public Player(Registerable parent, GamePanel panel) {
    super(parent);
    Body body =
        new RectangularBody(
            this, new Vector(0f, 0f), new Vector(0f, 0f), new Rectangle2D.Double(0, 0, 30, 30));
    body.setColor(Color.BLUE);
    addComponent(body);
    Controller controller = new Controller(this, panel);
    addComponent(controller);

    panel.addMouseListener(controller);
  }
示例#13
0
  public void notifyAccountLock(Account account, String context) {
    PartnerCode partnerCode = account.getPartnerCode();
    String lockedOutMessageBody =
        SysConfigManager.instance()
            .getValue("lockedOutMessageBody", LOCKED_OUT_MESSAGE_BODY, partnerCode);
    String lockedOutMessageSubject =
        SysConfigManager.instance()
            .getValue("lockedOutMessageSubject", LOCKED_OUT_MESSAGE_SUBJECT, partnerCode);
    String lockedOutMessageFrom =
        SysConfigManager.instance()
            .getValue("lockedOutMessageFrom", LOCKED_OUT_MESSAGE_FROM, partnerCode);
    String lockedOutMessageAlias =
        SysConfigManager.instance()
            .getValue("lockedOutMessageAlias", LOCKED_OUT_MESSAGE_ALIAS, partnerCode);

    try {
      Email email = new Email();
      email.setSubject(lockedOutMessageSubject);

      email.setStatus("0");
      email.setUserId(account.getUser_id());
      email.setMessage_type("EMAIL");

      email.setFrom(lockedOutMessageFrom);
      email.setFrom_alias(lockedOutMessageAlias);
      email.setTo(account.getLoginName());
      email.setBodySize(lockedOutMessageBody.length());

      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      email.setMaildate(dateFormat.format(new Date(System.currentTimeMillis()))); // ugh!

      email.setOriginal_account(account.getLoginName());

      // create the pojgo
      EmailPojo emailPojo = new EmailPojo();
      emailPojo.setEmail(email);

      Body body = new Body();
      body.setData(lockedOutMessageBody.getBytes());

      // note, the email will be encoded to prevent sql-injection. since this email is destined
      // directly for the
      // device, we need to reverse the encoding after the call to newSaveEmail
      new EmailRecievedService().newSaveEmail(account, email, body);

      // Added by Dan so we stop checking accounts that have incorrect passwords
      account.setStatus("0");

    } catch (Throwable t) {
      log.warn(String.format("failed to save locked out message for %s", context), t);
    }
  }
示例#14
0
  /**
   * @ast method
   * @aspect Expressions
   * @declaredat
   *     /Users/eric/Documents/workspaces/clara-soot/JastAddExtensions/JimpleBackend/Expressions.jrag:84
   */
  public soot.Value eval(Body b) {
    TypeDecl dest = getDest().type();
    TypeDecl source = getSource().type();
    if (dest.isString()) {

      Value lvalue = getDest().eval(b);

      Value v = asImmediate(b, lvalue);

      // new StringBuffer(left)
      Local local =
          b.newTemp(b.newNewExpr(lookupType("java.lang", "StringBuffer").sootRef(), this));
      b.setLine(this);
      b.add(
          b.newInvokeStmt(
              b.newSpecialInvokeExpr(
                  local,
                  Scene.v()
                      .getMethod("<java.lang.StringBuffer: void <init>(java.lang.String)>")
                      .makeRef(),
                  v,
                  this),
              this));

      // append right
      Local rightResult =
          b.newTemp(
              b.newVirtualInvokeExpr(
                  local,
                  lookupType("java.lang", "StringBuffer")
                      .methodWithArgs("append", new TypeDecl[] {source.stringPromotion()})
                      .sootRef(),
                  asImmediate(b, getSource().eval(b)),
                  this));

      // toString
      Local result =
          b.newTemp(
              b.newVirtualInvokeExpr(
                  rightResult,
                  Scene.v()
                      .getMethod("<java.lang.StringBuffer: java.lang.String toString()>")
                      .makeRef(),
                  this));

      Value v2 = lvalue instanceof Local ? lvalue : (Value) lvalue.clone();
      getDest().emitStore(b, v2, result, this);
      return result;
    } else {
      return super.eval(b);
    }
  }
示例#15
0
  public NBodySystem() {
    bodies = new Body[] {Body.sun(), Body.jupiter(), Body.saturn(), Body.uranus(), Body.neptune()};

    double px = 0.0;
    double py = 0.0;
    double pz = 0.0;
    for (int i = 0; i < bodies.length; ++i) {
      px += bodies[i].vx * bodies[i].mass;
      py += bodies[i].vy * bodies[i].mass;
      pz += bodies[i].vz * bodies[i].mass;
    }
    bodies[0].offsetMomentum(px, py, pz);
  }
示例#16
0
 /**
  * Fires the weapon, if it has passed it's cooldown interval.
  *
  * @param body the body of the firing entity.
  */
 public void fire(Body body, EntityType whoFired) {
   if (System.currentTimeMillis() - lastFireTime >= FIRE_INTERVAL) {
     lastFireTime = System.currentTimeMillis();
     Bullet bullet = new Bullet(whoFired);
     bullet.body.setPos(body.getX(), body.getY());
     bullet.body.setVectorX(0);
     if (whoFired == EntityType.PLAYER) {
       bullet.body.setVectorY(10);
     } else {
       bullet.body.setVectorY(-10);
     }
     EntityManager.addBullet(bullet);
   }
 }
  public void decode(ByteBuffer bytes, int pos) {

    if (bytes.array() == null) {
      return;
    }
    if (bytes.order() != ByteOrder.LITTLE_ENDIAN) {
      bytes.order(ByteOrder.LITTLE_ENDIAN);
    }

    m_MsgHeader.decode(bytes, pos);
    pos += m_MsgHeader.getSize();
    m_Body.decode(bytes, pos);
    pos += m_Body.getSize();
  }
 public boolean isEqual(Body value) {
   if (!m_RejectEventRequestRec.isEqual(value.getRejectEventRequestRec())) {
     return false;
   }
   /// This code is currently not supported
   return true;
 }
 @Override
 public void clear() {
   mHeader.clear();
   mBody.clear();
   mCRT.clear();
   mTrailer.clear();
 }
  private void analyzeMethod(SootMethod method) {
    if (!method.hasActiveBody()) {
      return;
    }
    Body activeBody = method.getActiveBody();

    List<ValueBox> useAndDefBoxes = activeBody.getUseAndDefBoxes();
    for (ValueBox valueBox : useAndDefBoxes) {
      Value value = valueBox.getValue();
      if (value instanceof FieldRef) {
        analyzeField(method, value);
      } else if (value instanceof Local) {
        analyzeLocal(method, value);
      }
    }
  }
示例#21
0
  @Override
  public boolean updatePosition() {
    if (!active) return false;

    super.updatePosition();
    return true;
  }
  @Override
  public void addBody(Body body)
      throws SAXException, WingException, SQLException, IOException, AuthorizeException {
    Item item = workflowItem.getItem();
    Collection collection = workflowItem.getCollection();
    Request request = ObjectModelHelper.getRequest(objectModel);

    String actionURL = contextPath + "/handle/" + collection.getHandle() + "/xmlworkflow";

    // Retrieve our pagenumber
    int page = ReviewAction.MAIN_PAGE;
    if (request.getAttribute("page") != null) {
      page = Integer.parseInt(request.getAttribute("page").toString());
    }

    // Generate a from asking the user two questions: multiple
    // titles & published before.
    Division div =
        body.addInteractiveDivision(
            "perform-task", actionURL, Division.METHOD_POST, "primary workflow");
    div.setHead(T_HEAD);

    addWorkflowItemInformation(div, item, request);

    switch (page) {
      case org.dspace.xmlworkflow.state.actions.processingaction.AcceptEditRejectAction.MAIN_PAGE:
        renderMainPage(div);
        break;
      case ReviewAction.REJECT_PAGE:
        renderRejectPage(div);
        break;
    }

    div.addHidden("submission-continue").setValue(knot.getId());
  }
示例#23
0
  @Override
  public void updateForces() {
    if (!active) return;

    applyNonZeroFriction();
    super.updateForces();
  }
示例#24
0
  public void solveTOI(TimeStep subStep) {
    ContactSolver contactSolver = new ContactSolver(subStep, m_contacts, m_contactCount);

    // No warm starting needed for TOI events.

    // Solve velocity constraints.
    for (int i = 0; i < subStep.maxIterations; ++i) {
      contactSolver.solveVelocityConstraints();
    }

    // Don't store the TOI contact forces for warm starting
    // because they can be quite large.

    // Integrate positions.
    for (int i = 0; i < m_bodyCount; ++i) {
      Body b = m_bodies[i];

      if (b.isStatic()) continue;
      // System.out.println("(Island::SolveTOI 1) :"+b.m_sweep);
      // Store positions for continuous collision.
      b.m_sweep.c0.set(b.m_sweep.c);
      b.m_sweep.a0 = b.m_sweep.a;

      // Integrate
      b.m_sweep.c.x += subStep.dt * b.m_linearVelocity.x;
      b.m_sweep.c.y += subStep.dt * b.m_linearVelocity.y;
      b.m_sweep.a += subStep.dt * b.m_angularVelocity;

      // System.out.println("(Island::SolveTOI 2) :"+b.m_sweep);
      // Compute new transform
      b.synchronizeTransform();

      //	System.out.println("(Island::SolveTOI 3) :"+b.m_sweep);
      // Note: shapes are synchronized later.
    }

    // Solve position constraints.
    final float k_toiBaumgarte = 0.75f;
    for (int i = 0; i < subStep.maxIterations; ++i) {
      boolean contactsOkay = contactSolver.solvePositionConstraints(k_toiBaumgarte);
      if (contactsOkay) {
        break;
      }
    }

    report(contactSolver.m_constraints);
  }
  /**
   * Returns the number of bytes the used data members of the class occupies in the buffer. This is
   * not the number of bytes the data type occupies in Java, but the bytes expected on the wire.
   *
   * @return
   */
  public long getSize() {
    int size = 0;

    size += m_MsgHeader.getSize();
    size += m_Body.getSize();

    return size;
  }
示例#26
0
 public static void rewalk(Body body) {
   V.clear(4, 0, 0);
   V.clear(1, 0, 0);
   V.S(2, 0, body.x, body.y, 0);
   V.S(3, 0, body.x, body.y, 0);
   int i = V.G(5, 0, body.x, body.y);
   V.S(5, 0, body.x, body.y, 0);
   body.x = x;
   body.y = y;
   V.S(2, 0, body.x, body.y, body.img);
   V.S(5, 0, body.x, body.y, i);
   uw.closeHPanel();
   uw.closeTPanel();
   uw.closeAPanel();
   map.setWalkPaint(body);
   map.repaint();
 }
示例#27
0
  /**
   * Prints out the method corresponding to b Body, (declaration and body), in the textual format
   * corresponding to the IR used to encode b body.
   *
   * @param out a PrintWriter instance to print to.
   */
  public void printTo(Body b, PrintWriter out) {
    b.validate();

    boolean isPrecise = !useAbbreviations();

    String decl = b.getMethod().getDeclaration();

    out.println("    " + decl);
    // incJimpleLnNum();

    // only print tags if not printing attributes in a file
    if (!addJimpleLn()) {
      /*for( Iterator tIt = b.getMethod().getTags().iterator(); tIt.hasNext(); ) {    final Tag t = (Tag) tIt.next();
          out.println(t);
          incJimpleLnNum();

      }*/
    }

    if (addJimpleLn()) {
      setJimpleLnNum(addJimpleLnTags(getJimpleLnNum(), b.getMethod()));
      // G.v().out.println("added jimple ln tag for method: "+b.getMethod().toString()+"
      // "+b.getMethod().getDeclaringClass().getName());
    }

    out.println("    {");
    incJimpleLnNum();

    UnitGraph unitGraph = new soot.toolkits.graph.BriefUnitGraph(b);

    LabeledUnitPrinter up;
    if (isPrecise) up = new NormalUnitPrinter(b);
    else up = new BriefUnitPrinter(b);

    if (addJimpleLn()) {
      up.setPositionTagger(new AttributesUnitPrinter(getJimpleLnNum()));
    }

    printLocalsInBody(b, up);

    printStatementsInBody(b, out, up, unitGraph);

    out.println("    }");
    incJimpleLnNum();
  }
  public static void main(String args[]) {
    // Set classPath
    String exemplePath = "/Users/gamyot/Documents/workspace/Soot_Exemples/src/";
    String objectPath = "/System/Library/Frameworks/JavaVM.framework/Classes/classes.jar";
    String tracePath = "/Users/gamyot/Documents/workspace/SootInstrumenter/src/";

    Scene.v().setSootClassPath(".:" + objectPath + ":" + exemplePath + ":" + tracePath);

    Scene.v().loadClassAndSupport("java.lang.Object");
    Scene.v().loadClassAndSupport("java.lang.System");

    // Set up the class we’re working with
    SootClass c = Scene.v().loadClassAndSupport("MyExemples.ExempleBasic");
    c.setApplicationClass();

    // Get methods
    Iterator<SootMethod> methodIterator = c.methodIterator();
    while (methodIterator.hasNext()) methodList.add(methodIterator.next());
    // Iterate through the method list
    for (SootMethod m : methodList) {
      Body body = m.retrieveActiveBody();
      PatchingChain<Unit> unitList = body.getUnits();
      // get the all the "if statements" Units
      List<Unit> ifStmtList = searchIfStmts(body);

      // for each "if statement" unit, instrument and add the instrumentation code right after
      for (Unit ifStmtUnit : ifStmtList) {
        // Chain<Unit> instrumentedChain = generateInstrumentationUnits(ifStmtUnit, body);
        // unitList.insertAfter(instrumentedChain, ifStmtUnit);
        Chain<Unit> testChain = generateInstrumentationUnits(ifStmtUnit, body);
        unitList.insertAfter(testChain, ifStmtUnit);
      }
      // Output all the units for this method on terminal
      String methodName = m.getName();
      System.out.println(
          "____Method: \"" + methodName + "\"__________________________________________________");
      LoadAndGenerate.printAllUnits(body);
    }

    try {
      LoadAndGenerate.outputClassToBinary(c);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
示例#29
0
 /**
  * an action call with cache
  *
  * @param ac the action invocation wrapper
  * @param key user specified key, the user needs to explicitly compose a key from the action and
  *     arguments. The template transformer can put the action calling string as prefix of the key,
  *     e.g., if the acton is Application.show(post), the key should be compose of
  *     "Application.show()-" + post.toString(). Note we cannot use "post" literally since post as
  *     the var name can be anything that the template author chooses to use. Problem: Application
  *     needs to be imported or all controllers package must be imported. Controllers in sub
  *     packages needs special care in importing since a simple import controllers.* won't work for
  *     controllers in sub packages.
  * @param ttl expiration Ex: 10s, 3mn, 8h
  */
 public void render(String key, String ttl, Body body) {
   String co = (String) Cache.get(key);
   if (co == null) {
     co = body.render();
     Cache.set(key, co, Time.parseDuration(ttl));
   }
   p(co);
   return;
 }
 @Override
 public String toPDFString() {
   StringBuilder sb = new StringBuilder();
   sb.append(mHeader.toPDFString());
   sb.append(mBody.toPDFString());
   mCRT.setObjectNumberStart(mBody.getObjectNumberStart());
   int x = 0;
   while (x < mBody.getObjectsCount()) {
     IndirectObject iobj = mBody.getObjectByNumberID(++x);
     if (iobj != null) {
       mCRT.addObjectXRefInfo(iobj.getByteOffset(), iobj.getGeneration(), iobj.getInUse());
     }
   }
   mTrailer.setObjectsCount(mBody.getObjectsCount());
   mTrailer.setCrossReferenceTableByteOffset(sb.length());
   mTrailer.setId(Indentifiers.generateId());
   return sb.toString() + mCRT.toPDFString() + mTrailer.toPDFString();
 }