static Map<Imt, Map<Gmm, List<Double>>> initValueMaps(Set<Imt> imts, Set<Gmm> gmms, int size) {

      Map<Imt, Map<Gmm, List<Double>>> imtMap = Maps.newEnumMap(Imt.class);
      for (Imt imt : imts) {
        Map<Gmm, List<Double>> gmmMap = Maps.newEnumMap(Gmm.class);
        for (Gmm gmm : gmms) {
          gmmMap.put(gmm, Doubles.asList(new double[size]));
        }
        imtMap.put(imt, gmmMap);
      }
      return imtMap;
    }
 /**
  * Parses the search query.
  *
  * @param query the query.
  * @return the result map with query tokens. Never returns null.
  * @throws InvalidQueryException if the query contains invalid params.
  */
 Map<TokenQueryType, Set<String>> parseQuery(String query) throws InvalidQueryException {
   Preconditions.checkArgument(query != null);
   query = query.trim();
   // If query is empty - return.
   if (query.isEmpty()) {
     return Collections.emptyMap();
   }
   String[] tokens = query.split("\\s+");
   Map<TokenQueryType, Set<String>> tokensMap = Maps.newEnumMap(TokenQueryType.class);
   for (String token : tokens) {
     String[] pair = token.split(":");
     if (pair.length != 2 || !TokenQueryType.hasToken(pair[0])) {
       String msg = "Invalid query param: " + token;
       throw new InvalidQueryException(msg);
     }
     String tokenValue = pair[1];
     TokenQueryType tokenType = TokenQueryType.fromToken(pair[0]);
     // Verify the orderby param.
     if (tokenType.equals(TokenQueryType.ORDERBY)) {
       try {
         OrderByValueType.fromToken(tokenValue);
       } catch (IllegalArgumentException e) {
         String msg = "Invalid orderby query value: " + tokenValue;
         throw new InvalidQueryException(msg);
       }
     }
     Set<String> valuesPerToken = tokensMap.get(tokenType);
     if (valuesPerToken == null) {
       valuesPerToken = Sets.newLinkedHashSet();
       tokensMap.put(tokenType, valuesPerToken);
     }
     valuesPerToken.add(tokenValue);
   }
   return tokensMap;
 }
 public RequestDispatcher(Iterable<GrizzletHandler> grizzlets) {
   Map<String, Map<HttpMethod, GrizzletHandler>> modifiableHandlersMap = Maps.newHashMap();
   for (GrizzletHandler handler : grizzlets) {
     Map<HttpMethod, GrizzletHandler> handlerByMethod =
         modifiableHandlersMap.get(handler.getPath());
     if (handlerByMethod == null) {
       handlerByMethod = Maps.newEnumMap(HttpMethod.class);
       modifiableHandlersMap.put(handler.getPath(), handlerByMethod);
     }
     for (HttpMethod method : handler.getMethods()) {
       GrizzletHandler alreadyHandler = handlerByMethod.put(method, handler);
       if (alreadyHandler != null) {
         throw new IllegalArgumentException(
             "More than one handler detected for path='"
                 + handler.getPath()
                 + "', method='"
                 + method.name()
                 + '\'');
       }
     }
   }
   for (Map.Entry<String, Map<HttpMethod, GrizzletHandler>> entry :
       modifiableHandlersMap.entrySet()) {
     modifiableHandlersMap.put(entry.getKey(), Collections.unmodifiableMap(entry.getValue()));
   }
   handlers = ImmutableMap.copyOf(modifiableHandlersMap);
 }
Example #4
0
 private List<BlockFamily> processMultiBlockFamily(
     AssetUri blockDefUri, BlockDefinition blockDef) {
   List<BlockFamily> result = Lists.newArrayList();
   for (String shapeString : blockDef.shapes) {
     BlockShape shape = (BlockShape) Assets.get(AssetType.SHAPE, shapeString);
     if (shape != null) {
       BlockUri familyUri;
       if (shape.equals(cubeShape)) {
         familyUri = new BlockUri(blockDefUri.getModuleName(), blockDefUri.getAssetName());
       } else {
         familyUri =
             new BlockUri(
                 blockDefUri.getModuleName(),
                 blockDefUri.getAssetName(),
                 shape.getURI().getModuleName(),
                 shape.getURI().getAssetName());
       }
       blockDef.shape = shapeString;
       if (shape.isCollisionYawSymmetric()) {
         Block block = constructSingleBlock(blockDefUri, blockDef);
         result.add(new SymmetricFamily(familyUri, block, blockDef.categories));
       } else {
         Map<Side, Block> blockMap = Maps.newEnumMap(Side.class);
         constructHorizontalBlocks(blockDefUri, blockDef, blockMap);
         result.add(new HorizontalBlockFamily(familyUri, blockMap, blockDef.categories));
       }
     }
   }
   return result;
 }
Example #5
0
 Map<IdProperty, String> getProps() {
   Map<IdProperty, String> props = Maps.newEnumMap(IdProperty.class);
   props.put(IdProperty.email, "alice@Net");
   props.put(IdProperty.nick, "aliceW");
   props.put(IdProperty.fullName, "Alice Wonderland");
   props.put(IdProperty.firstName, "alice");
   props.put(IdProperty.lastName, "wonderland");
   props.put(IdProperty.derivedFullName, "alice wonderland");
   return props;
 }
  public LibraryVariantData(
      @NonNull AndroidConfig androidConfig,
      @NonNull TaskManager taskManager,
      @NonNull GradleVariantConfiguration config,
      @NonNull ErrorReporter errorReporter) {
    super(androidConfig, taskManager, config, errorReporter);
    testVariants = Maps.newEnumMap(VariantType.class);

    // create default output
    createOutput(OutputFile.OutputType.MAIN, Collections.<FilterData>emptyList());
  }
Example #7
0
 private BlockAppearance createAppearance(
     BlockShape shape, Map<BlockPart, AssetUri> tileUris, Rotation rot) {
   Map<BlockPart, BlockMeshPart> meshParts = Maps.newEnumMap(BlockPart.class);
   Map<BlockPart, Vector2f> textureAtlasPositions = Maps.newEnumMap(BlockPart.class);
   for (BlockPart part : BlockPart.values()) {
     // TODO: Need to be more sensible with the texture atlas. Because things like block particles
     // read from a part that may not exist, we're being fairly lenient
     Vector2f atlasPos = atlas.getTexCoords(tileUris.get(part), shape.getMeshPart(part) != null);
     BlockPart targetPart = part.rotate(rot);
     textureAtlasPositions.put(targetPart, atlasPos);
     if (shape.getMeshPart(part) != null) {
       meshParts.put(
           targetPart,
           shape
               .getMeshPart(part)
               .rotate(rot.getQuat4f())
               .mapTexCoords(atlasPos, atlas.getRelativeTileSize()));
     }
   }
   return new BlockAppearance(meshParts, textureAtlasPositions);
 }
Example #8
0
  public BlockFamily loadWithShape(BlockUri uri) {
    try (ModuleContext.ContextSpan ignored = ModuleContext.setContext(uri.getModuleName())) {
      BlockShape shape = cubeShape;
      if (uri.hasShape()) {
        AssetUri shapeUri = uri.getShapeUri();
        if (!shapeUri.isValid()) {
          return null;
        }
        shape = (BlockShape) Assets.get(shapeUri);
        if (shape == null) {
          return null;
        }
      }
      AssetUri blockDefUri =
          new AssetUri(AssetType.BLOCK_DEFINITION, uri.getModuleName(), uri.getFamilyName());
      BlockDefinition def;
      if (assetManager.getAssetURLs(blockDefUri).isEmpty()) {
        // An auto-block
        def = new BlockDefinition();
      } else {
        def =
            createBlockDefinition(
                inheritData(blockDefUri, readJson(blockDefUri).getAsJsonObject()));
      }

      def.shape = (shape.getURI().toSimpleString());
      if (shape.isCollisionYawSymmetric()) {
        Block block = constructSingleBlock(blockDefUri, def);
        if (block.getDisplayName().isEmpty()) {
          block.setDisplayName(shape.getDisplayName());
        } else if (!shape.getDisplayName().isEmpty()) {
          block.setDisplayName(block.getDisplayName() + " " + shape.getDisplayName());
        }
        return new SymmetricFamily(uri, block, def.categories);
      } else {
        Map<Side, Block> blockMap = Maps.newEnumMap(Side.class);
        constructHorizontalBlocks(blockDefUri, def, blockMap);
        for (Block block : blockMap.values()) {
          if (block.getDisplayName().isEmpty()) {
            block.setDisplayName(shape.getDisplayName());
          } else if (!shape.getDisplayName().isEmpty()) {
            block.setDisplayName(block.getDisplayName() + " " + shape.getDisplayName());
          }
        }
        return new HorizontalBlockFamily(uri, blockMap, def.categories);
      }
    } catch (Exception e) {
      logger.error("Error loading block shape {}", uri, e);
    }
    return null;
  }
/**
 * The type Open nLPPOS annotator.
 *
 * @author David B. Bracewell
 */
public class OpenNLPPOSAnnotator extends SentenceLevelAnnotator {
  private static final long serialVersionUID = 1L;
  private volatile Map<Language, POSModel> posModels = Maps.newEnumMap(Language.class);

  @Override
  public void annotate(Annotation sentence) {
    POSTaggerME posTagger = new POSTaggerME(loadPOSTagger(sentence.getLanguage()));
    String[] tokens = sentence.tokens().stream().map(Object::toString).toArray(String[]::new);
    String[] tags = posTagger.tag(tokens);
    for (int i = 0; i < tokens.length; i++) {
      Annotation token = sentence.tokenAt(i);
      token.put(Types.PART_OF_SPEECH, POS.fromString(tags[i]));
    }
  }

  private POSModel loadPOSTagger(Language language) {
    if (!posModels.containsKey(language)) {
      synchronized (OpenNLPPOSAnnotator.class) {
        if (!posModels.containsKey(language)) {
          try {
            posModels.put(
                language,
                new POSModel(
                    Config.get("opennlp", language, "part_of_speech", "model")
                        .asResource()
                        .inputStream()));
          } catch (IOException e) {
            throw Throwables.propagate(e);
          }
        }
      }
    }
    return posModels.get(language);
  }

  @Override
  public Set<AnnotatableType> satisfies() {
    return Collections.singleton(Types.PART_OF_SPEECH);
  }

  @Override
  public Set<AnnotatableType> furtherRequires() {
    return Collections.singleton(Types.TOKEN);
  }

  @Override
  public String getVersion() {
    return "1.6.0";
  }
} // END OF OpenNLPPOSAnnotator
Example #10
0
 private Map<BlockPart, Vector4f> prepareColorOffsets(BlockDefinition blockDef) {
   Map<BlockPart, Vector4f> result = Maps.newEnumMap(BlockPart.class);
   for (BlockPart part : BlockPart.values()) {
     result.put(part, blockDef.colorOffset);
   }
   if (blockDef.colorOffsets != null) {
     for (BlockPart part : BlockPart.values()) {
       if (blockDef.colorOffsets.map.get(part) != null) {
         result.put(part, blockDef.colorOffsets.map.get(part));
       }
     }
   }
   return result;
 }
Example #11
0
 private Map<BlockPart, Block.ColorSource> prepareColorSources(BlockDefinition blockDef) {
   Map<BlockPart, Block.ColorSource> result = Maps.newEnumMap(BlockPart.class);
   for (BlockPart part : BlockPart.values()) {
     result.put(part, blockDef.colorSource);
   }
   if (blockDef.colorSources != null) {
     for (BlockPart part : BlockPart.values()) {
       if (blockDef.colorSources.map.get(part) != null) {
         result.put(part, blockDef.colorSources.map.get(part));
       }
     }
   }
   return result;
 }
Example #12
0
  private static class Registration<P extends Event, S extends org.spongepowered.api.event.Event>
      implements HandlerList.Adapter {

    private final Class<P> pore;
    private final Class<S> sponge;
    private SimpleConstructor<P, S> constructor;

    private final EnumMap<EventPriority, PoreEventHandler<S>> listeners =
        Maps.newEnumMap(EventPriority.class);

    public Registration(Class<P> pore, Class<S> sponge) {
      this.pore = pore;
      this.sponge = sponge;
    }

    @Override
    public void register(EventPriority priority) {
      PoreEventHandler<S> listener = listeners.get(priority);
      if (listener == null) {
        if (constructor == null) {
          this.constructor = PoreConstructors.create(pore, sponge);
        }

        listener = new PoreEventHandler<>(priority, constructor);
        listeners.put(priority, listener);
      }

      Pore.getGame()
          .getEventManager()
          .registerListener(
              Pore.getPlugin(), sponge, EventPriorityConverter.of(priority), listener);
    }

    @Override
    public void unregister() {
      EventManager manager = Pore.getGame().getEventManager();

      for (Object listener : listeners.values()) {
        manager.unregisterListeners(listener);
      }
    }

    @Override
    public void unregister(EventPriority priority) {
      Object listener = listeners.get(priority);
      if (listener != null) {
        Pore.getGame().getEventManager().unregisterListeners(listener);
      }
    }
  }
public class EquipmentEditor extends Editor {
  private final NPC npc;
  private final Player player;

  public EquipmentEditor(Player player, NPC npc) {
    this.player = player;
    this.npc = npc;
  }

  @Override
  public void begin() {
    Messaging.sendTr(player, Messages.EQUIPMENT_EDITOR_BEGIN);
  }

  @Override
  public void end() {
    Messaging.sendTr(player, Messages.EQUIPMENT_EDITOR_END);
  }

  @EventHandler
  public void onPlayerInteract(PlayerInteractEvent event) {
    if (event.getAction() == Action.RIGHT_CLICK_AIR && Editor.hasEditor(event.getPlayer()))
      event.setUseItemInHand(Result.DENY);
  }

  @EventHandler
  public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
    if (!npc.isSpawned()
        || !event.getPlayer().equals(player)
        || !npc.equals(CitizensAPI.getNPCRegistry().getNPC(event.getRightClicked()))) return;

    Equipper equipper = EQUIPPERS.get(npc.getEntity().getType());
    if (equipper == null) equipper = new GenericEquipper();
    equipper.equip(event.getPlayer(), npc);
    event.setCancelled(true);
  }

  private static final Map<EntityType, Equipper> EQUIPPERS = Maps.newEnumMap(EntityType.class);

  static {
    EQUIPPERS.put(EntityType.PIG, new PigEquipper());
    EQUIPPERS.put(EntityType.SHEEP, new SheepEquipper());
    EQUIPPERS.put(EntityType.ENDERMAN, new EndermanEquipper());
    EQUIPPERS.put(EntityType.HORSE, new HorseEquipper());
  }
}
Example #14
0
    @Override
    public List<BakedQuad> getFaceQuads(EnumFacing side) {
      if (faces == null) {
        // Create map of each face's quads.
        EnumMap<EnumFacing, ImmutableList<BakedQuad>> faces = Maps.newEnumMap(EnumFacing.class);

        for (EnumFacing face : EnumFacing.values()) {
          ImmutableList.Builder<BakedQuad> faceQuads = ImmutableList.builder();
          if (base != null) faceQuads.addAll(base.getFaceQuads(face));
          for (IFlexibleBakedModel bakedPart : parts.values())
            faceQuads.addAll(bakedPart.getFaceQuads(face));
          faces.put(face, faceQuads.build());
        }
        this.faces = Maps.immutableEnumMap(faces);
      }
      return faces.get(side);
    }
Example #15
0
  public DefOverviewModel() throws QuickFixException {

    AuraContext context = Aura.getContextService().getCurrentContext();
    BaseComponent<?, ?> component = context.getCurrentComponent();

    String desc = (String) component.getAttributes().getValue("descriptor");

    DefType defType =
        DefType.valueOf(((String) component.getAttributes().getValue("defType")).toUpperCase());
    DefinitionService definitionService = Aura.getDefinitionService();
    DefDescriptor<?> descriptor =
        definitionService.getDefDescriptor(desc, defType.getPrimaryInterface());

    Definition def = descriptor.getDef();
    ReferenceTreeModel.assertAccess(def);

    Map<DefType, List<DefModel>> depsMap = Maps.newEnumMap(DefType.class);

    Set<DefDescriptor<?>> deps = Sets.newHashSet();

    def.appendDependencies(deps);

    for (DefDescriptor<?> dep : deps) {
      DefType type = dep.getDefType();

      List<DefModel> depsList = depsMap.get(type);
      if (depsList == null) {
        depsList = Lists.newArrayList();
        depsMap.put(type, depsList);
      }
      depsList.add(new DefModel(dep));
    }

    for (Entry<DefType, List<DefModel>> entry : depsMap.entrySet()) {
      List<DefModel> list = entry.getValue();
      Collections.sort(list);

      Map<String, Object> group = Maps.newHashMap();
      group.put("type", AuraTextUtil.initCap(entry.getKey().toString().toLowerCase()));
      group.put("list", list);
      dependencies.add(group);
    }
  }
Example #16
0
  private Map<BlockPart, AssetUri> prepareTiles(BlockDefinition blockDef, AssetUri uri) {
    AssetUri tileUri = getDefaultTile(blockDef, uri);

    Map<BlockPart, AssetUri> tileUris = Maps.newEnumMap(BlockPart.class);
    for (BlockPart part : BlockPart.values()) {
      tileUris.put(part, tileUri);
    }

    if (blockDef.tiles != null) {
      for (BlockPart part : BlockPart.values()) {
        String partTile = blockDef.tiles.map.get(part);
        if (partTile != null) {
          tileUri = assetManager.resolve(AssetType.BLOCK_TILE, blockDef.tiles.map.get(part));
          tileUris.put(part, tileUri);
        }
      }
    }
    return tileUris;
  }
  @Override
  public void fireEvent(final ClockTick event) {
    if (Bootstrap.isFinished() && Hosts.isCoordinator()) {

      final List<ResourceAvailabilityEvent> resourceAvailabilityEvents = Lists.newArrayList();
      final Map<ResourceAvailabilityEvent.ResourceType, AvailabilityAccumulator> availabilities =
          Maps.newEnumMap(ResourceAvailabilityEvent.ResourceType.class);
      final Iterable<VmType> vmTypes = Lists.newArrayList(VmTypes.list());
      for (final Cluster cluster : Clusters.getInstance().listValues()) {
        availabilities.put(Core, new AvailabilityAccumulator(VmType.SizeProperties.Cpu));
        availabilities.put(Disk, new AvailabilityAccumulator(VmType.SizeProperties.Disk));
        availabilities.put(Memory, new AvailabilityAccumulator(VmType.SizeProperties.Memory));

        for (final VmType vmType : vmTypes) {
          final ResourceState.VmTypeAvailability va =
              cluster.getNodeState().getAvailability(vmType.getName());

          resourceAvailabilityEvents.add(
              new ResourceAvailabilityEvent(
                  Instance,
                  new ResourceAvailabilityEvent.Availability(
                      va.getMax(),
                      va.getAvailable(),
                      Lists.<ResourceAvailabilityEvent.Tag>newArrayList(
                          new ResourceAvailabilityEvent.Dimension(
                              "availabilityZone", cluster.getPartition()),
                          new ResourceAvailabilityEvent.Dimension("cluster", cluster.getName()),
                          new ResourceAvailabilityEvent.Type("vm-type", vmType.getName())))));

          for (final AvailabilityAccumulator availability : availabilities.values()) {
            availability.total =
                Math.max(
                    availability.total, va.getMax() * availability.valueExtractor.apply(vmType));
            availability.available =
                Math.max(
                    availability.available,
                    va.getAvailable() * availability.valueExtractor.apply(vmType));
          }
        }

        for (final AvailabilityAccumulator availability : availabilities.values()) {
          availability.rollUp(
              Lists.<ResourceAvailabilityEvent.Tag>newArrayList(
                  new ResourceAvailabilityEvent.Dimension(
                      "availabilityZone", cluster.getPartition()),
                  new ResourceAvailabilityEvent.Dimension("cluster", cluster.getName())));
        }
      }

      for (final Map.Entry<ResourceAvailabilityEvent.ResourceType, AvailabilityAccumulator> entry :
          availabilities.entrySet()) {
        resourceAvailabilityEvents.add(
            new ResourceAvailabilityEvent(entry.getKey(), entry.getValue().availabilities));
      }

      for (final ResourceAvailabilityEvent resourceAvailabilityEvent : resourceAvailabilityEvents)
        try {
          ListenerRegistry.getInstance().fireEvent(resourceAvailabilityEvent);
        } catch (Exception ex) {
          logger.error(ex, ex);
        }
    }
  }
  protected void init() {
    final ArrayList<ObjectTemplateWithChanged> objectTemplates =
        Lists.newArrayList(
            new ObjectTemplateWithChanged(
                ObjectType.AS_BLOCK,
                7,
                new AttributeTemplate(AS_BLOCK, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, OPTIONAL, MULTIPLE),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.AS_SET,
                9,
                new AttributeTemplate(AS_SET, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(MEMBERS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(MBRS_BY_REF, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.AUT_NUM,
                8,
                new AttributeTemplate(AUT_NUM, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(AS_NAME, MANDATORY, SINGLE),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(MEMBER_OF, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(IMPORT_VIA, OPTIONAL, MULTIPLE, USER_ORDER),
                new AttributeTemplate(IMPORT, OPTIONAL, MULTIPLE, USER_ORDER),
                new AttributeTemplate(MP_IMPORT, OPTIONAL, MULTIPLE, USER_ORDER),
                new AttributeTemplate(EXPORT_VIA, OPTIONAL, MULTIPLE, USER_ORDER),
                new AttributeTemplate(EXPORT, OPTIONAL, MULTIPLE, USER_ORDER),
                new AttributeTemplate(MP_EXPORT, OPTIONAL, MULTIPLE, USER_ORDER),
                new AttributeTemplate(DEFAULT, OPTIONAL, MULTIPLE, USER_ORDER),
                new AttributeTemplate(MP_DEFAULT, OPTIONAL, MULTIPLE, USER_ORDER),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, SINGLE, INVERSE_KEY),
                new AttributeTemplate(SPONSORING_ORG, OPTIONAL, SINGLE),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(STATUS, GENERATED, SINGLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_ROUTES, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.DOMAIN,
                30,
                new AttributeTemplate(DOMAIN, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ZONE_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NSERVER, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(DS_RDATA, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.FILTER_SET,
                21,
                new AttributeTemplate(FILTER_SET, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(FILTER, OPTIONAL, SINGLE),
                new AttributeTemplate(MP_FILTER, OPTIONAL, SINGLE),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.INET_RTR,
                15,
                new AttributeTemplate(INET_RTR, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(ALIAS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(LOCAL_AS, MANDATORY, SINGLE, INVERSE_KEY),
                new AttributeTemplate(IFADDR, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(INTERFACE, OPTIONAL, MULTIPLE),
                new AttributeTemplate(PEER, OPTIONAL, MULTIPLE),
                new AttributeTemplate(MP_PEER, OPTIONAL, MULTIPLE),
                new AttributeTemplate(MEMBER_OF, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.INET6NUM,
                6,
                new AttributeTemplate(INET6NUM, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(NETNAME, MANDATORY, SINGLE, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(COUNTRY, MANDATORY, MULTIPLE),
                new AttributeTemplate(GEOLOC, OPTIONAL, SINGLE),
                new AttributeTemplate(LANGUAGE, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, SINGLE, INVERSE_KEY),
                new AttributeTemplate(SPONSORING_ORG, OPTIONAL, SINGLE),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(STATUS, MANDATORY, SINGLE),
                new AttributeTemplate(ASSIGNMENT_SIZE, OPTIONAL, SINGLE),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_ROUTES, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_DOMAINS, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_IRT, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.INETNUM,
                5,
                new AttributeTemplate(INETNUM, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(NETNAME, MANDATORY, SINGLE, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(COUNTRY, MANDATORY, MULTIPLE),
                new AttributeTemplate(GEOLOC, OPTIONAL, SINGLE),
                new AttributeTemplate(LANGUAGE, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, SINGLE, INVERSE_KEY),
                new AttributeTemplate(SPONSORING_ORG, OPTIONAL, SINGLE),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(STATUS, MANDATORY, SINGLE),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_DOMAINS, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_ROUTES, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_IRT, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.IRT,
                41,
                new AttributeTemplate(IRT, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(ADDRESS, MANDATORY, MULTIPLE),
                new AttributeTemplate(PHONE, OPTIONAL, MULTIPLE),
                new AttributeTemplate(FAX_NO, OPTIONAL, MULTIPLE),
                new AttributeTemplate(E_MAIL, MANDATORY, MULTIPLE, LOOKUP_KEY),
                new AttributeTemplate(ABUSE_MAILBOX, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(SIGNATURE, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ENCRYPTION, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(AUTH, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(IRT_NFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.KEY_CERT,
                45,
                new AttributeTemplate(KEY_CERT, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(METHOD, GENERATED, SINGLE),
                new AttributeTemplate(OWNER, GENERATED, MULTIPLE),
                new AttributeTemplate(FINGERPR, GENERATED, SINGLE, INVERSE_KEY),
                new AttributeTemplate(CERTIF, MANDATORY, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.MNTNER,
                40,
                new AttributeTemplate(MNTNER, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(UPD_TO, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_NFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(AUTH, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ABUSE_MAILBOX, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.ORGANISATION,
                48,
                new AttributeTemplate(ORGANISATION, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(ORG_NAME, MANDATORY, SINGLE, LOOKUP_KEY),
                new AttributeTemplate(ORG_TYPE, MANDATORY, SINGLE),
                new AttributeTemplate(DESCR, OPTIONAL, MULTIPLE),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ADDRESS, MANDATORY, MULTIPLE),
                new AttributeTemplate(PHONE, OPTIONAL, MULTIPLE),
                new AttributeTemplate(FAX_NO, OPTIONAL, MULTIPLE),
                new AttributeTemplate(E_MAIL, MANDATORY, MULTIPLE, LOOKUP_KEY),
                new AttributeTemplate(GEOLOC, OPTIONAL, SINGLE),
                new AttributeTemplate(LANGUAGE, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ABUSE_C, OPTIONAL, SINGLE, INVERSE_KEY),
                new AttributeTemplate(REF_NFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_REF, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ABUSE_MAILBOX, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.PEERING_SET,
                22,
                new AttributeTemplate(PEERING_SET, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(PEERING, OPTIONAL, MULTIPLE),
                new AttributeTemplate(MP_PEERING, OPTIONAL, MULTIPLE),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.PERSON,
                50,
                new AttributeTemplate(PERSON, MANDATORY, SINGLE, LOOKUP_KEY),
                new AttributeTemplate(ADDRESS, MANDATORY, MULTIPLE),
                new AttributeTemplate(PHONE, MANDATORY, MULTIPLE),
                new AttributeTemplate(FAX_NO, OPTIONAL, MULTIPLE),
                new AttributeTemplate(E_MAIL, OPTIONAL, MULTIPLE, LOOKUP_KEY),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NIC_HDL, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ABUSE_MAILBOX, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.POEM,
                37,
                new AttributeTemplate(POEM, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, OPTIONAL, MULTIPLE),
                new AttributeTemplate(FORM, MANDATORY, SINGLE, INVERSE_KEY),
                new AttributeTemplate(TEXT, MANDATORY, MULTIPLE),
                new AttributeTemplate(AUTHOR, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, SINGLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.POETIC_FORM,
                36,
                new AttributeTemplate(POETIC_FORM, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.ROLE,
                49,
                new AttributeTemplate(ROLE, MANDATORY, SINGLE, LOOKUP_KEY),
                new AttributeTemplate(ADDRESS, MANDATORY, MULTIPLE),
                new AttributeTemplate(PHONE, OPTIONAL, MULTIPLE),
                new AttributeTemplate(FAX_NO, OPTIONAL, MULTIPLE),
                new AttributeTemplate(E_MAIL, MANDATORY, MULTIPLE, LOOKUP_KEY),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NIC_HDL, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ABUSE_MAILBOX, OPTIONAL, SINGLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.ROUTE_SET,
                12,
                new AttributeTemplate(ROUTE_SET, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(MEMBERS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(MP_MEMBERS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(MBRS_BY_REF, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.ROUTE,
                10,
                new AttributeTemplate(ROUTE, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(ORIGIN, MANDATORY, SINGLE, PRIMARY_KEY, INVERSE_KEY),
                new AttributeTemplate(PINGABLE, OPTIONAL, MULTIPLE),
                new AttributeTemplate(PING_HDL, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(HOLES, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MEMBER_OF, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(INJECT, OPTIONAL, MULTIPLE),
                new AttributeTemplate(AGGR_MTD, OPTIONAL, SINGLE),
                new AttributeTemplate(AGGR_BNDRY, OPTIONAL, SINGLE),
                new AttributeTemplate(EXPORT_COMPS, OPTIONAL, SINGLE),
                new AttributeTemplate(COMPONENTS, OPTIONAL, SINGLE),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_ROUTES, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.ROUTE6,
                11,
                new AttributeTemplate(ROUTE6, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(ORIGIN, MANDATORY, SINGLE, PRIMARY_KEY, INVERSE_KEY),
                new AttributeTemplate(PINGABLE, OPTIONAL, MULTIPLE),
                new AttributeTemplate(PING_HDL, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(HOLES, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MEMBER_OF, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(INJECT, OPTIONAL, MULTIPLE),
                new AttributeTemplate(AGGR_MTD, OPTIONAL, SINGLE),
                new AttributeTemplate(AGGR_BNDRY, OPTIONAL, SINGLE),
                new AttributeTemplate(EXPORT_COMPS, OPTIONAL, SINGLE),
                new AttributeTemplate(COMPONENTS, OPTIONAL, SINGLE),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_ROUTES, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)),
            new ObjectTemplateWithChanged(
                ObjectType.RTR_SET,
                23,
                new AttributeTemplate(RTR_SET, MANDATORY, SINGLE, PRIMARY_KEY, LOOKUP_KEY),
                new AttributeTemplate(DESCR, MANDATORY, MULTIPLE),
                new AttributeTemplate(MEMBERS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(MP_MEMBERS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(MBRS_BY_REF, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(REMARKS, OPTIONAL, MULTIPLE),
                new AttributeTemplate(ORG, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(TECH_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(ADMIN_C, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(NOTIFY, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_BY, MANDATORY, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(MNT_LOWER, OPTIONAL, MULTIPLE, INVERSE_KEY),
                new AttributeTemplate(CHANGED, DEPRECATED, MULTIPLE),
                new AttributeTemplate(CREATED, GENERATED, SINGLE),
                new AttributeTemplate(LAST_MODIFIED, GENERATED, SINGLE),
                new AttributeTemplate(SOURCE, MANDATORY, SINGLE)));

    final Map<ObjectType, ObjectTemplate> templateMap = Maps.newEnumMap(ObjectType.class);
    for (final ObjectTemplate objectTemplate : objectTemplates) {
      templateMap.put(objectTemplate.getObjectType(), objectTemplate);
    }

    TEMPLATE_MAP = Collections.unmodifiableMap(templateMap);
  }
  @Override
  public void generateChunkMesh(ChunkView view, ChunkMesh chunkMesh, int x, int y, int z) {
    Biome selfBiome = view.getBiome(x, y, z);
    Block selfBlock = view.getBlock(x, y, z);

    // TODO: Needs review - too much hardcoded special cases and corner cases resulting from this.
    ChunkVertexFlag vertexFlag = ChunkVertexFlag.NORMAL;
    if (selfBlock.isWater()) {
      if (view.getBlock(x, y + 1, z).isWater()) {
        vertexFlag = ChunkVertexFlag.WATER;
      } else {
        vertexFlag = ChunkVertexFlag.WATER_SURFACE;
      }
    } else if (selfBlock.isLava()) {
      vertexFlag = ChunkVertexFlag.LAVA;
    } else if (selfBlock.isWaving() && selfBlock.isDoubleSided()) {
      vertexFlag = ChunkVertexFlag.WAVING;
    } else if (selfBlock.isWaving()) {
      vertexFlag = ChunkVertexFlag.WAVING_BLOCK;
    }

    // Gather adjacent blocks
    Map<Side, Block> adjacentBlocks = Maps.newEnumMap(Side.class);
    for (Side side : Side.values()) {
      Vector3i offset = side.getVector3i();
      Block blockToCheck = view.getBlock(x + offset.x, y + offset.y, z + offset.z);
      adjacentBlocks.put(side, blockToCheck);
    }

    BlockAppearance blockAppearance = selfBlock.getAppearance(adjacentBlocks);

    /*
     * Determine the render process.
     */
    ChunkMesh.RenderType renderType = ChunkMesh.RenderType.TRANSLUCENT;

    if (!selfBlock.isTranslucent()) {
      renderType = ChunkMesh.RenderType.OPAQUE;
    }
    // TODO: Review special case, or alternatively compare uris.
    if (selfBlock.isWater() || selfBlock.isIce()) {
      renderType = ChunkMesh.RenderType.WATER_AND_ICE;
    }
    if (selfBlock.isDoubleSided()) {
      renderType = ChunkMesh.RenderType.BILLBOARD;
    }

    if (blockAppearance.getPart(BlockPart.CENTER) != null) {
      Vector4f colorOffset = selfBlock.calcColorOffsetFor(BlockPart.CENTER, selfBiome);
      blockAppearance
          .getPart(BlockPart.CENTER)
          .appendTo(chunkMesh, x, y, z, colorOffset, renderType, vertexFlag);
    }

    boolean[] drawDir = new boolean[6];

    for (Side side : Side.values()) {
      drawDir[side.ordinal()] =
          blockAppearance.getPart(BlockPart.fromSide(side)) != null
              && isSideVisibleForBlockTypes(adjacentBlocks.get(side), selfBlock, side);
    }

    // If the selfBlock is lowered, some more faces may have to be drawn
    if (selfBlock.isLiquid()) {
      Block bottomBlock = adjacentBlocks.get(Side.BOTTOM);
      // Draw horizontal sides if visible from below
      for (Side side : Side.horizontalSides()) {
        Vector3i offset = side.getVector3i();
        Block adjacentBelow = view.getBlock(x + offset.x, y - 1, z + offset.z);
        Block adjacent = adjacentBlocks.get(side);

        boolean visible =
            (blockAppearance.getPart(BlockPart.fromSide(side)) != null
                && isSideVisibleForBlockTypes(adjacentBelow, selfBlock, side)
                && !isSideVisibleForBlockTypes(bottomBlock, adjacent, side.reverse()));
        drawDir[side.ordinal()] |= visible;
      }

      // Draw the top if below a non-lowered selfBlock
      // TODO: Don't need to render the top if each side and the selfBlock above each side are
      // either liquid or opaque solids.
      Block blockToCheck = adjacentBlocks.get(Side.TOP);
      drawDir[Side.TOP.ordinal()] |= !blockToCheck.isLiquid();

      if (bottomBlock.isLiquid() || bottomBlock.isInvisible()) {
        for (Side dir : Side.values()) {
          if (drawDir[dir.ordinal()]) {
            Vector4f colorOffset = selfBlock.calcColorOffsetFor(BlockPart.fromSide(dir), selfBiome);
            selfBlock
                .getLoweredLiquidMesh(dir)
                .appendTo(chunkMesh, x, y, z, colorOffset, renderType, vertexFlag);
          }
        }
        return;
      }
    }

    for (Side dir : Side.values()) {
      if (drawDir[dir.ordinal()]) {
        Vector4f colorOffset = selfBlock.calcColorOffsetFor(BlockPart.fromSide(dir), selfBiome);
        // TODO: Needs review since the new per-vertex flags introduce a lot of special scenarios -
        // probably a per-side setting?
        if (selfBlock.isGrass() && dir != Side.TOP && dir != Side.BOTTOM) {
          blockAppearance
              .getPart(BlockPart.fromSide(dir))
              .appendTo(chunkMesh, x, y, z, colorOffset, renderType, ChunkVertexFlag.COLOR_MASK);
        } else {
          // if(dir == Side.TOP) logger.info("Generating: " + (new Vector3i(x, y, z)).toString() + "
          // " + view.getChunkRegion().toString() + " " + dir.toString());
          blockAppearance
              .getPart(BlockPart.fromSide(dir))
              .appendTo(chunkMesh, x, y, z, colorOffset, renderType, vertexFlag);
        }
      }
    }
  }
Example #20
0
  static {
    final IndexStrategy[] indexStrategies = {
      new IndexWithReference(AttributeType.ABUSE_C, "abuse_c", "pe_ro_id"),
      new IndexWithValueAndType(AttributeType.ABUSE_MAILBOX, "abuse_mailbox", "abuse_mailbox"),
      new Unindexed(AttributeType.ADDRESS),
      new IndexWithReference(AttributeType.ADMIN_C, "admin_c", "pe_ro_id"),
      new Unindexed(AttributeType.AGGR_BNDRY),
      new Unindexed(AttributeType.AGGR_MTD),
      new Unindexed(AttributeType.ALIAS),
      new Unindexed(AttributeType.ASSIGNMENT_SIZE),
      new IndexWithAsBlock(AttributeType.AS_BLOCK),
      new Unindexed(AttributeType.AS_NAME),
      new IndexWithValue(AttributeType.AS_SET, "as_set", "as_set"),
      new IndexWithAuth(AttributeType.AUTH, "auth", "auth"),
      new IndexWithReference(AttributeType.AUTHOR, "author", "pe_ro_id"),
      new IndexWithValue(AttributeType.AUT_NUM, "aut_num", "aut_num"),
      new Unindexed(AttributeType.CERTIF),
      new Unindexed(AttributeType.CHANGED),
      new Unindexed(AttributeType.COMPONENTS),
      new Unindexed(AttributeType.COUNTRY),
      new Unindexed(AttributeType.DEFAULT),
      new Unindexed(AttributeType.DESCR),
      new IndexWithValue(AttributeType.DOMAIN, "domain", "domain"),
      new IndexWithValue(AttributeType.DS_RDATA, "ds_rdata", "ds_rdata"),
      new Unindexed(AttributeType.ENCRYPTION),
      new Unindexed(AttributeType.EXPORT),
      new Unindexed(AttributeType.EXPORT_VIA),
      new Unindexed(AttributeType.EXPORT_COMPS),
      new IndexWithValueAndType(AttributeType.E_MAIL, "e_mail", "e_mail"),
      new Unindexed(AttributeType.FAX_NO),
      new Unindexed(AttributeType.FILTER),
      new IndexWithValue(AttributeType.FILTER_SET, "filter_set", "filter_set"),
      new IndexWithValue(AttributeType.FINGERPR, "fingerpr", "fingerpr"),
      new IndexWithReference(AttributeType.FORM, "form", "form_id"),
      new Unindexed(AttributeType.GEOLOC),
      new Unindexed(AttributeType.HOLES),
      new IndexWithIfAddr(AttributeType.IFADDR),
      new Unindexed(AttributeType.IMPORT),
      new Unindexed(AttributeType.IMPORT_VIA),
      new IndexWithInet6num(AttributeType.INET6NUM),
      new IndexWithInetnum(AttributeType.INETNUM),
      new IndexWithValue(AttributeType.INET_RTR, "inet_rtr", "inet_rtr"),
      new Unindexed(AttributeType.INJECT),
      new Unindexed(AttributeType.INTERFACE),
      new IndexWithValue(AttributeType.IRT, "irt", "irt"),
      new IndexWithValue(AttributeType.IRT_NFY, "irt_nfy", "irt_nfy"),
      new IndexWithValue(AttributeType.KEY_CERT, "key_cert", "key_cert"),
      new Unindexed(AttributeType.LANGUAGE),
      new IndexWithLocalAs(AttributeType.LOCAL_AS),
      new IndexWithReference(AttributeType.MBRS_BY_REF, "mbrs_by_ref", "mnt_id"),
      new Unindexed(AttributeType.MEMBERS),
      new IndexWithMemberOf(AttributeType.MEMBER_OF),
      new Unindexed(AttributeType.METHOD),
      new IndexWithMaintainer(AttributeType.MNTNER, "mntner", "mntner"),
      new IndexWithReference(AttributeType.MNT_BY, "mnt_by", "mnt_id"),
      new IndexWithReference(AttributeType.MNT_DOMAINS, "mnt_domains", "mnt_id"),
      new IndexWithReference(AttributeType.MNT_IRT, "mnt_irt", "irt_id"),
      new IndexWithReference(AttributeType.MNT_LOWER, "mnt_lower", "mnt_id"),
      new IndexWithValue(AttributeType.MNT_NFY, "mnt_nfy", "mnt_nfy"),
      new IndexWithReference(AttributeType.MNT_REF, "mnt_ref", "mnt_id"),
      new IndexWithMntRoutes(AttributeType.MNT_ROUTES),
      new Unindexed(AttributeType.MP_DEFAULT),
      new Unindexed(AttributeType.MP_EXPORT),
      new Unindexed(AttributeType.MP_FILTER),
      new Unindexed(AttributeType.MP_IMPORT),
      new Unindexed(AttributeType.MP_MEMBERS),
      new Unindexed(AttributeType.MP_PEER),
      new Unindexed(AttributeType.MP_PEERING),
      new Unindexed(
          AttributeType
              .NETNAME), // TODO: [AH] ATM this is handled by JdbcInetnumDao/JdbcInet6numDao as a
      // special case
      new IndexWithValueAndType(AttributeType.NIC_HDL, "person_role", "nic_hdl"),
      new IndexWithValueAndType(AttributeType.NOTIFY, "notify", "notify"),
      new IndexWithNServer(AttributeType.NSERVER, "nserver", "host"),
      new IndexWithReference(AttributeType.ORG, "org", "org_id"),
      new Unindexed(AttributeType.ORG_TYPE),
      new IndexWithValue(AttributeType.ORGANISATION, "organisation", "organisation"),
      new IndexWithName(AttributeType.ORG_NAME, "org_name"),
      new IndexWithOrigin(AttributeType.ORIGIN),
      new Unindexed(AttributeType.OWNER),
      new Unindexed(AttributeType.PEER),
      new Unindexed(AttributeType.PEERING),
      new IndexWithValue(AttributeType.PEERING_SET, "peering_set", "peering_set"),
      new IndexWithNameAndType(AttributeType.PERSON, ObjectType.PERSON, "names"),
      new Unindexed(AttributeType.PHONE),
      new IndexWithReference(AttributeType.PING_HDL, "ping_hdl", "pe_ro_id"),
      new Unindexed(AttributeType.PINGABLE),
      new IndexWithValue(AttributeType.POEM, "poem", "poem"),
      new IndexWithValue(AttributeType.POETIC_FORM, "poetic_form", "poetic_form"),
      new IndexWithReference(AttributeType.REFERRAL_BY, "referral_by", "mnt_id"),
      new IndexWithValue(AttributeType.REF_NFY, "ref_nfy", "ref_nfy"),
      new Unindexed(AttributeType.REMARKS),
      new IndexWithNameAndType(AttributeType.ROLE, ObjectType.ROLE, "names"),
      new IndexWithRoute(AttributeType.ROUTE),
      new IndexWithRoute6(AttributeType.ROUTE6),
      new IndexWithValue(AttributeType.ROUTE_SET, "route_set", "route_set"),
      new IndexWithValue(AttributeType.RTR_SET, "rtr_set", "rtr_set"),
      new Unindexed(AttributeType.SIGNATURE),
      new Unindexed(AttributeType.SOURCE),
      new IndexWithReference(AttributeType.SPONSORING_ORG, "sponsoring_org", "org_id"),
      new Unindexed(AttributeType.STATUS),
      new IndexWithReference(AttributeType.TECH_C, "tech_c", "pe_ro_id"),
      new Unindexed(AttributeType.TEXT),
      new IndexWithValue(AttributeType.UPD_TO, "upd_to", "upd_to"),
      new IndexWithReference(AttributeType.ZONE_C, "zone_c", "pe_ro_id")
    };

    final Map<AttributeType, IndexStrategy> indexByAttribute = Maps.newEnumMap(AttributeType.class);
    for (final IndexStrategy indexStrategy : indexStrategies) {
      final AttributeType attributeType = indexStrategy.getAttributeType();
      final IndexStrategy previous = indexByAttribute.put(attributeType, indexStrategy);
      Validate.isTrue(previous == null, "Multiple definitions for: " + attributeType);
    }
    INDEX_BY_ATTRIBUTE = Collections.unmodifiableMap(indexByAttribute);

    final Map<ObjectType, List<IndexStrategy>> indexesReferingObject =
        Maps.newEnumMap(ObjectType.class);
    for (final ObjectType objectType : ObjectType.values()) {
      final List<IndexStrategy> indexesRefererringCurrentObject = Lists.newArrayList();
      for (final IndexStrategy indexStrategy : indexStrategies) {
        if (indexStrategy.getAttributeType().getReferences().contains(objectType)) {
          indexesRefererringCurrentObject.add(indexStrategy);
        }
      }

      indexesReferingObject.put(
          objectType, Collections.unmodifiableList(indexesRefererringCurrentObject));
    }
    INDEXES_REFERING_OBJECT = Collections.unmodifiableMap(indexesReferingObject);
  }
Example #21
0
@SuppressWarnings("unchecked")
public class NMS {
  private NMS() {
    // util class
  }

  private static final float DEFAULT_SPEED = 0.4F;
  private static Map<Class<?>, Integer> ENTITY_CLASS_TO_INT;
  private static final Map<Class<?>, Constructor<?>> ENTITY_CONSTRUCTOR_CACHE =
      new WeakHashMap<Class<?>, Constructor<?>>();
  private static Map<Integer, Class<?>> ENTITY_INT_TO_CLASS;
  private static Field GOAL_FIELD;
  private static Field LAND_SPEED_MODIFIER_FIELD;
  private static final Map<EntityType, Float> MOVEMENT_SPEEDS = Maps.newEnumMap(EntityType.class);
  private static Field NAVIGATION_WORLD_FIELD;
  private static final Location packetCacheLocation = new Location(null, 0, 0, 0);
  private static Field PATHFINDING_RANGE;
  private static final Random RANDOM = Util.getFastRandom();
  private static Field SPEED_FIELD;
  private static Field THREAD_STOPPER;

  public static void addOrRemoveFromPlayerList(LivingEntity bukkitEntity, boolean remove) {
    if (bukkitEntity == null) return;
    EntityLiving handle = getHandle(bukkitEntity);
    if (handle.world == null) return;
    if (remove) {
      handle.world.players.remove(handle);
    } else if (!handle.world.players.contains(handle)) {
      handle.world.players.add(handle);
    }
  }

  public static void attack(EntityLiving handle, Entity target) {
    int damage = handle instanceof EntityMonster ? ((EntityMonster) handle).c(target) : 2;

    if (handle.hasEffect(MobEffectList.INCREASE_DAMAGE)) {
      damage += 3 << handle.getEffect(MobEffectList.INCREASE_DAMAGE).getAmplifier();
    }

    if (handle.hasEffect(MobEffectList.WEAKNESS)) {
      damage -= 2 << handle.getEffect(MobEffectList.WEAKNESS).getAmplifier();
    }

    int knockbackLevel = 0;

    if (target instanceof EntityLiving) {
      damage += EnchantmentManager.a(handle, (EntityLiving) target);
      knockbackLevel +=
          EnchantmentManager.getKnockbackEnchantmentLevel(handle, (EntityLiving) target);
    }

    boolean success = target.damageEntity(DamageSource.mobAttack(handle), damage);

    if (!success) return;
    if (knockbackLevel > 0) {
      target.g(
          -MathHelper.sin((float) (handle.yaw * Math.PI / 180.0F)) * knockbackLevel * 0.5F,
          0.1D,
          MathHelper.cos((float) (handle.yaw * Math.PI / 180.0F)) * knockbackLevel * 0.5F);
      handle.motX *= 0.6D;
      handle.motZ *= 0.6D;
    }

    int fireAspectLevel = EnchantmentManager.getFireAspectEnchantmentLevel(handle);

    if (fireAspectLevel > 0) target.setOnFire(fireAspectLevel * 4);
  }

  public static void clearGoals(PathfinderGoalSelector... goalSelectors) {
    if (GOAL_FIELD == null || goalSelectors == null) return;
    for (PathfinderGoalSelector selector : goalSelectors) {
      try {
        List<?> list = (List<?>) NMS.GOAL_FIELD.get(selector);
        list.clear();
      } catch (Exception e) {
        Messaging.logTr(Messages.ERROR_CLEARING_GOALS, e.getMessage());
      }
    }
  }

  private static Constructor<?> getCustomEntityConstructor(Class<?> clazz, EntityType type)
      throws SecurityException, NoSuchMethodException {
    Constructor<?> constructor = ENTITY_CONSTRUCTOR_CACHE.get(clazz);
    if (constructor == null) {
      constructor = clazz.getConstructor(World.class);
      constructor.setAccessible(true);
      ENTITY_CLASS_TO_INT.put(clazz, (int) type.getTypeId());
      ENTITY_CONSTRUCTOR_CACHE.put(clazz, constructor);
    }
    return constructor;
  }

  public static Field getField(Class<?> clazz, String field) {
    Field f = null;
    try {
      f = clazz.getDeclaredField(field);
      f.setAccessible(true);
    } catch (Exception e) {
      Messaging.logTr(Messages.ERROR_GETTING_FIELD, field, e.getMessage());
    }
    return f;
  }

  public static EntityLiving getHandle(LivingEntity entity) {
    return ((CraftLivingEntity) entity).getHandle();
  }

  public static float getHeadYaw(EntityLiving handle) {
    return handle.aA;
  }

  public static float getSpeedFor(NPC npc) {
    EntityType entityType = npc.getBukkitEntity().getType();
    Float cached = MOVEMENT_SPEEDS.get(entityType);
    if (cached != null) return cached;
    if (SPEED_FIELD == null) {
      MOVEMENT_SPEEDS.put(entityType, DEFAULT_SPEED);
      return DEFAULT_SPEED;
    }
    try {
      float speed = SPEED_FIELD.getFloat(((CraftEntity) npc.getBukkitEntity()).getHandle());
      MOVEMENT_SPEEDS.put(entityType, speed);
      return speed;
    } catch (IllegalAccessException ex) {
      ex.printStackTrace();
      return DEFAULT_SPEED;
    }
  }

  public static boolean inWater(LivingEntity entity) {
    EntityLiving mcEntity = getHandle(entity);
    return mcEntity.G() || mcEntity.I();
  }

  public static void loadPlugins() {
    ((CraftServer) Bukkit.getServer()).enablePlugins(PluginLoadOrder.POSTWORLD);
  }

  public static void look(EntityLiving handle, Entity target) {
    handle.getControllerLook().a(target, 10.0F, handle.bs());
  }

  public static void look(LivingEntity bukkitEntity, float yaw, float pitch) {
    EntityLiving handle = getHandle(bukkitEntity);
    handle.yaw = yaw;
    setHeadYaw(handle, yaw);
    handle.pitch = pitch;
  }

  public static float modifiedSpeed(float baseSpeed, NPC npc) {
    return npc == null
        ? baseSpeed
        : baseSpeed * npc.getNavigator().getLocalParameters().speedModifier();
  }

  public static void registerEntityClass(Class<?> clazz) {
    if (ENTITY_CLASS_TO_INT.containsKey(clazz)) return;
    Class<?> search = clazz;
    while ((search = search.getSuperclass()) != null && Entity.class.isAssignableFrom(search)) {
      if (!ENTITY_CLASS_TO_INT.containsKey(search)) continue;
      int code = ENTITY_CLASS_TO_INT.get(search);
      ENTITY_INT_TO_CLASS.put(code, clazz);
      ENTITY_CLASS_TO_INT.put(clazz, code);
      return;
    }
    throw new IllegalArgumentException("unable to find valid entity superclass");
  }

  public static void removeFromServerPlayerList(Player player) {
    EntityPlayer handle = ((CraftPlayer) player).getHandle();
    ((CraftServer) Bukkit.getServer()).getHandle().players.remove(handle);
  }

  public static void sendPacket(Player player, Packet packet) {
    ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet);
  }

  public static void sendPacketNearby(Location location, Packet packet) {
    NMS.sendPacketsNearby(location, Arrays.asList(packet), 64);
  }

  public static void sendPacketsNearby(Location location, Collection<Packet> packets) {
    NMS.sendPacketsNearby(location, packets, 64);
  }

  public static void sendPacketsNearby(
      Location location, Collection<Packet> packets, double radius) {
    radius *= radius;
    final org.bukkit.World world = location.getWorld();
    for (Player ply : Bukkit.getServer().getOnlinePlayers()) {
      if (ply == null || world != ply.getWorld()) {
        continue;
      }
      if (location.distanceSquared(ply.getLocation(packetCacheLocation)) > radius) {
        continue;
      }
      for (Packet packet : packets) {
        sendPacket(ply, packet);
      }
    }
  }

  public static void sendPacketsNearby(Location location, Packet... packets) {
    NMS.sendPacketsNearby(location, Arrays.asList(packets), 64);
  }

  public static void sendToOnline(Packet... packets) {
    Validate.notNull(packets, "packets cannot be null");
    for (Player player : Bukkit.getOnlinePlayers()) {
      if (player == null || !player.isOnline()) continue;
      for (Packet packet : packets) {
        sendPacket(player, packet);
      }
    }
  }

  public static void setDestination(
      LivingEntity bukkitEntity, double x, double y, double z, float speed) {
    ((CraftLivingEntity) bukkitEntity).getHandle().getControllerMove().a(x, y, z, speed);
  }

  public static void setHeadYaw(EntityLiving handle, float yaw) {
    while (yaw < -180.0F) {
      yaw += 360.0F;
    }

    while (yaw >= 180.0F) {
      yaw -= 360.0F;
    }
    handle.aA = yaw;
    if (!(handle instanceof EntityHuman)) handle.ay = yaw;
    handle.aB = yaw;
  }

  public static void setLandSpeedModifier(EntityLiving handle, float speed) {
    if (LAND_SPEED_MODIFIER_FIELD == null) return;
    try {
      LAND_SPEED_MODIFIER_FIELD.setFloat(handle, speed);
    } catch (Exception e) {
      Messaging.logTr(Messages.ERROR_UPDATING_SPEED, e.getMessage());
    }
  }

  public static void setShouldJump(LivingEntity entity) {
    ControllerJump controller = getHandle(entity).getControllerJump();
    controller.a();
  }

  public static org.bukkit.entity.Entity spawnCustomEntity(
      org.bukkit.World world, Location at, Class<? extends Entity> clazz, EntityType type) {
    World handle = ((CraftWorld) world).getHandle();
    Entity entity = null;
    try {
      Constructor<?> constructor = getCustomEntityConstructor(clazz, type);
      entity = (Entity) constructor.newInstance(handle);
    } catch (Exception e) {
      Messaging.logTr(Messages.ERROR_SPAWNING_CUSTOM_ENTITY, e.getMessage());
      return null;
    }
    handle.addEntity(entity);
    entity.setLocation(at.getX(), at.getY(), at.getZ(), at.getYaw(), at.getPitch());
    return entity.getBukkitEntity();
  }

  public static void stopNetworkThreads(NetworkManager manager) {
    if (THREAD_STOPPER == null) return;
    try {
      THREAD_STOPPER.set(manager, false);
    } catch (Exception e) {
      Messaging.logTr(Messages.ERROR_STOPPING_NETWORK_THREADS, e.getMessage());
    }
  }

  public static void trySwim(LivingEntity handle) {
    trySwim(handle, 0.04F);
  }

  public static void trySwim(LivingEntity entity, float power) {
    Entity handle = getHandle(entity);
    if (RANDOM.nextFloat() < 0.8F && inWater(entity)) {
      handle.motY += power;
    }
  }

  public static void updateAI(EntityLiving entity) {
    updateSenses(entity);
    entity.getNavigation().e();
    entity.getControllerMove().c();
    entity.getControllerLook().a();
    entity.getControllerJump().b();
  }

  public static void updateNavigationWorld(LivingEntity entity, org.bukkit.World world) {
    if (NAVIGATION_WORLD_FIELD == null) return;
    EntityLiving handle = ((CraftLivingEntity) entity).getHandle();
    World worldHandle = ((CraftWorld) world).getHandle();
    try {
      NAVIGATION_WORLD_FIELD.set(handle.getNavigation(), worldHandle);
    } catch (Exception e) {
      Messaging.logTr(Messages.ERROR_UPDATING_NAVIGATION_WORLD, e.getMessage());
    }
  }

  public static void updatePathfindingRange(NPC npc, float pathfindingRange) {
    if (PATHFINDING_RANGE == null) return;
    Navigation navigation = ((CraftLivingEntity) npc.getBukkitEntity()).getHandle().getNavigation();
    try {
      PATHFINDING_RANGE.set(navigation, pathfindingRange);
    } catch (Exception e) {
      Messaging.logTr(Messages.ERROR_UPDATING_PATHFINDING_RANGE, e.getMessage());
    }
  }

  public static void updateSenses(EntityLiving entity) {
    entity.aD().a();
  }

  static {
    // true field above false and three synchronised lists
    THREAD_STOPPER = getField(NetworkManager.class, "n");

    // constants taken from source code
    MOVEMENT_SPEEDS.put(EntityType.CHICKEN, 0.25F);
    MOVEMENT_SPEEDS.put(EntityType.COW, 0.2F);
    MOVEMENT_SPEEDS.put(EntityType.CREEPER, 0.3F);
    MOVEMENT_SPEEDS.put(EntityType.IRON_GOLEM, 0.15F);
    MOVEMENT_SPEEDS.put(EntityType.MUSHROOM_COW, 0.2F);
    MOVEMENT_SPEEDS.put(EntityType.OCELOT, 0.23F);
    MOVEMENT_SPEEDS.put(EntityType.SHEEP, 0.25F);
    MOVEMENT_SPEEDS.put(EntityType.SNOWMAN, 0.25F);
    MOVEMENT_SPEEDS.put(EntityType.PIG, 0.27F);
    MOVEMENT_SPEEDS.put(EntityType.PLAYER, 1F);
    MOVEMENT_SPEEDS.put(EntityType.VILLAGER, 0.3F);

    LAND_SPEED_MODIFIER_FIELD = getField(EntityLiving.class, "bQ");
    SPEED_FIELD = getField(EntityLiving.class, "bI");
    NAVIGATION_WORLD_FIELD = getField(Navigation.class, "b");
    PATHFINDING_RANGE = getField(Navigation.class, "e");
    GOAL_FIELD = getField(PathfinderGoalSelector.class, "a");

    try {
      Field field = getField(EntityTypes.class, "d");
      ENTITY_INT_TO_CLASS = (Map<Integer, Class<?>>) field.get(null);
      field = getField(EntityTypes.class, "e");
      ENTITY_CLASS_TO_INT = (Map<Class<?>, Integer>) field.get(null);
    } catch (Exception e) {
      Messaging.logTr(Messages.ERROR_GETTING_ID_MAPPING, e.getMessage());
    }
  }
}
Example #22
0
public class EntitySheep extends EntityAnimal {
  /**
   * Internal crafting inventory used to check the result of mixing dyes corresponding to the fleece
   * color when breeding sheep.
   */
  private final InventoryCrafting inventoryCrafting =
      new InventoryCrafting(
          new Container() {
            private static final String __OBFID = "CL_00001649";

            public boolean canInteractWith(EntityPlayer playerIn) {
              return false;
            }
          },
          2,
          1);

  private static final Map field_175514_bm = Maps.newEnumMap(DyeColor.class);

  /**
   * Used to control movement as well as wool regrowth. Set to 40 on handleHealthUpdate and counts
   * down with each tick.
   */
  private int sheepTimer;

  private EntityAIEatGrass entityAIEatGrass = new EntityAIEatGrass(this);
  private static final String __OBFID = "CL_00001648";

  public static float[] func_175513_a(DyeColor p_175513_0_) {
    return (float[]) field_175514_bm.get(p_175513_0_);
  }

  public EntitySheep(World world) {
    super(world);
    this.setSize(0.9F, 1.3F);
    ((PathNavigateGround) this.getNavigator()).func_179690_a(true);
    this.tasks.addTask(0, new EntityAISwimming(this));
    this.tasks.addTask(1, new EntityAIPanic(this, 1.25D));
    this.tasks.addTask(2, new EntityAIMate(this, 1.0D));
    this.tasks.addTask(3, new EntityAITempt(this, 1.1D, Items.wheat, false));
    this.tasks.addTask(4, new EntityAIFollowParent(this, 1.1D));
    this.tasks.addTask(5, this.entityAIEatGrass);
    this.tasks.addTask(6, new EntityAIWander(this, 1.0D));
    this.tasks.addTask(7, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F));
    this.tasks.addTask(8, new EntityAILookIdle(this));
    this.inventoryCrafting.set(0, new ItemStack(Items.dye, 1, 0));
    this.inventoryCrafting.set(1, new ItemStack(Items.dye, 1, 0));
  }

  protected void updateAITasks() {
    this.sheepTimer = this.entityAIEatGrass.getEatingGrassTimer();
    super.updateAITasks();
  }

  /**
   * Called frequently so the entity can update its state every tick as required. For example,
   * zombies and skeletons use this to react to sunlight and start to burn.
   */
  public void onLivingUpdate() {
    if (this.world.isRemote) {
      this.sheepTimer = Math.max(0, this.sheepTimer - 1);
    }

    super.onLivingUpdate();
  }

  protected void applyEntityAttributes() {
    super.applyEntityAttributes();
    this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D);
    this.getEntityAttribute(SharedMonsterAttributes.movementSpeed)
        .setBaseValue(0.23000000417232513D);
  }

  protected void entityInit() {
    super.entityInit();
    this.dataWatcher.addObject(16, new Byte((byte) 0));
  }

  /** Drop 0-2 items of this living's type */
  protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) {
    if (!this.getSheared()) {
      this.dropItem(
          new ItemStack(
              Item.getItemForBlock(Blocks.wool),
              1,
              this.func_175509_cj().getInverseDyeColorValue()),
          0.0F);
    }

    int var3 = this.rand.nextInt(2) + 1 + this.rand.nextInt(1 + p_70628_2_);

    for (int var4 = 0; var4 < var3; ++var4) {
      if (this.isBurning()) {
        this.dropItem(Items.cooked_mutton, 1);
      } else {
        this.dropItem(Items.mutton, 1);
      }
    }
  }

  protected Item getDropItem() {
    return Item.getItemForBlock(Blocks.wool);
  }

  public void handleHealthUpdate(byte value) {
    if (value == 10) {
      this.sheepTimer = 40;
    } else {
      super.handleHealthUpdate(value);
    }
  }

  public float getHeadRotationPointY(float p_70894_1_) {
    return this.sheepTimer <= 0
        ? 0.0F
        : (this.sheepTimer >= 4 && this.sheepTimer <= 36
            ? 1.0F
            : (this.sheepTimer < 4
                ? ((float) this.sheepTimer - p_70894_1_) / 4.0F
                : -((float) (this.sheepTimer - 40) - p_70894_1_) / 4.0F));
  }

  public float getHeadRotationAngleX(float p_70890_1_) {
    if (this.sheepTimer > 4 && this.sheepTimer <= 36) {
      float var2 = ((float) (this.sheepTimer - 4) - p_70890_1_) / 32.0F;
      return ((float) Math.PI / 5F) + ((float) Math.PI * 7F / 100F) * M.sin(var2 * 28.7F);
    } else {
      return this.sheepTimer > 0 ? ((float) Math.PI / 5F) : this.pitch / (180F / (float) Math.PI);
    }
  }

  /**
   * Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a
   * pig.
   */
  public boolean interact(EntityPlayer player) {
    ItemStack var2 = player.inventory.getCurrentItem();

    if (var2 != null && var2.getItem() == Items.shears && !this.getSheared() && !this.isChild()) {
      if (!this.world.isRemote) {
        this.setSheared(true);
        int var3 = 1 + this.rand.nextInt(3);

        for (int var4 = 0; var4 < var3; ++var4) {
          EntityItem var5 =
              this.dropItem(
                  new ItemStack(
                      Item.getItemForBlock(Blocks.wool),
                      1,
                      this.func_175509_cj().getInverseDyeColorValue()),
                  1.0F);
          var5.motionY += (double) (this.rand.nextFloat() * 0.05F);
          var5.motionX += (double) ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.1F);
          var5.motionZ += (double) ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.1F);
        }
      }

      var2.damageItem(1, player);
      this.playSound("mob.sheep.shear", 1.0F, 1.0F);
    }

    return super.interact(player);
  }

  /** (abstract) Protected helper method to write subclass entity data to NBT. */
  public void writeEntityToNBT(NBTTagCompound tag) {
    super.writeEntityToNBT(tag);
    tag.setBoolean("Sheared", this.getSheared());
    tag.setByte("Color", (byte) this.func_175509_cj().getInverseDyeColorValue());
  }

  /** (abstract) Protected helper method to read subclass entity data from NBT. */
  public void readEntityFromNBT(NBTTagCompound tag) {
    super.readEntityFromNBT(tag);
    this.setSheared(tag.getBoolean("Sheared"));
    this.func_175512_b(DyeColor.getDyeColorForInverseValue(tag.getByte("Color")));
  }

  /** Returns the sound this mob makes while it's alive. */
  protected String getLivingSound() {
    return "mob.sheep.say";
  }

  /** Returns the sound this mob makes when it is hurt. */
  protected String getHurtSound() {
    return "mob.sheep.say";
  }

  /** Returns the sound this mob makes on death. */
  protected String getDeathSound() {
    return "mob.sheep.say";
  }

  protected void playStepSound(BlockPos p_180429_1_, IBlock p_180429_2_) {
    this.playSound("mob.sheep.step", 0.15F, 1.0F);
  }

  public DyeColor func_175509_cj() {
    return DyeColor.getDyeColorForInverseValue(this.dataWatcher.getWatchableObjectByte(16) & 15);
  }

  public void func_175512_b(DyeColor p_175512_1_) {
    byte var2 = this.dataWatcher.getWatchableObjectByte(16);
    this.dataWatcher.updateObject(
        16, Byte.valueOf((byte) (var2 & 240 | p_175512_1_.getInverseDyeColorValue() & 15)));
  }

  /** returns true if a sheeps wool has been sheared */
  public boolean getSheared() {
    return (this.dataWatcher.getWatchableObjectByte(16) & 16) != 0;
  }

  /** make a sheep sheared if set to true */
  public void setSheared(boolean p_70893_1_) {
    byte var2 = this.dataWatcher.getWatchableObjectByte(16);

    if (p_70893_1_) {
      this.dataWatcher.updateObject(16, Byte.valueOf((byte) (var2 | 16)));
    } else {
      this.dataWatcher.updateObject(16, Byte.valueOf((byte) (var2 & -17)));
    }
  }

  public static DyeColor func_175510_a(Random p_175510_0_) {
    int var1 = p_175510_0_.nextInt(100);
    return var1 < 5
        ? DyeColor.BLACK
        : (var1 < 10
            ? DyeColor.GRAY
            : (var1 < 15
                ? DyeColor.SILVER
                : (var1 < 18
                    ? DyeColor.BROWN
                    : (p_175510_0_.nextInt(500) == 0 ? DyeColor.PINK : DyeColor.WHITE))));
  }

  public EntitySheep func_180491_b(EntityAgeable p_180491_1_) {
    EntitySheep var2 = (EntitySheep) p_180491_1_;
    EntitySheep var3 = new EntitySheep(this.world);
    var3.func_175512_b(this.func_175511_a(this, var2));
    return var3;
  }

  /**
   * This function applies the benefits of growing back wool and faster growing up to the acting
   * entity. (This function is used in the AIEatGrass)
   */
  public void eatGrassBonus() {
    this.setSheared(false);

    if (this.isChild()) {
      this.addGrowth(60);
    }
  }

  public IEntityLivingData setDifficulty(
      DifficultyInstance p_180482_1_, IEntityLivingData p_180482_2_) {
    p_180482_2_ = super.setDifficulty(p_180482_1_, p_180482_2_);
    this.func_175512_b(func_175510_a(this.world.rand));
    return p_180482_2_;
  }

  private DyeColor func_175511_a(EntityAnimal p_175511_1_, EntityAnimal p_175511_2_) {
    int var3 = ((EntitySheep) p_175511_1_).func_175509_cj().getDyeColorValue();
    int var4 = ((EntitySheep) p_175511_2_).func_175509_cj().getDyeColorValue();
    this.inventoryCrafting.get(0).setItemDamage(var3);
    this.inventoryCrafting.get(1).setItemDamage(var4);
    ItemStack var5 =
        CraftingManager.getInstance()
            .findMatchingRecipe(this.inventoryCrafting, ((EntitySheep) p_175511_1_).world);
    int var6;

    if (var5 != null && var5.getItem() == Items.dye) {
      var6 = var5.getMetadata();
    } else {
      var6 = this.world.rand.nextBoolean() ? var3 : var4;
    }

    return DyeColor.getDyeColorForValue(var6);
  }

  public float getEyeHeight() {
    return 0.95F * this.height;
  }

  public EntityAgeable createChild(EntityAgeable p_90011_1_) {
    return this.func_180491_b(p_90011_1_);
  }

  static {
    field_175514_bm.put(DyeColor.WHITE, new float[] {1.0F, 1.0F, 1.0F});
    field_175514_bm.put(DyeColor.ORANGE, new float[] {0.85F, 0.5F, 0.2F});
    field_175514_bm.put(DyeColor.MAGENTA, new float[] {0.7F, 0.3F, 0.85F});
    field_175514_bm.put(DyeColor.LIGHT_BLUE, new float[] {0.4F, 0.6F, 0.85F});
    field_175514_bm.put(DyeColor.YELLOW, new float[] {0.9F, 0.9F, 0.2F});
    field_175514_bm.put(DyeColor.LIME, new float[] {0.5F, 0.8F, 0.1F});
    field_175514_bm.put(DyeColor.PINK, new float[] {0.95F, 0.5F, 0.65F});
    field_175514_bm.put(DyeColor.GRAY, new float[] {0.3F, 0.3F, 0.3F});
    field_175514_bm.put(DyeColor.SILVER, new float[] {0.6F, 0.6F, 0.6F});
    field_175514_bm.put(DyeColor.CYAN, new float[] {0.3F, 0.5F, 0.6F});
    field_175514_bm.put(DyeColor.PURPLE, new float[] {0.5F, 0.25F, 0.7F});
    field_175514_bm.put(DyeColor.BLUE, new float[] {0.2F, 0.3F, 0.7F});
    field_175514_bm.put(DyeColor.BROWN, new float[] {0.4F, 0.3F, 0.2F});
    field_175514_bm.put(DyeColor.GREEN, new float[] {0.4F, 0.5F, 0.2F});
    field_175514_bm.put(DyeColor.RED, new float[] {0.6F, 0.2F, 0.2F});
    field_175514_bm.put(DyeColor.BLACK, new float[] {0.1F, 0.1F, 0.1F});
  }
}
Example #23
0
    public BakedFluid(
        Optional<TRSRTransformation> transformation,
        ImmutableMap<TransformType, TRSRTransformation> transforms,
        VertexFormat format,
        int color,
        TextureAtlasSprite still,
        TextureAtlasSprite flowing,
        boolean gas,
        boolean statePresent,
        int[] cornerRound,
        int flowRound) {
      this.transformation = transformation;
      this.transforms = transforms;
      this.format = format;
      this.color = color;
      this.still = still;
      this.flowing = flowing;
      this.gas = gas;

      faceQuads = Maps.newEnumMap(EnumFacing.class);
      for (EnumFacing side : EnumFacing.values()) {
        faceQuads.put(side, ImmutableList.<BakedQuad>of());
      }

      if (statePresent) {
        float[] y = new float[4];
        for (int i = 0; i < 4; i++) {
          if (gas) {
            y[i] = 1 - cornerRound[i] / 768f;
          } else {
            y[i] = cornerRound[i] / 768f;
          }
        }

        float flow = (float) Math.toRadians(flowRound);

        // top

        TextureAtlasSprite topSprite = flowing;
        float scale = 4;
        if (flow < -17F) {
          flow = 0;
          scale = 8;
          topSprite = still;
        }

        float c = MathHelper.cos(flow) * scale;
        float s = MathHelper.sin(flow) * scale;

        EnumFacing side = gas ? EnumFacing.DOWN : EnumFacing.UP;
        UnpackedBakedQuad.Builder builder;
        ImmutableList.Builder<BakedQuad> topFaceBuilder = ImmutableList.builder();
        for (int k = 0; k < 2; k++) {
          builder = new UnpackedBakedQuad.Builder(format);
          builder.setQuadOrientation(side);
          builder.setTexture(topSprite);
          for (int i = gas ? 3 : 0; i != (gas ? -1 : 4); i += (gas ? -1 : 1)) {
            int l = (k * 3) + (1 - 2 * k) * i;
            putVertex(
                builder,
                side,
                x[l],
                y[l],
                z[l],
                topSprite.getInterpolatedU(8 + c * (x[l] * 2 - 1) + s * (z[l] * 2 - 1)),
                topSprite.getInterpolatedV(
                    8 + c * (x[(l + 1) % 4] * 2 - 1) + s * (z[(l + 1) % 4] * 2 - 1)));
          }
          topFaceBuilder.add(builder.build());
        }
        faceQuads.put(side, topFaceBuilder.build());

        // bottom

        side = side.getOpposite();
        builder = new UnpackedBakedQuad.Builder(format);
        builder.setQuadOrientation(side);
        builder.setTexture(still);
        for (int i = gas ? 3 : 0; i != (gas ? -1 : 4); i += (gas ? -1 : 1)) {
          putVertex(
              builder,
              side,
              z[i],
              gas ? 1 : 0,
              x[i],
              still.getInterpolatedU(z[i] * 16),
              still.getInterpolatedV(x[i] * 16));
        }
        faceQuads.put(side, ImmutableList.<BakedQuad>of(builder.build()));

        // sides

        for (int i = 0; i < 4; i++) {
          side = EnumFacing.getHorizontal((5 - i) % 4);
          BakedQuad q[] = new BakedQuad[2];

          for (int k = 0; k < 2; k++) {
            builder = new UnpackedBakedQuad.Builder(format);
            builder.setQuadOrientation(side);
            builder.setTexture(flowing);
            for (int j = 0; j < 4; j++) {
              int l = (k * 3) + (1 - 2 * k) * j;
              float yl = z[l] * y[(i + x[l]) % 4];
              if (gas && z[l] == 0) yl = 1;
              putVertex(
                  builder,
                  side,
                  x[(i + x[l]) % 4],
                  yl,
                  z[(i + x[l]) % 4],
                  flowing.getInterpolatedU(x[l] * 8),
                  flowing.getInterpolatedV((gas ? yl : 1 - yl) * 8));
            }
            q[k] = builder.build();
          }
          faceQuads.put(side, ImmutableList.of(q[0], q[1]));
        }
      } else {
        // 1 quad for inventory
        UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(format);
        builder.setQuadOrientation(EnumFacing.UP);
        builder.setTexture(still);
        for (int i = 0; i < 4; i++) {
          putVertex(
              builder,
              EnumFacing.UP,
              z[i],
              x[i],
              0,
              still.getInterpolatedU(z[i] * 16),
              still.getInterpolatedV(x[i] * 16));
        }
        faceQuads.put(EnumFacing.SOUTH, ImmutableList.<BakedQuad>of(builder.build()));
      }
    }
Example #24
0
/** @author Immortius */
public class BlockShapeImpl extends BlockShape {

  private String displayName;
  private EnumMap<BlockPart, BlockMeshPart> meshParts = Maps.newEnumMap(BlockPart.class);
  private EnumBooleanMap<Side> fullSide = new EnumBooleanMap<>(Side.class);
  private CollisionShape baseCollisionShape;
  private Vector3f baseCollisionOffset = new Vector3f();
  private boolean yawSymmetric;
  private boolean pitchSymmetric;
  private boolean rollSymmetric;

  private Map<Rotation, CollisionShape> collisionShape = Maps.newHashMap();

  public BlockShapeImpl(
      ResourceUrn urn, AssetType<?, BlockShapeData> assetType, BlockShapeData data) {
    super(urn, assetType);
    reload(data);
  }

  @Override
  public String getDisplayName() {
    return displayName;
  }

  public BlockMeshPart getMeshPart(BlockPart part) {
    return meshParts.get(part);
  }

  public boolean isBlockingSide(Side side) {
    return fullSide.get(side);
  }

  @Override
  protected void doReload(BlockShapeData data) {
    collisionShape.clear();
    displayName = data.getDisplayName();
    for (BlockPart part : BlockPart.values()) {
      this.meshParts.put(part, data.getMeshPart(part));
    }
    for (Side side : Side.values()) {
      this.fullSide.put(side, data.isBlockingSide(side));
    }
    this.baseCollisionShape = data.getCollisionShape();
    this.baseCollisionOffset.set(data.getCollisionOffset());
    collisionShape.put(Rotation.none(), baseCollisionShape);

    yawSymmetric = data.isYawSymmetric();
    pitchSymmetric = data.isPitchSymmetric();
    rollSymmetric = data.isRollSymmetric();
  }

  @Override
  protected void doDispose() {}

  public CollisionShape getCollisionShape(Rotation rot) {
    Rotation simplifiedRot = applySymmetry(rot);
    CollisionShape result = collisionShape.get(simplifiedRot);
    if (result == null && baseCollisionShape != null) {
      result = rotate(baseCollisionShape, simplifiedRot.getQuat4f());
      collisionShape.put(simplifiedRot, result);
    }
    return result;
  }

  public Vector3f getCollisionOffset(Rotation rot) {
    Rotation simplifiedRot = applySymmetry(rot);
    if (simplifiedRot.equals(Rotation.none())) {
      return new Vector3f(baseCollisionOffset);
    }
    return QuaternionUtil.quatRotate(
        simplifiedRot.getQuat4f(), baseCollisionOffset, new Vector3f());
  }

  @Override
  public boolean isCollisionYawSymmetric() {
    return yawSymmetric;
  }

  private Rotation applySymmetry(Rotation rot) {
    return Rotation.rotate(
        yawSymmetric ? Yaw.NONE : rot.getYaw(),
        pitchSymmetric ? Pitch.NONE : rot.getPitch(),
        rollSymmetric ? Roll.NONE : rot.getRoll());
  }

  private CollisionShape rotate(CollisionShape shape, Quat4f rot) {
    if (shape instanceof BoxShape) {
      BoxShape box = (BoxShape) shape;
      javax.vecmath.Vector3f extents = box.getHalfExtentsWithMargin(new javax.vecmath.Vector3f());
      com.bulletphysics.linearmath.QuaternionUtil.quatRotate(VecMath.to(rot), extents, extents);
      extents.absolute();
      return new BoxShape(extents);
    } else if (shape instanceof CompoundShape) {
      CompoundShape compound = (CompoundShape) shape;
      CompoundShape newShape = new CompoundShape();
      for (CompoundShapeChild child : compound.getChildList()) {
        CollisionShape rotatedChild = rotate(child.childShape, rot);
        javax.vecmath.Vector3f offset =
            com.bulletphysics.linearmath.QuaternionUtil.quatRotate(
                VecMath.to(rot), child.transform.origin, new javax.vecmath.Vector3f());
        newShape.addChildShape(
            new Transform(
                new javax.vecmath.Matrix4f(VecMath.to(Rotation.none().getQuat4f()), offset, 1.0f)),
            rotatedChild);
      }
      return newShape;
    } else if (shape instanceof ConvexHullShape) {
      ConvexHullShape convexHull = (ConvexHullShape) shape;
      ObjectArrayList<javax.vecmath.Vector3f> transformedVerts = new ObjectArrayList<>();
      for (javax.vecmath.Vector3f vert : convexHull.getPoints()) {
        transformedVerts.add(
            com.bulletphysics.linearmath.QuaternionUtil.quatRotate(
                VecMath.to(rot), vert, new javax.vecmath.Vector3f()));
      }
      return new ConvexHullShape(transformedVerts);
    }
    return shape;
  }
}
/**
 * A builder class to create JSON response for the Legacy Login RPC handler.
 *
 * @author [email protected] (Guibin Kong)
 */
public class LegacySigninJsonResponseBuilder {
  public static enum Status {
    OK("ok"),
    PASSWORD_ERROR("passwordError"),
    FEDERATED("federated"),
    EMAIL_NOT_EXIST("emailNotExist");

    private String jsonString;

    private Status(String jsonString) {
      this.jsonString = jsonString;
    }

    public String toJsonString() {
      return this.jsonString;
    }
  }

  /** Enumerates the fields in the JSON response. */
  protected static enum JsonField {
    STATUS,
    IDP,
    DISPLAY_NAME,
    PHOTO_URL
  }

  /** A map holds the value for each field. */
  protected Map<JsonField, Object> values = Maps.newEnumMap(JsonField.class);

  /**
   * Builds the JSON format response string.
   *
   * @return the JSON format response string
   * @throws JSONException if error occurs when building the JSONObject
   */
  public String build() throws JSONException {
    JSONObject result = new JSONObject();
    Iterator<JsonField> iterator = values.keySet().iterator();
    while (iterator.hasNext()) {
      JsonField key = iterator.next();
      Object value = values.get(key);
      if (value != null) {
        switch (key) {
          case STATUS:
            {
              Status status = (Status) value;
              result.put("status", status.toJsonString());
              break;
            }
          case IDP:
            {
              result.put("idp", value);
              break;
            }
          case DISPLAY_NAME:
            {
              result.put("displayName", value);
              break;
            }
          case PHOTO_URL:
            {
              result.put("photoUrl", value);
              break;
            }
        }
      }
    }
    return result.toString();
  }

  /**
   * Clears the builder.
   *
   * @return the builder itself
   */
  public LegacySigninJsonResponseBuilder reset() {
    values.clear();
    return this;
  }

  /**
   * Sets the registered field.
   *
   * @param registered whether the user is registered
   * @return the builder itself
   */
  public LegacySigninJsonResponseBuilder status(Status status) {
    if (status != null) {
      values.put(JsonField.STATUS, status);
    }
    return this;
  }

  /**
   * Sets the idp field.
   *
   * @param idp whether the user is registered
   * @return the builder itself
   */
  public LegacySigninJsonResponseBuilder idp(String idp) {
    values.put(JsonField.IDP, idp);
    return this;
  }

  /**
   * Sets the displayName field.
   *
   * @param displayName the display name of the user.
   * @return the builder itself
   */
  public LegacySigninJsonResponseBuilder displayName(String displayName) {
    values.put(JsonField.DISPLAY_NAME, displayName);
    return this;
  }

  /**
   * Sets the photoUrl field.
   *
   * @param photoUrl the photo url of the user.
   * @return the builder itself
   */
  public LegacySigninJsonResponseBuilder photoUrl(String photoUrl) {
    values.put(JsonField.PHOTO_URL, photoUrl);
    return this;
  }
}
public class PacketHandler {
  public static final EnumMap<Side, FMLEmbeddedChannel> channels = Maps.newEnumMap(Side.class);

  public static void init() {
    if (!channels.isEmpty()) // avoid duplicate inits..
    return;

    Codec codec = new Codec();

    codec.addDiscriminator(0, PacketMachine.class);
    codec.addDiscriminator(1, PacketEntity.class);
    codec.addDiscriminator(2, PacketDimInfo.class);
    codec.addDiscriminator(3, PacketSatellite.class);
    codec.addDiscriminator(4, PacketStellarInfo.class);
    codec.addDiscriminator(5, PacketItemModifcation.class);

    channels.putAll(
        NetworkRegistry.INSTANCE.newChannel(AdvancedRocketry.modId, codec, new HandlerServer()));

    // add handlers
    if (FMLCommonHandler.instance().getSide().isClient()) {
      // for the client
      FMLEmbeddedChannel channel = channels.get(Side.CLIENT);
      String codecName = channel.findChannelHandlerNameForType(Codec.class);
      channel.pipeline().addAfter(codecName, "ClientHandler", new HandlerClient());
    }
  }

  public static final void sendToServer(BasePacket packet) {
    channels
        .get(Side.CLIENT)
        .attr(FMLOutboundHandler.FML_MESSAGETARGET)
        .set(FMLOutboundHandler.OutboundTarget.TOSERVER);
    channels.get(Side.CLIENT).writeOutbound(packet);
  }

  @SideOnly(Side.SERVER)
  public static final void sendToPlayersTrackingEntity(BasePacket packet, Entity entity) {

    for (EntityPlayer player :
        ((WorldServer) entity.worldObj).getEntityTracker().getTrackingPlayers(entity)) {

      channels
          .get(Side.SERVER)
          .attr(FMLOutboundHandler.FML_MESSAGETARGET)
          .set(FMLOutboundHandler.OutboundTarget.PLAYER);
      channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
      channels.get(Side.SERVER).writeOutbound(packet);
    }
  }

  public static final void sendToAll(BasePacket packet) {
    channels
        .get(Side.SERVER)
        .attr(FMLOutboundHandler.FML_MESSAGETARGET)
        .set(FMLOutboundHandler.OutboundTarget.ALL);
    channels.get(Side.SERVER).writeOutbound(packet);
  }

  public static final void sendToPlayer(BasePacket packet, EntityPlayer player) {
    channels
        .get(Side.SERVER)
        .attr(FMLOutboundHandler.FML_MESSAGETARGET)
        .set(FMLOutboundHandler.OutboundTarget.PLAYER);
    channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
    channels.get(Side.SERVER).writeOutbound(packet);
  }

  public static final void sendToDispatcher(BasePacket packet, NetworkManager netman) {
    channels
        .get(Side.SERVER)
        .attr(FMLOutboundHandler.FML_MESSAGETARGET)
        .set(FMLOutboundHandler.OutboundTarget.DISPATCHER);
    channels
        .get(Side.SERVER)
        .attr(FMLOutboundHandler.FML_MESSAGETARGETARGS)
        .set(NetworkDispatcher.get(netman));
    channels.get(Side.SERVER).writeOutbound(packet);
  }

  public static final void sendToNearby(
      BasePacket packet, int dimId, int x, int y, int z, double dist) {
    channels
        .get(Side.SERVER)
        .attr(FMLOutboundHandler.FML_MESSAGETARGET)
        .set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);
    channels
        .get(Side.SERVER)
        .attr(FMLOutboundHandler.FML_MESSAGETARGETARGS)
        .set(new NetworkRegistry.TargetPoint(dimId, x, y, z, dist));
    channels.get(Side.SERVER).writeOutbound(packet);
  }

  private static final class Codec extends FMLIndexedMessageToMessageCodec<BasePacket> {

    @Override
    public void encodeInto(ChannelHandlerContext ctx, BasePacket msg, ByteBuf data)
        throws Exception {
      msg.write(data);
    }

    @Override
    public void decodeInto(ChannelHandlerContext ctx, ByteBuf data, BasePacket packet) {

      switch (FMLCommonHandler.instance().getEffectiveSide()) {
        case CLIENT:
          packet.readClient(data);
          // packet.executeClient((EntityPlayer)Minecraft.getMinecraft().thePlayer);
          break;
        case SERVER:
          INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
          packet.read(data);
          // packet.executeServer(((NetHandlerPlayServer) netHandler).playerEntity);
          break;
      }
    }
  }

  @Sharable
  @SideOnly(Side.CLIENT)
  private static final class HandlerClient extends SimpleChannelInboundHandler<BasePacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BasePacket packet) throws Exception {
      Minecraft mc = Minecraft.getMinecraft();
      packet.executeClient(mc.thePlayer); // actionClient(mc.theWorld, );
    }
  }

  @Sharable
  private static final class HandlerServer extends SimpleChannelInboundHandler<BasePacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BasePacket packet) throws Exception {
      if (FMLCommonHandler.instance().getEffectiveSide().isClient()) {
        // nothing on the client thread
        return;
      }
      EntityPlayerMP player =
          ((NetHandlerPlayServer) ctx.channel().attr(NetworkRegistry.NET_HANDLER).get())
              .playerEntity;
      packet.executeServer(player); // (player.worldObj, player);
    }
  }
}
Example #27
0
/** Chunk meshes are used to store the vertex data of tessellated chunks. */
@SuppressWarnings("PointlessArithmeticExpression")
public class ChunkMesh {

  /** Possible rendering types. */
  public enum RenderType {
    OPAQUE(0),
    TRANSLUCENT(1),
    BILLBOARD(2),
    WATER_AND_ICE(3);

    private int meshIndex;

    private RenderType(int index) {
      meshIndex = index;
    }

    public int getIndex() {
      return meshIndex;
    }
  }

  public enum RenderPhase {
    OPAQUE,
    ALPHA_REJECT,
    REFRACTIVE,
    Z_PRE_PASS
  }

  /* CONST */
  public static final int SIZE_VERTEX = 3;
  public static final int SIZE_TEX0 = 3;
  public static final int SIZE_TEX1 = 3;
  public static final int SIZE_COLOR = 1;
  public static final int SIZE_NORMAL = 3;

  private static final int OFFSET_VERTEX = 0;
  private static final int OFFSET_TEX_0 = OFFSET_VERTEX + SIZE_VERTEX * 4;
  private static final int OFFSET_TEX_1 = OFFSET_TEX_0 + SIZE_TEX0 * 4;
  private static final int OFFSET_COLOR = OFFSET_TEX_1 + SIZE_TEX1 * 4;
  private static final int OFFSET_NORMAL = OFFSET_COLOR + SIZE_COLOR * 4;
  private static final int STRIDE = OFFSET_NORMAL + SIZE_NORMAL * 4;

  /* VERTEX DATA */
  private final int[] vertexBuffers = new int[4];
  private final int[] idxBuffers = new int[4];
  private final int[] vertexCount = new int[4];

  /* STATS */
  private int triangleCount = -1;

  /* TEMPORARY DATA */
  private Map<RenderType, VertexElements> vertexElements = Maps.newEnumMap(RenderType.class);

  private boolean disposed;

  /* CONCURRENCY */
  private ReentrantLock lock = new ReentrantLock();

  /* MEASUREMENTS */
  private int timeToGenerateBlockVertices;
  private int timeToGenerateOptimizedBuffers;

  private GLBufferPool bufferPool;

  public ChunkMesh(GLBufferPool bufferPool) {
    this.bufferPool = bufferPool;
    for (RenderType type : RenderType.values()) {
      vertexElements.put(type, new VertexElements());
    }
  }

  public VertexElements getVertexElements(RenderType renderType) {
    return vertexElements.get(renderType);
  }

  public boolean isGenerated() {
    return vertexElements == null;
  }

  /**
   * Generates the VBOs from the pre calculated arrays.
   *
   * @return True if something was generated
   */
  public boolean generateVBOs() {
    if (lock.tryLock()) {
      try {
        // IMPORTANT: A mesh can only be generated once.
        if (vertexElements == null || disposed) {
          return false;
        }

        for (RenderType type : RenderType.values()) {
          generateVBO(type);
        }

        // Free unused space on the heap
        vertexElements = null;
        // Calculate the final amount of triangles
        triangleCount = (vertexCount[0] + vertexCount[1] + vertexCount[2] + vertexCount[3]) / 3;
      } finally {
        lock.unlock();
      }

      return true;
    }

    return false;
  }

  private void generateVBO(RenderType type) {
    VertexElements elements = vertexElements.get(type);
    int id = type.getIndex();
    if (!disposed && elements.finalIndices.limit() > 0 && elements.finalVertices.limit() > 0) {
      vertexBuffers[id] = bufferPool.get("chunkMesh");
      idxBuffers[id] = bufferPool.get("chunkMesh");
      vertexCount[id] = elements.finalIndices.limit();

      VertexBufferObjectUtil.bufferVboElementData(
          idxBuffers[id], elements.finalIndices, GL15.GL_STATIC_DRAW);
      VertexBufferObjectUtil.bufferVboData(
          vertexBuffers[id], elements.finalVertices, GL15.GL_STATIC_DRAW);
    } else {
      vertexBuffers[id] = 0;
      idxBuffers[id] = 0;
      vertexCount[id] = 0;
    }
  }

  private void renderVbo(int id) {
    if (lock.tryLock()) {
      try {
        if (vertexBuffers[id] <= 0 || disposed) {
          return;
        }

        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glEnableClientState(GL_COLOR_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);

        GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, idxBuffers[id]);
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vertexBuffers[id]);

        glVertexPointer(SIZE_VERTEX, GL11.GL_FLOAT, STRIDE, OFFSET_VERTEX);

        GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
        glTexCoordPointer(SIZE_TEX0, GL11.GL_FLOAT, STRIDE, OFFSET_TEX_0);

        GL13.glClientActiveTexture(GL13.GL_TEXTURE1);
        glTexCoordPointer(SIZE_TEX1, GL11.GL_FLOAT, STRIDE, OFFSET_TEX_1);

        glColorPointer(SIZE_COLOR * 4, GL11.GL_UNSIGNED_BYTE, STRIDE, OFFSET_COLOR);

        glNormalPointer(GL11.GL_FLOAT, STRIDE, OFFSET_NORMAL);

        GL11.glDrawElements(GL11.GL_TRIANGLES, vertexCount[id], GL11.GL_UNSIGNED_INT, 0);

        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
        GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);

        glDisableClientState(GL_NORMAL_ARRAY);
        glDisableClientState(GL_COLOR_ARRAY);
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        glDisableClientState(GL_VERTEX_ARRAY);

      } finally {
        lock.unlock();
      }
    }
  }

  public void render(RenderPhase type) {
    switch (type) {
      case OPAQUE:
        renderVbo(0);
        break;
      case ALPHA_REJECT:
        renderVbo(1);
        glDisable(GL_CULL_FACE);
        renderVbo(2);
        glEnable(GL_CULL_FACE);
        break;
      case REFRACTIVE:
        renderVbo(3);
        break;
      default:
        break;
    }
  }

  public void dispose() {
    lock.lock();
    try {
      if (!disposed) {
        for (int i = 0; i < vertexBuffers.length; i++) {
          int id = vertexBuffers[i];
          if (id != 0) {
            bufferPool.dispose(id);
            vertexBuffers[i] = 0;
          }

          id = idxBuffers[i];
          if (id != 0) {
            bufferPool.dispose(id);
            idxBuffers[i] = 0;
          }
        }

        disposed = true;
        vertexElements = null;
      }
    } finally {
      lock.unlock();
    }
  }

  public boolean isDisposed() {
    return disposed;
  }

  public int triangleCount(RenderPhase phase) {
    if (phase == RenderPhase.OPAQUE) {
      return vertexCount[0] / 3;
    } else if (phase == RenderPhase.ALPHA_REJECT) {
      return (vertexCount[1] + vertexCount[2]) / 3;
    } else {
      return vertexCount[3] / 3;
    }
  }

  public int triangleCount() {
    return triangleCount;
  }

  public boolean isEmpty() {
    return triangleCount == 0;
  }

  public void setTimeToGenerateBlockVertices(int timeToGenerateBlockVertices) {
    this.timeToGenerateBlockVertices = timeToGenerateBlockVertices;
  }

  public int getTimeToGenerateBlockVertices() {
    return timeToGenerateBlockVertices;
  }

  public void setTimeToGenerateOptimizedBuffers(int timeToGenerateOptimizedBuffers) {
    this.timeToGenerateOptimizedBuffers = timeToGenerateOptimizedBuffers;
  }

  public int getTimeToGenerateOptimizedBuffers() {
    return timeToGenerateOptimizedBuffers;
  }

  /** Data structure for storing vertex data. Abused like a "struct" in C/C++. Just sad. */
  public static class VertexElements {

    public final TFloatList normals;
    public final TFloatList vertices;
    public final TFloatList tex;
    public final TFloatList color;
    public final TIntList indices;
    public final TIntList flags;
    public int vertexCount;

    public IntBuffer finalVertices;
    public IntBuffer finalIndices;

    public VertexElements() {
      vertexCount = 0;
      normals = new TFloatArrayList();
      vertices = new TFloatArrayList();
      tex = new TFloatArrayList();
      color = new TFloatArrayList();
      indices = new TIntArrayList();
      flags = new TIntArrayList();
    }
  }
}
Example #28
0
public class EntityHumanNPC extends EntityPlayer implements NPCHolder, SkinnableEntity {
  private final Map<PathType, Float> bz = Maps.newEnumMap(PathType.class);
  private PlayerControllerJump controllerJump;
  private PlayerControllerLook controllerLook;
  private PlayerControllerMove controllerMove;
  private int jumpTicks = 0;
  private PlayerNavigation navigation;
  private final CitizensNPC npc;
  private final Location packetLocationCache = new Location(null, 0, 0, 0);
  private final SkinPacketTracker skinTracker;
  private int updateCounter = 0;

  public EntityHumanNPC(
      MinecraftServer minecraftServer,
      WorldServer world,
      GameProfile gameProfile,
      PlayerInteractManager playerInteractManager,
      NPC npc) {
    super(minecraftServer, world, gameProfile, playerInteractManager);

    this.npc = (CitizensNPC) npc;
    if (npc != null) {
      skinTracker = new SkinPacketTracker(this);
      playerInteractManager.setGameMode(EnumGamemode.SURVIVAL);
      initialise(minecraftServer);
    } else {
      skinTracker = null;
    }
  }

  @Override
  protected void a(double d0, boolean flag, IBlockData block, BlockPosition blockposition) {
    if (npc == null || !npc.isFlyable()) {
      super.a(d0, flag, block, blockposition);
    }
  }

  public float a(PathType pathtype) {
    return this.bz.containsKey(pathtype) ? this.bz.get(pathtype).floatValue() : pathtype.a();
  }

  public void a(PathType pathtype, float f) {
    this.bz.put(pathtype, Float.valueOf(f));
  }

  @Override
  public void A_() {
    super.A_();
    if (npc == null) return;
    if (updateCounter + 1 > Setting.PACKET_UPDATE_DELAY.asInt()) {
      updateEffects = true;
    }
    livingEntityBaseTick();

    boolean navigating = npc.getNavigator().isNavigating();
    updatePackets(navigating);
    if (!navigating
        && getBukkitEntity() != null
        && npc.getTrait(Gravity.class).hasGravity()
        && Util.isLoaded(getBukkitEntity().getLocation(LOADED_LOCATION))) {
      g(0, 0);
    }
    if (Math.abs(motX) < EPSILON && Math.abs(motY) < EPSILON && Math.abs(motZ) < EPSILON) {
      motX = motY = motZ = 0;
    }
    if (navigating) {
      if (!NMSImpl.isNavigationFinished(navigation)) {
        NMSImpl.updateNavigation(navigation);
      }
      moveOnCurrentHeading();
    }
    NMSImpl.updateAI(this);

    if (noDamageTicks > 0) {
      --noDamageTicks;
    }

    npc.update();
  }

  @Override
  public void collide(net.minecraft.server.v1_11_R1.Entity entity) {
    // this method is called by both the entities involved - cancelling
    // it will not stop the NPC from moving.
    super.collide(entity);
    if (npc != null) {
      Util.callCollisionEvent(npc, entity.getBukkitEntity());
    }
  }

  @Override
  public boolean damageEntity(DamageSource damagesource, float f) {
    // knock back velocity is cancelled and sent to client for handling when
    // the entity is a player. there is no client so make this happen
    // manually.
    boolean damaged = super.damageEntity(damagesource, f);
    if (damaged && velocityChanged) {
      velocityChanged = false;
      Bukkit.getScheduler()
          .runTask(
              CitizensAPI.getPlugin(),
              new Runnable() {
                @Override
                public void run() {
                  EntityHumanNPC.this.velocityChanged = true;
                }
              });
    }
    return damaged;
  }

  @Override
  public void die(DamageSource damagesource) {
    // players that die are not normally removed from the world. when the
    // NPC dies, we are done with the instance and it should be removed.
    if (dead) {
      return;
    }
    super.die(damagesource);
    Bukkit.getScheduler()
        .runTaskLater(
            CitizensAPI.getPlugin(),
            new Runnable() {
              @Override
              public void run() {
                world.removeEntity(EntityHumanNPC.this);
              }
            },
            35); // give enough time for death and smoke animation
  }

  @Override
  public void e(float f, float f1) {
    if (npc == null || !npc.isFlyable()) {
      super.e(f, f1);
    }
  }

  @Override
  public void enderTeleportTo(double d0, double d1, double d2) {
    if (npc == null) super.enderTeleportTo(d0, d1, d2);
    NPCEnderTeleportEvent event = new NPCEnderTeleportEvent(npc);
    Bukkit.getPluginManager().callEvent(event);
    if (!event.isCancelled()) {
      super.enderTeleportTo(d0, d1, d2);
    }
  }

  @Override
  public void f(double x, double y, double z) {
    if (npc == null) {
      super.f(x, y, z);
      return;
    }
    if (NPCPushEvent.getHandlerList().getRegisteredListeners().length == 0) {
      if (!npc.data().get(NPC.DEFAULT_PROTECTED_METADATA, true)) {
        super.f(x, y, z);
      }
      return;
    }
    Vector vector = new Vector(x, y, z);
    NPCPushEvent event = Util.callPushEvent(npc, vector);
    if (!event.isCancelled()) {
      vector = event.getCollisionVector();
      super.f(vector.getX(), vector.getY(), vector.getZ());
    }
    // when another entity collides, this method is called to push the
    // NPC so we prevent it from doing anything if the event is
    // cancelled.
  }

  @Override
  public void g(float f, float f1) {
    if (npc == null || !npc.isFlyable()) {
      super.g(f, f1);
    } else {
      NMSImpl.flyingMoveLogic(this, f, f1);
    }
  }

  @Override
  public CraftPlayer getBukkitEntity() {
    if (npc != null && !(bukkitEntity instanceof NPCHolder)) {
      bukkitEntity = new PlayerNPC(this);
    }
    return super.getBukkitEntity();
  }

  public PlayerControllerJump getControllerJump() {
    return controllerJump;
  }

  public PlayerControllerMove getControllerMove() {
    return controllerMove;
  }

  public NavigationAbstract getNavigation() {
    return navigation;
  }

  @Override
  public NPC getNPC() {
    return npc;
  }

  @Override
  public IChatBaseComponent getPlayerListName() {
    if (Setting.REMOVE_PLAYERS_FROM_PLAYER_LIST.asBoolean()) {
      return new ChatComponentText("");
    }
    return super.getPlayerListName();
  }

  @Override
  public String getSkinName() {
    MetadataStore meta = npc.data();

    String skinName = meta.get(NPC.PLAYER_SKIN_UUID_METADATA);
    if (skinName == null) {
      skinName = ChatColor.stripColor(getName());
    }
    return skinName.toLowerCase();
  }

  @Override
  public SkinPacketTracker getSkinTracker() {
    return skinTracker;
  }

  private void initialise(MinecraftServer minecraftServer) {
    Socket socket = new EmptySocket();
    NetworkManager conn = null;
    try {
      conn = new EmptyNetworkManager(EnumProtocolDirection.CLIENTBOUND);
      playerConnection = new EmptyNetHandler(minecraftServer, conn, this);
      conn.setPacketListener(playerConnection);
      socket.close();
    } catch (IOException e) {
      // swallow
    }

    AttributeInstance range = getAttributeInstance(GenericAttributes.FOLLOW_RANGE);
    if (range == null) {
      range = getAttributeMap().b(GenericAttributes.FOLLOW_RANGE);
    }
    range.setValue(Setting.DEFAULT_PATHFINDING_RANGE.asDouble());

    controllerJump = new PlayerControllerJump(this);
    controllerLook = new PlayerControllerLook(this);
    controllerMove = new PlayerControllerMove(this);
    navigation = new PlayerNavigation(this, world);
    NMS.setStepHeight(getBukkitEntity(), 1); // the default (0) breaks step climbing

    setSkinFlags((byte) 0xFF);
  }

  @Override
  public boolean isCollidable() {
    return npc == null ? super.isCollidable() : npc.data().get(NPC.COLLIDABLE_METADATA, true);
  }

  public boolean isNavigating() {
    return npc.getNavigator().isNavigating();
  }

  public void livingEntityBaseTick() {
    cA();
    this.aC = this.aD;
    this.aJ = this.aK;
    if (this.hurtTicks > 0) {
      this.hurtTicks -= 1;
    }
    tickPotionEffects();
    this.aZ = this.aY;
    this.aO = this.aN;
    this.aQ = this.aP;
    this.lastYaw = this.yaw;
    this.lastPitch = this.pitch;
  }

  @Override
  public boolean m_() {
    if (npc == null || !npc.isFlyable()) {
      return super.m_();
    } else {
      return false;
    }
  }

  private void moveOnCurrentHeading() {
    if (bd) {
      if (onGround && jumpTicks == 0) {
        cm();
        jumpTicks = 10;
      }
    } else {
      jumpTicks = 0;
    }
    be *= 0.98F;
    bf *= 0.98F;
    bg *= 0.9F;
    g(be, bf); // movement method
    NMS.setHeadYaw(getBukkitEntity(), yaw);
    if (jumpTicks > 0) {
      jumpTicks--;
    }
  }

  public void setMoveDestination(double x, double y, double z, double speed) {
    controllerMove.a(x, y, z, speed);
  }

  public void setShouldJump() {
    controllerJump.a();
  }

  @Override
  public void setSkinFlags(byte flags) {
    // set skin flag byte
    getDataWatcher().set(EntityHuman.bq, flags);
  }

  @Override
  public void setSkinName(String name) {
    setSkinName(name, false);
  }

  @Override
  public void setSkinName(String name, boolean forceUpdate) {
    Preconditions.checkNotNull(name);

    npc.data().setPersistent(NPC.PLAYER_SKIN_UUID_METADATA, name.toLowerCase());
    skinTracker.notifySkinChange(forceUpdate);
  }

  public void setTargetLook(Entity target, float yawOffset, float renderOffset) {
    controllerLook.a(target, yawOffset, renderOffset);
  }

  public void setTargetLook(Location target) {
    controllerLook.a(target.getX(), target.getY(), target.getZ(), 10, 40);
  }

  public void updateAI() {
    controllerMove.c();
    controllerLook.a();
    controllerJump.b();
  }

  private void updatePackets(boolean navigating) {
    if (updateCounter++ <= Setting.PACKET_UPDATE_DELAY.asInt()) return;

    updateCounter = 0;
    Location current = getBukkitEntity().getLocation(packetLocationCache);
    Packet<?>[] packets =
        new Packet[navigating ? EnumItemSlot.values().length : EnumItemSlot.values().length + 1];
    if (!navigating) {
      packets[5] =
          new PacketPlayOutEntityHeadRotation(
              this, (byte) MathHelper.d(NMSImpl.getHeadYaw(this) * 256.0F / 360.0F));
    }
    int i = 0;
    for (EnumItemSlot slot : EnumItemSlot.values()) {
      packets[i++] = new PacketPlayOutEntityEquipment(getId(), slot, getEquipment(slot));
    }
    NMSImpl.sendPacketsNearby(getBukkitEntity(), current, packets);
  }

  public void updatePathfindingRange(float pathfindingRange) {
    this.navigation.setRange(pathfindingRange);
  }

  public static class PlayerNPC extends CraftPlayer implements NPCHolder, SkinnableEntity {
    private final CraftServer cserver;
    private final CitizensNPC npc;

    private PlayerNPC(EntityHumanNPC entity) {
      super((CraftServer) Bukkit.getServer(), entity);
      this.npc = entity.npc;
      this.cserver = (CraftServer) Bukkit.getServer();
      npc.getTrait(Inventory.class);
    }

    @Override
    public Player getBukkitEntity() {
      return this;
    }

    @Override
    public EntityHumanNPC getHandle() {
      return (EntityHumanNPC) this.entity;
    }

    @Override
    public List<MetadataValue> getMetadata(String metadataKey) {
      return cserver.getEntityMetadata().getMetadata(this, metadataKey);
    }

    @Override
    public NPC getNPC() {
      return npc;
    }

    @Override
    public String getSkinName() {
      return ((SkinnableEntity) this.entity).getSkinName();
    }

    @Override
    public SkinPacketTracker getSkinTracker() {
      return ((SkinnableEntity) this.entity).getSkinTracker();
    }

    @Override
    public boolean hasMetadata(String metadataKey) {
      return cserver.getEntityMetadata().hasMetadata(this, metadataKey);
    }

    @Override
    public void removeMetadata(String metadataKey, Plugin owningPlugin) {
      cserver.getEntityMetadata().removeMetadata(this, metadataKey, owningPlugin);
    }

    @Override
    public void setMetadata(String metadataKey, MetadataValue newMetadataValue) {
      cserver.getEntityMetadata().setMetadata(this, metadataKey, newMetadataValue);
    }

    @Override
    public void setSkinFlags(byte flags) {
      ((SkinnableEntity) this.entity).setSkinFlags(flags);
    }

    @Override
    public void setSkinName(String name) {
      ((SkinnableEntity) this.entity).setSkinName(name);
    }

    @Override
    public void setSkinName(String skinName, boolean forceUpdate) {
      ((SkinnableEntity) this.entity).setSkinName(skinName, forceUpdate);
    }
  }

  private static final float EPSILON = 0.005F;
  private static final Location LOADED_LOCATION = new Location(null, 0, 0, 0);
}
/** Default implementation for {@link RestRequestBuilderFactory}. */
public class DefaultRestRequestBuilderFactory implements RestRequestBuilderFactory {
  private static final Map<HttpMethod, Method> HTTP_METHODS = Maps.newEnumMap(HttpMethod.class);
  private static final String JSON_UTF8 = "application/json; charset=utf-8";

  static {
    HTTP_METHODS.put(HttpMethod.GET, RequestBuilder.GET);
    HTTP_METHODS.put(HttpMethod.POST, RequestBuilder.POST);
    HTTP_METHODS.put(HttpMethod.PUT, RequestBuilder.PUT);
    HTTP_METHODS.put(HttpMethod.DELETE, RequestBuilder.DELETE);
    HTTP_METHODS.put(HttpMethod.HEAD, RequestBuilder.HEAD);
  }

  private final ActionMetadataProvider metadataProvider;
  private final Serialization serialization;
  private final HttpRequestBuilderFactory httpRequestBuilderFactory;
  private final UrlUtils urlUtils;
  private final Multimap<HttpMethod, RestParameter> globalHeaderParams;
  private final Multimap<HttpMethod, RestParameter> globalQueryParams;
  private final String baseUrl;
  private final String securityHeaderName;
  private final Integer requestTimeoutMs;

  @Inject
  DefaultRestRequestBuilderFactory(
      ActionMetadataProvider metadataProvider,
      Serialization serialization,
      HttpRequestBuilderFactory httpRequestBuilderFactory,
      UrlUtils urlUtils,
      @GlobalHeaderParams Multimap<HttpMethod, RestParameter> globalHeaderParams,
      @GlobalQueryParams Multimap<HttpMethod, RestParameter> globalQueryParams,
      @RestApplicationPath String baseUrl,
      @XsrfHeaderName String securityHeaderName,
      @RequestTimeout Integer requestTimeoutMs) {
    this.metadataProvider = metadataProvider;
    this.serialization = serialization;
    this.httpRequestBuilderFactory = httpRequestBuilderFactory;
    this.urlUtils = urlUtils;
    this.globalHeaderParams = globalHeaderParams;
    this.globalQueryParams = globalQueryParams;
    this.baseUrl = baseUrl;
    this.securityHeaderName = securityHeaderName;
    this.requestTimeoutMs = requestTimeoutMs;
  }

  @Override
  public <A extends RestAction<?>> RequestBuilder build(A action, String securityToken)
      throws ActionException {
    Method httpMethod = HTTP_METHODS.get(action.getHttpMethod());
    String url = buildUrl(action);
    String xsrfToken = action.isSecured() ? securityToken : "";

    RequestBuilder requestBuilder = httpRequestBuilderFactory.create(httpMethod, url);
    requestBuilder.setTimeoutMillis(requestTimeoutMs);

    buildHeaders(requestBuilder, xsrfToken, action);
    buildBody(requestBuilder, action);

    return requestBuilder;
  }

  /**
   * Encodes the given {@link RestParameter} as a path parameter. The default implementation
   * delegates to {@link UrlUtils#encodePathSegment(String)}.
   *
   * @param value the value to encode.
   * @return the encoded path parameter.
   * @throws ActionException if an exception occurred while encoding the path parameter.
   * @see #encode(com.gwtplatform.dispatch.rest.shared.RestParameter)
   */
  protected String encodePathParam(String value) throws ActionException {
    return urlUtils.encodePathSegment(value);
  }

  /**
   * Encodes the given {@link RestParameter} as a query parameter. The default implementation
   * delegates to {@link UrlUtils#encodeQueryString(String)}.
   *
   * @param value the value to encode.
   * @return the encoded query parameter.
   * @throws ActionException if an exception occurred while encoding the query parameter.
   * @see #encode(com.gwtplatform.dispatch.rest.shared.RestParameter)
   */
  protected String encodeQueryParam(String value) throws ActionException {
    return urlUtils.encodeQueryString(value);
  }

  /**
   * Verify if the provided <code>bodyType</code> can be serialized.
   *
   * @param bodyType the parameterized type to verify if it can be serialized.
   * @return <code>true</code> if <code>bodyType</code> can be serialized, otherwise <code>false
   *     </code>.
   */
  protected boolean canSerialize(String bodyType) {
    return serialization.canSerialize(bodyType);
  }

  /**
   * Serialize the given object. We assume {@link #canSerialize(String)} returns <code>true</code>
   * or a runtime exception may be thrown.
   *
   * @param object the object to serialize.
   * @param bodyType The parameterized type of the object to serialize.
   * @return The serialized string.
   */
  protected String serialize(Object object, String bodyType) {
    return serialization.serialize(object, bodyType);
  }

  private void buildHeaders(RequestBuilder requestBuilder, String xsrfToken, RestAction<?> action)
      throws ActionException {
    String path = action.getPath();
    List<RestParameter> actionParams = action.getHeaderParams();
    Collection<RestParameter> applicableGlobalParams =
        globalHeaderParams.get(action.getHttpMethod());

    // By setting the most generic headers first, we make sure they can be overridden by more
    // specific ones
    requestBuilder.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    requestBuilder.setHeader(HttpHeaders.CONTENT_TYPE, JSON_UTF8);

    if (!isAbsoluteUrl(path)) {
      requestBuilder.setHeader(MODULE_BASE_HEADER, baseUrl);
    }

    if (!Strings.isNullOrEmpty(xsrfToken)) {
      requestBuilder.setHeader(securityHeaderName, xsrfToken);
    }

    for (RestParameter parameter : applicableGlobalParams) {
      String value = parameter.getStringValue();

      if (value != null) {
        requestBuilder.setHeader(parameter.getName(), value);
      }
    }

    for (RestParameter param : actionParams) {
      requestBuilder.setHeader(param.getName(), param.getStringValue());
    }
  }

  private <A extends RestAction<?>> void buildBody(RequestBuilder requestBuilder, A action)
      throws ActionException {
    if (action.hasFormParams()) {
      requestBuilder.setRequestData(buildQueryString(action.getFormParams()));
    } else if (action.hasBodyParam()) {
      requestBuilder.setRequestData(getSerializedValue(action, action.getBodyParam()));
    }
  }

  private String buildUrl(RestAction<?> action) throws ActionException {
    List<RestParameter> queryParams = getGlobalQueryParamsForAction(action);
    queryParams.addAll(action.getQueryParams());

    String queryString = buildQueryString(queryParams);
    if (!queryString.isEmpty()) {
      queryString = "?" + queryString;
    }

    String path = buildPath(action.getPath(), action.getPathParams());

    String prefix = "";
    if (!isAbsoluteUrl(path)) {
      prefix = baseUrl;
    }

    return prefix + path + queryString;
  }

  private List<RestParameter> getGlobalQueryParamsForAction(RestAction<?> action) {
    List<RestParameter> queryParams = Lists.newArrayList();

    for (RestParameter parameter : globalQueryParams.get(action.getHttpMethod())) {
      String value = parameter.getStringValue();

      if (value != null) {
        queryParams.add(new RestParameter(parameter.getName(), value));
      }
    }

    return queryParams;
  }

  private boolean isAbsoluteUrl(String path) {
    return path.startsWith("http://") || path.startsWith("https://");
  }

  private String buildPath(String rawPath, List<RestParameter> params) throws ActionException {
    String path = rawPath;

    for (RestParameter param : params) {
      String encodedParam = encodePathParam(param.getStringValue());
      path = path.replace("{" + param.getName() + "}", encodedParam);
    }

    return path;
  }

  private String buildQueryString(List<RestParameter> params) throws ActionException {
    StringBuilder queryString = new StringBuilder();

    for (RestParameter param : params) {
      queryString
          .append("&")
          .append(param.getName())
          .append("=")
          .append(encodeQueryParam(param.getStringValue()));
    }

    if (queryString.length() != 0) {
      queryString.deleteCharAt(0);
    }

    return queryString.toString();
  }

  private String getSerializedValue(RestAction<?> action, Object object) throws ActionException {
    String bodyType = (String) metadataProvider.getValue(action, MetadataType.BODY_TYPE);

    if (bodyType != null && canSerialize(bodyType)) {
      try {
        return serialize(object, bodyType);
      } catch (JsonMappingException e) {
        throw new ActionException(
            "Unable to serialize request body. An unexpected error occurred.", e);
      }
    }

    throw new ActionException("Unable to serialize request body. No serializer found.");
  }
}