Esempio n. 1
1
  public void moveToShape(Collection<ShapeInArea> des, Class<? extends MoveType> type)
      throws SOSActionException {

    if (!(me.me() instanceof Human)) {
      log().warn("can't use move in Center Agent " + me + "\n");
      return;
    }
    try {
      checkTraffic(); // TODO uncomment
      MoveType mt = moves.get(type.hashCode());
      if (mt != null) {
        Path path = mt.getPathToShape(des);
        log().debug("MOVE " + type.getSimpleName() + "\nTO : " + path + "\n");
        move(path);
      } else log().error(new Error("in move can not found type=" + type.getSimpleName()));

    } catch (SOSActionException e) {
      throw e;
    } catch (Exception er) {
      log().error(er);
      log().warn("using bfs for finding path");
      ArrayList<Area> goals = new ArrayList<Area>();

      for (ShapeInArea shapeInArea : des) {
        goals.add(shapeInArea.getArea(me.model()));
      }
      move(bfs.breadthFirstSearch((Area) me.location(), goals));
    }
    log().error("in move can not found type=" + type.getSimpleName());
    me.problemRest("in move can not found type=" + type.getSimpleName());
  }
Esempio n. 2
0
  public ArrayList<Building> getProbabilisticFieryBuilding() {
    if (agent.model().time() == time) return res;
    time = agent.model().time();
    res.clear();
    resCluster.clear();
    log.info("new fire probability computer");

    ArrayList<Building> probabilisticBuilding = getProbabilisticBuilding();
    log.info("Probabilistic buildings :::> " + probabilisticBuilding);

    ArrayList<ArrayList<Building>> regions = getRegions(probabilisticBuilding);

    removeCheckedBuildings(regions);

    int index = 0;

    for (ArrayList<Building> region : regions) {
      HashSet<Building> x = new HashSet<Building>();
      for (Building b : getBestProb(region))
        if (b.getValuSpecialForFire() > 0) {
          res.add(b);
          x.add(b);
        }
      if (x.size() > 0) {
        ClusterData cd = new ClusterData(x, index++);
        resCluster.add(cd);
      }
    }

    log.info("result ::> " + res);

    return res;
  }
Esempio n. 3
0
  private ArrayList<Building> getProbabilisticBuilding() {

    ArrayList<Building> probabilisticBuildings = new ArrayList<Building>();
    boolean[] checked = new boolean[agent.model().buildings().size()];

    for (Building b : agent.model().buildings()) {
      b.setSpecialForFire(0, "reset");
      boolean fireProbability = hasFireProbability(b);

      if (fireProbability) {
        log.info("Fire Prob  " + b);
        if (!checked[b.getBuildingIndex()]) {
          b.setSpecialForFire(0, "reset");
          probabilisticBuildings.add(b);
          checked[b.getBuildingIndex()] = true;
          log.info("\t\t aded " + b);
        }

        for (Building neigh : b.realNeighbors_Building()) {
          if (!checked[neigh.getBuildingIndex()]) { // && hasFireProbability(neigh)
            neigh.setSpecialForFire(0, "reset");
            probabilisticBuildings.add(neigh);
            checked[neigh.getBuildingIndex()] = true;
            log.info("\t\t aded " + neigh);
          }
        }
      }
    }

    return probabilisticBuildings;
  }
Esempio n. 4
0
 public void moveXY(
     Collection<Pair<? extends Area, Point2D>> destinations, Class<? extends MoveType> type)
     throws SOSActionException {
   if (!(me.me() instanceof Human)) {
     log().warn("can't use move in Center Agent " + me + "\n");
     return;
   }
   try {
     checkTraffic();
     MoveType mt = moves.get(type.hashCode());
     if (mt != null) {
       Path path = mt.getPathToPoints(destinations);
       log().debug("MOVE XY" + type.getSimpleName() + "\nTO : " + path + "\n");
       move(path);
     } else log().error(new Error("in move can not found type=" + type.getSimpleName()));
   } catch (SOSActionException e) {
     throw e;
   } catch (Exception er) {
     log().error(er);
     log().warn("using bfs for finding path");
     move(bfs.breadthFirstSearchXY((Area) me.location(), destinations));
   }
   log().error("in move can not found type=" + type.getSimpleName());
   me.problemRest("in move can not found type=" + type.getSimpleName());
 }
Esempio n. 5
0
  private void addProbScore(ArrayList<Building> region, Building center) {
    for (Building neigh : center.realNeighbors_Building()) {
      neigh.setSpecialForFire(neigh.getValuSpecialForFire() - 100000, " -100  " + center);
      //////////////////////////////////////
      if (neigh.updatedtime() >= center.updatedtime()) {
        log.info("\t\t\t Neigh is update " + neigh);
        continue;
      }
      if (neigh.updatedtime() >= center.getTemperatureIncreasedTime()) {
        log.info(
            "\t\t\t Neigh is update after sensed temp "
                + neigh
                + "    NeighUpdTime="
                + neigh.updatedtime()
                + "\t increaseTime="
                + center.getTemperatureIncreasedTime());
        continue;
      }
      /////////////////////////////////
      if (agent.model().time() - neigh.updatedtime() < Math.min(8, agent.model().time() / 2))
        continue;

      if (center.updatedtime() < neigh.updatedtime() + 3) continue;

      if (!region.contains(neigh)) continue;

      neigh.setSpecialForFire(neigh.getValuSpecialForFire() + 100000, "Add 100 score ");

      double t = temperatureScore(center);

      t *=
          (center.getRealNeighValue(neigh) + 0.001)
              * 100d
              / ((Math.max(1, distance(center, neigh) / 1000)));
      if (center.getTemperature() < 3)
        t += center.getNeighValue(neigh) * 200 * temperatureScore(center);

      double c = 1;
      for (Building n2 : neigh.realNeighbors_Building()) {
        if (n2.getTemperature() > 0) c -= neigh.getNeighValue(n2);
        else c += neigh.getRealNeighValue(n2);
      }

      neigh.setSpecialForFire(
          neigh.getValuSpecialForFire() + (int) (Math.ceil(t * c)),
          " temp = "
              + temperatureScore(center)
              + " distance and neigh = "
              + t
              + "  c "
              + c
              + " "
              + center);

      //			if (!res.contains(neigh))
      //				res.add(neigh);

    }
  }
Esempio n. 6
0
  private void chooseRoadMessages() { // TODO choose to spread it over time
    if (!(agent instanceof SOSAgent<?>)) return;

    PriorityQueue<Road> roads =
        new PriorityQueue<Road>(
            agent.model().roads().size(),
            new Comparator<Road>() {

              @Override
              public int compare(Road o1, Road o2) {
                return o2.updatedtime() - o1.updatedtime();
              }
            });
    FOR:
    for (Road road : agent.model().roads()) {
      if (road.updatedtime() <= 1) continue;
      boolean haveAnOpenEdge = false;
      for (int j = 0; j < road.getGraphEdges().length; j++) {
        GraphEdge ge = model().graphEdges().get(road.getGraphEdges()[j]);
        //				if (ge.getState() == GraphEdgeState.FoggyBlock ||
        //						ge.getState() == GraphEdgeState.FoggyOpen)
        //					continue FOR;
        if (ge.getState() == GraphEdgeState.Open) haveAnOpenEdge = true;
      }
      if (haveAnOpenEdge) roads.add(road);
    }
    int priority = 6;
    int count = 0;
    SOSAgent<?> agent = (SOSAgent<?>) this.agent;
    for (Road rd : roads) {

      count++;
      if (priority > 0 && count % 10 == 0) priority--;
      boolean isAllOpen = true;
      for (Short ind : rd.getGraphEdges()) {
        GraphEdge ge = agent.model().graphEdges().get(ind);
        if (ge instanceof WorldGraphEdge && ge.getState() != GraphEdgeState.Open) {
          isAllOpen = false;
          break;
        }
      }
      if (isAllOpen) {
        MessageBlock messageBlock = new MessageBlock(HEADER_OPEN_ROAD);
        messageBlock.addData(DATA_ROAD_INDEX, rd.getRoadIndex());
        sayMessages.add(messageBlock);
      } else {
        SOSBitArray states = new SOSBitArray(rd.getWorldGraphEdgesSize());
        for (int i = 0; i < rd.getWorldGraphEdgesSize(); i++) {
          states.set(
              i,
              agent.model().graphEdges().get(rd.getGraphEdges()[i]).getState()
                  != GraphEdgeState.Open);
        }
        MessageBlock messageBlock = new DynamicSizeMessageBlock(HEADER_ROAD_STATE, states);
        messageBlock.addData(DATA_ROAD_INDEX, rd.getRoadIndex());
        sayMessages.add(messageBlock);
      }
    }
  }
Esempio n. 7
0
 private void removeTemporaryTrafficBlocks() {
   while (!traffic.isEmpty() && me.time() > traffic.getFirst().second() + this.trafficRemainTime) {
     traffic.getFirst().first().setFreeTraffic();
     log().info(" traffic removed " + traffic.getFirst().first());
     traffic.removeFirst();
   }
   if (me.location() instanceof Road) {
     //			inBuildingStoppedCount = 0;
     // isBuildingCenterPassed = false;
   }
 }
Esempio n. 8
0
  public void move(Path path, Class<? extends MoveType> type) throws SOSActionException {
    if (!(me.me() instanceof Human)) {
      log().warn("can't use move in Center Agent " + me + "\n");
      return;
    }
    MoveType mt = moves.get(type.hashCode());
    if (mt != null) {
      log().debug("MOVE " + type.getSimpleName() + "\nTO : " + path + "\n");
      move(path);
    } else log().error(new Error("in move can not found type=" + type.getSimpleName()));

    log().error("in move can not found type=" + type.getSimpleName());
    me.problemRest("in move can not found type=" + type.getSimpleName());
  }
Esempio n. 9
0
 // TODO add stopped time to 3 cycles
 private void checkStock(Path path) throws SOSActionException {
   log().info("Checking stock");
   if (me.time() < 4) {
     log().debug("No Stock! Beacuse time is less than 4");
     return;
   }
   //		if(!(me instanceof PoliceForceAgent))
   //				check4CycleStock();
   //				check3CycleStock();
   checkAlakiStock(path);
   check2CycleStock();
   if (me.getMapInfo().getRealMapName()
       == MapName.VC /* || me.getMapInfo().getRealMapName() == MapName.Kobe */)
     checkEarlyStock(path);
   lastStockTime = 0;
 }
Esempio n. 10
0
 public SOSFireProbability(SOSAgent agent) {
   this.agent = agent;
   log =
       new SOSLoggerSystem(
           (StandardEntity) agent.me(), "SOSFireProbability/", true, OutputType.File, true);
   agent.sosLogger.addToAllLogType(log);
 }
Esempio n. 11
0
  private ArrayList<Building> getBestProb(ArrayList<Building> region) {

    for (Building b : region) {

      if (hasFireProbability(b)) {

        addProbScore(region, b);

      } else {

        if (agent.model().time() - b.updatedtime() < Math.min(7, agent.model().time() / 2)
            && b.isTemperatureDefined()
            && b.getTemperature() == 0) {
          for (Building neigh : b.realNeighbors_Building()) {
            double t = 0;
            double c = 0;
            for (Building n2 : neigh.realNeighbors_Building()) {
              if (n2.getTemperature() > 0) c -= neigh.getRealNeighValue(n2);
              else c += neigh.getRealNeighValue(n2);
            }
            t =
                (b.getRealNeighValue(neigh) + 0.001)
                    * 100d
                    / (Math.max(1, distance(b, neigh) / 1000))
                    * 3;
            if (c > 0)
              neigh.setSpecialForFire(
                  neigh.getValuSpecialForFire() - (int) (Math.ceil(t * c)),
                  "negative center=" + b + "  t" + t + "  c" + c);
          }
        }

        if (agent.model().time() == b.updatedtime()) {
          if (b.getTemperature() == 0) {
            for (Building neigh : b.realNeighbors_Building()) {
              if (neigh.getGroundArea() > 1.7 * b.getGroundArea())
                neigh.setSpecialForFire(
                    neigh.getValuSpecialForFire() - 50,
                    "negative value update in big building=" + b + "   " + (-50));
            }
          }
        }
      }
    }

    return region;
  }
Esempio n. 12
0
  private void checkAlakiStock(Path path) throws SOSActionException {
    log().info("checking alaki stock");
    CycleInformations cycleinfo1 = me.informationStacker.getInformations(1);
    CycleInformations cycleinfo2 = me.informationStacker.getInformations(2);
    CycleInformations cycleinfo3 = me.informationStacker.getInformations(3);
    // Move Stock Move Stock Stock Stock
    log().trace("cycleinfo1:" + cycleinfo1);
    log().trace("cycleinfo2:" + cycleinfo2);
    log().trace("cycleinfo3:" + cycleinfo3);
    if (!(cycleinfo1.getAct() instanceof MoveAction)
        || cycleinfo1.getAct() instanceof StockMoveAction) return;
    if (
    /* !(cycleinfo2.getAct() instanceof MoveAction) || */ !(cycleinfo2.getAct()
        instanceof StockMoveAction)) return;
    if (!(cycleinfo3.getAct() instanceof MoveAction)
        || cycleinfo3.getAct() instanceof StockMoveAction) return;

    log()
        .debug(
            "cycleinfo1:"
                + cycleinfo1.getPositionPair()
                + "cycleinfo2:"
                + cycleinfo2.getPositionPair()
                + " cycleinfo3:"
                + cycleinfo3.getPositionPair());
    if (SOSGeometryTools.getDistance(
                cycleinfo1.getPositionPair().second(), cycleinfo2.getPositionPair().second())
            < MoveConstants.TRAFFIC_CHECKING_DISTANCE
        && SOSGeometryTools.getDistance(
                cycleinfo1.getPositionPair().second(), cycleinfo3.getPositionPair().second())
            < MoveConstants.TRAFFIC_CHECKING_DISTANCE) {
      Path randomPath = bfs.getDummyRandomWalkPath();

      me.send(
          new AKMove(
              me.getID(),
              me.time(),
              randomPath.getIds(),
              randomPath.getDestination().second().getIntX(),
              randomPath.getDestination().second().getIntY()));
      sendStockMessage(path);
      me.informationStacker.addInfo(me.model(), new StockMoveAction(randomPath));
      throw new SOSActionException("Move Stock Random Walk(" + randomPath + ")");
    }
  }
Esempio n. 13
0
  public void move(Path path, boolean checkStock) throws SOSActionException {
    if (!(me.me() instanceof Human)) {
      log().warn("can't use move in Center Agent " + me + "\n");
      return;
    }
    if (path == null) {
      log().error("move to null??....doing random walk");
      ((PlatoonAgent<?>) me).randomWalk(true);
    }

    log().debug("MOVE TO : " + path + "\n");
    if (checkStock) checkStock(path);
    Point2D xy = path.getDestination().second();

    me.informationStacker.addInfo(me.model(), new MoveAction(path));
    me.send(
        new AKMove(me.getID(), me.model().time(), path.getIds(), (int) xy.getX(), (int) xy.getY()));
    throw new SOSActionException("MoveXY(" + path + ", " + xy + ")");
  }
Esempio n. 14
0
 public boolean isReallyReacahble(Collection<Pair<? extends Area, Point2D>> targets) {
   if (!(me.me() instanceof Human)) {
     log()
         .warn(
             "can't use isReallyUnreachableXY in Center Agent "
                 + me
                 + " "
                 + Arrays.toString(new Error().getStackTrace()));
     return false;
   }
   PoliceReachablityMove pm = getMoveType(PoliceReachablityMove.class);
   return pm.isReallyReachableXY(targets);
 }
Esempio n. 15
0
 public boolean isReallyUnreachableXY(Collection<Pair<? extends Area, Point2D>> targets) {
   if (!(me.me() instanceof Human)) {
     log()
         .warn(
             "can't use isReallyUnreachableXY in Center Agent "
                 + me
                 + " "
                 + Arrays.toString(new Error().getStackTrace()));
     return false;
   }
   StandardMove sm = (StandardMove) moves.get(StandardMove.class.hashCode());
   return sm.isReallyUnreachableXY(targets);
 }
Esempio n. 16
0
 public SOSFireZoneManager(SOSWorldModel model, SOSAgent<?> me, AgentType agentType) {
   this.me = me;
   this.model = model;
   log =
       new SOSLoggerSystem(
           me.me(),
           "SOSFireSite/SOSFireSiteManager",
           SOSConstant.CREATE_BASE_LOGS,
           OutputType.File,
           true);
   fireSites = new ArrayList<Pair<ArrayList<SOSRealFireZone>, SOSEstimatedFireZone>>();
   me.sosLogger.addToAllLogType(log);
   merger = new SOSFireZoneMerger(this);
 }
Esempio n. 17
0
 public long getWeightToLowProcess(List<ShapeInArea> targets, Class<? extends MoveType> type) {
   long min = Long.MAX_VALUE;
   MoveType movetype = moves.get(type.hashCode());
   for (ShapeInArea shapeInArea : targets) {
     if (shapeInArea
         .getArea(me.model())
         .equals(me.me().getAreaPosition())) { // source and destination is in same area
       if (shapeInArea.contains(((Human) me.me()).getX(), ((Human) me.me()).getY())) {
         log().debug("in shape--Yoosef");
         return 0;
       }
     }
     min =
         Math.min(
             min,
             movetype.getWeightToLowProcess(
                 shapeInArea.getArea(me.model()),
                 shapeInArea.getCenterX(),
                 shapeInArea.getCenterY()));
   }
   if (min < 0) log().error(new Error("why it become negetive here???"));
   return min;
 }
Esempio n. 18
0
 // TODO add stopped time to 3 cycles
 private void checkTraffic() throws SOSActionException {
   log().info("Checking traffic");
   if (me.time() < 4) {
     log().debug("No Traffic! Beacuse time is less than 4");
     return;
   }
   CycleInformations cycleinfo1 = me.informationStacker.getInformations(1);
   CycleInformations cycleinfo2 = me.informationStacker.getInformations(2);
   CycleInformations cycleinfo3 = me.informationStacker.getInformations(3);
   if (cycleinfo1.getAct() instanceof MoveAction
       && cycleinfo2.getAct() instanceof MoveAction
       && cycleinfo3.getAct() instanceof MoveAction) {
     //		Path path1 = ((MoveAction) cycleinfo1.getAct()).getPath();
     Path path2 = ((MoveAction) cycleinfo2.getAct()).getPath();
     //		Path path3 = ((MoveAction) cycleinfo3.getAct()).getPath();
     log().info("Three(3) cycle move ....");
     log().debug("1 cycle ago position:" + cycleinfo1.getPositionPair());
     log().debug("2 cycle ago position:" + cycleinfo2.getPositionPair());
     log().debug("3 cycle ago position:" + cycleinfo3.getPositionPair());
     if (cycleinfo1.getPositionPair().first().equals(cycleinfo2.getPositionPair().first())
         && cycleinfo1.getPositionPair().first().equals(cycleinfo3.getPositionPair().first())) {
       if (SOSGeometryTools.getDistance(
                   cycleinfo1.getPositionPair().second(), cycleinfo2.getPositionPair().second())
               < MoveConstants.TRAFFIC_CHECKING_DISTANCE
           && SOSGeometryTools.getDistance(
                   cycleinfo1.getPositionPair().second(), cycleinfo3.getPositionPair().second())
               < MoveConstants.TRAFFIC_CHECKING_DISTANCE) {
         if (path2.getEdges() != null && !path2.getEdges()[0].haveTraffic()) {
           this.traffic.add(new Pair<GraphEdge, Integer>(path2.getEdges()[0], me.time()));
           path2.getEdges()[0].setHaveTraffic();
           log().info("Traffic added to " + path2.getEdges()[0]);
         }
       }
     }
   }
 }
Esempio n. 19
0
  private void sendStockMessage(Path path) {
    if (me instanceof PoliceForceAgent) return;

    if (!(me.me() instanceof Human)) return;

    if (me.time() < 50) return;

    Human meEntity = (Human) me.me();

    if (meEntity.isBuriednessDefined() && meEntity.getBuriedness() > 0) return;

    if (meEntity.getImReachableToEdges().isEmpty()) return;

    if (me.isTimeToActFinished()) return;

    if (me.lastException != null) return;

    try {
      //			if (me.getMyClusterData().isCoverer())
      //				return;

      if (me.me().getAreaPosition().isBlockadesDefined()
          && me.me().getAreaPosition().getBlockadesID().isEmpty()) {
        boolean haveBlock = false;
        for (Area neighbour : me.me().getAreaPosition().getNeighbours()) {
          if (neighbour.isBlockadesDefined() && !neighbour.getBlockadesID().isEmpty())
            haveBlock = true;
        }
        if (!haveBlock) return;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    log().debug("Sending Stock Message");
    me.messageBlock = new MessageBlock(MessageXmlConstant.HEADER_AGENT_STOCK);
    me.messageBlock.addData(
        MessageXmlConstant.DATA_AREA_INDEX, me.me().getAreaPosition().getAreaIndex());
    me.messages.add(me.messageBlock);
    me.lowCommunicationMessages.add(me.messageBlock);
  }
Esempio n. 20
0
  public Move(SOSAgent<? extends StandardEntity> me, WorldGraph graph) {
    this.me = me;
    this.moves = new HashMap<Integer, MoveType>();
    this.bfs = new BFS(me);
    this.traffic = new LinkedList<Pair<GraphEdge, Integer>>();
    this.trafficRemainTime = (me instanceof PoliceForceAgent) ? 9 : 6;
    this.nodesUnion = new UnionFind(graph.getNumberOfNodes());
    for (GraphEdge ge : me.model().graphEdges())
      if (ge instanceof VirtualGraphEdge) ge.setState(GraphEdgeState.Open);
    // ------------------------------------- Adding move types here
    moves.put(PoliceReachablityMove.class.hashCode(), new PoliceReachablityMove(me, graph));

    if (me instanceof PoliceForceAgent) {
      moves.put(PoliceMove.class.hashCode(), new PoliceMove(me, graph));
      moves.put(DistanceMove.class.hashCode(), new DistanceMove(me, graph));
    } else moves.put(StandardMove.class.hashCode(), new StandardMove(me, graph));
    //		if (me instanceof FireBrigadeAgent)
    //			moves.put(FireMove.class.hashCode(), new FireMove(me, graph));
    moves.put(SearchMove.class.hashCode(), new SearchMove(me, graph));
    // ------------------------------------------------------------
    cycle();
  }
Esempio n. 21
0
  public SOSBitArray toBitArray(ChannelSystemType channelType) {
    if (messageBitArray != null) {
      if (lastChannelType == channelType) return messageBitArray;

      SOSAgent.currentAgent()
          .sosLogger
          .messageContent
          .debug(
              "lastchanneltype is different!!!!!"
                  + lastChannelType
                  + " new chaneltype"
                  + channelType);
    }

    lastChannelType = channelType;
    MessageGroup messageGroup = ReadXml.getValidChannelMessages(channelType);

    messageBitArray = new SOSBitArray(getBitSize(channelType));
    int tempBitPosition = 0;

    messageBitArray.set(
        tempBitPosition,
        SOSBitArray.makeBit(messageGroup.headerToIndex(header), messageGroup.bitSize()));
    tempBitPosition += messageGroup.bitSize();

    DataArrayList xmlData = ReadXml.blocks.get(header).data();

    for (int i = 0; i < xmlData.size(); i++) {
      if (xmlData.getValue(i) < 0) {
        new Error("value is negetive!!!!!!!!!!!![TO BIT ARRAY]").printStackTrace();
        messageBitArray.set(tempBitPosition, SOSBitArray.makeBit(0, xmlData.getValue(i)));
      } else
        messageBitArray.set(
            tempBitPosition, SOSBitArray.makeBit(getData(xmlData.getKey(i)), xmlData.getValue(i)));
      tempBitPosition += xmlData.getValue(i);
    }
    return messageBitArray;
  }
Esempio n. 22
0
  public Path getPathToShapes(Collection<ShapeInArea> des, Class<? extends MoveType> type) {
    try {
      MoveType mt = moves.get(type.hashCode());
      if (mt != null) {
        Path path = mt.getPathToShape(des);
        return path;

      } else {
        log().error(new Error("in move can not found type=" + type.getSimpleName()));
      }

    } catch (Exception er) {
      log().error(er);
      log().warn("using bfs for finding path");
      ArrayList<Area> goals = new ArrayList<Area>();

      for (ShapeInArea shapeInArea : des) {
        goals.add(shapeInArea.getArea(me.model()));
      }
      return getPathTo(goals, type);
    }
    return null;
  }
Esempio n. 23
0
 public ArrayList<ClusterData> getClusterProbabilisticFieryBuilding() {
   if (agent.model().time() == time) return resCluster;
   getProbabilisticFieryBuilding();
   return resCluster;
 }
Esempio n. 24
0
  private void check2CycleStock() throws SOSActionException {
    CycleInformations cycleinfo1 = me.informationStacker.getInformations(1);
    CycleInformations cycleinfo2 = me.informationStacker.getInformations(2);
    if (!(cycleinfo1.getAct() instanceof MoveAction)
        || cycleinfo1.getAct() instanceof StockMoveAction) return;
    if (!(cycleinfo2.getAct() instanceof MoveAction)
        || cycleinfo1.getAct() instanceof StockMoveAction) return;

    Path path1 = ((MoveAction) cycleinfo1.getAct()).getPath();
    //			Path path2 = ((MoveAction) cycleinfo2.getAct()).getPath();
    log().info("Two(2) cycle move ....");
    log().debug("current position:" + me.me().getAreaPosition());
    log().debug("1 cycle ago position:" + cycleinfo1.getPositionPair());
    log().debug("2 cycle ago position:" + cycleinfo2.getPositionPair());
    if (!cycleinfo1.getPositionPair().first().equals(cycleinfo2.getPositionPair().first())) return;
    if (!cycleinfo1.getPositionPair().first().equals(me.me().getAreaPosition())) return;
    if (SOSGeometryTools.getDistance(
            cycleinfo1.getPositionPair().second(), cycleinfo2.getPositionPair().second())
        > MoveConstants.TRAFFIC_CHECKING_DISTANCE) return;

    //////////////// Stock Occured
    log().debug("2 cycle stock occured!!!!!!!");

    ArrayList<EntityID> entityPath = new ArrayList<EntityID>();
    Area area = me.me().getAreaPosition();
    log().debug("Current Position:" + area);
    entityPath.add(area.getID());
    Edge ed;
    Area ne;
    if (path1.getIds().size() > 0 && !path1.getIds().get(0).equals(area.getID())) {
      ne = (Area) me.model().getEntity(path1.getIds().get(0));
      ed = area.getEdgeTo(ne);
    } else if (path1.getIds().size() > 1 && path1.getIds().get(0).equals(area.getID())) {
      ne = (Area) me.model().getEntity(path1.getIds().get(1));
      ed = area.getEdgeTo(ne);
    } else {
      ne = area.getNeighbours().get(0);
      ed = area.getEdgeTo(ne);
    }
    log().debug("ne:" + ne + " ed:" + ed + " last move path:" + path1);
    if (ed == null) {
      log().error("[Move]edge is null!!!!!some problem!!!!");
      ne = area.getNeighbours().get(0);
      ed = area.getEdgeTo(ne);
      log().debug("changed!!!! ne:" + ne + " ed:" + ed + " last move path:" + path1);
    }
    Point2D destXYAPointNearEdge;
    if (ed != null) {
      //			if (area instanceof Road) {
      Pair<Point2D, Point2D> points = getAPointInReachblePartEdges(area, ed);
      destXYAPointNearEdge = points.second();
      //			} else {
      //				Line2D wallLine = ed.getLine();// new Line2D(edge.getStartX(), edge.getStartY(),
      // edge.getEndX() - edge.getStartX(), edge.getEndY() - edge.getStartY());
      //				// ppp.add(new ShapeDebugFrame.Line2DShapeInfo(wallLine, "edge", Color.white.darker(),
      // false, false));
      //				Vector2D offset;
      //				if (lastStockTime < me.time() - 4) {
      //					if (AliGeometryTools.havecorrectDirection(area)) {
      //						offset = wallLine.getDirection().getNormal().normalised().scale(1500);
      //					} else {
      //						offset = wallLine.getDirection().getNormal().normalised().scale(-1500);
      //					}
      //				} else {
      //					if (!AliGeometryTools.havecorrectDirection(area)) {
      //						offset = wallLine.getDirection().getNormal().normalised().scale(1500);
      //					} else {
      //						offset = wallLine.getDirection().getNormal().normalised().scale(-1500);
      //					}
      //				}
      //				destXYAPointNearEdge = ed.getMidPoint().plus(offset);
      //			}
    } else {
      log().error("[Move]edge is null!!!!!some problem!!!!");
      destXYAPointNearEdge = area.getPositionPair().second();
    }
    log().debug("dest area for stock:" + area + " dst point:" + destXYAPointNearEdge);
    me.send(
        new AKMove(
            me.getID(),
            me.time(),
            entityPath,
            (int) destXYAPointNearEdge.getX(),
            (int) destXYAPointNearEdge.getY()));
    Path path =
        new Path(
            null,
            null,
            entityPath,
            me.me().getPositionPair(),
            new Pair<Area, Point2D>(area, destXYAPointNearEdge),
            false);
    me.informationStacker.addInfo(me.model(), new StockMoveAction(path));
    //		log().warn("Traffic Handeling should be change due to server doesn't support AKMotion");
    lastStockTime = me.time();
    throw new SOSActionException("Move Stock(" + area + " " + destXYAPointNearEdge + ")");
  }
Esempio n. 25
0
 public boolean isReallyUnreachable(ShapeInArea sh) {
   if (sh.contains(me.me().getPositionPoint().toGeomPoint())) return false;
   long weightTo = moves.get(StandardMove.class.hashCode()).getWeightTo(sh);
   if (weightTo < 0) log().error(new Error("why it become negetive here???"));
   return weightTo > UNREACHABLE_COST;
 }
Esempio n. 26
0
  private void checkEarlyStock(Path path) throws SOSActionException {
    Area source = me.me().getAreaPosition();
    if (me.informationStacker.getInformations(1).getAct() instanceof MoveAction
        && me.informationStacker.getInformations(1).getPositionPair().first() instanceof Building) {
      log()
          .debug(
              "last act is move and current position is in building ==> don't check early stock");
      return;
    }
    if (me.informationStacker.getInformations(1).getAct() instanceof StockMoveAction) {
      log().debug("last act is stock move ==> don't check early stock");
      return;
    }

    if (source instanceof Building) {
      log().debug("early stock detected!!! agent is in " + source);
      ArrayList<EntityID> entityPath = new ArrayList<EntityID>();
      entityPath.add(source.getID());
      Area second = null;
      Area third = null;

      if (path.getIds().size() > 0 && !path.getIds().get(0).equals(source.getID())) {
        second = (Area) me.model().getEntity(path.getIds().get(0));
        if (path.getIds().size() > 1) third = (Area) me.model().getEntity(path.getIds().get(1));
      } else if (path.getIds().size() > 1 && path.getIds().get(0).equals(source.getID())) {
        second = (Area) me.model().getEntity(path.getIds().get(1));
        if (path.getIds().size() > 2) third = (Area) me.model().getEntity(path.getIds().get(2));
      } else {
        log().warn("move path size is 0 can't checkEarlyStock!!!");
        return;
      }
      if (second == null) {
        log().warn("second is null can't checkEarlyStock!!!");
        return;
      } else {
        ArrayList<Edge> edges = second.getEdgesTo(source);
        int minDistance = Integer.MAX_VALUE;
        for (Edge edge : edges) {
          minDistance =
              (int)
                  Math.min(
                      minDistance, SOSGeometryTools.distance(edge, me.me().getPositionPoint()));
        }
        //				Edge fedge = second.getEdgeTo(source);
        //				if (SOSGeometryTools.distance(fedge, me.me().getPositionPoint()) <
        // MoveConstants.ENTRACE_DISTANCE_MM+1000)
        //					return;
        if (minDistance < MoveConstants.ENTRACE_DISTANCE_MM + 1000) {
          log().debug("I'm too neat to edge in building... no need to check early stock");
          return;
        }
        entityPath.add(second.getID());
      }
      if (third == null) {
        log().debug("Move path is too small!!! no need to early stock handle");
        return;
      } else {
        Edge ed = second.getEdgeTo(third);
        Point2D destXYAPointNearEdge;
        if (ed != null) {
          Line2D wallLine =
              ed
                  .getLine(); // new Line2D(edge.getStartX(), edge.getStartY(), edge.getEndX() -
                              // edge.getStartX(), edge.getEndY() - edge.getStartY());
          // ppp.add(new ShapeDebugFrame.Line2DShapeInfo(wallLine, "edge", Color.white.darker(),
          // false, false));
          Vector2D offset;
          if (AliGeometryTools.havecorrectDirection(second)) {
            offset = wallLine.getDirection().getNormal().normalised().scale(15);
          } else {
            offset = wallLine.getDirection().getNormal().normalised().scale(-15);
          }
          destXYAPointNearEdge = ed.getMidPoint().plus(offset);
        } else {
          log().error("[Move]edge is null!!!!!some problem!!!!");
          destXYAPointNearEdge = second.getPositionPair().second();
        }
        log()
            .debug(
                "source:"
                    + source
                    + " dest area for stock:"
                    + second
                    + " dst point:"
                    + destXYAPointNearEdge);
        me.send(
            new AKMove(
                me.getID(),
                me.time(),
                entityPath,
                (int) destXYAPointNearEdge.getX(),
                (int) destXYAPointNearEdge.getY()));
        path =
            new Path(
                null,
                null,
                entityPath,
                me.me().getPositionPair(),
                new Pair<Area, Point2D>(second, destXYAPointNearEdge),
                false);
        me.informationStacker.addInfo(me.model(), new StockMoveAction(path));
        throw new SOSActionException(
            "Move Stock(" + source + "," + second + " " + destXYAPointNearEdge + ")");
      }
    }
  }