<commit_before>/*
Copyright (c) 2014-2019 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/

#include "StdAfx.h"
#include "Server/Packets/CmsgAuctionListOwnerItems.h"
#include "Server/Packets/CmsgAuctionListItems.h"
#include "Server/Packets/CmsgAuctionRemoveItem.h"
#include "Server/Packets/SmsgAuctionCommandResult.h"
#include "Server/Packets/CmsgAuctionListIBidderItemse.h"
#include "Server/Packets/CmsgAuctionListIPendingSales.h"
#include "Server/Packets/CmsgAuctionPlaceBid.h"
#include "Server/Packets/CmsgAuctionSellItem.h"
#include "Server/WorldSession.h"
#include "Units/Players/Player.h"
#include "Map/MapMgr.h"
#include "Units/Creatures/Creature.h"
#include "Management/AuctionMgr.h"
#include "Management/ItemInterface.h"

using namespace AscEmu::Packets;

void WorldSession::handleAuctionListOwnerItems(WorldPacket& recvPacket)
{
    CmsgAuctionListOwnerItems srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_LIST_OWNER_ITEMS %u (guidLow)", srlPacket.guid.getGuidLow());

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.guid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    creature->auctionHouse->SendOwnerListPacket(_player, nullptr);
}

void WorldSession::handleAuctionListItems(WorldPacket& recvPacket)
{
    CmsgAuctionListItems srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_LIST_OWNER_ITEMS %u (guidLow)", srlPacket.guid.getGuidLow());

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.guid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    creature->auctionHouse->SendAuctionList(_player, &recvPacket);
}

void WorldSession::handleCancelAuction(WorldPacket& recvPacket)
{
    CmsgAuctionRemoveItem srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_REMOVE_ITEM %u (auctionId)", srlPacket.auctionId);

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.guid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    const auto auction = creature->auctionHouse->GetAuction(srlPacket.auctionId);
    if (auction == nullptr)
        return;

    creature->auctionHouse->QueueDeletion(auction, AUCTION_REMOVE_CANCELLED);

    SendPacket(SmsgAuctionCommandResult(srlPacket.auctionId, AUCTION_CANCEL, AUCTION_ERROR_NONE).serialise().get());

    creature->auctionHouse->SendOwnerListPacket(_player, nullptr);
}

void WorldSession::handleAuctionListBidderItems(WorldPacket& recvPacket)
{
    CmsgAuctionListIBidderItemse srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_LIST_BIDDER_ITEMS %u (lowguid)", srlPacket.guid.getGuidLow());

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.guid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    creature->auctionHouse->SendBidListPacket(_player, &recvPacket);
}

void WorldSession::handleAuctionListPendingSales(WorldPacket& recvPacket)
{
#if VERSION_STRING > TBC
    CmsgAuctionListIPendingSales srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_LIST_PRENDING_SALES %u (lowguid)", srlPacket.guid.getGuidLow());

    //\todo SMSG_AUCTION_LIST_PENDING_SALES needs to be researched!
#endif
}

void WorldSession::handleAuctionSellItem(WorldPacket& recvPacket)
{
    CmsgAuctionSellItem srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_SELL_ITEM");

    if (!srlPacket.bidMoney || !srlPacket.expireTime)
        return;

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.auctioneerGuid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    const auto auctionHouse = creature->auctionHouse;
    srlPacket.expireTime *= MINUTE;

    switch (srlPacket.expireTime)
    {
        case 1 * MIN_AUCTION_TIME:
        case 2 * MIN_AUCTION_TIME:
        case 4 * MIN_AUCTION_TIME:
            break;
        default:
            return;
    }

    Item* items[MAX_AUCTION_ITEMS];

    uint32_t finalCount = 0;

    for (uint32_t i = 0; i < srlPacket.itemsCount; ++i)
    {
        const auto item = _player->getItemInterface()->GetItemByGUID(srlPacket.itemGuids[i]);
        if (!item)
        {
            _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_ITEM);
            return;
        }

        items[i] = item;
        finalCount += srlPacket.count[i];
    }

    if (!finalCount)
    {
        _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_INTERNAL);
        return;
    }

    for (uint32_t i = 0; i < srlPacket.itemsCount; ++i)
    {
        if (items[i] == nullptr || items[i]->getStackCount() < finalCount)
        {
            _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_INTERNAL);
            return;
        }
    }

    for (uint32_t i = 0; i < srlPacket.itemsCount; ++i)
    {
        if (items[i] == nullptr)
        {
            _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_INTERNAL);
            return;
        }

        const uint32_t item_worth = items[i]->getItemProperties()->SellPrice * items[i]->getStackCount();
        const uint32_t item_deposit = static_cast<uint32_t>(item_worth * auctionHouse->deposit_percent) * static_cast<uint32_t>(srlPacket.expireTime / 240.0f);

        if (!_player->hasEnoughCoinage(item_deposit))
        {
            _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_MONEY);
            return;
        }

        _player->modCoinage(-int32(item_deposit));

        const auto item = _player->getItemInterface()->SafeRemoveAndRetreiveItemByGuid(srlPacket.itemGuids[i], false);
        if (!item)
        {
            _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_ITEM);
            return;
        };

        if (item->IsInWorld())
            item->RemoveFromWorld();

        item->setOwner(nullptr);
        item->m_isDirty = true;
        item->SaveToDB(INVENTORY_SLOT_NOT_SET, 0, true, nullptr);

        const auto auction = new Auction;
        auction->BuyoutPrice = static_cast<uint32_t>(srlPacket.buyoutPrice);
        auction->ExpiryTime = static_cast<uint32_t>(UNIXTIME) + srlPacket.expireTime * MINUTE;
        auction->StartingPrice = static_cast<uint32_t>(srlPacket.bidMoney);
        auction->HighestBid = 0;
        auction->HighestBidder = 0;
        auction->Id = sAuctionMgr.GenerateAuctionId();
        auction->Owner = _player->getGuidLow();
        auction->pItem = item;
        auction->Deleted = false;
        auction->DeletedReason = 0;
        auction->DepositAmount = item_deposit;

        auctionHouse->AddAuction(auction);
        auction->SaveToDB(auctionHouse->GetID());

        _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_NONE);
    }

    auctionHouse->SendOwnerListPacket(_player, &recvPacket);
}

void WorldSession::handleAuctionPlaceBid(WorldPacket& recvPacket)
{
    CmsgAuctionPlaceBid srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_PLACE_BID: %u (auctionId), %u (price)", srlPacket.auctionId, srlPacket.price);

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.guid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    const auto auctionHouse = creature->auctionHouse;
    const auto auction = auctionHouse->GetAuction(srlPacket.auctionId);
    if (auction == nullptr || !auction->Owner || _player == nullptr)
    {
        SendPacket(SmsgAuctionCommandResult(0, AUCTION_BID, AUCTION_ERROR_INTERNAL, 0).serialise().get());
        return;
    }

    if (auction->Owner == _player->getGuidLow())
    {
        SendPacket(SmsgAuctionCommandResult(0, AUCTION_BID, AUCTION_ERROR_BID_OWN_AUCTION, 0).serialise().get());
        return;
    }

    if (auction->HighestBid > srlPacket.price && srlPacket.price != auction->BuyoutPrice)
    {
        SendPacket(SmsgAuctionCommandResult(0, AUCTION_BID, AUCTION_ERROR_INTERNAL, 0).serialise().get());
        return;
    }

    if (!_player->hasEnoughCoinage(srlPacket.price))
    {
        SendPacket(SmsgAuctionCommandResult(0, AUCTION_BID, AUCTION_ERROR_MONEY, 0).serialise().get());
        return;
    }

    _player->modCoinage(-static_cast<int32_t>(srlPacket.price));
    if (auction->HighestBidder != 0)
    {
        char subject[100];
        snprintf(subject, 100, "%u:0:0", static_cast<int>(auction->pItem->getEntry()));
        sMailSystem.SendAutomatedMessage(MAIL_TYPE_AUCTION, auctionHouse->GetID(), auction->HighestBidder, subject, "", auction->HighestBid, 0, 0, MAIL_STATIONERY_AUCTION);

        if (auction->HighestBidder != _player->getGuidLow())
            auctionHouse->SendAuctionOutBidNotificationPacket(auction, _player->getGuid(), srlPacket.price);
    }

    if (auction->BuyoutPrice == srlPacket.price)
    {
        auction->HighestBidder = _player->getGuidLow();
        auction->HighestBid = srlPacket.price;

        auctionHouse->QueueDeletion(auction, AUCTION_REMOVE_WON);

        SendPacket(SmsgAuctionCommandResult(auction->Id, AUCTION_BID, AUCTION_ERROR_NONE, 0).serialise().get());
        auctionHouse->SendAuctionBuyOutNotificationPacket(auction);
    }
    else
    {
        auction->HighestBidder = _player->getGuidLow();
        auction->HighestBid = srlPacket.price;
        auction->UpdateInDB();

        SendPacket(SmsgAuctionCommandResult(auction->Id, AUCTION_BID, AUCTION_ERROR_NONE, 0).serialise().get());
    }
}
<commit_msg>Resolved CID 351862 (#1 of 1): Dereference before null check<commit_after>/*
Copyright (c) 2014-2019 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/

#include "StdAfx.h"
#include "Server/Packets/CmsgAuctionListOwnerItems.h"
#include "Server/Packets/CmsgAuctionListItems.h"
#include "Server/Packets/CmsgAuctionRemoveItem.h"
#include "Server/Packets/SmsgAuctionCommandResult.h"
#include "Server/Packets/CmsgAuctionListIBidderItemse.h"
#include "Server/Packets/CmsgAuctionListIPendingSales.h"
#include "Server/Packets/CmsgAuctionPlaceBid.h"
#include "Server/Packets/CmsgAuctionSellItem.h"
#include "Server/WorldSession.h"
#include "Units/Players/Player.h"
#include "Map/MapMgr.h"
#include "Units/Creatures/Creature.h"
#include "Management/AuctionMgr.h"
#include "Management/ItemInterface.h"

using namespace AscEmu::Packets;

void WorldSession::handleAuctionListOwnerItems(WorldPacket& recvPacket)
{
    CmsgAuctionListOwnerItems srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_LIST_OWNER_ITEMS %u (guidLow)", srlPacket.guid.getGuidLow());

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.guid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    creature->auctionHouse->SendOwnerListPacket(_player, nullptr);
}

void WorldSession::handleAuctionListItems(WorldPacket& recvPacket)
{
    CmsgAuctionListItems srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_LIST_OWNER_ITEMS %u (guidLow)", srlPacket.guid.getGuidLow());

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.guid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    creature->auctionHouse->SendAuctionList(_player, &recvPacket);
}

void WorldSession::handleCancelAuction(WorldPacket& recvPacket)
{
    CmsgAuctionRemoveItem srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_REMOVE_ITEM %u (auctionId)", srlPacket.auctionId);

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.guid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    const auto auction = creature->auctionHouse->GetAuction(srlPacket.auctionId);
    if (auction == nullptr)
        return;

    creature->auctionHouse->QueueDeletion(auction, AUCTION_REMOVE_CANCELLED);

    SendPacket(SmsgAuctionCommandResult(srlPacket.auctionId, AUCTION_CANCEL, AUCTION_ERROR_NONE).serialise().get());

    creature->auctionHouse->SendOwnerListPacket(_player, nullptr);
}

void WorldSession::handleAuctionListBidderItems(WorldPacket& recvPacket)
{
    CmsgAuctionListIBidderItemse srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_LIST_BIDDER_ITEMS %u (lowguid)", srlPacket.guid.getGuidLow());

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.guid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    creature->auctionHouse->SendBidListPacket(_player, &recvPacket);
}

void WorldSession::handleAuctionListPendingSales(WorldPacket& recvPacket)
{
#if VERSION_STRING > TBC
    CmsgAuctionListIPendingSales srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_LIST_PRENDING_SALES %u (lowguid)", srlPacket.guid.getGuidLow());

    //\todo SMSG_AUCTION_LIST_PENDING_SALES needs to be researched!
#endif
}

void WorldSession::handleAuctionSellItem(WorldPacket& recvPacket)
{
    CmsgAuctionSellItem srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_SELL_ITEM");

    if (!srlPacket.bidMoney || !srlPacket.expireTime)
        return;

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.auctioneerGuid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    const auto auctionHouse = creature->auctionHouse;
    srlPacket.expireTime *= MINUTE;

    switch (srlPacket.expireTime)
    {
        case 1 * MIN_AUCTION_TIME:
        case 2 * MIN_AUCTION_TIME:
        case 4 * MIN_AUCTION_TIME:
            break;
        default:
            return;
    }

    Item* items[MAX_AUCTION_ITEMS];

    uint32_t finalCount = 0;

    for (uint32_t i = 0; i < srlPacket.itemsCount; ++i)
    {
        const auto item = _player->getItemInterface()->GetItemByGUID(srlPacket.itemGuids[i]);
        if (!item)
        {
            _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_ITEM);
            return;
        }

        items[i] = item;
        finalCount += srlPacket.count[i];
    }

    if (!finalCount)
    {
        _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_INTERNAL);
        return;
    }

    for (uint32_t i = 0; i < srlPacket.itemsCount; ++i)
    {
        if (items[i] == nullptr || items[i]->getStackCount() < finalCount)
        {
            _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_INTERNAL);
            return;
        }
    }

    for (uint32_t i = 0; i < srlPacket.itemsCount; ++i)
    {
        if (items[i] == nullptr)
        {
            _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_INTERNAL);
            return;
        }

        const uint32_t item_worth = items[i]->getItemProperties()->SellPrice * items[i]->getStackCount();
        const uint32_t item_deposit = static_cast<uint32_t>(item_worth * auctionHouse->deposit_percent) * static_cast<uint32_t>(srlPacket.expireTime / 240.0f);

        if (!_player->hasEnoughCoinage(item_deposit))
        {
            _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_MONEY);
            return;
        }

        _player->modCoinage(-int32(item_deposit));

        const auto item = _player->getItemInterface()->SafeRemoveAndRetreiveItemByGuid(srlPacket.itemGuids[i], false);
        if (!item)
        {
            _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_ITEM);
            return;
        };

        if (item->IsInWorld())
            item->RemoveFromWorld();

        item->setOwner(nullptr);
        item->m_isDirty = true;
        item->SaveToDB(INVENTORY_SLOT_NOT_SET, 0, true, nullptr);

        const auto auction = new Auction;
        auction->BuyoutPrice = static_cast<uint32_t>(srlPacket.buyoutPrice);
        auction->ExpiryTime = static_cast<uint32_t>(UNIXTIME) + srlPacket.expireTime * MINUTE;
        auction->StartingPrice = static_cast<uint32_t>(srlPacket.bidMoney);
        auction->HighestBid = 0;
        auction->HighestBidder = 0;
        auction->Id = sAuctionMgr.GenerateAuctionId();
        auction->Owner = _player->getGuidLow();
        auction->pItem = item;
        auction->Deleted = false;
        auction->DeletedReason = 0;
        auction->DepositAmount = item_deposit;

        auctionHouse->AddAuction(auction);
        auction->SaveToDB(auctionHouse->GetID());

        _player->sendAuctionCommandResult(nullptr, AUCTION_CREATE, AUCTION_ERROR_NONE);
    }

    auctionHouse->SendOwnerListPacket(_player, &recvPacket);
}

void WorldSession::handleAuctionPlaceBid(WorldPacket& recvPacket)
{
    CmsgAuctionPlaceBid srlPacket;
    if (!srlPacket.deserialise(recvPacket))
        return;

    LogDebugFlag(LF_OPCODE, "Received CMSG_AUCTION_PLACE_BID: %u (auctionId), %u (price)", srlPacket.auctionId, srlPacket.price);

    const auto creature = _player->GetMapMgr()->GetCreature(srlPacket.guid.getGuidLow());
    if (creature == nullptr || creature->auctionHouse == nullptr)
        return;

    const auto auctionHouse = creature->auctionHouse;
    const auto auction = auctionHouse->GetAuction(srlPacket.auctionId);
    if (auction == nullptr || !auction->Owner)
    {
        SendPacket(SmsgAuctionCommandResult(0, AUCTION_BID, AUCTION_ERROR_INTERNAL, 0).serialise().get());
        return;
    }

    if (auction->Owner == _player->getGuidLow())
    {
        SendPacket(SmsgAuctionCommandResult(0, AUCTION_BID, AUCTION_ERROR_BID_OWN_AUCTION, 0).serialise().get());
        return;
    }

    if (auction->HighestBid > srlPacket.price && srlPacket.price != auction->BuyoutPrice)
    {
        SendPacket(SmsgAuctionCommandResult(0, AUCTION_BID, AUCTION_ERROR_INTERNAL, 0).serialise().get());
        return;
    }

    if (!_player->hasEnoughCoinage(srlPacket.price))
    {
        SendPacket(SmsgAuctionCommandResult(0, AUCTION_BID, AUCTION_ERROR_MONEY, 0).serialise().get());
        return;
    }

    _player->modCoinage(-static_cast<int32_t>(srlPacket.price));
    if (auction->HighestBidder != 0)
    {
        char subject[100];
        snprintf(subject, 100, "%u:0:0", static_cast<int>(auction->pItem->getEntry()));
        sMailSystem.SendAutomatedMessage(MAIL_TYPE_AUCTION, auctionHouse->GetID(), auction->HighestBidder, subject, "", auction->HighestBid, 0, 0, MAIL_STATIONERY_AUCTION);

        if (auction->HighestBidder != _player->getGuidLow())
            auctionHouse->SendAuctionOutBidNotificationPacket(auction, _player->getGuid(), srlPacket.price);
    }

    if (auction->BuyoutPrice == srlPacket.price)
    {
        auction->HighestBidder = _player->getGuidLow();
        auction->HighestBid = srlPacket.price;

        auctionHouse->QueueDeletion(auction, AUCTION_REMOVE_WON);

        SendPacket(SmsgAuctionCommandResult(auction->Id, AUCTION_BID, AUCTION_ERROR_NONE, 0).serialise().get());
        auctionHouse->SendAuctionBuyOutNotificationPacket(auction);
    }
    else
    {
        auction->HighestBidder = _player->getGuidLow();
        auction->HighestBid = srlPacket.price;
        auction->UpdateInDB();

        SendPacket(SmsgAuctionCommandResult(auction->Id, AUCTION_BID, AUCTION_ERROR_NONE, 0).serialise().get());
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.

#include <gtk/gtk.h>

#include "views/controls/combobox/native_combobox_gtk.h"

#include "app/combobox_model.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "views/controls/combobox/combobox.h"

namespace views {

////////////////////////////////////////////////////////////////////////////////
// NativeComboboxGtk, public:

NativeComboboxGtk::NativeComboboxGtk(Combobox* combobox)
    : combobox_(combobox) {
  set_focus_view(combobox);
}

NativeComboboxGtk::~NativeComboboxGtk() {
}

////////////////////////////////////////////////////////////////////////////////
// NativeComboboxGtk, NativeComboboxWrapper implementation:

void NativeComboboxGtk::UpdateFromModel() {
  if (!native_view())
    return;

  preferred_size_ = gfx::Size();

  GtkListStore* store =
      GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(native_view())));
  ComboboxModel* model = combobox_->model();
  int count = model->GetItemCount();
  gtk_list_store_clear(store);
  GtkTreeIter iter;
  while (count-- > 0) {
    gtk_list_store_prepend(store, &iter);
    gtk_list_store_set(store, &iter,
                       0, WideToUTF8(model->GetItemAt(count)).c_str(),
                       -1);
  }
}

void NativeComboboxGtk::UpdateSelectedItem() {
  if (!native_view())
    return;
  gtk_combo_box_set_active(
      GTK_COMBO_BOX(native_view()), combobox_->selected_item());
}

void NativeComboboxGtk::UpdateEnabled() {
  SetEnabled(combobox_->IsEnabled());
}

int NativeComboboxGtk::GetSelectedItem() const {
  if (!native_view())
    return 0;
  return gtk_combo_box_get_active(GTK_COMBO_BOX(native_view()));
}

bool NativeComboboxGtk::IsDropdownOpen() const {
  if (!native_view())
    return false;
  gboolean popup_shown;
  g_object_get(G_OBJECT(native_view()), "popup-shown", &popup_shown, NULL);
  return popup_shown;
}

gfx::Size NativeComboboxGtk::GetPreferredSize() {
  if (!native_view())
    return gfx::Size();

  if (preferred_size_.IsEmpty()) {
    GtkRequisition size_request = { 0, 0 };
    gtk_widget_size_request(native_view(), &size_request);
    // TODO(oshima|scott): we may not need ::max to 29. revisit this.
    preferred_size_.SetSize(size_request.width,
                            std::max(size_request.height, 29));
  }
  return preferred_size_;
}

View* NativeComboboxGtk::GetView() {
  return this;
}

void NativeComboboxGtk::SetFocus() {
  Focus();
}

gfx::NativeView NativeComboboxGtk::GetTestingHandle() const {
  return native_view();
}

////////////////////////////////////////////////////////////////////////////////
// NativeComboboxGtk, NativeControlGtk overrides:
void NativeComboboxGtk::CreateNativeControl() {
  GtkListStore* store = gtk_list_store_new(1, G_TYPE_STRING);
  GtkWidget* widget = gtk_combo_box_new_with_model(GTK_TREE_MODEL(store));
  g_object_unref(G_OBJECT(store));

  GtkCellRenderer* cell = gtk_cell_renderer_text_new();
  gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(widget), cell, TRUE);
  gtk_cell_layout_set_attributes(
      GTK_CELL_LAYOUT(widget), cell, "text", 0, NULL);
  g_signal_connect(G_OBJECT(widget), "changed",
                   G_CALLBACK(CallChanged), this);

  NativeControlCreated(widget);
}

void NativeComboboxGtk::NativeControlCreated(GtkWidget* native_control) {
  NativeControlGtk::NativeControlCreated(native_control);

  // Set the data from combobox
  UpdateFromModel();
  // and show the 1st item by default.
  gtk_combo_box_set_active(GTK_COMBO_BOX(native_control), 0);
}

////////////////////////////////////////////////////////////////////////////////
// NativeComboboxGtk, private:
void NativeComboboxGtk::SelectionChanged() {
  combobox_->SelectionChanged();
}

// static
void NativeComboboxGtk::CallChanged(GtkWidget* widget,
                                    NativeComboboxGtk* combo) {
  combo->SelectionChanged();
}

////////////////////////////////////////////////////////////////////////////////
// NativeComboboxWrapper, public:

// static
NativeComboboxWrapper* NativeComboboxWrapper::CreateWrapper(
    Combobox* combobox) {
  return new NativeComboboxGtk(combobox);
}

}  // namespace views
<commit_msg>style fix. the header for .cc has to be the 1st include.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.

#include "views/controls/combobox/native_combobox_gtk.h"

#include <gtk/gtk.h>

#include "app/combobox_model.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "views/controls/combobox/combobox.h"

namespace views {

////////////////////////////////////////////////////////////////////////////////
// NativeComboboxGtk, public:

NativeComboboxGtk::NativeComboboxGtk(Combobox* combobox)
    : combobox_(combobox) {
  set_focus_view(combobox);
}

NativeComboboxGtk::~NativeComboboxGtk() {
}

////////////////////////////////////////////////////////////////////////////////
// NativeComboboxGtk, NativeComboboxWrapper implementation:

void NativeComboboxGtk::UpdateFromModel() {
  if (!native_view())
    return;

  preferred_size_ = gfx::Size();

  GtkListStore* store =
      GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(native_view())));
  ComboboxModel* model = combobox_->model();
  int count = model->GetItemCount();
  gtk_list_store_clear(store);
  GtkTreeIter iter;
  while (count-- > 0) {
    gtk_list_store_prepend(store, &iter);
    gtk_list_store_set(store, &iter,
                       0, WideToUTF8(model->GetItemAt(count)).c_str(),
                       -1);
  }
}

void NativeComboboxGtk::UpdateSelectedItem() {
  if (!native_view())
    return;
  gtk_combo_box_set_active(
      GTK_COMBO_BOX(native_view()), combobox_->selected_item());
}

void NativeComboboxGtk::UpdateEnabled() {
  SetEnabled(combobox_->IsEnabled());
}

int NativeComboboxGtk::GetSelectedItem() const {
  if (!native_view())
    return 0;
  return gtk_combo_box_get_active(GTK_COMBO_BOX(native_view()));
}

bool NativeComboboxGtk::IsDropdownOpen() const {
  if (!native_view())
    return false;
  gboolean popup_shown;
  g_object_get(G_OBJECT(native_view()), "popup-shown", &popup_shown, NULL);
  return popup_shown;
}

gfx::Size NativeComboboxGtk::GetPreferredSize() {
  if (!native_view())
    return gfx::Size();

  if (preferred_size_.IsEmpty()) {
    GtkRequisition size_request = { 0, 0 };
    gtk_widget_size_request(native_view(), &size_request);
    // TODO(oshima|scott): we may not need ::max to 29. revisit this.
    preferred_size_.SetSize(size_request.width,
                            std::max(size_request.height, 29));
  }
  return preferred_size_;
}

View* NativeComboboxGtk::GetView() {
  return this;
}

void NativeComboboxGtk::SetFocus() {
  Focus();
}

gfx::NativeView NativeComboboxGtk::GetTestingHandle() const {
  return native_view();
}

////////////////////////////////////////////////////////////////////////////////
// NativeComboboxGtk, NativeControlGtk overrides:
void NativeComboboxGtk::CreateNativeControl() {
  GtkListStore* store = gtk_list_store_new(1, G_TYPE_STRING);
  GtkWidget* widget = gtk_combo_box_new_with_model(GTK_TREE_MODEL(store));
  g_object_unref(G_OBJECT(store));

  GtkCellRenderer* cell = gtk_cell_renderer_text_new();
  gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(widget), cell, TRUE);
  gtk_cell_layout_set_attributes(
      GTK_CELL_LAYOUT(widget), cell, "text", 0, NULL);
  g_signal_connect(G_OBJECT(widget), "changed",
                   G_CALLBACK(CallChanged), this);

  NativeControlCreated(widget);
}

void NativeComboboxGtk::NativeControlCreated(GtkWidget* native_control) {
  NativeControlGtk::NativeControlCreated(native_control);

  // Set the data from combobox
  UpdateFromModel();
  // and show the 1st item by default.
  gtk_combo_box_set_active(GTK_COMBO_BOX(native_control), 0);
}

////////////////////////////////////////////////////////////////////////////////
// NativeComboboxGtk, private:
void NativeComboboxGtk::SelectionChanged() {
  combobox_->SelectionChanged();
}

// static
void NativeComboboxGtk::CallChanged(GtkWidget* widget,
                                    NativeComboboxGtk* combo) {
  combo->SelectionChanged();
}

////////////////////////////////////////////////////////////////////////////////
// NativeComboboxWrapper, public:

// static
NativeComboboxWrapper* NativeComboboxWrapper::CreateWrapper(
    Combobox* combobox) {
  return new NativeComboboxGtk(combobox);
}

}  // namespace views
<|endoftext|>


<commit_before>/**
   @file ast.cpp
   @brief Implementation file for AST-related classes
   @copyright 2014 Assured Information Security, Inc.
   @author Jacob Torrey <torreyj@ainfosec.com>

   Stores the implementations for the AST classes. Includes pretty-printing logic
   and some operator overloads for AST manipulation and analysis.
*/
#include "ast.h"
#include "parser.h"

/**
   Overload for the == operator to allow for simple comparison of two NIdentifiers

   @param i1 First NIdentifier to compare
   @param i2 Second NIdentifier to compare
   @return true if the Identifiers resolve to the same value, false otherwise
*/
bool operator==(const NIdentifier & i1, const NIdentifier & i2)
{
  return i1.value == i2.value;
}

/**
   Overload for the << operator to allow pretty printing of AST objects and AST as a whole

   @param os Output stream to print to
   @param node Node to pretty-print
   @return Output stream passed in
*/
std::ostream & operator<<(std::ostream & os, const Node & node)
{
  node.print(os);
  return os;
}

std::ostream & NBlock::print(std::ostream & os) const
{
    os << "Block: {" << std::endl;
    for (int i = 0; i < statements.size(); i++)
    {
      os << *(statements[i]) << std::endl;
    }
    os << "}" << std::endl;
    return os;
}

std::ostream & NVariableDeclaration::print(std::ostream & os) const
{
  if (!type.isList)
  {
      os << "Variable declared --- (" << type << " " << ident << ")";
  }
  else
  {
      os << "List declared --- (" << type << " " << ident << "[])";
  }
  if (initializationExpression != NULL)
  {
      os << " = " << *initializationExpression;
  }
  os << std::endl;
  return os;
}

std::ostream & NFunctionDeclaration::print(std::ostream & os) const
{
  os << "Function declared --- (" << type << " " << ident << "(";
  for (int i = 0; i < variables.size(); i++)
    {
      os << *(variables[i]) << " ";
    }
  os << ") " << *body << ")";
  os << std::endl;

  return os;
}

std::ostream & NStructureDeclaration::print(std::ostream & os) const
{
  os << "Struct declared --- (" << ident << " {";
  for (int i = 0; i < members.size(); i++)
    {
      os << *(members[i]) << " ";
    }
  os << "})";
  os << std::endl;

  return os;
}

std::ostream & NAssignmentStatement::print(std::ostream & os) const
{
  os << "(Assignment: " << ident << " = " << expr << ")" << std::endl;
  return os;
}

std::ostream & NListAssignmentStatement::print(std::ostream & os) const
{
  os << "(Assignment: " << list << " = " << expr << "<" << std::endl;
  return os;
}

std::ostream & NStructureAssignmentStatement::print(std::ostream & os) const
{
  os << "(Assignment: " << structure << " = " << expr << ")" << std::endl;
  return os;
}

std::ostream & NBinaryOperator::print(std::ostream & os) const
{
  std::string symbol;
  switch(op)
  {
  case TMUL:
      symbol = "*";
      break;
  case TADD:
      symbol = "+";
      break;
  case TDIV:
      symbol = "/";
      break;
  case TSUB:
      symbol = "-";
      break;
  case TMOD:
      symbol = "%";
      break;
  case TBAND:
      symbol = "&";
      break;
  case TBXOR:
      symbol = "^";
      break;
  case TBOR:
      symbol = "|";
      break;
  case TLNOT:
      symbol = "!";
      break;
  case TLOR:
      symbol = "||";
      break;
  case TLAND:
      symbol = "&&";
      break;
  default:
      symbol = "UNKNOWN OP";
      break;

  }
  os << "(BINOP: " << lhs << " " << symbol << " " << rhs << ")" << std::endl;
  return os;
}

std::ostream & NIdentifier::print(std::ostream & os) const
{
  os << "Identifier: " << value;
  return os;
}

std::ostream & NListAccess::print(std::ostream & os) const
{
  os << "(List access: " << ident << "[" << index << "])";
  return os;
}

std::ostream & NVariableAccess::print(std::ostream & os) const
{
  os << "(Variable access: " << ident << ")";
  return os;
}

std::ostream & NStructureAccess::print(std::ostream & os) const
{
  os << "(Struct access: " << ident << "." << member << ")";
  return os;
}

std::ostream & NReturn::print(std::ostream & os) const
{
  os << "(Return: " << retExpr << ")";
  os << std::endl;
  return os;
}

std::ostream & NDouble::print(std::ostream & os) const
{
  os << "DOUBLE:" << value;
  return os;
}

std::ostream & NBool::print(std::ostream & os) const
{
  os << "BOOL:" << value;
  return os;
}

std::ostream & NInt::print(std::ostream & os) const
{
  os << "INT:" << value;
  return os;
}

std::ostream & NValue::print(std::ostream & os) const
{
  os << "(Generic NValue)" << std::endl;
  return os;
}

std::ostream & NUInt::print(std::ostream & os) const
{
  os << "UINT:" << value;
  return os;
}

std::ostream & NString::print(std::ostream & os) const
{
  os << "STRING:" << value;
  return os;
}

std::ostream & NLoopStatement::print(std::ostream & os) const
{
  os << "Loop: " << list << " as " << asVar << std::endl;
  os << "{" << loopBlock << "}" << std::endl;
  return os;
}

std::ostream & NIfStatement::print(std::ostream & os) const
{
  if (elseblock == NULL && elseif == NULL)
    os << "If: (" << condition << ") then " << thenblock << std::endl;
  if (elseblock != NULL && elseif == NULL)
    os << "If: (" << condition << ") then: " << thenblock << " else: " << *(elseblock) << std::endl;
  if (elseblock == NULL && elseif != NULL)
    {
      os << "If: (" << condition << ") then " << thenblock << std::endl;
      os << "Else if: " << *(elseif) << std::endl;
    }
  if (elseblock != NULL && elseif != NULL)
    {
      os << "If: (" << condition << ") then " << thenblock << std::endl;
      os << "Else if: " << *(elseif) << " else: " << *(elseblock) << std::endl;
    }
  return os;
}

std::ostream & NFunctionCall::print(std::ostream & os) const
{
  os << "Function Call: " << ident << std::endl;
  for (int i = 0; i < args.size(); i++)
    {
      os << args[i] << std::endl;
    }
  return os;
}

std::ostream & NList::print(std::ostream & os) const
{
    os << "List: [";
    for (int i = 0; i < value.size(); i++)
    {
	os << *(value[i]) << " ";
    }
    os << "]" << std::endl;
    return os;
}
<commit_msg>Adding comments and improving print functions in ast.cpp<commit_after>/**
   @file ast.cpp
   @brief Implementation file for AST-related classes
   @copyright 2014 Assured Information Security, Inc.
   @author Jacob Torrey <torreyj@ainfosec.com>

   Stores the implementations for the AST classes. Includes pretty-printing logic
   and some operator overloads for AST manipulation and analysis.
*/
#include "ast.h"
#include "parser.h"

/**
   Overload for the == operator to allow for simple comparison of two NIdentifiers.
   The NIdentifier values being compared are of type string, which represent the names of
   variables, lists, structs, struct members, etc.

   @param i1 First NIdentifier to compare
   @param i2 Second NIdentifier to compare
   @return true if the Identifiers resolve to the same value, false otherwise
*/
bool operator==(const NIdentifier & i1, const NIdentifier & i2)
{
  return i1.value == i2.value;
}

/**
   Overload for the << operator to allow pretty printing of AST objects and AST as a whole

   @param os Output stream to print to
   @param node Node to pretty-print
   @return Output stream passed in
*/
std::ostream & operator<<(std::ostream & os, const Node & node)
{
  node.print(os);
  return os;
}

/**
   Print function for NBlock objects in the AST. Each block is composed of a vector of
   statements. This function iterators over the typedef std::vector<NStatement*> StatementList,
   printing each each statement in a given block, and returning the output stream.

   @param os Output stream to print to
   @return Output stream passed in
*/
std::ostream & NBlock::print(std::ostream & os) const
{
    os << "Block: {" << std::endl;

    for (StatementList::const_iterator it = statements.begin(); it != statements.end(); ++it)
      os << *(*it) << std::endl;

    os << "}" << std::endl;
    return os;
}

/**
   Print function for NVariableDeclaration objects. There are three members of the
   NVariableDeclaration object that are printed:

   1) Type
   2) NIdentifier (Variable name)
   3) Associated value or RHS (optional)

   The initializationExpression is the RHS in variable assignments (e.g. the 4 in int a = 4).
   If initializationExpression is NULL, then the no value was assigned to variable (e.g. int a).

   @param os Output stream to print to
   @return Output stream passed in
*/
std::ostream & NVariableDeclaration::print(std::ostream & os) const
{
  if (!type.isList)
  {
      os << "Variable declared --- (" << type << " " << ident << ")";
  }
  else
  {
      os << "List declared --- (" << type << " " << ident << "[])";
  }
  if (initializationExpression != NULL)
  {
      os << " = " << *initializationExpression;
  }
  os << std::endl;
  return os;
}

/**
   Print function for NFunctionDeclaration objects. It first prints the return type
   and name of the function followed by the arguments contained within the
   typedef std::vector<NVariableDeclaration *> VariableList. Then, the NBlock body
   of the function is printed.

   @param os Output stream to print to
   @return Output stream passed in
*/
std::ostream & NFunctionDeclaration::print(std::ostream & os) const
{
  os << "Function declared --- (" << type << " " << ident << "(";

  for (VariableList::const_iterator it = variables.begin(); it != variables.end(); ++it)
      os << *(*it) << ") ";

  os << *body << ")";
  os << std::endl;

  return os;
}

std::ostream & NStructureDeclaration::print(std::ostream & os) const
{
  os << "Struct declared --- (" << ident << " {";
  for (int i = 0; i < members.size(); i++)
    {
      os << *(members[i]) << " ";
    }
  os << "})";
  os << std::endl;

  return os;
}

std::ostream & NAssignmentStatement::print(std::ostream & os) const
{
  os << "(Assignment: " << ident << " = " << expr << ")" << std::endl;
  return os;
}

std::ostream & NListAssignmentStatement::print(std::ostream & os) const
{
  os << "(Assignment: " << list << " = " << expr << "<" << std::endl;
  return os;
}

std::ostream & NStructureAssignmentStatement::print(std::ostream & os) const
{
  os << "(Assignment: " << structure << " = " << expr << ")" << std::endl;
  return os;
}

std::ostream & NBinaryOperator::print(std::ostream & os) const
{
  std::string symbol;
  switch(op)
  {
  case TMUL:
      symbol = "*";
      break;
  case TADD:
      symbol = "+";
      break;
  case TDIV:
      symbol = "/";
      break;
  case TSUB:
      symbol = "-";
      break;
  case TMOD:
      symbol = "%";
      break;
  case TBAND:
      symbol = "&";
      break;
  case TBXOR:
      symbol = "^";
      break;
  case TBOR:
      symbol = "|";
      break;
  case TLNOT:
      symbol = "!";
      break;
  case TLOR:
      symbol = "||";
      break;
  case TLAND:
      symbol = "&&";
      break;
  default:
      symbol = "UNKNOWN OP";
      break;

  }
  os << "(BINOP: " << lhs << " " << symbol << " " << rhs << ")" << std::endl;
  return os;
}

std::ostream & NIdentifier::print(std::ostream & os) const
{
  os << "Identifier: " << value;
  return os;
}

std::ostream & NListAccess::print(std::ostream & os) const
{
  os << "(List access: " << ident << "[" << index << "])";
  return os;
}

std::ostream & NVariableAccess::print(std::ostream & os) const
{
  os << "(Variable access: " << ident << ")";
  return os;
}

std::ostream & NStructureAccess::print(std::ostream & os) const
{
  os << "(Struct access: " << ident << "." << member << ")";
  return os;
}

std::ostream & NReturn::print(std::ostream & os) const
{
  os << "(Return: " << retExpr << ")";
  os << std::endl;
  return os;
}

std::ostream & NDouble::print(std::ostream & os) const
{
  os << "DOUBLE:" << value;
  return os;
}

std::ostream & NBool::print(std::ostream & os) const
{
  os << "BOOL:" << value;
  return os;
}

std::ostream & NInt::print(std::ostream & os) const
{
  os << "INT:" << value;
  return os;
}

std::ostream & NValue::print(std::ostream & os) const
{
  os << "(Generic NValue)" << std::endl;
  return os;
}

std::ostream & NUInt::print(std::ostream & os) const
{
  os << "UINT:" << value;
  return os;
}

std::ostream & NString::print(std::ostream & os) const
{
  os << "STRING:" << value;
  return os;
}

std::ostream & NLoopStatement::print(std::ostream & os) const
{
  os << "Loop: " << list << " as " << asVar << std::endl;
  os << "{" << loopBlock << "}" << std::endl;
  return os;
}

std::ostream & NIfStatement::print(std::ostream & os) const
{
  if (elseblock == NULL && elseif == NULL)
    os << "If: (" << condition << ") then " << thenblock << std::endl;
  if (elseblock != NULL && elseif == NULL)
    os << "If: (" << condition << ") then: " << thenblock << " else: " << *(elseblock) << std::endl;
  if (elseblock == NULL && elseif != NULL)
    {
      os << "If: (" << condition << ") then " << thenblock << std::endl;
      os << "Else if: " << *(elseif) << std::endl;
    }
  if (elseblock != NULL && elseif != NULL)
    {
      os << "If: (" << condition << ") then " << thenblock << std::endl;
      os << "Else if: " << *(elseif) << " else: " << *(elseblock) << std::endl;
    }
  return os;
}

std::ostream & NFunctionCall::print(std::ostream & os) const
{
  os << "Function Call: " << ident << std::endl;
  for (int i = 0; i < args.size(); i++)
    {
      os << args[i] << std::endl;
    }
  return os;
}

std::ostream & NList::print(std::ostream & os) const
{
    os << "List: [";
    for (int i = 0; i < value.size(); i++)
    {
	os << *(value[i]) << " ";
    }
    os << "]" << std::endl;
    return os;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <string>
#include <stdexcept>
#include <sstream>
#include <iomanip>
#include <cctype>
#include <algorithm>
#include <iostream>
#include <limits>

#include <boost/optional.hpp>
#include <boost/array.hpp>

#include "libtorrent/assert.hpp"
#include "libtorrent/escape_string.hpp"

namespace libtorrent
{

	// lexical_cast's result depends on the locale. We need
	// a well defined result
	boost::array<char, 3 + std::numeric_limits<size_type>::digits10> to_string(size_type n)
	{
		boost::array<char, 3 + std::numeric_limits<size_type>::digits10> ret;
		char *p = &ret.back();;
		*p = '\0';
		unsigned_size_type un = n;
		if (n < 0)  un = -un;
		do {
			*--p = '0' + un % 10;
			un /= 10;
		} while (un);
		if (n < 0) *--p = '-';
		std::memmove(&ret.front(), p, sizeof(ret.elems));
		return ret;
	}

	std::string unescape_string(std::string const& s)
	{
		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
		{
			if(*i == '+')
			{
				ret += ' ';
			}
			else if (*i != '%')
			{
				ret += *i;
			}
			else
			{
				++i;
				if (i == s.end())
#ifdef BOOST_NO_EXCEPTIONS
					return ret;
#else
					throw std::runtime_error("invalid escaped string");
#endif

				int high;
				if(*i >= '0' && *i <= '9') high = *i - '0';
				else if(*i >= 'A' && *i <= 'F') high = *i + 10 - 'A';
				else if(*i >= 'a' && *i <= 'f') high = *i + 10 - 'a';
				else
#ifdef BOOST_NO_EXCEPTIONS
					return ret;
#else
					throw std::runtime_error("invalid escaped string");
#endif

				++i;
				if (i == s.end())
#ifdef BOOST_NO_EXCEPTIONS
					return ret;
#else
					throw std::runtime_error("invalid escaped string");
#endif

				int low;
				if(*i >= '0' && *i <= '9') low = *i - '0';
				else if(*i >= 'A' && *i <= 'F') low = *i + 10 - 'A';
				else if(*i >= 'a' && *i <= 'f') low = *i + 10 - 'a';
				else
#ifdef BOOST_NO_EXCEPTIONS
					return ret;
#else
					throw std::runtime_error("invalid escaped string");
#endif

				ret += char(high * 16 + low);
			}
		}
		return ret;
	}

	std::string escape_string(const char* str, int len)
	{
		TORRENT_ASSERT(str != 0);
		TORRENT_ASSERT(len >= 0);
		// http://www.ietf.org/rfc/rfc2396.txt
		// section 2.3
		// some trackers seems to require that ' is escaped
//		static const char unreserved_chars[] = "-_.!~*'()";
		static const char unreserved_chars[] = "-_.!~*()"
			"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
			"0123456789";

		std::stringstream ret;
		ret << std::hex << std::setfill('0');
		for (int i = 0; i < len; ++i)
		{
			if (std::count(
					unreserved_chars
					, unreserved_chars+sizeof(unreserved_chars)-1
					, *str))
			{
				ret << *str;
			}
			else
			{
				ret << '%'
					<< std::setw(2)
					<< (int)static_cast<unsigned char>(*str);
			}
			++str;
		}
		return ret.str();
	}

	std::string escape_path(const char* str, int len)
	{
		TORRENT_ASSERT(str != 0);
		TORRENT_ASSERT(len >= 0);
		static const char unreserved_chars[] = "/-_.!~*()"
			"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
			"0123456789";

		std::stringstream ret;
		ret << std::hex << std::setfill('0');
		for (int i = 0; i < len; ++i)
		{
			if (std::count(
					unreserved_chars
					, unreserved_chars+sizeof(unreserved_chars)-1
					, *str))
			{
				ret << *str;
			}
			else
			{
				ret << '%'
					<< std::setw(2)
					<< (int)static_cast<unsigned char>(*str);
			}
			++str;
		}
		return ret.str();
	}

	std::string base64encode(const std::string& s)
	{
		static const char base64_table[] =
		{
			'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
			'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
			'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
			'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
			'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
			'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
			'w', 'x', 'y', 'z', '0', '1', '2', '3',
			'4', '5', '6', '7', '8', '9', '+', '/'
		};

		unsigned char inbuf[3];
		unsigned char outbuf[4];

		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end();)
		{
			// available input is 1,2 or 3 bytes
			// since we read 3 bytes at a time at most
			int available_input = (std::min)(3, (int)std::distance(i, s.end()));

			// clear input buffer
			std::fill(inbuf, inbuf+3, 0);

			// read a chunk of input into inbuf
			std::copy(i, i + available_input, inbuf);
			i += available_input;

			// encode inbuf to outbuf
			outbuf[0] = (inbuf[0] & 0xfc) >> 2;
			outbuf[1] = ((inbuf[0] & 0x03) << 4) | ((inbuf [1] & 0xf0) >> 4);
			outbuf[2] = ((inbuf[1] & 0x0f) << 2) | ((inbuf [2] & 0xc0) >> 6);
			outbuf[3] = inbuf[2] & 0x3f;

			// write output
			for (int j = 0; j < available_input+1; ++j)
			{
				ret += base64_table[outbuf[j]];
			}

			// write pad
			for (int j = 0; j < 3 - available_input; ++j)
			{
				ret += '=';
			}
		}
		return ret;
	}

	std::string base32encode(std::string const& s)
	{
		static const char base32_table[] =
		{
			'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
			'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
			'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
			'Y', 'Z', '2', '3', '4', '5', '6', '7'
		};

		int input_output_mapping[] = {0, 2, 4, 5, 7, 8};

		unsigned char inbuf[5];
		unsigned char outbuf[8];

		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end();)
		{
			int available_input = (std::min)(5, (int)std::distance(i, s.end()));

			// clear input buffer
			std::fill(inbuf, inbuf+5, 0);

			// read a chunk of input into inbuf
			std::copy(i, i + available_input, inbuf);
			i += available_input;

			// encode inbuf to outbuf
			outbuf[0] = (inbuf[0] & 0xf8) >> 3;
			outbuf[1] = ((inbuf[0] & 0x07) << 2) | ((inbuf[1] & 0xc0) >> 6);
			outbuf[2] = ((inbuf[1] & 0x3e) >> 1);
			outbuf[3] = ((inbuf[1] & 0x01) << 4) | ((inbuf[2] & 0xf0) >> 4);
			outbuf[4] = ((inbuf[2] & 0x0f) << 1) | ((inbuf[3] & 0x80) >> 7);
			outbuf[5] = ((inbuf[3] & 0x7c) >> 2);
			outbuf[6] = ((inbuf[3] & 0x03) << 3) | ((inbuf[4] & 0xe0) >> 5);
			outbuf[7] = inbuf[4] & 0x1f;

			// write output
			int num_out = input_output_mapping[available_input];
			for (int j = 0; j < num_out; ++j)
			{
				ret += base32_table[outbuf[j]];
			}

			// write pad
			for (int j = 0; j < 8 - num_out; ++j)
			{
				ret += '=';
			}
		}
		return ret;
	}

	std::string base32decode(std::string const& s)
	{
		unsigned char inbuf[8];
		unsigned char outbuf[5];

		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end();)
		{
			int available_input = (std::min)(8, (int)std::distance(i, s.end()));

			int pad_start = 0;
			if (available_input < 8) pad_start = available_input;

			// clear input buffer
			std::fill(inbuf, inbuf+8, 0);
			for (int j = 0; j < available_input; ++j)
			{
				char in = std::toupper(*i++);
				if (in >= 'A' && in <= 'Z')
					inbuf[j] = in - 'A';
				else if (in >= '2' && in <= '7')
					inbuf[j] = in - '2' + ('Z' - 'A') + 1;
				else if (in == '=')
				{
					inbuf[j] = 0;
					if (pad_start == 0) pad_start = j;
				}
				else if (in == '1')
					inbuf[j] = 'I' - 'A';
				else
					return std::string();
				TORRENT_ASSERT(inbuf[j] == (inbuf[j] & 0x1f));
			}

			// decode inbuf to outbuf
			outbuf[0] = inbuf[0] << 3;
			outbuf[0] |= inbuf[1] >> 2;
			outbuf[1] = (inbuf[1] & 0x3) << 6;
			outbuf[1] |= inbuf[2] << 1;
			outbuf[1] |= (inbuf[3] & 0x10) >> 4;
			outbuf[2] = (inbuf[3] & 0x0f) << 4;
			outbuf[2] |= (inbuf[4] & 0x1e) >> 1;
			outbuf[3] = (inbuf[4] & 0x01) << 7;
			outbuf[3] |= (inbuf[5] & 0x1f) << 2;
			outbuf[3] |= (inbuf[6] & 0x18) >> 3;
			outbuf[4] = (inbuf[6] & 0x07) << 5;
			outbuf[4] |= inbuf[7];

			int input_output_mapping[] = {5, 1, 1, 2, 2, 3, 4, 4, 5};
			int num_out = input_output_mapping[pad_start];

			// write output
			std::copy(outbuf, outbuf + num_out, std::back_inserter(ret));
		}
		return ret;
	}

	boost::optional<std::string> url_has_argument(
		std::string const& url, std::string argument)
	{
		size_t i = url.find('?');
		if (i == std::string::npos) return boost::optional<std::string>();
		++i;

		argument += '=';

		if (url.compare(i, argument.size(), argument) == 0)
		{
			size_t pos = i + argument.size();
			return url.substr(pos, url.find('&', pos) - pos);
		}
		argument.insert(0, "&");
		i = url.find(argument, i);
		if (i == std::string::npos) return boost::optional<std::string>();
		size_t pos = i + argument.size();
		return url.substr(pos, url.find('&', pos) - pos);
	}

	TORRENT_EXPORT std::string to_hex(std::string const& s)
	{
		std::string ret;
		char const* digits = "0123456789abcdef";
		for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
		{
			ret += digits[((unsigned char)*i) >> 4];
			ret += digits[((unsigned char)*i) & 0xf];
		}
		return ret;
	}

}

<commit_msg>added missing include<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <string>
#include <stdexcept>
#include <sstream>
#include <iomanip>
#include <cctype>
#include <algorithm>
#include <iostream>
#include <limits>
#include <cstring>

#include <boost/optional.hpp>
#include <boost/array.hpp>

#include "libtorrent/assert.hpp"
#include "libtorrent/escape_string.hpp"

namespace libtorrent
{

	// lexical_cast's result depends on the locale. We need
	// a well defined result
	boost::array<char, 3 + std::numeric_limits<size_type>::digits10> to_string(size_type n)
	{
		boost::array<char, 3 + std::numeric_limits<size_type>::digits10> ret;
		char *p = &ret.back();;
		*p = '\0';
		unsigned_size_type un = n;
		if (n < 0)  un = -un;
		do {
			*--p = '0' + un % 10;
			un /= 10;
		} while (un);
		if (n < 0) *--p = '-';
		std::memmove(&ret.front(), p, sizeof(ret.elems));
		return ret;
	}

	std::string unescape_string(std::string const& s)
	{
		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
		{
			if(*i == '+')
			{
				ret += ' ';
			}
			else if (*i != '%')
			{
				ret += *i;
			}
			else
			{
				++i;
				if (i == s.end())
#ifdef BOOST_NO_EXCEPTIONS
					return ret;
#else
					throw std::runtime_error("invalid escaped string");
#endif

				int high;
				if(*i >= '0' && *i <= '9') high = *i - '0';
				else if(*i >= 'A' && *i <= 'F') high = *i + 10 - 'A';
				else if(*i >= 'a' && *i <= 'f') high = *i + 10 - 'a';
				else
#ifdef BOOST_NO_EXCEPTIONS
					return ret;
#else
					throw std::runtime_error("invalid escaped string");
#endif

				++i;
				if (i == s.end())
#ifdef BOOST_NO_EXCEPTIONS
					return ret;
#else
					throw std::runtime_error("invalid escaped string");
#endif

				int low;
				if(*i >= '0' && *i <= '9') low = *i - '0';
				else if(*i >= 'A' && *i <= 'F') low = *i + 10 - 'A';
				else if(*i >= 'a' && *i <= 'f') low = *i + 10 - 'a';
				else
#ifdef BOOST_NO_EXCEPTIONS
					return ret;
#else
					throw std::runtime_error("invalid escaped string");
#endif

				ret += char(high * 16 + low);
			}
		}
		return ret;
	}

	std::string escape_string(const char* str, int len)
	{
		TORRENT_ASSERT(str != 0);
		TORRENT_ASSERT(len >= 0);
		// http://www.ietf.org/rfc/rfc2396.txt
		// section 2.3
		// some trackers seems to require that ' is escaped
//		static const char unreserved_chars[] = "-_.!~*'()";
		static const char unreserved_chars[] = "-_.!~*()"
			"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
			"0123456789";

		std::stringstream ret;
		ret << std::hex << std::setfill('0');
		for (int i = 0; i < len; ++i)
		{
			if (std::count(
					unreserved_chars
					, unreserved_chars+sizeof(unreserved_chars)-1
					, *str))
			{
				ret << *str;
			}
			else
			{
				ret << '%'
					<< std::setw(2)
					<< (int)static_cast<unsigned char>(*str);
			}
			++str;
		}
		return ret.str();
	}

	std::string escape_path(const char* str, int len)
	{
		TORRENT_ASSERT(str != 0);
		TORRENT_ASSERT(len >= 0);
		static const char unreserved_chars[] = "/-_.!~*()"
			"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
			"0123456789";

		std::stringstream ret;
		ret << std::hex << std::setfill('0');
		for (int i = 0; i < len; ++i)
		{
			if (std::count(
					unreserved_chars
					, unreserved_chars+sizeof(unreserved_chars)-1
					, *str))
			{
				ret << *str;
			}
			else
			{
				ret << '%'
					<< std::setw(2)
					<< (int)static_cast<unsigned char>(*str);
			}
			++str;
		}
		return ret.str();
	}

	std::string base64encode(const std::string& s)
	{
		static const char base64_table[] =
		{
			'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
			'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
			'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
			'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
			'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
			'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
			'w', 'x', 'y', 'z', '0', '1', '2', '3',
			'4', '5', '6', '7', '8', '9', '+', '/'
		};

		unsigned char inbuf[3];
		unsigned char outbuf[4];

		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end();)
		{
			// available input is 1,2 or 3 bytes
			// since we read 3 bytes at a time at most
			int available_input = (std::min)(3, (int)std::distance(i, s.end()));

			// clear input buffer
			std::fill(inbuf, inbuf+3, 0);

			// read a chunk of input into inbuf
			std::copy(i, i + available_input, inbuf);
			i += available_input;

			// encode inbuf to outbuf
			outbuf[0] = (inbuf[0] & 0xfc) >> 2;
			outbuf[1] = ((inbuf[0] & 0x03) << 4) | ((inbuf [1] & 0xf0) >> 4);
			outbuf[2] = ((inbuf[1] & 0x0f) << 2) | ((inbuf [2] & 0xc0) >> 6);
			outbuf[3] = inbuf[2] & 0x3f;

			// write output
			for (int j = 0; j < available_input+1; ++j)
			{
				ret += base64_table[outbuf[j]];
			}

			// write pad
			for (int j = 0; j < 3 - available_input; ++j)
			{
				ret += '=';
			}
		}
		return ret;
	}

	std::string base32encode(std::string const& s)
	{
		static const char base32_table[] =
		{
			'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
			'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
			'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
			'Y', 'Z', '2', '3', '4', '5', '6', '7'
		};

		int input_output_mapping[] = {0, 2, 4, 5, 7, 8};

		unsigned char inbuf[5];
		unsigned char outbuf[8];

		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end();)
		{
			int available_input = (std::min)(5, (int)std::distance(i, s.end()));

			// clear input buffer
			std::fill(inbuf, inbuf+5, 0);

			// read a chunk of input into inbuf
			std::copy(i, i + available_input, inbuf);
			i += available_input;

			// encode inbuf to outbuf
			outbuf[0] = (inbuf[0] & 0xf8) >> 3;
			outbuf[1] = ((inbuf[0] & 0x07) << 2) | ((inbuf[1] & 0xc0) >> 6);
			outbuf[2] = ((inbuf[1] & 0x3e) >> 1);
			outbuf[3] = ((inbuf[1] & 0x01) << 4) | ((inbuf[2] & 0xf0) >> 4);
			outbuf[4] = ((inbuf[2] & 0x0f) << 1) | ((inbuf[3] & 0x80) >> 7);
			outbuf[5] = ((inbuf[3] & 0x7c) >> 2);
			outbuf[6] = ((inbuf[3] & 0x03) << 3) | ((inbuf[4] & 0xe0) >> 5);
			outbuf[7] = inbuf[4] & 0x1f;

			// write output
			int num_out = input_output_mapping[available_input];
			for (int j = 0; j < num_out; ++j)
			{
				ret += base32_table[outbuf[j]];
			}

			// write pad
			for (int j = 0; j < 8 - num_out; ++j)
			{
				ret += '=';
			}
		}
		return ret;
	}

	std::string base32decode(std::string const& s)
	{
		unsigned char inbuf[8];
		unsigned char outbuf[5];

		std::string ret;
		for (std::string::const_iterator i = s.begin(); i != s.end();)
		{
			int available_input = (std::min)(8, (int)std::distance(i, s.end()));

			int pad_start = 0;
			if (available_input < 8) pad_start = available_input;

			// clear input buffer
			std::fill(inbuf, inbuf+8, 0);
			for (int j = 0; j < available_input; ++j)
			{
				char in = std::toupper(*i++);
				if (in >= 'A' && in <= 'Z')
					inbuf[j] = in - 'A';
				else if (in >= '2' && in <= '7')
					inbuf[j] = in - '2' + ('Z' - 'A') + 1;
				else if (in == '=')
				{
					inbuf[j] = 0;
					if (pad_start == 0) pad_start = j;
				}
				else if (in == '1')
					inbuf[j] = 'I' - 'A';
				else
					return std::string();
				TORRENT_ASSERT(inbuf[j] == (inbuf[j] & 0x1f));
			}

			// decode inbuf to outbuf
			outbuf[0] = inbuf[0] << 3;
			outbuf[0] |= inbuf[1] >> 2;
			outbuf[1] = (inbuf[1] & 0x3) << 6;
			outbuf[1] |= inbuf[2] << 1;
			outbuf[1] |= (inbuf[3] & 0x10) >> 4;
			outbuf[2] = (inbuf[3] & 0x0f) << 4;
			outbuf[2] |= (inbuf[4] & 0x1e) >> 1;
			outbuf[3] = (inbuf[4] & 0x01) << 7;
			outbuf[3] |= (inbuf[5] & 0x1f) << 2;
			outbuf[3] |= (inbuf[6] & 0x18) >> 3;
			outbuf[4] = (inbuf[6] & 0x07) << 5;
			outbuf[4] |= inbuf[7];

			int input_output_mapping[] = {5, 1, 1, 2, 2, 3, 4, 4, 5};
			int num_out = input_output_mapping[pad_start];

			// write output
			std::copy(outbuf, outbuf + num_out, std::back_inserter(ret));
		}
		return ret;
	}

	boost::optional<std::string> url_has_argument(
		std::string const& url, std::string argument)
	{
		size_t i = url.find('?');
		if (i == std::string::npos) return boost::optional<std::string>();
		++i;

		argument += '=';

		if (url.compare(i, argument.size(), argument) == 0)
		{
			size_t pos = i + argument.size();
			return url.substr(pos, url.find('&', pos) - pos);
		}
		argument.insert(0, "&");
		i = url.find(argument, i);
		if (i == std::string::npos) return boost::optional<std::string>();
		size_t pos = i + argument.size();
		return url.substr(pos, url.find('&', pos) - pos);
	}

	TORRENT_EXPORT std::string to_hex(std::string const& s)
	{
		std::string ret;
		char const* digits = "0123456789abcdef";
		for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
		{
			ret += digits[((unsigned char)*i) >> 4];
			ret += digits[((unsigned char)*i) & 0xf];
		}
		return ret;
	}

}

<|endoftext|>


<commit_before>/*
 event_counter.cpp
 Classic Invaders

 Copyright (c) 2013, Todd Steinackle, Simon Que
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted
 provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this list of conditions
 and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the documentation and/or other
 materials provided with the distribution.

 * Neither the name of The No Quarter Arcade (http://www.noquarterarcade.com/)  nor the names of
 its contributors may be used to endorse or promote products derived from this software without
 specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "event_counter.h"

void EventCounter::report()
{
    if (num_loops == 0)
        return;
    printf("Per-loop stats, averaged over %d loops:\n", num_loops);
    printf("- Collision checks: %d\n", num_collision_checks / num_loops);
    printf("- Movement calls: %d\n", num_movement_calls / num_loops);
    printf("- Loop time in ticks: %d\n",
           (latest_time - game_loop_start_time) / num_loops);
    uint32_t total_game_logic_time = 0;
    for (int i = 0; i < MAX_GAME_LOGIC_SECTIONS; ++i) {
        if (game_logic_times[i] == 0)
            continue;
        printf("- Game logic section %d, time in ticks: %d\n", i,
               game_logic_times[i] / num_loops);
        total_game_logic_time += game_logic_times[i];
    }
    printf("- Total game logic time in ticks: %d\n",
           total_game_logic_time / num_loops);
}
<commit_msg>Event counter: print info more compactly<commit_after>/*
 event_counter.cpp
 Classic Invaders

 Copyright (c) 2013, Todd Steinackle, Simon Que
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted
 provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this list of conditions
 and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the documentation and/or other
 materials provided with the distribution.

 * Neither the name of The No Quarter Arcade (http://www.noquarterarcade.com/)  nor the names of
 its contributors may be used to endorse or promote products derived from this software without
 specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "event_counter.h"

void EventCounter::report()
{
    if (num_loops == 0)
        return;
    printf("Per-loop stats, averaged over %d loops:\n", num_loops);
    printf("- Collision checks: %d\n", num_collision_checks / num_loops);
    printf("- Movement calls: %d\n", num_movement_calls / num_loops);
    printf("- Loop time in ticks: %d\n",
           (latest_time - game_loop_start_time) / num_loops);
    uint32_t total_game_logic_time = 0;
    printf("- Per-section game logic times: ");
    for (int i = 0; i < MAX_GAME_LOGIC_SECTIONS; ++i) {
        total_game_logic_time += game_logic_times[i];
        if (game_logic_times[i] >= num_loops)
            printf("%lu ", game_logic_times[i] / num_loops);
        else    // If the rounded-down value is zero, don't bother printing it.
            printf("_ ");   // Just print a placeholder.
    }
    printf("\n");
    printf("- Total game logic time in ticks: %d\n",
           total_game_logic_time / num_loops);
}
<|endoftext|>


<commit_before><commit_msg>change transformation matrix<commit_after><|endoftext|>


<commit_before><commit_msg>planning: add CROSSWALK tag to learning data<commit_after><|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2016-2017 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/postprocessing/processors/hdrbloom.h>
#include <modules/opengl/image/imagegl.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/openglutils.h>
#include <modules/opengl/sharedopenglresources.h>
#include <modules/opengl/geometry/meshgl.h>
#include <random>

namespace inviwo {

// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo HdrBloom::processorInfo_{
    "org.inviwo.HdrBloom",  // Class identifier
    "HDR Bloom",            // Display name
    "Postprocessing",       // Category
    CodeState::Stable,      // Code state
    Tags::GL,               // Tags
};

const ProcessorInfo HdrBloom::getProcessorInfo() const { return processorInfo_; }

HdrBloom::HdrBloom()
    : Processor()
    , inport_("inport")
    , outport_("outport")
    , enable_("enable", "Enable Operation", true)
    , threshold_("threshold", "Threshold", 1.f, 0.f, 10.f)
    , strength_("strength", "Strength", 1.f, 0.f, 3.f)
    , radius_("radius", "Radius", 0.5f, 0.f, 1.f)
    , highPass_("fullscreenquad.vert", "bloomhighpass.frag")
    , blur_("fullscreenquad.vert", "bloomblur.frag")
    , compose_("fullscreenquad.vert", "bloomcompose.frag")
    , width_(0)
    , height_(0)
    , texBright_(size2_t(256, 256), GLFormats::get(DataFormatId::Vec4Float16), GL_LINEAR) {
    addPort(inport_);
    addPort(outport_);

    addProperty(enable_);
    addProperty(threshold_);
    addProperty(strength_);
    addProperty(radius_);

    for (int i = 0; i < Levels; i++) {
        texHorizontal_[i] = std::make_unique<Texture2D>(
            size2_t(256, 256), GLFormats::get(DataFormatId::Vec4Float16), GL_LINEAR);
        texVertical_[i] = std::make_unique<Texture2D>(
            size2_t(256, 256), GLFormats::get(DataFormatId::Vec4Float16), GL_LINEAR);
        fboHorizontal_[i].activate();
        fboHorizontal_[i].attachColorTexture(texHorizontal_[i].get());
        fboVertical_[i].activate();
        fboVertical_[i].attachColorTexture(texVertical_[i].get());
    }
    fboBright_.activate();
    fboBright_.attachColorTexture(&texBright_);
    FrameBufferObject::deactivateFBO();

    inport_.onChange([this]() {
        const DataFormatBase* format = inport_.getData()->getDataFormat();
        const auto swizzleMask = inport_.getData()->getColorLayer()->getSwizzleMask();

        if (!outport_.hasEditableData() || format != outport_.getData()->getDataFormat() ||
            swizzleMask != outport_.getData()->getColorLayer()->getSwizzleMask()) {
            auto dim = outport_.getData()->getDimensions();
            Image* img = new Image(dim, format);
            img->copyMetaDataFrom(*inport_.getData());
            // forward swizzle mask of the input
            img->getColorLayer()->setSwizzleMask(swizzleMask);

            outport_.setData(img);
        }
    });
}

HdrBloom::~HdrBloom() {}

void HdrBloom::process() {
    if (!enable_.get()) {
        outport_.setData(inport_.getData());
        return;
    }
    const int width = static_cast<int>(outport_.getDimensions().x);
    const int height = static_cast<int>(outport_.getDimensions().y);

    if (width != width_ || height != height_) {
        resizeTextures(width, height);
    }

    // Copy color, depth and picking
    utilgl::activateTargetAndCopySource(outport_, inport_);

    auto imageGL = inport_.getData()->getRepresentation<ImageGL>();
    auto colorLayer = imageGL->getColorLayerGL();
    auto colorTex = colorLayer->getTexture()->getID();

    // This geometry is actually never used in the shader
    auto rect = SharedOpenGLResources::getPtr()->imagePlaneRect();
    utilgl::Enable<MeshGL> enable(rect);

    utilgl::GlBoolState depth(GL_DEPTH_TEST, false);
    glActiveTexture(GL_TEXTURE0);

    // --- HIGHPASS ---
    fboBright_.activate();
    utilgl::ViewportState(ivec4(0, 0, texBright_.getWidth(), texBright_.getHeight()));
    glBindTexture(GL_TEXTURE_2D, colorTex);
    highPass_.activate();
    highPass_.setUniform("threshold", threshold_.get());
    highPass_.setUniform("texSource", 0);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    // --- BLUR ---
    Texture2D* input_tex = &texBright_;
    blur_.activate();
    blur_.setUniform("texSource", 0);
    for (int i = 0; i < Levels; i++) {
        auto inv_res = 1.f / vec2(input_tex->getWidth(), input_tex->getHeight());
        glViewport(0, 0, static_cast<GLsizei>(texHorizontal_[i]->getWidth()),
                   static_cast<GLsizei>(texHorizontal_[i]->getHeight()));

        // --- X-PASS ---
        input_tex->bind();
        fboHorizontal_[i].activate();
        blur_.setUniform("direction", vec2(1, 0) * inv_res);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        // --- Y-PASS ---
        texHorizontal_[i]->bind();
        fboVertical_[i].activate();
        blur_.setUniform("direction", vec2(0, 1) * inv_res);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        input_tex = texVertical_[i].get();
    }

    // --- COMPOSE ---
    utilgl::activateTarget(outport_, ImageType::ColorOnly);
    compose_.activate();

    // Blend bloom results onto colorchannel of outport.
    utilgl::GlBoolState blend(GL_BLEND, true);
    glBlendFunc(GL_ONE, GL_ONE);
    glBlendEquationSeparate(GL_FUNC_ADD, GL_MAX);
    std::array<float, Levels> factors{1.0f, 0.8f, 0.6f, 0.4f, 0.2f};
    compose_.setUniform("bloomStrength", strength_.get());
    compose_.setUniform("bloomRadius", radius_.get());
    for (int i = 0; i < Levels; i++) {
        glActiveTexture(GL_TEXTURE0 + i);
        texVertical_[i]->bind();
        compose_.setUniform("tex" + std::to_string(i), i);
    }
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glBlendEquation(GL_FUNC_ADD);

    compose_.deactivate();
    glBindTexture(GL_TEXTURE_2D, 0);
}

void HdrBloom::resizeTextures(int width, int height) {
    int res_x = width / 2;
    int res_y = height / 2;

    texBright_.resize(size2_t(width, height));

    for (int i = 0; i < Levels; i++) {
        texHorizontal_[i]->resize(size2_t(res_x, res_y));
        texVertical_[i]->resize(size2_t(res_x, res_y));
        res_x /= 2;
        res_y /= 2;
    }

    width_ = width;
    height_ = height;
}

}  // namespace inviwo
<commit_msg>ProstProcessing: Removed unused variable<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2016-2017 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/postprocessing/processors/hdrbloom.h>
#include <modules/opengl/image/imagegl.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/openglutils.h>
#include <modules/opengl/sharedopenglresources.h>
#include <modules/opengl/geometry/meshgl.h>
#include <random>

namespace inviwo {

// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo HdrBloom::processorInfo_{
    "org.inviwo.HdrBloom",  // Class identifier
    "HDR Bloom",            // Display name
    "Postprocessing",       // Category
    CodeState::Stable,      // Code state
    Tags::GL,               // Tags
};

const ProcessorInfo HdrBloom::getProcessorInfo() const { return processorInfo_; }

HdrBloom::HdrBloom()
    : Processor()
    , inport_("inport")
    , outport_("outport")
    , enable_("enable", "Enable Operation", true)
    , threshold_("threshold", "Threshold", 1.f, 0.f, 10.f)
    , strength_("strength", "Strength", 1.f, 0.f, 3.f)
    , radius_("radius", "Radius", 0.5f, 0.f, 1.f)
    , highPass_("fullscreenquad.vert", "bloomhighpass.frag")
    , blur_("fullscreenquad.vert", "bloomblur.frag")
    , compose_("fullscreenquad.vert", "bloomcompose.frag")
    , width_(0)
    , height_(0)
    , texBright_(size2_t(256, 256), GLFormats::get(DataFormatId::Vec4Float16), GL_LINEAR) {
    addPort(inport_);
    addPort(outport_);

    addProperty(enable_);
    addProperty(threshold_);
    addProperty(strength_);
    addProperty(radius_);

    for (int i = 0; i < Levels; i++) {
        texHorizontal_[i] = std::make_unique<Texture2D>(
            size2_t(256, 256), GLFormats::get(DataFormatId::Vec4Float16), GL_LINEAR);
        texVertical_[i] = std::make_unique<Texture2D>(
            size2_t(256, 256), GLFormats::get(DataFormatId::Vec4Float16), GL_LINEAR);
        fboHorizontal_[i].activate();
        fboHorizontal_[i].attachColorTexture(texHorizontal_[i].get());
        fboVertical_[i].activate();
        fboVertical_[i].attachColorTexture(texVertical_[i].get());
    }
    fboBright_.activate();
    fboBright_.attachColorTexture(&texBright_);
    FrameBufferObject::deactivateFBO();

    inport_.onChange([this]() {
        const DataFormatBase* format = inport_.getData()->getDataFormat();
        const auto swizzleMask = inport_.getData()->getColorLayer()->getSwizzleMask();

        if (!outport_.hasEditableData() || format != outport_.getData()->getDataFormat() ||
            swizzleMask != outport_.getData()->getColorLayer()->getSwizzleMask()) {
            auto dim = outport_.getData()->getDimensions();
            Image* img = new Image(dim, format);
            img->copyMetaDataFrom(*inport_.getData());
            // forward swizzle mask of the input
            img->getColorLayer()->setSwizzleMask(swizzleMask);

            outport_.setData(img);
        }
    });
}

HdrBloom::~HdrBloom() {}

void HdrBloom::process() {
    if (!enable_.get()) {
        outport_.setData(inport_.getData());
        return;
    }
    const int width = static_cast<int>(outport_.getDimensions().x);
    const int height = static_cast<int>(outport_.getDimensions().y);

    if (width != width_ || height != height_) {
        resizeTextures(width, height);
    }

    // Copy color, depth and picking
    utilgl::activateTargetAndCopySource(outport_, inport_);

    auto imageGL = inport_.getData()->getRepresentation<ImageGL>();
    auto colorLayer = imageGL->getColorLayerGL();
    auto colorTex = colorLayer->getTexture()->getID();

    // This geometry is actually never used in the shader
    auto rect = SharedOpenGLResources::getPtr()->imagePlaneRect();
    utilgl::Enable<MeshGL> enable(rect);

    utilgl::GlBoolState depth(GL_DEPTH_TEST, false);
    glActiveTexture(GL_TEXTURE0);

    // --- HIGHPASS ---
    fboBright_.activate();
    utilgl::ViewportState(ivec4(0, 0, texBright_.getWidth(), texBright_.getHeight()));
    glBindTexture(GL_TEXTURE_2D, colorTex);
    highPass_.activate();
    highPass_.setUniform("threshold", threshold_.get());
    highPass_.setUniform("texSource", 0);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    // --- BLUR ---
    Texture2D* input_tex = &texBright_;
    blur_.activate();
    blur_.setUniform("texSource", 0);
    for (int i = 0; i < Levels; i++) {
        auto inv_res = 1.f / vec2(input_tex->getWidth(), input_tex->getHeight());
        glViewport(0, 0, static_cast<GLsizei>(texHorizontal_[i]->getWidth()),
                   static_cast<GLsizei>(texHorizontal_[i]->getHeight()));

        // --- X-PASS ---
        input_tex->bind();
        fboHorizontal_[i].activate();
        blur_.setUniform("direction", vec2(1, 0) * inv_res);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        // --- Y-PASS ---
        texHorizontal_[i]->bind();
        fboVertical_[i].activate();
        blur_.setUniform("direction", vec2(0, 1) * inv_res);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        input_tex = texVertical_[i].get();
    }

    // --- COMPOSE ---
    utilgl::activateTarget(outport_, ImageType::ColorOnly);
    compose_.activate();

    // Blend bloom results onto colorchannel of outport.
    utilgl::GlBoolState blend(GL_BLEND, true);
    glBlendFunc(GL_ONE, GL_ONE);
    glBlendEquationSeparate(GL_FUNC_ADD, GL_MAX);

    compose_.setUniform("bloomStrength", strength_.get());
    compose_.setUniform("bloomRadius", radius_.get());
    for (int i = 0; i < Levels; i++) {
        glActiveTexture(GL_TEXTURE0 + i);
        texVertical_[i]->bind();
        compose_.setUniform("tex" + std::to_string(i), i);
    }
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glBlendEquation(GL_FUNC_ADD);

    compose_.deactivate();
    glBindTexture(GL_TEXTURE_2D, 0);
}

void HdrBloom::resizeTextures(int width, int height) {
    int res_x = width / 2;
    int res_y = height / 2;

    texBright_.resize(size2_t(width, height));

    for (int i = 0; i < Levels; i++) {
        texHorizontal_[i]->resize(size2_t(res_x, res_y));
        texVertical_[i]->resize(size2_t(res_x, res_y));
        res_x /= 2;
        res_y /= 2;
    }

    width_ = width;
    height_ = height;
}

}  // namespace inviwo
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include <cmath>

#include "modules/prediction/common/prediction_gflags.h"

// System gflags
DEFINE_string(prediction_module_name, "prediction",
              "Default prediciton module name");
DEFINE_string(prediction_conf_file,
              "modules/prediction/conf/prediction_conf.pb.txt",
              "Default conf file for prediction");
DEFINE_string(prediction_adapter_config_filename,
              "modules/prediction/conf/adapter.conf",
              "Default conf file for prediction");
DEFINE_bool(prediction_test_mode, false, "Set prediction to test mode");
DEFINE_double(
    prediction_test_duration, -1.0,
    "The runtime duration in test mode (in seconds). Negative value will not "
    "restrict the runtime duration.");

DEFINE_double(prediction_duration, 5.0, "Prediction duration (in seconds)");
DEFINE_double(prediction_period, 0.1, "Prediction period (in seconds");
DEFINE_double(double_precision, 1e-6, "precision of double");
DEFINE_double(min_prediction_length, 50.0,
              "Minimal length of prediction trajectory");

// Bag replay timestamp gap
DEFINE_double(replay_timestamp_gap, 10.0,
              "Max timestamp gap for rosbag replay");

// Map
DEFINE_double(lane_search_radius, 3.0, "Search radius for a candidate lane");
DEFINE_double(junction_search_radius, 1.0, "Search radius for a junction");

// Obstacle features
DEFINE_bool(enable_kf_tracking, false, "Use measurements with KF tracking");
DEFINE_double(max_acc, 4.0, "Upper bound of acceleration");
DEFINE_double(min_acc, -4.0, "Lower bound of deceleration");
DEFINE_double(max_speed, 35.0, "Max speed");
DEFINE_double(q_var, 0.01, "Processing noise covariance");
DEFINE_double(r_var, 0.25, "Measurement noise covariance");
DEFINE_double(p_var, 0.1, "Error covariance");
DEFINE_double(go_approach_rate, 0.995,
              "The rate to approach to the reference line of going straight");
DEFINE_double(cutin_approach_rate, 0.9,
              "The rate to approach to the reference line of lane change");
DEFINE_int32(still_obstacle_history_length, 10,
             "Min # historical frames for still obstacles");
DEFINE_double(still_obstacle_speed_threshold, 2.0,
              "Speed threshold for still obstacles");
DEFINE_double(still_pedestrian_speed_threshold, 0.5,
              "Speed threshold for still pedestrians");
DEFINE_double(still_obstacle_position_std, 1.0,
              "Position standard deviation for still obstacles");
DEFINE_double(max_history_time, 7.0, "Obstacles' maximal historical time.");
DEFINE_double(target_lane_gap, 2.0, "gap between two lane points.");
DEFINE_int32(max_num_current_lane, 1, "Max number to search current lanes");
DEFINE_int32(max_num_nearby_lane, 2, "Max number to search nearby lanes");
DEFINE_double(max_lane_angle_diff, M_PI / 2.0,
              "Max angle difference for a candiate lane");
DEFINE_bool(enable_pedestrian_acc, false, "Enable calculating speed by acc");
DEFINE_double(coeff_mul_sigma, 2.0, "coefficient multiply standard deviation");
DEFINE_double(pedestrian_max_speed, 10.0, "speed upper bound for pedestrian");
DEFINE_double(pedestrian_max_acc, 2.0, "maximum pedestrian acceleration");
DEFINE_double(prediction_pedestrian_total_time, 10.0,
              "Total prediction time for pedestrians");
DEFINE_double(still_speed, 0.01, "speed considered to be still");
DEFINE_string(evaluator_vehicle_mlp_file,
              "modules/prediction/data/mlp_vehicle_model.bin",
              "mlp model file for vehicle evaluator");
DEFINE_string(evaluator_vehicle_rnn_file,
              "modules/prediction/data/rnn_vehicle_model.bin",
              "rnn model file for vehicle evaluator");
DEFINE_int32(max_num_obstacles, 100,
             "maximal number of obstacles stored in obstacles container.");
DEFINE_double(valid_position_diff_threshold, 0.5,
              "threshold of valid position difference");
DEFINE_double(valid_position_diff_rate_threshold, 0.075,
              "threshold of valid position difference rate");
DEFINE_double(split_rate, 0.5,
              "obstacle split rate for adjusting velocity");
DEFINE_double(rnn_min_lane_relatice_s, 5.0,
              "Minimal relative s for RNN model.");
DEFINE_bool(enable_adjust_velocity_heading, false,
            "adjust velocity heading to lane heading");
DEFINE_double(heading_filter_param, 0.99, "heading filter parameter");

// Obstacle trajectory
DEFINE_double(lane_sequence_threshold, 0.5,
              "Threshold for trimming lane sequence trajectories");
DEFINE_double(lane_change_dist, 10.0, "Lane change distance with ADC");
DEFINE_bool(enable_lane_sequence_acc, false,
            "If use acceleration in lane sequence.");
DEFINE_bool(enable_trim_prediction_trajectory, false,
            "If trim the prediction trajectory to avoid crossing"
            "protected adc planning trajectory.");
DEFINE_double(distance_beyond_junction, 0.5,
              "If the obstacle is in junction more than this threshold,"
              "consider it in junction.");
DEFINE_double(adc_trajectory_search_length, 10.0,
              "How far to search junction along adc planning trajectory");
DEFINE_double(virtual_lane_radius, 0.5, "Radius to search virtual lanes");
DEFINE_double(default_lateral_approach_speed, 0.5,
              "Default lateral speed approaching to center of lane");

// move sequence prediction
DEFINE_double(time_upper_bound_to_lane_center, 5.0,
              "Upper bound of time to get to the lane center");
DEFINE_double(time_lower_bound_to_lane_center, 1.0,
              "Lower bound of time to get to the lane center");
DEFINE_double(sample_time_gap, 0.2,
              "Gap of time to sample time to get to the lane center");
DEFINE_double(cost_alpha, 100.0,
              "The coefficient of lateral acceleration in cost function");
DEFINE_double(default_time_to_lane_center, 5.0,
              "The default time to lane center");
<commit_msg>Prediction: modify min_prediction_length to 20.0<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include <cmath>

#include "modules/prediction/common/prediction_gflags.h"

// System gflags
DEFINE_string(prediction_module_name, "prediction",
              "Default prediciton module name");
DEFINE_string(prediction_conf_file,
              "modules/prediction/conf/prediction_conf.pb.txt",
              "Default conf file for prediction");
DEFINE_string(prediction_adapter_config_filename,
              "modules/prediction/conf/adapter.conf",
              "Default conf file for prediction");
DEFINE_bool(prediction_test_mode, false, "Set prediction to test mode");
DEFINE_double(
    prediction_test_duration, -1.0,
    "The runtime duration in test mode (in seconds). Negative value will not "
    "restrict the runtime duration.");

DEFINE_double(prediction_duration, 5.0, "Prediction duration (in seconds)");
DEFINE_double(prediction_period, 0.1, "Prediction period (in seconds");
DEFINE_double(double_precision, 1e-6, "precision of double");
DEFINE_double(min_prediction_length, 20.0,
              "Minimal length of prediction trajectory");

// Bag replay timestamp gap
DEFINE_double(replay_timestamp_gap, 10.0,
              "Max timestamp gap for rosbag replay");

// Map
DEFINE_double(lane_search_radius, 3.0, "Search radius for a candidate lane");
DEFINE_double(junction_search_radius, 1.0, "Search radius for a junction");

// Obstacle features
DEFINE_bool(enable_kf_tracking, false, "Use measurements with KF tracking");
DEFINE_double(max_acc, 4.0, "Upper bound of acceleration");
DEFINE_double(min_acc, -4.0, "Lower bound of deceleration");
DEFINE_double(max_speed, 35.0, "Max speed");
DEFINE_double(q_var, 0.01, "Processing noise covariance");
DEFINE_double(r_var, 0.25, "Measurement noise covariance");
DEFINE_double(p_var, 0.1, "Error covariance");
DEFINE_double(go_approach_rate, 0.995,
              "The rate to approach to the reference line of going straight");
DEFINE_double(cutin_approach_rate, 0.9,
              "The rate to approach to the reference line of lane change");
DEFINE_int32(still_obstacle_history_length, 10,
             "Min # historical frames for still obstacles");
DEFINE_double(still_obstacle_speed_threshold, 2.0,
              "Speed threshold for still obstacles");
DEFINE_double(still_pedestrian_speed_threshold, 0.5,
              "Speed threshold for still pedestrians");
DEFINE_double(still_obstacle_position_std, 1.0,
              "Position standard deviation for still obstacles");
DEFINE_double(max_history_time, 7.0, "Obstacles' maximal historical time.");
DEFINE_double(target_lane_gap, 2.0, "gap between two lane points.");
DEFINE_int32(max_num_current_lane, 1, "Max number to search current lanes");
DEFINE_int32(max_num_nearby_lane, 2, "Max number to search nearby lanes");
DEFINE_double(max_lane_angle_diff, M_PI / 2.0,
              "Max angle difference for a candiate lane");
DEFINE_bool(enable_pedestrian_acc, false, "Enable calculating speed by acc");
DEFINE_double(coeff_mul_sigma, 2.0, "coefficient multiply standard deviation");
DEFINE_double(pedestrian_max_speed, 10.0, "speed upper bound for pedestrian");
DEFINE_double(pedestrian_max_acc, 2.0, "maximum pedestrian acceleration");
DEFINE_double(prediction_pedestrian_total_time, 10.0,
              "Total prediction time for pedestrians");
DEFINE_double(still_speed, 0.01, "speed considered to be still");
DEFINE_string(evaluator_vehicle_mlp_file,
              "modules/prediction/data/mlp_vehicle_model.bin",
              "mlp model file for vehicle evaluator");
DEFINE_string(evaluator_vehicle_rnn_file,
              "modules/prediction/data/rnn_vehicle_model.bin",
              "rnn model file for vehicle evaluator");
DEFINE_int32(max_num_obstacles, 100,
             "maximal number of obstacles stored in obstacles container.");
DEFINE_double(valid_position_diff_threshold, 0.5,
              "threshold of valid position difference");
DEFINE_double(valid_position_diff_rate_threshold, 0.075,
              "threshold of valid position difference rate");
DEFINE_double(split_rate, 0.5,
              "obstacle split rate for adjusting velocity");
DEFINE_double(rnn_min_lane_relatice_s, 5.0,
              "Minimal relative s for RNN model.");
DEFINE_bool(enable_adjust_velocity_heading, false,
            "adjust velocity heading to lane heading");
DEFINE_double(heading_filter_param, 0.99, "heading filter parameter");

// Obstacle trajectory
DEFINE_double(lane_sequence_threshold, 0.5,
              "Threshold for trimming lane sequence trajectories");
DEFINE_double(lane_change_dist, 10.0, "Lane change distance with ADC");
DEFINE_bool(enable_lane_sequence_acc, false,
            "If use acceleration in lane sequence.");
DEFINE_bool(enable_trim_prediction_trajectory, false,
            "If trim the prediction trajectory to avoid crossing"
            "protected adc planning trajectory.");
DEFINE_double(distance_beyond_junction, 0.5,
              "If the obstacle is in junction more than this threshold,"
              "consider it in junction.");
DEFINE_double(adc_trajectory_search_length, 10.0,
              "How far to search junction along adc planning trajectory");
DEFINE_double(virtual_lane_radius, 0.5, "Radius to search virtual lanes");
DEFINE_double(default_lateral_approach_speed, 0.5,
              "Default lateral speed approaching to center of lane");

// move sequence prediction
DEFINE_double(time_upper_bound_to_lane_center, 5.0,
              "Upper bound of time to get to the lane center");
DEFINE_double(time_lower_bound_to_lane_center, 1.0,
              "Lower bound of time to get to the lane center");
DEFINE_double(sample_time_gap, 0.2,
              "Gap of time to sample time to get to the lane center");
DEFINE_double(cost_alpha, 100.0,
              "The coefficient of lateral acceleration in cost function");
DEFINE_double(default_time_to_lane_center, 5.0,
              "The default time to lane center");
<|endoftext|>