OGRGeometryCollection::~OGRGeometryCollection()

{
    empty();
}
Beispiel #2
0
void MotionMaster::MoveIdle()
{
    if( empty() || !isStatic( top() ) )
        push( &si_idleMovement );
}
Beispiel #3
0
Status DatabasePlugin::call(const PluginRequest& request,
                            PluginResponse& response) {
  if (request.count("action") == 0) {
    return Status(1, "Database plugin must include a request action");
  }

  // Get a domain/key, which are used for most database plugin actions.
  auto domain = (request.count("domain") > 0) ? request.at("domain") : "";
  auto key = (request.count("key") > 0) ? request.at("key") : "";

  if (request.at("action") == "reset") {
    WriteLock lock(kDatabaseReset);
    DatabasePlugin::kDBInitialized = false;
    // Prevent RocksDB reentrancy by logger plugins during plugin setup.
    VLOG(1) << "Resetting the database plugin: " << getName();
    auto status = this->reset();
    if (!status.ok()) {
      // The active database could not be reset, fallback to an ephemeral.
      Registry::get().setActive("database", "ephemeral");
      LOG(WARNING) << "Unable to reset database plugin: " << getName();
    }
    DatabasePlugin::kDBInitialized = true;
    return status;
  }

  // Switch over the possible database plugin actions.
  ReadLock lock(kDatabaseReset);
  if (request.at("action") == "get") {
    std::string value;
    auto status = this->get(domain, key, value);
    response.push_back({{"v", value}});
    return status;
  } else if (request.at("action") == "put") {
    if (request.count("value") == 0) {
      return Status(1, "Database plugin put action requires a value");
    }
    return this->put(domain, key, request.at("value"));
  } else if (request.at("action") == "remove") {
    return this->remove(domain, key);
  } else if (request.at("action") == "remove_range") {
    auto key_high = (request.count("high") > 0) ? request.at("key_high") : "";
    if (!key_high.empty() && !key.empty()) {
      return this->removeRange(domain, key, key_high);
    }
    return Status(1, "Missing range");
  } else if (request.at("action") == "scan") {
    // Accumulate scanned keys into a vector.
    std::vector<std::string> keys;
    // Optionally allow the caller to request a max number of keys.
    size_t max = 0;
    if (request.count("max") > 0) {
      max = std::stoul(request.at("max"));
    }
    auto status = this->scan(domain, keys, request.at("prefix"), max);
    for (const auto& k : keys) {
      response.push_back({{"k", k}});
    }
    return status;
  }

  return Status(1, "Unknown database plugin action");
}
int SoapyRPCSocket::multicastJoin(const std::string &group, const bool loop, const int ttl, int iface)
{
    /*
     * Multicast join docs:
     * http://www.tldp.org/HOWTO/Multicast-HOWTO-6.html
     * http://www.tenouk.com/Module41c.html
     */

    //lookup group url
    SoapyURL urlObj(group);
    SockAddrData addr;
    const auto errorMsg = urlObj.toSockAddr(addr);
    if (not errorMsg.empty())
    {
        this->reportError("getaddrinfo("+group+")", errorMsg);
        return -1;
    }

    //create socket if null
    if (this->null()) _sock = ::socket(addr.addr()->sa_family, SOCK_DGRAM, 0);
    if (this->null()) return -1;
    int ret = 0;

    int loopInt = loop?1:0;

    switch(addr.addr()->sa_family)
    {
    case AF_INET: {

        //setup IP_MULTICAST_LOOP
        ret = ::setsockopt(_sock, IPPROTO_IP, IP_MULTICAST_LOOP, (const char *)&loopInt, sizeof(loopInt));
        if (ret != 0)
        {
            this->reportError("setsockopt(IP_MULTICAST_LOOP)");
            return -1;
        }

        //setup IP_MULTICAST_TTL
        ret = ::setsockopt(_sock, IPPROTO_IP, IP_MULTICAST_TTL, (const char *)&ttl, sizeof(ttl));
        if (ret != 0)
        {
            this->reportError("setsockopt(IP_MULTICAST_TTL)");
            return -1;
        }

        //setup IP_ADD_MEMBERSHIP
        auto *addr_in = (const struct sockaddr_in *)addr.addr();
        struct ip_mreq mreq;
        mreq.imr_multiaddr = addr_in->sin_addr;
        mreq.imr_interface.s_addr = INADDR_ANY;
        ret = ::setsockopt(_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char *)&mreq, sizeof(mreq));
        if (ret != 0)
        {
            this->reportError("setsockopt(IP_ADD_MEMBERSHIP)");
            return -1;
        }
        break;
    }
    case AF_INET6: {

        //setup IPV6_MULTICAST_LOOP
        ret = ::setsockopt(_sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (const char *)&loopInt, sizeof(loopInt));
        if (ret != 0)
        {
            this->reportError("setsockopt(IPV6_MULTICAST_LOOP)");
            return -1;
        }

        //setup IPV6_MULTICAST_HOPS
        ret = ::setsockopt(_sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (const char *)&ttl, sizeof(ttl));
        if (ret != 0)
        {
            this->reportError("setsockopt(IPV6_MULTICAST_HOPS)");
            return -1;
        }

        //setup IPV6_MULTICAST_IF
        if (iface == 0) iface = getDefaultIfaceIndex();
        if (iface != 0)
        {
            ret = ::setsockopt(_sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, (const char *)&iface, sizeof(iface));
            if (ret != 0)
            {
                this->reportError("setsockopt(IPV6_MULTICAST_IF)");
                return -1;
            }
        }

        //setup IPV6_ADD_MEMBERSHIP
        auto *addr_in6 = (const struct sockaddr_in6 *)addr.addr();
        struct ipv6_mreq mreq6;
        mreq6.ipv6mr_multiaddr = addr_in6->sin6_addr;
        mreq6.ipv6mr_interface = iface;
        ret = ::setsockopt(_sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (const char *)&mreq6, sizeof(mreq6));
        if (ret != 0)
        {
            this->reportError("setsockopt(IPV6_ADD_MEMBERSHIP)");
            return -1;
        }
        break;
    }
    default:
        break;
    }

    return 0;
}
Beispiel #5
0
SrcKey RegionDesc::start() const {
  assertx(!empty());
  return m_blocks[0]->start();
}
req::ptr<File> HttpStreamWrapper::open(const String& filename,
                                       const String& mode, int /*options*/,
                                       const req::ptr<StreamContext>& context) {
  if (RuntimeOption::ServerHttpSafeMode && !is_cli_mode()) {
    return nullptr;
  }

  if (strncmp(filename.data(), "http://",  sizeof("http://")  - 1) &&
      strncmp(filename.data(), "https://", sizeof("https://") - 1)) {
    return nullptr;
  }

  Array headers;
  String method = s_GET;
  String post_data = null_string;
  String proxy_host;
  String proxy_user;
  String proxy_pass;
  int proxy_port = -1;
  int max_redirs = 20;
  int timeout = -1;
  bool ignore_errors = false;

  if (context && !context->getOptions().isNull() &&
      !context->getOptions()[s_http].isNull()) {
    Array opts = context->getOptions()[s_http].toArray();
    if (opts.exists(s_method)) {
      method = opts[s_method].toString();
    }
    if (opts.exists(s_header)) {
      Array lines;
      if (opts[s_header].isString()) {
        lines = StringUtil::Explode(
          opts[s_header].toString(), "\r\n").toArray();
      } else if (opts[s_header].isArray()) {
        lines = opts[s_header];
      }

      for (ArrayIter it(lines); it; ++it) {
        Array parts = StringUtil::Explode(
          it.second().toString(), ":", 2).toArray();
        headers.set(parts.rvalAt(0).unboxed().tv(), parts.rvalAt(1).tv());
      }
    }
    if (opts.exists(s_user_agent) && !headers.exists(s_User_Agent)) {
      headers.set(s_User_Agent, opts[s_user_agent]);
    }
    if (opts.exists(s_max_redirects)) {
      max_redirs = opts[s_max_redirects].toInt64();
    }
    if (opts.exists(s_timeout)) {
      timeout = opts[s_timeout].toInt64();
    }
    if (opts.exists(s_ignore_errors)) {
      ignore_errors = opts[s_ignore_errors].toBoolean();
    }
    if (opts.exists(s_proxy)) {
      Variant host = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_HOST);
      Variant port = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_PORT);
      if (!same(host, false) && !same(port, false)) {
        proxy_host = host.toString();
        proxy_port = port.toInt64();
        Variant user = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_USER);
        Variant pass = f_parse_url(opts[s_proxy].toString(), k_PHP_URL_PASS);
        if (!same(user, false) && !same(pass, false)) {
          proxy_user = user.toString();
          proxy_pass = pass.toString();
        }
      }
    }
    post_data = opts[s_content].toString();
  }

  if (!headers.exists(s_User_Agent)) {
    auto default_user_agent = ThreadInfo::s_threadInfo.getNoCheck()
      ->m_reqInjectionData.getUserAgent();
    if (!default_user_agent.empty()) {
      headers.set(s_User_Agent, default_user_agent);
    }
  }
  auto file = req::make<UrlFile>(method.data(), headers,
                                    post_data, max_redirs,
                                    timeout, ignore_errors);
  file->setStreamContext(context);
  file->setProxy(proxy_host, proxy_port, proxy_user, proxy_pass);
  bool ret = file->open(filename, mode);
  if (!ret) {
    raise_warning("Failed to open %s (%s)", filename.data(),
                  file->getLastError().c_str());
    return nullptr;
  }
  return file;
}
void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile)
{
	int Seed = m_ChunkGenerator.GetSeed();
	eDimension Dimension = StringToDimension(a_IniFile.GetValue("General", "Dimension", "Overworld"));
	auto seaLevel = a_IniFile.GetValueI("Generator", "SeaLevel");

	AString Finishers = a_IniFile.GetValueSet("Generator", "Finishers", "");

	// Create all requested finishers:
	AStringVector Str = StringSplitAndTrim(Finishers, ",");
	for (AStringVector::const_iterator itr = Str.begin(); itr != Str.end(); ++itr)
	{
		auto split = StringSplitAndTrim(*itr, ":");
		if (split.empty())
		{
			continue;
		}
		const auto & finisher = split[0];
		// Finishers, alpha-sorted:
		if (NoCaseCompare(finisher, "Animals") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenPassiveMobs(Seed, a_IniFile, Dimension)));
		}
		else if (NoCaseCompare(finisher, "BottomLava") == 0)
		{
			int DefaultBottomLavaLevel = (Dimension == dimNether) ? 30 : 10;
			int BottomLavaLevel = a_IniFile.GetValueSetI("Generator", "BottomLavaLevel", DefaultBottomLavaLevel);
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenBottomLava(BottomLavaLevel)));
		}
		else if (NoCaseCompare(finisher, "DeadBushes") == 0)
		{
			// A list with all the allowed biomes.
			cFinishGenSingleTopBlock::BiomeList AllowedBiomes;
			AllowedBiomes.push_back(biDesert);
			AllowedBiomes.push_back(biDesertHills);
			AllowedBiomes.push_back(biDesertM);
			AllowedBiomes.push_back(biMesa);
			AllowedBiomes.push_back(biMesaBryce);
			AllowedBiomes.push_back(biMesaPlateau);
			AllowedBiomes.push_back(biMesaPlateauF);
			AllowedBiomes.push_back(biMesaPlateauFM);
			AllowedBiomes.push_back(biMesaPlateauM);
			AllowedBiomes.push_back(biMegaTaiga);

			// A list with all the allowed blocks that can be below the dead bush.
			cFinishGenSingleTopBlock::BlockList AllowedBlocks;
			AllowedBlocks.push_back(E_BLOCK_SAND);
			AllowedBlocks.push_back(E_BLOCK_HARDENED_CLAY);
			AllowedBlocks.push_back(E_BLOCK_STAINED_CLAY);

			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSingleTopBlock(Seed, E_BLOCK_DEAD_BUSH, AllowedBiomes, 2, AllowedBlocks)));
		}
		else if (NoCaseCompare(finisher, "DirectOverhangs") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cStructGenDirectOverhangs(Seed)));
		}
		else if (NoCaseCompare(finisher, "DirtPockets") == 0)
		{
			auto gen = std::make_shared<cFinishGenOrePockets>(Seed + 1, cFinishGenOrePockets::DefaultNaturalPatches());
			if (gen->Initialize(a_IniFile, "DirtPockets"))
			{
				m_FinishGens.push_back(gen);
			}
		}
		else if (NoCaseCompare(finisher, "DistortedMembraneOverhangs") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cStructGenDistortedMembraneOverhangs(Seed)));
		}
		else if (NoCaseCompare(finisher, "DualRidgeCaves") == 0)
		{
			float Threshold = static_cast<float>(a_IniFile.GetValueSetF("Generator", "DualRidgeCavesThreshold", 0.3));
			m_FinishGens.push_back(cFinishGenPtr(new cStructGenDualRidgeCaves(Seed, Threshold)));
		}
		else if (NoCaseCompare(finisher, "DungeonRooms") == 0)
		{
			int     GridSize      = a_IniFile.GetValueSetI("Generator", "DungeonRoomsGridSize", 48);
			int     MaxSize       = a_IniFile.GetValueSetI("Generator", "DungeonRoomsMaxSize", 7);
			int     MinSize       = a_IniFile.GetValueSetI("Generator", "DungeonRoomsMinSize", 5);
			AString HeightDistrib = a_IniFile.GetValueSet ("Generator", "DungeonRoomsHeightDistrib", "0, 0; 10, 10; 11, 500; 40, 500; 60, 40; 90, 1");
			m_FinishGens.push_back(cFinishGenPtr(new cDungeonRoomsFinisher(m_ShapeGen, Seed, GridSize, MaxSize, MinSize, HeightDistrib)));
		}
		else if (NoCaseCompare(finisher, "GlowStone") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenGlowStone(Seed)));
		}
		else if (NoCaseCompare(finisher, "Ice") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenIce));
		}
		else if (NoCaseCompare(finisher, "LavaLakes") == 0)
		{
			int Probability = a_IniFile.GetValueSetI("Generator", "LavaLakesProbability", 10);
			m_FinishGens.push_back(cFinishGenPtr(new cStructGenLakes(Seed * 5 + 16873, E_BLOCK_STATIONARY_LAVA, m_ShapeGen, Probability)));
		}
		else if (NoCaseCompare(finisher, "LavaSprings") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenFluidSprings(Seed, E_BLOCK_LAVA, a_IniFile, Dimension)));
		}
		else if (NoCaseCompare(finisher, "Lilypads") == 0)
		{
			// A list with all the allowed biomes.
			cFinishGenSingleTopBlock::BiomeList AllowedBiomes;
			AllowedBiomes.push_back(biSwampland);
			AllowedBiomes.push_back(biSwamplandM);

			// A list with all the allowed blocks that can be below the lilypad.
			cFinishGenSingleTopBlock::BlockList AllowedBlocks;
			AllowedBlocks.push_back(E_BLOCK_WATER);
			AllowedBlocks.push_back(E_BLOCK_STATIONARY_WATER);

			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSingleTopBlock(Seed, E_BLOCK_LILY_PAD, AllowedBiomes, 4, AllowedBlocks)));
		}
		else if (NoCaseCompare(finisher, "MarbleCaves") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cStructGenMarbleCaves(Seed)));
		}
		else if (NoCaseCompare(finisher, "MineShafts") == 0)
		{
			int GridSize        = a_IniFile.GetValueSetI("Generator", "MineShaftsGridSize",        512);
			int MaxOffset       = a_IniFile.GetValueSetI("Generator", "MineShaftsMaxOffset",       256);
			int MaxSystemSize   = a_IniFile.GetValueSetI("Generator", "MineShaftsMaxSystemSize",   160);
			int ChanceCorridor  = a_IniFile.GetValueSetI("Generator", "MineShaftsChanceCorridor",  600);
			int ChanceCrossing  = a_IniFile.GetValueSetI("Generator", "MineShaftsChanceCrossing",  200);
			int ChanceStaircase = a_IniFile.GetValueSetI("Generator", "MineShaftsChanceStaircase", 200);
			m_FinishGens.push_back(cFinishGenPtr(new cStructGenMineShafts(
				Seed, GridSize, MaxOffset, MaxSystemSize,
				ChanceCorridor, ChanceCrossing, ChanceStaircase
			)));
		}
		else if (NoCaseCompare(finisher, "NaturalPatches") == 0)
		{
			m_FinishGens.push_back(std::make_shared<cFinishGenOreNests>(Seed + 1, cFinishGenOreNests::DefaultNaturalPatches()));
		}
		else if (NoCaseCompare(finisher, "NetherClumpFoliage") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenNetherClumpFoliage(Seed)));
		}
		else if (NoCaseCompare(*itr, "NetherForts") == 0)
		{
			LOGINFO("The NetherForts finisher is obsolete, you should use \"PieceStructures: NetherFort\" instead.");
			auto gen = std::make_shared<cPieceStructuresGen>(Seed);
			if (gen->Initialize("NetherFort", seaLevel, m_BiomeGen, m_CompositedHeightCache))
			{
				m_FinishGens.push_back(gen);
			}
		}
		else if (NoCaseCompare(finisher, "NetherOreNests") == 0)
		{
			m_FinishGens.push_back(std::make_shared<cFinishGenOreNests>(Seed + 2, cFinishGenOreNests::DefaultNetherOres()));
		}
		else if (NoCaseCompare(finisher, "OreNests") == 0)
		{
			m_FinishGens.push_back(std::make_shared<cFinishGenOreNests>(Seed + 3, cFinishGenOreNests::DefaultOverworldOres()));
		}
		else if (NoCaseCompare(finisher, "OrePockets") == 0)
		{
			auto gen = std::make_shared<cFinishGenOrePockets>(Seed + 2, cFinishGenOrePockets::DefaultOverworldOres());
			if (gen->Initialize(a_IniFile, "OrePockets"))
			{
				m_FinishGens.push_back(gen);
			}
		}
		else if (NoCaseCompare(finisher, "OverworldClumpFlowers") == 0)
		{
			auto flowers = cFinishGenClumpTopBlock::ParseIniFile(a_IniFile, "OverworldClumpFlowers");
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenClumpTopBlock(Seed, flowers)));
		}
		else if (NoCaseCompare(finisher, "PieceStructures") == 0)
		{
			if (split.size() < 2)
			{
				LOGWARNING("The PieceStructures generator needs the structures to use. Example: \"PieceStructures: NetherFort\".");
				continue;
			}

			auto gen = std::make_shared<cPieceStructuresGen>(Seed);
			if (gen->Initialize(split[1], seaLevel, m_BiomeGen, m_CompositedHeightCache))
			{
				m_FinishGens.push_back(gen);
			}
		}
		else if (NoCaseCompare(finisher, "PreSimulator") == 0)
		{
			// Load the settings
			bool PreSimulateFallingBlocks = a_IniFile.GetValueSetB("Generator", "PreSimulatorFallingBlocks", true);
			bool PreSimulateWater         = a_IniFile.GetValueSetB("Generator", "PreSimulatorWater", true);
			bool PreSimulateLava          = a_IniFile.GetValueSetB("Generator", "PreSimulatorLava", true);

			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenPreSimulator(PreSimulateFallingBlocks, PreSimulateWater, PreSimulateLava)));
		}
		else if (NoCaseCompare(finisher, "RainbowRoads") == 0)
		{
			LOGINFO("The RainbowRoads finisher is obsolete, you should use \"PieceStructures: RainbowRoads\" instead.");
			auto gen = std::make_shared<cPieceStructuresGen>(Seed);
			if (gen->Initialize("RainbowRoads", seaLevel, m_BiomeGen, m_CompositedHeightCache))
			{
				m_FinishGens.push_back(gen);
			}
		}
		else if (NoCaseCompare(finisher, "Ravines") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cStructGenRavines(Seed, 128)));
		}
		else if (NoCaseCompare(finisher, "RoughRavines") == 0)
		{
			int GridSize                  = a_IniFile.GetValueSetI("Generator", "RoughRavinesGridSize",              256);
			int MaxOffset                 = a_IniFile.GetValueSetI("Generator", "RoughRavinesMaxOffset",             128);
			int MaxSize                   = a_IniFile.GetValueSetI("Generator", "RoughRavinesMaxSize",               128);
			int MinSize                   = a_IniFile.GetValueSetI("Generator", "RoughRavinesMinSize",                64);
			double MaxCenterWidth         = a_IniFile.GetValueSetF("Generator", "RoughRavinesMaxCenterWidth",          8);
			double MinCenterWidth         = a_IniFile.GetValueSetF("Generator", "RoughRavinesMinCenterWidth",          2);
			double MaxRoughness           = a_IniFile.GetValueSetF("Generator", "RoughRavinesMaxRoughness",            0.2);
			double MinRoughness           = a_IniFile.GetValueSetF("Generator", "RoughRavinesMinRoughness",            0.05);
			double MaxFloorHeightEdge     = a_IniFile.GetValueSetF("Generator", "RoughRavinesMaxFloorHeightEdge",      8);
			double MinFloorHeightEdge     = a_IniFile.GetValueSetF("Generator", "RoughRavinesMinFloorHeightEdge",     30);
			double MaxFloorHeightCenter   = a_IniFile.GetValueSetF("Generator", "RoughRavinesMaxFloorHeightCenter",   20);
			double MinFloorHeightCenter   = a_IniFile.GetValueSetF("Generator", "RoughRavinesMinFloorHeightCenter",    6);
			double MaxCeilingHeightEdge   = a_IniFile.GetValueSetF("Generator", "RoughRavinesMaxCeilingHeightEdge",   56);
			double MinCeilingHeightEdge   = a_IniFile.GetValueSetF("Generator", "RoughRavinesMinCeilingHeightEdge",   38);
			double MaxCeilingHeightCenter = a_IniFile.GetValueSetF("Generator", "RoughRavinesMaxCeilingHeightCenter", 58);
			double MinCeilingHeightCenter = a_IniFile.GetValueSetF("Generator", "RoughRavinesMinCeilingHeightCenter", 36);
			m_FinishGens.push_back(cFinishGenPtr(new cRoughRavines(
				Seed, MaxSize, MinSize,
				static_cast<float>(MaxCenterWidth),
				static_cast<float>(MinCenterWidth),
				static_cast<float>(MaxRoughness),
				static_cast<float>(MinRoughness),
				static_cast<float>(MaxFloorHeightEdge),
				static_cast<float>(MinFloorHeightEdge),
				static_cast<float>(MaxFloorHeightCenter),
				static_cast<float>(MinFloorHeightCenter),
				static_cast<float>(MaxCeilingHeightEdge),
				static_cast<float>(MinCeilingHeightEdge),
				static_cast<float>(MaxCeilingHeightCenter),
				static_cast<float>(MinCeilingHeightCenter),
				GridSize, MaxOffset
			)));
		}
		else if (NoCaseCompare(finisher, "SoulsandRims") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSoulsandRims(Seed)));
		}
		else if (NoCaseCompare(finisher, "Snow") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSnow));
		}
		else if (NoCaseCompare(finisher, "SprinkleFoliage") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSprinkleFoliage(Seed)));
		}
		else if (NoCaseCompare(finisher, "TallGrass") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenTallGrass(Seed)));
		}
		else if (NoCaseCompare(finisher, "Trees") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cStructGenTrees(Seed, m_BiomeGen, m_ShapeGen, m_CompositionGen)));
		}
		else if (NoCaseCompare(finisher, "UnderwaterBases") == 0)
		{
			LOGINFO("The UnderwaterBases finisher is obsolete, you should use \"PieceStructures: UnderwaterBases\" instead.");
			auto gen = std::make_shared<cPieceStructuresGen>(Seed);
			if (gen->Initialize("UnderwaterBases", seaLevel, m_BiomeGen, m_CompositedHeightCache))
			{
				m_FinishGens.push_back(gen);
			}
		}
		else if (NoCaseCompare(finisher, "Villages") == 0)
		{
			int GridSize   = a_IniFile.GetValueSetI("Generator", "VillageGridSize",  384);
			int MaxOffset  = a_IniFile.GetValueSetI("Generator", "VillageMaxOffset", 128);
			int MaxDepth   = a_IniFile.GetValueSetI("Generator", "VillageMaxDepth",    2);
			int MaxSize    = a_IniFile.GetValueSetI("Generator", "VillageMaxSize",   128);
			int MinDensity = a_IniFile.GetValueSetI("Generator", "VillageMinDensity", 50);
			int MaxDensity = a_IniFile.GetValueSetI("Generator", "VillageMaxDensity", 80);
			AString PrefabList = a_IniFile.GetValueSet("Generator", "VillagePrefabs", "PlainsVillage, SandVillage");
			auto Prefabs = StringSplitAndTrim(PrefabList, ",");
			m_FinishGens.push_back(std::make_shared<cVillageGen>(Seed, GridSize, MaxOffset, MaxDepth, MaxSize, MinDensity, MaxDensity, m_BiomeGen, m_CompositedHeightCache, seaLevel, Prefabs));
		}
		else if (NoCaseCompare(finisher, "Vines") == 0)
		{
			int Level = a_IniFile.GetValueSetI("Generator", "VinesLevel", 40);
			m_FinishGens.push_back(std::make_shared<cFinishGenVines>(Seed, Level));
		}
		else if (NoCaseCompare(finisher, "WaterLakes") == 0)
		{
			int Probability = a_IniFile.GetValueSetI("Generator", "WaterLakesProbability", 25);
			m_FinishGens.push_back(cFinishGenPtr(new cStructGenLakes(Seed * 3 + 652, E_BLOCK_STATIONARY_WATER, m_ShapeGen, Probability)));
		}
		else if (NoCaseCompare(finisher, "WaterSprings") == 0)
		{
			m_FinishGens.push_back(cFinishGenPtr(new cFinishGenFluidSprings(Seed, E_BLOCK_WATER, a_IniFile, Dimension)));
		}
		else if (NoCaseCompare(finisher, "WormNestCaves") == 0)
		{
			int Size      = a_IniFile.GetValueSetI("Generator", "WormNestCavesSize", 64);
			int Grid      = a_IniFile.GetValueSetI("Generator", "WormNestCavesGrid", 96);
			int MaxOffset = a_IniFile.GetValueSetI("Generator", "WormNestMaxOffset", 32);
			m_FinishGens.push_back(cFinishGenPtr(new cStructGenWormNestCaves(Seed, Size, Grid, MaxOffset)));
		}
		else
		{
			LOGWARNING("Unknown Finisher in the [Generator] section: \"%s\". Ignoring.", finisher.c_str());
		}
	}  // for itr - Str[]
}
    void CameraParameterReader::readParameters(const std::string& cameraParameterPath,
                                               const std::vector<std::string>& serialNumbers)
    {
        try
        {
            // Serial numbers
            if (serialNumbers.empty())
            {
                mSerialNumbers = getFilesOnDirectory(cameraParameterPath, "xml");
                for (auto& serialNumber : mSerialNumbers)
                    serialNumber = getFileNameNoExtension(serialNumber);
            }
            else
                mSerialNumbers = serialNumbers;

            // Commong saving/loading
            const auto dataFormat = DataFormat::Xml;
            const std::vector<std::string> cvMatNames {
                "CameraMatrix", "Intrinsics", "Distortion"
            };

            // Load parameters
            mCameraMatrices.clear();
            mCameraExtrinsics.clear();
            mCameraIntrinsics.clear();
            mCameraDistortions.clear();
            // log("Camera matrices:");
            for (auto i = 0ull ; i < mSerialNumbers.size() ; i++)
            {
                const auto parameterPath = cameraParameterPath + mSerialNumbers.at(i);
                const auto cameraParameters = loadData(cvMatNames, parameterPath, dataFormat);
                // Error if empty element
                if (cameraParameters.empty() || cameraParameters.at(0).empty()
                    || cameraParameters.at(1).empty() || cameraParameters.at(2).empty())
                {
                    const std::string errorMessage = " of the camera with serial number `" + mSerialNumbers[i]
                                                   + "` (file: " + parameterPath + "." + dataFormatToString(dataFormat)
                                                   + "). Is its format valid? You might want to check the example xml"
                                                   + " file.";
                    if (cameraParameters.empty())
                        error("Error at reading the camera parameters" + errorMessage,
                              __LINE__, __FUNCTION__, __FILE__);
                    if (cameraParameters.at(0).empty())
                        error("Error at reading the camera matrix parameters" + errorMessage,
                              __LINE__, __FUNCTION__, __FILE__);
                    if (cameraParameters.at(1).empty())
                        error("Error at reading the camera intrinsics parameters" + errorMessage,
                              __LINE__, __FUNCTION__, __FILE__);
                    if (cameraParameters.at(2).empty())
                        error("Error at reading the camera distortion parameters" + errorMessage,
                              __LINE__, __FUNCTION__, __FILE__);
                }
                mCameraExtrinsics.emplace_back(cameraParameters.at(0));
                mCameraIntrinsics.emplace_back(cameraParameters.at(1));
                mCameraDistortions.emplace_back(cameraParameters.at(2));
                mCameraMatrices.emplace_back(mCameraIntrinsics.back() * mCameraExtrinsics.back());
                // log(cameraParameters.at(0));
            }
            // // mCameraMatrices
            // log("\nFull camera matrices:");
            // for (const auto& cvMat : mCameraMatrices)
            //     log(cvMat);
            // // mCameraIntrinsics
            // log("\nCamera intrinsic parameters:");
            // for (const auto& cvMat : mCameraIntrinsics)
            //     log(cvMat);
            // // mCameraDistortions
            // log("\nCamera distortion parameters:");
            // for (const auto& cvMat : mCameraDistortions)
            //     log(cvMat);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }
Beispiel #9
0
/**
 * Reads in a vehicle part from a JsonObject.
 */
void vpart_info::load( JsonObject &jo, const std::string &src )
{
    vpart_info def;

    if( jo.has_string( "copy-from" ) ) {
        auto const base = vpart_info_all.find( vpart_id( jo.get_string( "copy-from" ) ) );
        auto const ab = abstract_parts.find( vpart_id( jo.get_string( "copy-from" ) ) );
        if( base != vpart_info_all.end() ) {
            def = base->second;
        } else if( ab != abstract_parts.end() ) {
            def = ab->second;
        } else {
            deferred.emplace_back( jo.str(), src );
            return;
        }
    }

    if( jo.has_string( "abstract" ) ) {
        def.id = vpart_id( jo.get_string( "abstract" ) );
    } else {
        def.id = vpart_id( jo.get_string( "id" ) );
    }

    assign( jo, "name", def.name_ );
    assign( jo, "item", def.item );
    assign( jo, "location", def.location );
    assign( jo, "durability", def.durability );
    assign( jo, "damage_modifier", def.dmg_mod );
    assign( jo, "power", def.power );
    assign( jo, "epower", def.epower );
    assign( jo, "fuel_type", def.fuel_type );
    assign( jo, "default_ammo", def.default_ammo );
    assign( jo, "folded_volume", def.folded_volume );
    assign( jo, "size", def.size );
    assign( jo, "difficulty", def.difficulty );
    assign( jo, "bonus", def.bonus );
    assign( jo, "flags", def.flags );

    if( jo.has_member( "requirements" ) ) {
        auto reqs = jo.get_object( "requirements" );

        parse_vp_reqs( reqs, def.id.str(), "install", def.install_reqs, def.install_skills, def.install_moves );
        parse_vp_reqs( reqs, def.id.str(), "removal", def.removal_reqs, def.removal_skills, def.removal_moves );
        parse_vp_reqs( reqs, def.id.str(), "repair",  def.repair_reqs,  def.repair_skills,  def.repair_moves  );

        def.legacy = false;
    }

    if( jo.has_member( "symbol" ) ) {
        def.sym = jo.get_string( "symbol" )[ 0 ];
    }
    if( jo.has_member( "broken_symbol" ) ) {
        def.sym_broken = jo.get_string( "broken_symbol" )[ 0 ];
    }

    if( jo.has_member( "color" ) ) {
        def.color = color_from_string( jo.get_string( "color" ) );
    }
    if( jo.has_member( "broken_color" ) ) {
        def.color_broken = color_from_string( jo.get_string( "broken_color" ) );
    }

    if( jo.has_member( "breaks_into" ) ) {
        JsonIn& stream = *jo.get_raw( "breaks_into" );
        def.breaks_into_group = item_group::load_item_group( stream, "collection" );
    }

    auto qual = jo.get_array( "qualities" );
    if( !qual.empty() ) {
        def.qualities.clear();
        while( qual.has_more() ) {
            auto pair = qual.next_array();
            def.qualities[ quality_id( pair.get_string( 0 ) ) ] = pair.get_int( 1 );
        }
    }

    if( jo.has_member( "damage_reduction" ) ) {
        JsonObject dred = jo.get_object( "damage_reduction" );
        def.damage_reduction = load_damage_array( dred );
    } else {
        def.damage_reduction.fill( 0.0f );
    }

    if( jo.has_string( "abstract" ) ) {
        abstract_parts[def.id] = def;
    } else {
        vpart_info_all[def.id] = def;
    }
}
Beispiel #10
0
Engine::Engine(util::Dir *data_dir, const char *windowtitle)
	:
	OptionNode{"Engine"},
	running{false},
	drawing_debug_overlay{this, "drawing_debug_overlay", true},
	drawing_huds{this, "drawing_huds", true},
	engine_coord_data{this->get_coord_data()},
	current_player{this, "current_player", 1},
	data_dir{data_dir},
	audio_manager{} {

	for (uint32_t size : {12, 20}) {
		fonts[size] = std::unique_ptr<Font>{new Font{"DejaVu Serif", "Book", size}};
	}

	this->logsink_file = std::make_unique<log::FileSink>("/tmp/openage-log", true);

	// enqueue the engine's own input handler to the
	// execution list.
	this->register_resize_action(this);

	// register the engines input manager
	this->register_input_action(&this->input_manager);

	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		throw Error(MSG(err) << "SDL video initialization: " << SDL_GetError());
	} else {
		log::log(MSG(info) << "Initialized SDL video subsystems.");
	}

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
	SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

	int32_t window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED;
	this->window = SDL_CreateWindow(
		windowtitle,
		SDL_WINDOWPOS_CENTERED,
		SDL_WINDOWPOS_CENTERED,
		this->engine_coord_data->window_size.x,
		this->engine_coord_data->window_size.y,
		window_flags
	);

	if (this->window == nullptr) {
		throw Error(MSG(err) << "Failed to create SDL window: " << SDL_GetError());
	}

	// load support for the PNG image formats, jpg bit: IMG_INIT_JPG
	int wanted_image_formats = IMG_INIT_PNG;
	int sdlimg_inited = IMG_Init(wanted_image_formats);
	if ((sdlimg_inited & wanted_image_formats) != wanted_image_formats) {
		throw Error(MSG(err) << "Failed to init PNG support: " << IMG_GetError());
	}

	this->glcontext = SDL_GL_CreateContext(this->window);

	if (this->glcontext == nullptr) {
		throw Error(MSG(err) << "Failed creating OpenGL context: " << SDL_GetError());
	}

	// check the OpenGL version, for shaders n stuff
	if (!epoxy_is_desktop_gl() || epoxy_gl_version() < 21) {
		throw Error(MSG(err) << "OpenGL 2.1 not available");
	}

	// to quote the standard doc:
	// 'The value gives a rough estimate
	// of the largest texture that the GL can handle'
	// -> wat?
	// anyways, we need at least 1024x1024.
	int max_texture_size;
	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
	log::log(MSG(dbg) << "Maximum supported texture size: " << max_texture_size);
	if (max_texture_size < 1024) {
		throw Error(MSG(err) << "Maximum supported texture size too small: " << max_texture_size);
	}

	int max_texture_units;
	glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_texture_units);
	log::log(MSG(dbg) << "Maximum supported texture units: " << max_texture_units);
	if (max_texture_units < 2) {
		throw Error(MSG(err) << "Your GPU has too less texture units: " << max_texture_units);
	}

	// vsync on
	SDL_GL_SetSwapInterval(1);

	// enable alpha blending
	glEnable(GL_BLEND);

	// order of drawing relevant for depth
	// what gets drawn last is displayed on top.
	glDisable(GL_DEPTH_TEST);

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// initialize job manager with cpucount-2 worker threads
	int number_of_worker_threads = SDL_GetCPUCount() - 2;
	if (number_of_worker_threads <= 0) {
		number_of_worker_threads = 1;
	}
	this->job_manager = new job::JobManager{number_of_worker_threads};

	// initialize audio
	auto devices = audio::AudioManager::get_devices();
	if (devices.empty()) {
		throw Error{MSG(err) << "No audio devices found"};
	}

	// initialize engine related global keybinds
	auto &global_input_context = this->get_input_manager().get_global_context();
	global_input_context.bind(input::action_t::STOP_GAME, [this](const input::action_arg_t &) {
		this->stop();
	});
	global_input_context.bind(input::action_t::TOGGLE_HUD, [this](const input::action_arg_t &) {
		this->drawing_huds.value = !this->drawing_huds.value;
	});
	global_input_context.bind(input::action_t::SCREENSHOT, [this](const input::action_arg_t &) {
		this->get_screenshot_manager().save_screenshot();
	});
	global_input_context.bind(input::action_t::TOGGLE_DEBUG_OVERLAY, [this](const input::action_arg_t &) {
		this->drawing_debug_overlay.value = !this->drawing_debug_overlay.value;
	});
	global_input_context.bind(input::action_t::TOGGLE_PROFILER, [this](const input::action_arg_t &) {
		if (this->external_profiler.currently_profiling) {
			this->external_profiler.stop();
			this->external_profiler.show_results();
		} else {
			this->external_profiler.start();
		}
	});
	global_input_context.bind(input::event_class::MOUSE, [this](const input::action_arg_t &arg) {
		if (arg.e.cc.has_class(input::event_class::MOUSE_MOTION) &&
			this->get_input_manager().is_down(input::event_class::MOUSE_BUTTON, 2)) {
			this->move_phys_camera(arg.motion.x, arg.motion.y);
			return true;
		}
		return false;
	});

	// Switching between players with the 1-8 keys
	auto bind_player_switch = [this, &global_input_context](input::action_t action, int player) {
		global_input_context.bind(action, [this, player](const input::action_arg_t &) {
			this->current_player.value = player;
		});
	};
	bind_player_switch(input::action_t::SWITCH_TO_PLAYER_1, 1);
	bind_player_switch(input::action_t::SWITCH_TO_PLAYER_2, 2);
	bind_player_switch(input::action_t::SWITCH_TO_PLAYER_3, 3);
	bind_player_switch(input::action_t::SWITCH_TO_PLAYER_4, 4);
	bind_player_switch(input::action_t::SWITCH_TO_PLAYER_5, 5);
	bind_player_switch(input::action_t::SWITCH_TO_PLAYER_6, 6);
	bind_player_switch(input::action_t::SWITCH_TO_PLAYER_7, 7);
	bind_player_switch(input::action_t::SWITCH_TO_PLAYER_8, 8);
}
Beispiel #11
0
void MotionMaster::UpdateFinalDistanceToTarget(float fDistance)
{
    if (!empty())
        top()->UpdateFinalDistance(fDistance);
}
Beispiel #12
0
 static std::string MakeFunctionNameStandOut(std::string origName)
 {
     try // guard against exception, since this is used for exception reporting
     {
         auto name = origName;
         // strip off modifiers for parsing (will be put back at the end)
         std::string modifiers;
         auto pos = name.find_last_not_of(" abcdefghijklmnopqrstuvwxyz");
         if (pos != std::string::npos)
         {
             modifiers = name.substr(pos + 1);
             name = name.substr(0, pos + 1);
         }
         bool hasArgList = !name.empty() && name.back() == ')';
         size_t angleDepth = 0;
         size_t parenDepth = 0;
         bool hitEnd = !hasArgList; // hit end of function name already?
         bool hitStart = false;
         // we parse the function name from the end; escape nested <> and ()
         // We look for the end and start of the function name itself (without namespace qualifiers),
         // and for commas separating function arguments.
         for (size_t i = name.size(); i--> 0;)
         {
             // account for nested <> and ()
             if (name[i] == '>')
                 angleDepth++;
             else if (name[i] == '<')
                 angleDepth--;
             else if (name[i] == ')')
                 parenDepth++;
             else if (name[i] == '(')
                 parenDepth--;
             // space before '>'
             if (name[i] == ' ' && i + 1 < name.size() && name[i + 1] == '>')
                 name.erase(i, 1); // remove
             // commas
             if (name[i] == ',')
             {
                 if (i + 1 < name.size() && name[i + 1] == ' ')
                     name.erase(i + 1, 1);  // remove spaces after comma
                 if (!hitEnd && angleDepth == 0 && parenDepth == 1)
                     name.insert(i + 1, "  "); // except for top-level arguments, we separate them by 2 spaces for better readability
             }
             // function name
             if ((name[i] == '(' || name[i] == '<') &&
                 parenDepth == 0 && angleDepth == 0 &&
                 (i == 0 || name[i - 1] != '>') &&
                 !hitEnd && !hitStart) // we hit the start of the argument list
             {
                 hitEnd = true;
                 name.insert(i, "  ");
             }
             else if ((name[i] == ' ' || name[i] == ':' || name[i] == '>') && hitEnd && !hitStart && i > 0) // we hit the start of the function name
             {
                 if (name[i] != ' ')
                     name.insert(i + 1, " ");
                 name.insert(i + 1, " "); // in total insert 2 spaces
                 hitStart = true;
             }
         }
         return name + modifiers;
     }
     catch (...)
     {
         return origName;
     }
 }
Beispiel #13
0
void *t1(void *arg)
{
    int value;
    int i;
    __CS_cs();
    if (__CS_ret != 0) return 0;
    __CS_pthread_mutex_lock(&m[__CS_round]);
    __CS_cs();
    if (__CS_ret != 0) return 0;
    value = nondet_int();
    __CS_cs();
    if (__CS_ret != 0) return 0;
    if (enqueue(&queue[__CS_round], value))
    {
        __CS_cs();
        if (__CS_ret != 0) return 0;
        goto __CS_ERROR;
        __CS_cs();
        if (__CS_ret != 0) return 0;
    }
    __CS_cs();
    if (__CS_ret != 0) return 0;
    stored_elements[__CS_round][0] = value;
    __CS_cs();
    if (__CS_ret != 0) return 0;
    if (empty(&queue[__CS_round]))
    {
        __CS_cs();
        if (__CS_ret != 0) return 0;
        goto __CS_ERROR;
        __CS_cs();
        if (__CS_ret != 0) return 0;
    }
    __CS_cs();
    if (__CS_ret != 0) return 0;
    __CS_pthread_mutex_unlock(&m[__CS_round]);
    __CS_cs();
    if (__CS_ret != 0) return 0;
    for (i = 0; i < (20 - 1); i++)
    {
        __CS_cs();
        if (__CS_ret != 0) return 0;
        __CS_pthread_mutex_lock(&m[__CS_round]);
        __CS_cs();
        if (__CS_ret != 0) return 0;
        if (enqueue_flag[__CS_round])
        {
            __CS_cs();
            if (__CS_ret != 0) return 0;
            value = nondet_int();
            __CS_cs();
            if (__CS_ret != 0) return 0;
            enqueue(&queue[__CS_round], value);
            __CS_cs();
            if (__CS_ret != 0) return 0;
            stored_elements[__CS_round][i + 1] = value;
            __CS_cs();
            if (__CS_ret != 0) return 0;
            enqueue_flag[__CS_round] = 0;
            __CS_cs();
            if (__CS_ret != 0) return 0;
            dequeue_flag[__CS_round] = 1;
            __CS_cs();
            if (__CS_ret != 0) return 0;
        }
        __CS_cs();
        if (__CS_ret != 0) return 0;
        __CS_pthread_mutex_unlock(&m[__CS_round]);
        __CS_cs();
        if (__CS_ret != 0) return 0;
    }
    __CS_cs();
    if (__CS_ret != 0) return 0;
    return 0;
    __CS_cs();
    if (__CS_ret != 0) return 0;
__CS_ERROR:
    __CS_error = 1;
    __CS_ret = __CS_ret_ERROR;
    return 0;
    __CS_cs();
    if (__CS_ret != 0) return 0;
    ;

    __CS_cs();
    if (__CS_ret != 0) return 0;
}
Beispiel #14
0
TEST_F(TestHelpText, Application)
{
  qi::Application app(argc, argv);
  const auto helpText = app.helpText();
  EXPECT_FALSE(helpText.empty());
}
Beispiel #15
0
OGRErr OGRPoint::importFromWkt( char ** ppszInput )

{
    char        szToken[OGR_WKT_TOKEN_MAX];
    const char  *pszInput = *ppszInput;

/* -------------------------------------------------------------------- */
/*      Read and verify the ``POINT'' keyword token.                    */
/* -------------------------------------------------------------------- */
    pszInput = OGRWktReadToken( pszInput, szToken );

    if( !EQUAL(szToken,"POINT") )
        return OGRERR_CORRUPT_DATA;

/* -------------------------------------------------------------------- */
/*      Check for EMPTY ... but treat like a point at 0,0.              */
/* -------------------------------------------------------------------- */
    const char *pszPreScan;

    pszPreScan = OGRWktReadToken( pszInput, szToken );
    if( !EQUAL(szToken,"(") )
        return OGRERR_CORRUPT_DATA;

    pszPreScan = OGRWktReadToken( pszPreScan, szToken );
    if( EQUAL(szToken,"EMPTY") )
    {
        pszInput = OGRWktReadToken( pszPreScan, szToken );

        if( !EQUAL(szToken,")") )
            return OGRERR_CORRUPT_DATA;
        else
        {
            *ppszInput = (char *) pszInput;
            empty();
            return OGRERR_NONE;
        }
    }

/* -------------------------------------------------------------------- */
/*      Read the point list which should consist of exactly one point.  */
/* -------------------------------------------------------------------- */
    OGRRawPoint         *poPoints = NULL;
    double              *padfZ = NULL;
    int                 nMaxPoint = 0, nPoints = 0;

    pszInput = OGRWktReadPoints( pszInput, &poPoints, &padfZ,
                                 &nMaxPoint, &nPoints );
    if( pszInput == NULL || nPoints != 1 )
        return OGRERR_CORRUPT_DATA;

    x = poPoints[0].x;
    y = poPoints[0].y;

    CPLFree( poPoints );

    if( padfZ != NULL )
    {
        z = padfZ[0];
        CPLFree( padfZ );
    }

    *ppszInput = (char *) pszInput;

    return OGRERR_NONE;
}
Beispiel #16
0
void Item_modifier::modify(item &new_item) const
{

    if(new_item.is_null()) {
        return;
    }
    int dm = (damage.first == damage.second) ? damage.first : rng(damage.first, damage.second);
    if(dm >= -1 && dm <= 4) {
        new_item.damage = dm;
    }
    long ch = (charges.first == charges.second) ? charges.first : rng(charges.first, charges.second);
    const auto g = new_item.type->gun.get();
    const auto t = dynamic_cast<const it_tool *>(new_item.type);
   
    if(ch != -1) {
        if( new_item.count_by_charges() || new_item.made_of( LIQUID ) ) {
            // food, ammo
            // count_by_charges requires that charges is at least 1. It makes no sense to
            // spawn a "water (0)" item.
            new_item.charges = std::max( 1l, ch );
        } else if(t != NULL) {
            new_item.charges = std::min(ch, t->max_charges);
        } else if (g == nullptr){
            //not gun, food, ammo or tool. 
            new_item.charges = ch;
        }
    }
    
    if( g != nullptr && ( ammo.get() != nullptr || ch > 0 ) ) {
        if( ammo.get() == nullptr ) {
            // In case there is no explicit ammo item defined, use the default ammo
            const auto ammoid = default_ammo( g->ammo );
            if ( !ammoid.empty() ) {
                new_item.set_curammo( ammoid );
                new_item.charges = ch;
            }
        } else {
            const item am = ammo->create_single( new_item.bday );
            new_item.set_curammo( am );
            // Prefer explicit charges of the gun, else take the charges of the ammo item,
            // Gun charges are easier to define: {"item":"gun","charge":10,"ammo-item":"ammo"}
            if( ch > 0 ) {
                new_item.charges = ch;
            } else {
                new_item.charges = am.charges;
            }
        }
        // Make sure the item is in a valid state curammo==0 <=> charges==0 and respect clip size
        if( !new_item.has_curammo() ) {
            new_item.charges = 0;
        } else {
            new_item.charges = std::min<long>( new_item.charges, new_item.clip_size() );
        }
    }
    if(container.get() != NULL) {
        item cont = container->create_single(new_item.bday);
        if (!cont.is_null()) {
            if (new_item.made_of(LIQUID)) {
                long rc = cont.get_remaining_capacity_for_liquid(new_item);
                if(rc > 0 && (new_item.charges > rc || ch == -1)) {
                    // make sure the container is not over-full.
                    // fill up the container (if using default charges)
                    new_item.charges = rc;
                }
            }
            cont.put_in(new_item);
            new_item = cont;
        }
    }
    if (contents.get() != NULL) {
        Item_spawn_data::ItemList contentitems = contents->create(new_item.bday);
        new_item.contents.insert(new_item.contents.end(), contentitems.begin(), contentitems.end());
    }
}
//mbl test with Pocket_PC
void weak_horizontal_luma_MMX(unsigned char pix[], const int xstride, const unsigned char alpha, const unsigned char beta, const unsigned char tc0) {

    __m64 mp2 = _mm_set_pi16(pix[-3*xstride + 3], pix[-3*xstride + 2], pix[-3*xstride + 1], pix[-3*xstride]);
    __m64 mp1 = _mm_set_pi16(pix[-2*xstride + 3], pix[-2*xstride + 2], pix[-2*xstride + 1], pix[-2*xstride]);
    __m64 mp0 = _mm_set_pi16(pix[-1*xstride + 3], pix[-1*xstride + 2], pix[-1*xstride + 1], pix[-1*xstride]);
    __m64 mq0 = _mm_set_pi16(pix[3], pix[2], pix[1], pix[0]);
    __m64 mq1 = _mm_set_pi16(pix[xstride + 3], pix[xstride + 2], pix[xstride + 1], pix[xstride]);
    __m64 mq2 = _mm_set_pi16(pix[2*xstride + 3], pix[2*xstride + 2], pix[2*xstride + 1], pix[2*xstride]);

    __m64 mrshift = _mm_set_pi16(0,0,0,1);
    __m64 maddp0_q0 =  _mm_avg_pu8(mp0,mq0); //addp0_q0 = (p0 + q0 + 1) >> 1;
    __m64 maddp2 = _mm_add_pi16(maddp0_q0,mp2); //addp2 = (p2 + addp0_q0);
    __m64 maddq2 = _mm_add_pi16(maddp0_q0,mq2); //addp2 = (p2 + addp0_q0);
    __m64 maddp2_s = _mm_srl_pi16(maddp2,mrshift); //addp2 = (p2 + addp0_q0) >> 1;
    __m64 maddq2_s = _mm_srl_pi16(maddq2,mrshift); //addp2 = (p2 + addp0_q0) >> 1;
    __m64 mp1_c = _mm_sub_pi16(maddp2_s, mp1); //addp2 - p1
    __m64 mq1_c = _mm_sub_pi16(maddq2_s, mq1); // addq2 - q1



    //To calculate the mask
    __m64 malpha = _mm_set_pi16(alpha,alpha,alpha,alpha);
    __m64 malphab = _mm_set_pi16(-alpha,-alpha,-alpha,-alpha);
    __m64 mbeta = _mm_set_pi16(beta,beta,beta,beta);
    __m64 mbetab = _mm_set_pi16(-beta,-beta,-beta,-beta);


    __m64 mdiff_p0_q0 = _mm_sub_pi16(mq0,mp0); //abs(q0 - p0)
    __m64 mdiff_p1_p0 = _mm_sub_pi16(mp0,mp1); //abs(p1 - p0)
    __m64 mdiff_q1_q0 = _mm_sub_pi16(mq0, mq1); //abs(q1 - q0)
    __m64 mdiff_p2_p0 = _mm_sub_pi16(mp2,mp0); //abs(p2 - p0 ))
    __m64 mdiff_q2_q0 = _mm_sub_pi16(mq2,mq0); //abs(q2 - q0)

    __m64 mask0 = _mm_and_si64( _mm_cmpgt_pi16(malpha, mdiff_p0_q0), _mm_cmpgt_pi16(mdiff_p0_q0,malphab));
    __m64 mask1 = _mm_and_si64( _mm_cmpgt_pi16(mbeta, mdiff_p1_p0), _mm_cmpgt_pi16(mdiff_p1_p0,mbetab));
    __m64 mask2 = _mm_and_si64( _mm_cmpgt_pi16(mbeta, mdiff_q1_q0), _mm_cmpgt_pi16(mdiff_q1_q0,mbetab));
    __m64 mask3 = _mm_and_si64( _mm_cmpgt_pi16(mbeta, mdiff_p2_p0), _mm_cmpgt_pi16(mdiff_p2_p0,mbetab));
    __m64 mask4 = _mm_and_si64( _mm_cmpgt_pi16(mbeta, mdiff_q2_q0), _mm_cmpgt_pi16(mdiff_q2_q0,mbetab));

    __m64 first_mask = _mm_and_si64 (_mm_and_si64 (mask0,mask1),mask2); //(abs(q0 - p0) < alpha) && (abs(p1 - p0) < beta) && (abs(q1 - q0) < beta)
    __m64 second_mask = _mm_and_si64 (first_mask,mask3);
    __m64 third_mask = _mm_and_si64 (first_mask,mask4);


    __m64 mdiff_q0_p0 = _mm_sub_pi16(mq0,mp0); //(q0 - p0)
    __m64 mlshift = _mm_set_pi16(0,0,0,2);
    __m64 minter_1 = _mm_sll_pi16(mdiff_q0_p0, mlshift);//inter_1 = (q0 - p0 ) << 2;
    __m64 minter_2 = _mm_sub_pi16(mp1, mq1);//(p1 - q1)
    __m64 madd4 = _mm_set_pi16(4,4,4,4);
    __m64 minter_3 = _mm_add_pi16(minter_2, madd4);//inter_2 = (p1 - q1) + 4;
    __m64 minter_4 = _mm_add_pi16(minter_3,minter_1); //(inter_1 +  inter_2)
    __m64 mrshift3 = _mm_set_pi16(0,0,0,3);
    __m64 minter5 = _mm_sra_pi16(minter_4, mrshift3);



    //Clip3
    __m64 m_tc0 = _mm_set_pi16(tc0,tc0,tc0,tc0);
    __m64 m_tcb0 = _mm_set_pi16(-tc0,-tc0,-tc0,-tc0);
    __m64 mres_c1 = _mm_min_pi16(_mm_max_pi16(mp1_c,m_tcb0),m_tc0); //CLIP3(-tc0, tc0, addp2 - p1 );
    __m64 mres_c2 = _mm_min_pi16(_mm_max_pi16(mq1_c,m_tcb0),m_tc0); //CLIP3(-tc0, tc0, addq2 - q1 );
    __m64 merror0 = _mm_and_si64 (mres_c1,second_mask);
    __m64 merror1 = _mm_and_si64 (mres_c2,third_mask);


    __m64 m_1 = _mm_set_pi16(1,1,1,1);
    __m64 m_and1 = _mm_and_si64 (mask3, m_1); //tc++; if abs( p2 - p0 ) < beta
    __m64 m_and2 = _mm_and_si64 (mask4, m_1); //tc++; if abs( q2 - q0  ) < beta
    __m64 m_tc = _mm_add_pi16(m_and2,_mm_add_pi16(m_tc0,m_and1));
    __m64 m_tcn =_mm_sub_pi16(_mm_sub_pi16(m_tcb0,m_and1),m_and2);
    __m64 mres_c3 = _mm_min_pi16(_mm_max_pi16(minter5,m_tcn),m_tc); //CLIP3(-tc0, tc0, addp2 - p1 );
    __m64 merror2 = _mm_and_si64 (mres_c3,first_mask);


    __m64 result_p1 = _mm_add_pi16(merror0,mp1); //_mm_shuffle_pi16(_mm_add_pi16(merror0,mp1), 0x1B);
    __m64 result_q1 = _mm_add_pi16(merror1,mq1); //_mm_shuffle_pi16(_mm_add_pi16(merror1,mq1), 0x1B);
    __m64 result_p0 = _mm_add_pi16(merror2,mp0); //_mm_shuffle_pi16(_mm_add_pi16(merror2,mq1), 0x1B);
    __m64 result_q0 = _mm_sub_pi16(mq0, merror2);//_mm_shuffle_pi16(_mm_sub_pi16(mq1, merror2), 0x1B);

    *((unsigned int* )(&pix[-2*xstride])) = _mm_cvtsi64_si32(_mm_packs_pu16(result_p1,mrshift));
    *((unsigned int* )(&pix[-xstride])) = _mm_cvtsi64_si32(_mm_packs_pu16(result_p0,mrshift));
    *((unsigned int* )(&pix[0])) = _mm_cvtsi64_si32(_mm_packs_pu16(result_q0,mrshift));
    *((unsigned int* )(&pix[xstride])) = _mm_cvtsi64_si32(_mm_packs_pu16(result_q1,mrshift));

    empty();
}
Beispiel #18
0
bool ViewIndex::isEmpty() const {
  return objects.empty() && !anyHighlight;
}
 // Hash policy
 float load_factor() const noexcept {
   return empty() ? 0.0f : float(size()) / float(slot_count());
 }
Beispiel #20
0
bool ViewIndex::noObjects() const {
  PROFILE;
  return objects.empty();
}
Beispiel #21
0
void compile_standalone_runtime(std::string object_filename, Target t) {
    Module empty("standalone_runtime", t.without_feature(Target::NoRuntime));
    compile_module_to_object(empty, object_filename);
}
Beispiel #22
0
    T pop(){
      if(empty() == true)
        throw length_error("Empty Stack");
      else
        return _s.pop();
    }

    // const before :: return a const reference
    // const after :: do not let the function modify any variable
    const bool empty(void) const{
        return _s.empty();
    }

    void push(const T &x){
      _s.emplace(x, max(x, empty() : x ? _s.top().second));
    }

  private:
    std::stack<pair<T,T>> _s;
};

// 2nd SOlution:
/*
  This is using an auxillary stack made of pairs.
  pair.element.second represents number of times the max element occurs in the
  parent stack
  This is usually to decrease best case space complexity to O(1)
  WOrst case is O(n)

  While in our first solution both the best case and worst case is O(n) additional
Beispiel #23
0
RegionDesc::BlockPtr RegionDesc::entry() const {
  assertx(!empty());
  return m_blocks[0];
}
Beispiel #24
0
 T max(){
   if(empty() == false)
     return _s.top().second;
   else
     throw length_error("Empty Stack");
 }
Beispiel #25
0
void MotionMaster::MoveIdle()
{
    //! Should be preceded by MovementExpired or Clear if there's an overlying movementgenerator active
    if (empty() || !isStatic(top()))
        Mutate(&si_idleMovement, MOTION_SLOT_IDLE);
}
Beispiel #26
0
 T pop(){
   if(empty() == true)
     throw length_error("Empty Stack");
   else
     return _s.pop();
 }
Beispiel #27
0
annotation annotation_groups_factory::
handle_profiles(const type_group& tg, const std::unordered_map<std::string,
                annotation>& profiles, const std::vector<std::string>& candidate_labels,
                const annotation& original) const {

    BOOST_LOG_SEV(lg, debug) << "Started handling profiles. Original: "
                             << original;

    /*
     * If a profile name was specified via the meta-data, it must
     * exist on our profile collection. Locate it, merge it with the
     * original annotation and return that.
     */
    const auto profn(obtain_profile_name(tg, original));
    if (!profn.empty()) {
        BOOST_LOG_SEV(lg, debug) << "Configured profile: " << profn;
        const auto i(profiles.find(profn));
        if (i == profiles.end()) {
            BOOST_LOG_SEV(lg, error) << missing_profile << profn;
            BOOST_THROW_EXCEPTION(building_error(missing_profile + profn));
        }

        merger mg;
        const auto annotation_profile(i->second);
        const annotation r(mg.merge(original, annotation_profile));
        BOOST_LOG_SEV(lg, debug) << "Merged profile: " << r;
        return r;
    } else
        BOOST_LOG_SEV(lg, debug) << "Profile not set in meta-data.";

    /*
     * Lets try each of the candidate labels instead and see if any of
     * them bind to a profile.
     */
    const auto bound_labels(get_bound_labels(profiles, candidate_labels));
    if (bound_labels.size() > 1) {
        BOOST_LOG_SEV(lg, error) << too_many_binds << bound_labels;
        BOOST_THROW_EXCEPTION(building_error(too_many_binds));
    }

    for (const auto& bl : bound_labels) {
        BOOST_LOG_SEV(lg, debug) << "Bound label: " << bl;
        const auto i(profiles.find(bl));
        if (i == profiles.end()) {
            BOOST_LOG_SEV(lg, error) << missing_profile << bl;
            BOOST_THROW_EXCEPTION(building_error(missing_profile + bl));
        }

        merger mg;
        const auto annotation_profile(i->second);
        const annotation r(mg.merge(original, annotation_profile));
        BOOST_LOG_SEV(lg, debug) << "Merged profile: " << r;
        return r;
    }

    /*
     * If no profile name was found by now, we need to try looking for
     * the well-known default profiles, based on the scope of the
     * annotation. Not all scope types have a mapping, and the default
     * profiles do not necessarily exist.
     */
    const auto def_profn(get_default_profile_name_for_scope(original.scope()));
    if (!def_profn.empty()) {
        BOOST_LOG_SEV(lg, debug) << "Looking for default profile; " << def_profn;

        const auto i(profiles.find(def_profn));
        if (i != profiles.end()) {
            merger mg;
            const auto annotation_profile(i->second);
            const annotation r(mg.merge(original, annotation_profile));
            BOOST_LOG_SEV(lg, debug) << "Merged profile: " << r;
            return r;
        }
    } else
        BOOST_LOG_SEV(lg, debug) << "Scope does not have a default profile.";

    /*
     * If we could find nothing suitable, just return the original.
     */
    BOOST_LOG_SEV(lg, debug) << "No profiles found, using original.";
    return original;
}
Beispiel #28
0
void list<Object>::makeEmpty( )
{
    while( !empty( ) )
        pop_front( );
}
Beispiel #29
0
            virtual void getPageData(PageData &pd) const
            {
                typedef PageData::AString AString;
                S();L(path());
                pd.title = path().name();

                //Lookup the line and ix where locus_ starts
                size_t ix;
                {
                    auto line = lineNavigator_.getLine(&ix, locus_.begin());
                    if (line.empty())
                    {
                        //This locus_ is not known, we assume the file is empty
                        for (auto &dstLine: pd.lines)
                        {
                            AString astr("... empty file ...");
                            dstLine.second.push_back(astr);
                        }
                        return;
                    }
                }
                //We try to keep the start of the locus_ at 1/4th of the screen
                const auto focusIX = ix;
                ix = (ix < pd.lines.size()/4) ? 0 : ix-pd.lines.size()/4;
                L(ix);

                //Get the first line of the locus_, we will use it as a start point to fill the PageData lines
                bool foundBegin = false, foundEnd = false;
                for (auto &dstLine: pd.lines)
                {
                    auto line = lineNavigator_.getLine(ix);
                    if (!line.empty())
                    {
                        //The border: set the line number, note that we pre-increment to convert ix into a line number
                        {
                            std::ostringstream oss; oss << ++ix;
                            dstLine.first = oss.str();
                        }
                        //The body
                        {
                            std::ostringstream oss;
                            auto tmpLine = line;
                            while (!tmpLine.empty())
                            {
                                auto &ot = tmpLine.front();
                                if (&ot == &*locus_.begin())
                                    foundBegin = true;
                                if (&ot == &*locus_.end())
                                    foundEnd = true;
                                AString astr(ot.token.toString());
                                if (foundBegin && !foundEnd)
                                    astr.flags.set(PageData::Locus);
                                else if (ot.token.type == Token::Identifier)
                                    astr.flags.set(gubg::parse::cpp::isKeyword(ot.token.range) ? PageData::Keyword : PageData::Identifier);
                                dstLine.second.push_back(astr);
                                tmpLine.popFront();
                            }
                        }
                    }
                }
            }
Beispiel #30
0
HTKMLFReader::HTKMLFReader(MemoryProviderPtr provider,
    const ConfigParameters& readerConfig)
    : m_seed(0), m_provider(provider)
{
    // TODO: deserializers and transformers will be dynamically loaded
    // from external libraries based on the configuration/brain script.

    bool frameMode = readerConfig(L"frameMode", true);
    bool truncated = readerConfig(L"truncated", false);
    if (frameMode && truncated)
    {
        LogicError("frameMode and truncated BPTT are mutually exclusive.");
    }

    if (frameMode)
    {
        m_packingMode = PackingMode::sample;
    }
    else if (truncated)
    {
        m_packingMode = PackingMode::truncated;
    }
    else
    {
        m_packingMode = PackingMode::sequence;
    }

    // nbruttsineachrecurrentiter is old reader configuration, truncationLength is the new one.
    // If truncation length is specified we estimate
    // the number of parallel sequences we have to pack as max(1, (mbsize/truncationLength))
    // If nbruttsineachrecurrentiter is specified we assume that the truncation size is mbSize
    // and the real minibatch size in mbSize * nbruttsineachrecurrentiter[epochIndex]
    m_truncationLength = readerConfig(L"truncationLength", 0);
    m_numParallelSequencesForAllEpochs =
        readerConfig(L"nbruttsineachrecurrentiter", ConfigParameters::Array(intargvector(vector<int> { 1 })));

    ConfigHelper config(readerConfig);
    size_t window = config.GetRandomizationWindow();
    auto deserializers = CreateDeserializers(readerConfig);
    if (deserializers.empty())
    {
        LogicError("Please specify at least a single input stream.");
    }

    auto bundler = std::make_shared<Bundler>(readerConfig, deserializers[0], deserializers, false);
    int verbosity = readerConfig(L"verbosity", 2);
    std::wstring readMethod = config.GetRandomizer();

    // TODO: this should be bool. Change when config per deserializer is allowed.
    if (AreEqualIgnoreCase(readMethod, std::wstring(L"blockRandomize")))
    {
        m_randomizer = std::make_shared<BlockRandomizer>(verbosity, window, bundler, BlockRandomizer::DecimationMode::chunk, true /* useLegacyRandomization */);
    }
    else if (AreEqualIgnoreCase(readMethod, std::wstring(L"none")))
    {
        m_randomizer = std::make_shared<NoRandomizer>(bundler);
    }
    else
    {
        RuntimeError("readMethod must be 'blockRandomize' or 'none'.");
    }

    m_randomizer->Initialize(nullptr, readerConfig);

    // Create output stream descriptions (all dense)
    for (auto d : deserializers)
    {
        for (auto i : d->GetStreamDescriptions())
        {
            StreamDescriptionPtr stream = std::make_shared<StreamDescription>(*i);
            stream->m_storageType = StorageType::dense;
            stream->m_id = m_streams.size();
            m_streams.push_back(stream);
        }
    }

    // TODO: should we unify sample and sequence mode packers into a single one.
    // TODO: functionally they are the same, the only difference is how we handle
    // TODO: MBlayout and what is the perf hit for iterating/copying sequences.
    // TODO: Should do more perf tests before unifying these two.

    // TODO: As the next step the packers will be moved out of the readers into the
    // TODO: core CNTK. They are format agnostic and can be used with any type of 
    // TODO: deserializers.
    switch (m_packingMode)
    {
    case PackingMode::sample:
        m_packer = std::make_shared<FramePacker>(m_provider, m_randomizer, m_streams);
        break;
    case PackingMode::sequence:
        m_packer = std::make_shared<SequencePacker>(m_provider, m_randomizer, m_streams);
        break;
    case PackingMode::truncated:
        m_packer = std::make_shared<TruncatedBPTTPacker>(m_provider, m_randomizer, m_streams);
        break;
    default:
        LogicError("Unsupported type of packer '%d'.", (int)m_packingMode);
    }
}