<commit_before>/*
 *  illarionserver - server for the game Illarion
 *  Copyright 2011 Illarion e.V.
 *
 *  This file is part of illarionserver.
 *
 *  illarionserver is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  illarionserver is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with illarionserver.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Character.hpp"
#include "Player.hpp"
#include "globals.hpp"
#include <luabind/adopt_policy.hpp>
#include <luabind/out_value_policy.hpp>
#include <script/forwarder.hpp>
#include <data/Data.hpp>
#include "script/binding/binding.hpp"

namespace binding {

    luabind::scope character() {
        using ::position;

        luabind::value_vector skills;

        for (const auto &skill: Data::Skills) {
            skills.push_back(luabind::value(skill.second.serverName.c_str(), skill.first));
        }

        luabind::value_vector races;

        for (const auto &race: Data::Races) {
            races.push_back(luabind::value(race.second.serverName.c_str(), race.first));
        }

        return luabind::class_<Character>("Character")
                .def("isNewPlayer", &Character::isNewPlayer)
                .def("pageGM", &Character::pageGM)
                .def("requestInputDialog", &Character::requestInputDialog, luabind::adopt(_2))
                .def("requestMessageDialog", &Character::requestMessageDialog, luabind::adopt(_2))
                .def("requestMerchantDialog", &Character::requestMerchantDialog, luabind::adopt(_2))
                .def("requestSelectionDialog", &Character::requestSelectionDialog, luabind::adopt(_2))
                .def("requestCraftingDialog", &Character::requestCraftingDialog, luabind::adopt(_2))
                .def("idleTime", &Character::idleTime)
                .def("sendBook", &Character::sendBook)
                .def("updateAppearance", &Character::forceUpdateAppearanceForAll)
                .def("performAnimation", &Character::performAnimation)
                .def("alterSpokenMessage", &Character::alterSpokenMessage)
                .def("actionRunning", &Character::actionRunning)
                .def("changeQualityAt", &Character::changeQualityAt)
                .def("isAdmin", &Character::isAdmin)
                .def("talk", (void(Character:: *)(Character::talk_type, const std::string &))&Character::talk)
                .def("talk", (void(Character:: *)(Character::talk_type, const std::string &, const std::string &))&Character::talk)
                .def("sendCharDescription", &Character::sendCharDescription)
                .def("startAction", &Character::startAction)
                .def("abortAction", &Character::abortAction)
                .def("successAction", &Character::successAction)
                .def("disturbAction", &Character::actionDisturbed)
                .def("changeSource", (void(Character:: *)(Character *))&Character::changeSource)
                .def("changeSource", (void(Character:: *)(const ScriptItem &))&Character::changeSource)
                .def("changeSource", (void(Character:: *)(const position &))&Character::changeSource)
                .def("changeSource", (void(Character:: *)(void))&Character::changeSource)
                .def("changeTarget", (void(Character:: *)(Character *))&Character::changeTarget)
                .def("changeTarget", (void(Character:: *)(const ScriptItem &))&Character::changeTarget)
                .def("changeTarget", (void(Character:: *)(const position &))&Character::changeTarget)
                .def("changeTarget", (void(Character:: *)(void))&Character::changeTarget)
                .def("inform", inform_lua1)
                .def("inform", inform_lua2)
                .def("inform", inform_lua3)
                .def("inform", inform_lua4)
                .def("introduce", &Character::introducePlayer)
                .def("move", &Character::move)
                .def("turn", (void(Character:: *)(direction))&Character::turn)
                .def("turn", (void(Character:: *)(const position &))&Character::turn)
                .def("getNextStepDir", &Character::getNextStepDir, luabind::pure_out_value(_3))
                .def("setRace", &Character::changeRace)
                .def("getRace", &Character::getRace)
                .def("getFaceTo", &Character::getFaceTo)
                .def("getType", &Character::getType)
                .def("createItem", create_item)
                .def("getLoot", getLoot)
                .def("increasePoisonValue", &Character::increasePoisonValue)
                .def("getPoisonValue", &Character::getPoisonValue)
                .def("setPoisonValue", &Character::setPoisonValue)
                .def("getMentalCapacity", &Character::getMentalCapacity)
                .def("setMentalCapacity", &Character::setMentalCapacity)
                .def("increaseMentalCapacity", &Character::increaseMentalCapacity)
                .def("setClippingActive", &Character::setClippingActive)
                .def("getClippingActive", &Character::getClippingActive)
                .def("countItem", &Character::countItem)
                .def("countItemAt", count_item_at1)
                .def("countItemAt", count_item_at2)
                .def("eraseItem", erase_item1)
                .def("eraseItem", erase_item2)
                .def("increaseAtPos", &Character::increaseAtPos)
                .def("swapAtPos", &Character::swapAtPos)
                .def("createAtPos", &Character::createAtPos)
                .def("getItemAt", &Character::GetItemAt)
                .enum_("skills")
                [
                    skills
                ]
                .def("getSkillName", &Character::getSkillName)
                .def("getSkill", &Character::getSkill)
                .def("getMinorSkill", &Character::getMinorSkill)
                .def("increaseAttrib", &Character::increaseAttrib)
                .def("setAttrib", &Character::setAttrib)
                .def("isBaseAttributeValid", &Character::isBaseAttribValid)
                .def("getBaseAttributeSum", &Character::getBaseAttributeSum)
                .def("getMaxAttributePoints", &Character::getMaxAttributePoints)
                .def("saveBaseAttributes", &Character::saveBaseAttributes)
                .def("setBaseAttribute", &Character::setBaseAttrib)
                .def("getBaseAttribute", &Character::getBaseAttrib)
                .def("increaseBaseAttribute", &Character::increaseBaseAttrib)
                .def("increaseSkill", &Character::increaseSkill)
                .def("increaseMinorSkill", &Character::increaseMinorSkill)
                .def("setSkill", &Character::setSkill)
                .def("setSkinColour", &Character::setSkinColour)
                .def("getSkinColour", &Character::getSkinColour)
                .def("setHairColour", &Character::setHairColour)
                .def("getHairColour", &Character::getHairColour)
                .def("setHair", &Character::setHair)
                .def("getHair", &Character::getHair)
                .def("setBeard", &Character::setBeard)
                .def("getBeard", &Character::getBeard)
                .def("learn", &Character::learn)
                .def("getSkillValue",&Character::getSkillValue)
                .def("teachMagic", &Character::teachMagic)
                .def("isInRange", &Character::isInRange)
                .def("isInRangeToPosition", &Character::isInRangeToField)
                .def("distanceMetric", &Character::distanceMetric)
                .def("distanceMetricToPosition", &Character::distanceMetricToPosition)
                .def("getMagicType", &Character::getMagicType)
                .def("setMagicType", &Character::setMagicType)
                .def("getMagicFlags", &Character::getMagicFlags)
                .def("warp", &Character::Warp)
                .def("forceWarp", &Character::forceWarp)
                .def("startMusic", &Character::startMusic)
                .def("defaultMusic", &Character::defaultMusic)
                .def("callAttackScript", &Character::callAttackScript)
                .def("getItemList", character_getItemList)
                .property("lastSpokenText", &Character::getLastSpokenText)
                .def("getPlayerLanguage", getPlayerLanguageLua)
                .def("getBackPack", &Character::GetBackPack)
                .def("getDepot", &Character::GetDepot)
                .def("setQuestProgress", &Character::setQuestProgress)
                .def("getQuestProgress", &Character::getQuestProgress, luabind::pure_out_value(_3))
                .def("getOnRoute",&Character::getOnRoute)
                .def("setOnRoute",&Character::setOnRoute)
                .def("getMonsterType", &Character::getMonsterType)
                .def("logAdmin", &Character::logAdmin)
                .def_readonly("effects", &Character::effects)
                .def_readonly("waypoints", &Character::waypoints)
                .property("pos", &Character::getPosition)
                .property("name", &Character::getName)
                .property("id", &Character::getId)
                .property("activeLanguage", &Character::getActiveLanguage, &Character::setActiveLanguage)
                .property("movepoints", &Character::getActionPoints, &Character::setActionPoints)
                .property("fightpoints", &Character::getFightPoints, &Character::setFightPoints)
                .property("isinvisible", &Character::isInvisible, &Character::setInvisible)
                .property("attackmode", &Character::getAttackMode)
                //.def_readonly("isTarget", &Character::isTarget)
                .enum_("body_pos")
                [
                    luabind::value("backpack", BACKPACK),
                    luabind::value("head", HEAD),
                    luabind::value("neck", NECK),
                    luabind::value("breast", BREAST),
                    luabind::value("hands", HANDS),
                    luabind::value("left_tool", LEFT_TOOL),
                    luabind::value("right_tool", RIGHT_TOOL),
                    luabind::value("finger_left_hand", FINGER_LEFT_HAND),
                    luabind::value("finger_right_hand", FINGER_RIGHT_HAND),
                    luabind::value("legs", LEGS),
                    luabind::value("feet", FEET),
                    luabind::value("coat", COAT),
                    luabind::value("belt_pos_1", MAX_BODY_ITEMS),
                    luabind::value("belt_pos_2", MAX_BODY_ITEMS + 1),
                    luabind::value("belt_pos_3", MAX_BODY_ITEMS + 2),
                    luabind::value("belt_pos_4", MAX_BODY_ITEMS + 3),
                    luabind::value("belt_pos_5", MAX_BODY_ITEMS + 4),
                    luabind::value("belt_pos_6", MAX_BODY_ITEMS + 5)
                ]
                .enum_("magic_flags")
                [
                    luabind::value("mage", MAGE),
                    luabind::value("priest", PRIEST),
                    luabind::value("bard", BARD),
                    luabind::value("druid", DRUID)
                ]
                .enum_("talk_type")
                [
                    luabind::value("say", Character::tt_say),
                    luabind::value("whisper", Character::tt_whisper),
                    luabind::value("yell", Character::tt_yell)
                ]
                .enum_("direction")
                [
                    luabind::value("dir_north", dir_north),
                    luabind::value("dir_northeast", dir_northeast),
                    luabind::value("dir_east", dir_east),
                    luabind::value("dir_southeast", dir_southeast),
                    luabind::value("dir_south", dir_south),
                    luabind::value("dir_southwest", dir_southwest),
                    luabind::value("dir_west", dir_west),
                    luabind::value("dir_northwest", dir_northwest),
                    luabind::value("dir_up", dir_up),
                    luabind::value("dir_down", dir_down)
                ]
                .enum_("character_type")
                [
                    luabind::value("player", Character::player),
                    luabind::value("monster", Character::monster),
                    luabind::value("npc", Character::npc)
                ]
                .enum_("sex_type")
                [
                    luabind::value("male", Character::male),
                    luabind::value("female", Character::female)
                ]
                .enum_("face_to")
                [
                    luabind::value("north", Character::north),
                    luabind::value("northeast", Character::northeast),
                    luabind::value("east", Character::east),
                    luabind::value("southeast", Character::southeast),
                    luabind::value("south", Character::west),
                    luabind::value("southwest", Character::southwest),
                    luabind::value("west", Character::west),
                    luabind::value("northwest", Character::northwest)
                ]
                .enum_("race_type")
                [
                    races
                ]
                .enum_("inform_type")
                [
                    luabind::value("lowPriority", Character::informScriptLowPriority),
                    luabind::value("mediumPriority", Character::informScriptMediumPriority),
                    luabind::value("highPriority", Character::informScriptHighPriority)
                ];
    }

}
<commit_msg>Fix Lua binding of Character::south<commit_after>/*
 *  illarionserver - server for the game Illarion
 *  Copyright 2011 Illarion e.V.
 *
 *  This file is part of illarionserver.
 *
 *  illarionserver is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  illarionserver is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with illarionserver.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Character.hpp"
#include "Player.hpp"
#include "globals.hpp"
#include <luabind/adopt_policy.hpp>
#include <luabind/out_value_policy.hpp>
#include <script/forwarder.hpp>
#include <data/Data.hpp>
#include "script/binding/binding.hpp"

namespace binding {

    luabind::scope character() {
        using ::position;

        luabind::value_vector skills;

        for (const auto &skill: Data::Skills) {
            skills.push_back(luabind::value(skill.second.serverName.c_str(), skill.first));
        }

        luabind::value_vector races;

        for (const auto &race: Data::Races) {
            races.push_back(luabind::value(race.second.serverName.c_str(), race.first));
        }

        return luabind::class_<Character>("Character")
                .def("isNewPlayer", &Character::isNewPlayer)
                .def("pageGM", &Character::pageGM)
                .def("requestInputDialog", &Character::requestInputDialog, luabind::adopt(_2))
                .def("requestMessageDialog", &Character::requestMessageDialog, luabind::adopt(_2))
                .def("requestMerchantDialog", &Character::requestMerchantDialog, luabind::adopt(_2))
                .def("requestSelectionDialog", &Character::requestSelectionDialog, luabind::adopt(_2))
                .def("requestCraftingDialog", &Character::requestCraftingDialog, luabind::adopt(_2))
                .def("idleTime", &Character::idleTime)
                .def("sendBook", &Character::sendBook)
                .def("updateAppearance", &Character::forceUpdateAppearanceForAll)
                .def("performAnimation", &Character::performAnimation)
                .def("alterSpokenMessage", &Character::alterSpokenMessage)
                .def("actionRunning", &Character::actionRunning)
                .def("changeQualityAt", &Character::changeQualityAt)
                .def("isAdmin", &Character::isAdmin)
                .def("talk", (void(Character:: *)(Character::talk_type, const std::string &))&Character::talk)
                .def("talk", (void(Character:: *)(Character::talk_type, const std::string &, const std::string &))&Character::talk)
                .def("sendCharDescription", &Character::sendCharDescription)
                .def("startAction", &Character::startAction)
                .def("abortAction", &Character::abortAction)
                .def("successAction", &Character::successAction)
                .def("disturbAction", &Character::actionDisturbed)
                .def("changeSource", (void(Character:: *)(Character *))&Character::changeSource)
                .def("changeSource", (void(Character:: *)(const ScriptItem &))&Character::changeSource)
                .def("changeSource", (void(Character:: *)(const position &))&Character::changeSource)
                .def("changeSource", (void(Character:: *)(void))&Character::changeSource)
                .def("changeTarget", (void(Character:: *)(Character *))&Character::changeTarget)
                .def("changeTarget", (void(Character:: *)(const ScriptItem &))&Character::changeTarget)
                .def("changeTarget", (void(Character:: *)(const position &))&Character::changeTarget)
                .def("changeTarget", (void(Character:: *)(void))&Character::changeTarget)
                .def("inform", inform_lua1)
                .def("inform", inform_lua2)
                .def("inform", inform_lua3)
                .def("inform", inform_lua4)
                .def("introduce", &Character::introducePlayer)
                .def("move", &Character::move)
                .def("turn", (void(Character:: *)(direction))&Character::turn)
                .def("turn", (void(Character:: *)(const position &))&Character::turn)
                .def("getNextStepDir", &Character::getNextStepDir, luabind::pure_out_value(_3))
                .def("setRace", &Character::changeRace)
                .def("getRace", &Character::getRace)
                .def("getFaceTo", &Character::getFaceTo)
                .def("getType", &Character::getType)
                .def("createItem", create_item)
                .def("getLoot", getLoot)
                .def("increasePoisonValue", &Character::increasePoisonValue)
                .def("getPoisonValue", &Character::getPoisonValue)
                .def("setPoisonValue", &Character::setPoisonValue)
                .def("getMentalCapacity", &Character::getMentalCapacity)
                .def("setMentalCapacity", &Character::setMentalCapacity)
                .def("increaseMentalCapacity", &Character::increaseMentalCapacity)
                .def("setClippingActive", &Character::setClippingActive)
                .def("getClippingActive", &Character::getClippingActive)
                .def("countItem", &Character::countItem)
                .def("countItemAt", count_item_at1)
                .def("countItemAt", count_item_at2)
                .def("eraseItem", erase_item1)
                .def("eraseItem", erase_item2)
                .def("increaseAtPos", &Character::increaseAtPos)
                .def("swapAtPos", &Character::swapAtPos)
                .def("createAtPos", &Character::createAtPos)
                .def("getItemAt", &Character::GetItemAt)
                .enum_("skills")
                [
                    skills
                ]
                .def("getSkillName", &Character::getSkillName)
                .def("getSkill", &Character::getSkill)
                .def("getMinorSkill", &Character::getMinorSkill)
                .def("increaseAttrib", &Character::increaseAttrib)
                .def("setAttrib", &Character::setAttrib)
                .def("isBaseAttributeValid", &Character::isBaseAttribValid)
                .def("getBaseAttributeSum", &Character::getBaseAttributeSum)
                .def("getMaxAttributePoints", &Character::getMaxAttributePoints)
                .def("saveBaseAttributes", &Character::saveBaseAttributes)
                .def("setBaseAttribute", &Character::setBaseAttrib)
                .def("getBaseAttribute", &Character::getBaseAttrib)
                .def("increaseBaseAttribute", &Character::increaseBaseAttrib)
                .def("increaseSkill", &Character::increaseSkill)
                .def("increaseMinorSkill", &Character::increaseMinorSkill)
                .def("setSkill", &Character::setSkill)
                .def("setSkinColour", &Character::setSkinColour)
                .def("getSkinColour", &Character::getSkinColour)
                .def("setHairColour", &Character::setHairColour)
                .def("getHairColour", &Character::getHairColour)
                .def("setHair", &Character::setHair)
                .def("getHair", &Character::getHair)
                .def("setBeard", &Character::setBeard)
                .def("getBeard", &Character::getBeard)
                .def("learn", &Character::learn)
                .def("getSkillValue",&Character::getSkillValue)
                .def("teachMagic", &Character::teachMagic)
                .def("isInRange", &Character::isInRange)
                .def("isInRangeToPosition", &Character::isInRangeToField)
                .def("distanceMetric", &Character::distanceMetric)
                .def("distanceMetricToPosition", &Character::distanceMetricToPosition)
                .def("getMagicType", &Character::getMagicType)
                .def("setMagicType", &Character::setMagicType)
                .def("getMagicFlags", &Character::getMagicFlags)
                .def("warp", &Character::Warp)
                .def("forceWarp", &Character::forceWarp)
                .def("startMusic", &Character::startMusic)
                .def("defaultMusic", &Character::defaultMusic)
                .def("callAttackScript", &Character::callAttackScript)
                .def("getItemList", character_getItemList)
                .property("lastSpokenText", &Character::getLastSpokenText)
                .def("getPlayerLanguage", getPlayerLanguageLua)
                .def("getBackPack", &Character::GetBackPack)
                .def("getDepot", &Character::GetDepot)
                .def("setQuestProgress", &Character::setQuestProgress)
                .def("getQuestProgress", &Character::getQuestProgress, luabind::pure_out_value(_3))
                .def("getOnRoute",&Character::getOnRoute)
                .def("setOnRoute",&Character::setOnRoute)
                .def("getMonsterType", &Character::getMonsterType)
                .def("logAdmin", &Character::logAdmin)
                .def_readonly("effects", &Character::effects)
                .def_readonly("waypoints", &Character::waypoints)
                .property("pos", &Character::getPosition)
                .property("name", &Character::getName)
                .property("id", &Character::getId)
                .property("activeLanguage", &Character::getActiveLanguage, &Character::setActiveLanguage)
                .property("movepoints", &Character::getActionPoints, &Character::setActionPoints)
                .property("fightpoints", &Character::getFightPoints, &Character::setFightPoints)
                .property("isinvisible", &Character::isInvisible, &Character::setInvisible)
                .property("attackmode", &Character::getAttackMode)
                //.def_readonly("isTarget", &Character::isTarget)
                .enum_("body_pos")
                [
                    luabind::value("backpack", BACKPACK),
                    luabind::value("head", HEAD),
                    luabind::value("neck", NECK),
                    luabind::value("breast", BREAST),
                    luabind::value("hands", HANDS),
                    luabind::value("left_tool", LEFT_TOOL),
                    luabind::value("right_tool", RIGHT_TOOL),
                    luabind::value("finger_left_hand", FINGER_LEFT_HAND),
                    luabind::value("finger_right_hand", FINGER_RIGHT_HAND),
                    luabind::value("legs", LEGS),
                    luabind::value("feet", FEET),
                    luabind::value("coat", COAT),
                    luabind::value("belt_pos_1", MAX_BODY_ITEMS),
                    luabind::value("belt_pos_2", MAX_BODY_ITEMS + 1),
                    luabind::value("belt_pos_3", MAX_BODY_ITEMS + 2),
                    luabind::value("belt_pos_4", MAX_BODY_ITEMS + 3),
                    luabind::value("belt_pos_5", MAX_BODY_ITEMS + 4),
                    luabind::value("belt_pos_6", MAX_BODY_ITEMS + 5)
                ]
                .enum_("magic_flags")
                [
                    luabind::value("mage", MAGE),
                    luabind::value("priest", PRIEST),
                    luabind::value("bard", BARD),
                    luabind::value("druid", DRUID)
                ]
                .enum_("talk_type")
                [
                    luabind::value("say", Character::tt_say),
                    luabind::value("whisper", Character::tt_whisper),
                    luabind::value("yell", Character::tt_yell)
                ]
                .enum_("direction")
                [
                    luabind::value("dir_north", dir_north),
                    luabind::value("dir_northeast", dir_northeast),
                    luabind::value("dir_east", dir_east),
                    luabind::value("dir_southeast", dir_southeast),
                    luabind::value("dir_south", dir_south),
                    luabind::value("dir_southwest", dir_southwest),
                    luabind::value("dir_west", dir_west),
                    luabind::value("dir_northwest", dir_northwest),
                    luabind::value("dir_up", dir_up),
                    luabind::value("dir_down", dir_down)
                ]
                .enum_("character_type")
                [
                    luabind::value("player", Character::player),
                    luabind::value("monster", Character::monster),
                    luabind::value("npc", Character::npc)
                ]
                .enum_("sex_type")
                [
                    luabind::value("male", Character::male),
                    luabind::value("female", Character::female)
                ]
                .enum_("face_to")
                [
                    luabind::value("north", Character::north),
                    luabind::value("northeast", Character::northeast),
                    luabind::value("east", Character::east),
                    luabind::value("southeast", Character::southeast),
                    luabind::value("south", Character::south),
                    luabind::value("southwest", Character::southwest),
                    luabind::value("west", Character::west),
                    luabind::value("northwest", Character::northwest)
                ]
                .enum_("race_type")
                [
                    races
                ]
                .enum_("inform_type")
                [
                    luabind::value("lowPriority", Character::informScriptLowPriority),
                    luabind::value("mediumPriority", Character::informScriptMediumPriority),
                    luabind::value("highPriority", Character::informScriptHighPriority)
                ];
    }

}
<|endoftext|>


<commit_before>#pragma once

#include <curses.h>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <vector>
#include <sstream>
#include <boost/circular_buffer.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/noncopyable.hpp>

#include "logger.hh"

#define KEY_ESCAPE 27
#define BLOCKS 1
#define BLOCKSMOVE 100

class Actor;
typedef std::vector<Actor*> ActorPtrs;
typedef boost::ptr_vector<Actor> Actors;

typedef boost::circular_buffer_space_optimized<std::string> MsgBuffer;

/// Tiles

struct Tile {
	const static int TRANSPARENT = 255;
	char ch;
	int color;
	std::string desc;
	bool explored;
	bool visible;
	bool blocks_movement;
	int blocks_vision_dist;
	Actor* actor;

	Tile(char ch = ' ', int color = 0, int blocker = BLOCKS):
	ch(ch), color(color), explored(false), visible(false),
	blocks_movement(blocker), blocks_vision_dist(blocker ? (blocker == BLOCKSMOVE ? TRANSPARENT : 0) : TRANSPARENT), actor(NULL) {}

	bool isFree() const { return (!blocks_movement) && (actor == NULL); }

	bool operator==(const Tile& rhs) {
		return ch == rhs.ch && color == rhs.color;
	}
	bool operator!=(const Tile& rhs) { return !(*this==rhs); }
};

typedef std::vector<Tile> tilerow;
typedef std::vector<tilerow> tilearray;

Tile TileBuilder(std::string type);

/// Math

template<typename T>
std::string num2str(T i) { std::ostringstream oss; oss << i; return oss.str(); }

bool inline randbool() { return rand() % 2 == 0; }

int inline randint(int hi) { return rand() % hi; }

int inline randint(int lo, int hi) {
	return (rand() % (hi - lo + 1)) + lo;
}

template<typename T> T distance2d(T x1, T y1, T x2, T y2) {
	return sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) );
}

/** Implement C99 mathematical rounding (which C++ unfortunately currently lacks) **/
template <typename T> T round(T val) { return int(val + (val >= 0 ? 0.5 : -0.5)); }

/** Limit val to range [min, max] **/
template <typename T> T clamp(T val, T min = 0, T max = 1) {
	if (min > max) throw std::logic_error("min > max");
	if (val < min) return min;
	if (val > max) return max;
	return val;
}

/// Console

void setColor(WINDOW* scr, int color);

void setColor(int color);

void addcstr(std::string str);

void box2(int x, int y, int w, int h);

bool toggleDefaultColors();
<commit_msg>Random direction utils.<commit_after>#pragma once

#include <curses.h>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <vector>
#include <sstream>
#include <boost/circular_buffer.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/noncopyable.hpp>

#include "logger.hh"

#define KEY_ESCAPE 27
#define BLOCKS 1
#define BLOCKSMOVE 100

class Actor;
typedef std::vector<Actor*> ActorPtrs;
typedef boost::ptr_vector<Actor> Actors;

typedef boost::circular_buffer_space_optimized<std::string> MsgBuffer;

/// Tiles

struct Tile {
	const static int TRANSPARENT = 255;
	char ch;
	int color;
	std::string desc;
	bool explored;
	bool visible;
	bool blocks_movement;
	int blocks_vision_dist;
	Actor* actor;

	Tile(char ch = ' ', int color = 0, int blocker = BLOCKS):
	ch(ch), color(color), explored(false), visible(false),
	blocks_movement(blocker), blocks_vision_dist(blocker ? (blocker == BLOCKSMOVE ? TRANSPARENT : 0) : TRANSPARENT), actor(NULL) {}

	bool isFree() const { return (!blocks_movement) && (actor == NULL); }

	bool operator==(const Tile& rhs) {
		return ch == rhs.ch && color == rhs.color;
	}
	bool operator!=(const Tile& rhs) { return !(*this==rhs); }
};

typedef std::vector<Tile> tilerow;
typedef std::vector<tilerow> tilearray;

Tile TileBuilder(std::string type);

/// Math

template<typename T>
std::string num2str(T i) { std::ostringstream oss; oss << i; return oss.str(); }

bool inline randbool() { return rand() % 2 == 0; }

int inline randint(int hi) { return rand() % hi; }

int inline randint(int lo, int hi) {
	return (rand() % (hi - lo + 1)) + lo;
}

int inline randdir() { return randbool() ? 1 : -1; }
void inline swapdir(int& dir) { if (dir == 1) dir = -1; else dir = 1; }
void inline randdir(int& dx, int &dy) {
	if (randbool()) { dx = randdir(); dy = randint(-1,1); }
	else { dx = randint(-1,1); dy = randdir(); }
}

template<typename T> T distance2d(T x1, T y1, T x2, T y2) {
	return sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) );
}

/** Implement C99 mathematical rounding (which C++ unfortunately currently lacks) **/
template <typename T> T round(T val) { return int(val + (val >= 0 ? 0.5 : -0.5)); }

/** Limit val to range [min, max] **/
template <typename T> T clamp(T val, T min = 0, T max = 1) {
	if (min > max) throw std::logic_error("min > max");
	if (val < min) return min;
	if (val > max) return max;
	return val;
}

/// Console

void setColor(WINDOW* scr, int color);

void setColor(int color);

void addcstr(std::string str);

void box2(int x, int y, int w, int h);

bool toggleDefaultColors();
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2018 ARM Limited
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright 2015 LabWare
 * Copyright 2014 Google, Inc.
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * 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 copyright holders 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.
 */

#ifndef __REMOTE_GDB_HH__
#define __REMOTE_GDB_HH__

#include <sys/signal.h>

#include <cstdint>
#include <exception>
#include <map>
#include <string>
#include <vector>

#include "arch/types.hh"
#include "base/cprintf.hh"
#include "base/pollevent.hh"
#include "base/socket.hh"
#include "base/types.hh"
#include "cpu/pc_event.hh"
#include "sim/eventq.hh"

class System;
class ThreadContext;

class BaseRemoteGDB;
class HardBreakpoint;

/**
 * Concrete subclasses of this abstract class represent how the
 * register values are transmitted on the wire.  Usually each
 * architecture should define one subclass, but there can be more
 * if there is more than one possible wire format.  For example,
 * ARM defines both AArch32GdbRegCache and AArch64GdbRegCache.
 */
class BaseGdbRegCache
{
  public:

    /**
     * Return the pointer to the raw bytes buffer containing the
     * register values.  Each byte of this buffer is literally
     * encoded as two hex digits in the g or G RSP packet.
     *
     * @ingroup api_remote_gdb
     */
    virtual char *data() const = 0;

    /**
     * Return the size of the raw buffer, in bytes
     * (i.e., half of the number of digits in the g/G packet).
     *
     * @ingroup api_remote_gdb
     */
    virtual size_t size() const = 0;

    /**
     * Fill the raw buffer from the registers in the ThreadContext.
     *
     * @ingroup api_remote_gdb
     */
    virtual void getRegs(ThreadContext*) = 0;

    /**
     * Set the ThreadContext's registers from the values
     * in the raw buffer.
     *
     * @ingroup api_remote_gdb
     */
    virtual void setRegs(ThreadContext*) const = 0;

    /**
     * Return the name to use in places like DPRINTF.
     * Having each concrete superclass redefine this member
     * is useful in situations where the class of the regCache
     * can change on the fly.
     *
     * @ingroup api_remote_gdb
     */
    virtual const std::string name() const = 0;

    /**
     * @ingroup api_remote_gdb
     */
    BaseGdbRegCache(BaseRemoteGDB *g) : gdb(g)
    {}
    virtual ~BaseGdbRegCache()
    {}

  protected:
    BaseRemoteGDB *gdb;
};

class BaseRemoteGDB
{
    friend class HardBreakpoint;
  public:

    /**
     * @ingroup api_remote_gdb
     * @{
     */

    /**
     * Interface to other parts of the simulator.
     */
    BaseRemoteGDB(System *system, ThreadContext *context, int _port);
    virtual ~BaseRemoteGDB();

    std::string name();

    void listen();
    void connect();

    int port() const;

    void attach(int fd);
    void detach();
    bool isAttached() { return attached; }

    void replaceThreadContext(ThreadContext *_tc) { tc = _tc; }

    bool trap(int type);

    /** @} */ // end of api_remote_gdb

  private:
    /*
     * Connection to the external GDB.
     */
    void incomingData(int revent);
    void connectWrapper(int revent) { connect(); }

    template <void (BaseRemoteGDB::*F)(int revent)>
    class SocketEvent : public PollEvent
    {
      protected:
        BaseRemoteGDB *gdb;

      public:
        SocketEvent(BaseRemoteGDB *gdb, int fd, int e) :
            PollEvent(fd, e), gdb(gdb)
        {}

        void process(int revent) { (gdb->*F)(revent); }
    };

    typedef SocketEvent<&BaseRemoteGDB::connectWrapper> ConnectEvent;
    typedef SocketEvent<&BaseRemoteGDB::incomingData> DataEvent;

    friend ConnectEvent;
    friend DataEvent;

    ConnectEvent *connectEvent;
    DataEvent *dataEvent;

    ListenSocket listener;
    int _port;

    // The socket commands come in through.
    int fd;

    // Transfer data to/from GDB.
    uint8_t getbyte();
    void putbyte(uint8_t b);

    void recv(std::vector<char> &bp);
    void send(const char *data);
    void send(const std::string &data) { send(data.c_str()); }

    template <typename ...Args>
    void
    send(const char *format, const Args &...args)
    {
        send(csprintf(format, args...));
    }

    /*
     * Simulator side debugger state.
     */
    bool active;
    bool attached;

    System *sys;
    ThreadContext *tc;

    BaseGdbRegCache *regCachePtr;

    class TrapEvent : public Event
    {
      protected:
        int _type;
        BaseRemoteGDB *gdb;

      public:
        TrapEvent(BaseRemoteGDB *g) : gdb(g)
        {}

        void type(int t) { _type = t; }
        void process() { gdb->trap(_type); }
    } trapEvent;

    /*
     * The interface to the simulated system.
     */
    // Machine memory.
    bool read(Addr addr, size_t size, char *data);
    bool write(Addr addr, size_t size, const char *data);

    template <class T> T read(Addr addr);
    template <class T> void write(Addr addr, T data);

    // Single step.
    void singleStep();
    EventWrapper<BaseRemoteGDB, &BaseRemoteGDB::singleStep> singleStepEvent;

    void clearSingleStep();
    void setSingleStep();

    /// Schedule an event which will be triggered "delta" instructions later.
    void scheduleInstCommitEvent(Event *ev, int delta);
    /// Deschedule an instruction count based event.
    void descheduleInstCommitEvent(Event *ev);

    // Breakpoints.
    void insertSoftBreak(Addr addr, size_t len);
    void removeSoftBreak(Addr addr, size_t len);
    void insertHardBreak(Addr addr, size_t len);
    void removeHardBreak(Addr addr, size_t len);

    /*
     * GDB commands.
     */
    struct GdbCommand
    {
      public:
        struct Context
        {
            const GdbCommand *cmd;
            char cmdByte;
            int type;
            char *data;
            int len;
        };

        typedef bool (BaseRemoteGDB::*Func)(Context &ctx);

        const char * const name;
        const Func func;

        GdbCommand(const char *_name, Func _func) : name(_name), func(_func) {}
    };

    static std::map<char, GdbCommand> commandMap;

    bool cmdUnsupported(GdbCommand::Context &ctx);

    bool cmdSignal(GdbCommand::Context &ctx);
    bool cmdCont(GdbCommand::Context &ctx);
    bool cmdAsyncCont(GdbCommand::Context &ctx);
    bool cmdDetach(GdbCommand::Context &ctx);
    bool cmdRegR(GdbCommand::Context &ctx);
    bool cmdRegW(GdbCommand::Context &ctx);
    bool cmdSetThread(GdbCommand::Context &ctx);
    bool cmdMemR(GdbCommand::Context &ctx);
    bool cmdMemW(GdbCommand::Context &ctx);
    bool cmdQueryVar(GdbCommand::Context &ctx);
    bool cmdStep(GdbCommand::Context &ctx);
    bool cmdAsyncStep(GdbCommand::Context &ctx);
    bool cmdClrHwBkpt(GdbCommand::Context &ctx);
    bool cmdSetHwBkpt(GdbCommand::Context &ctx);

    struct QuerySetCommand
    {
        struct Context
        {
            const std::string &name;
            std::vector<std::string> args;

            Context(const std::string &_name) : name(_name) {}
        };

        using Func = void (BaseRemoteGDB::*)(Context &ctx);

        const char * const argSep;
        const Func func;

        QuerySetCommand(Func _func, const char *_argSep=nullptr) :
            argSep(_argSep), func(_func)
        {}
    };

    static std::map<std::string, QuerySetCommand> queryMap;

    void queryC(QuerySetCommand::Context &ctx);
    void querySupported(QuerySetCommand::Context &ctx);
    void queryXfer(QuerySetCommand::Context &ctx);
    void queryFThreadInfo(QuerySetCommand::Context &ctx);
    void querySThreadInfo(QuerySetCommand::Context &ctx);

  protected:
    ThreadContext *context() { return tc; }
    System *system() { return sys; }

    void encodeBinaryData(const std::string &unencoded,
            std::string &encoded) const;

    void encodeXferResponse(const std::string &unencoded,
        std::string &encoded, size_t offset, size_t unencoded_length) const;

    // To be implemented by subclasses.
    virtual bool checkBpLen(size_t len);

    virtual BaseGdbRegCache *gdbRegs() = 0;

    virtual bool acc(Addr addr, size_t len) = 0;

    virtual std::vector<std::string> availableFeatures() const;

    /**
     * Get an XML target description.
     *
     * @param[in] annex the XML filename
     * @param[out] output set to the decoded XML
     * @return true if the given annex was found
     */
    virtual bool getXferFeaturesRead(const std::string &annex,
            std::string &output);
};

template <class T>
inline T
BaseRemoteGDB::read(Addr addr)
{
    T temp;
    read(addr, sizeof(T), (char *)&temp);
    return temp;
}

template <class T>
inline void
BaseRemoteGDB::write(Addr addr, T data)
{
    write(addr, sizeof(T), (const char *)&data);
}

#endif /* __REMOTE_GDB_H__ */
<commit_msg>base: Add a link to documentation in the remote GDB header file.<commit_after>/*
 * Copyright (c) 2018 ARM Limited
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright 2015 LabWare
 * Copyright 2014 Google, Inc.
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * 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 copyright holders 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.
 */

#ifndef __REMOTE_GDB_HH__
#define __REMOTE_GDB_HH__

#include <sys/signal.h>

#include <cstdint>
#include <exception>
#include <map>
#include <string>
#include <vector>

#include "arch/types.hh"
#include "base/cprintf.hh"
#include "base/pollevent.hh"
#include "base/socket.hh"
#include "base/types.hh"
#include "cpu/pc_event.hh"
#include "sim/eventq.hh"

/*
 * This file implements a client for the GDB remote serial protocol as
 * described in this official documentation:
 *
 * https://sourceware.org/gdb/current/onlinedocs/gdb/Remote-Protocol.html
 */

class System;
class ThreadContext;

class BaseRemoteGDB;
class HardBreakpoint;

/**
 * Concrete subclasses of this abstract class represent how the
 * register values are transmitted on the wire.  Usually each
 * architecture should define one subclass, but there can be more
 * if there is more than one possible wire format.  For example,
 * ARM defines both AArch32GdbRegCache and AArch64GdbRegCache.
 */
class BaseGdbRegCache
{
  public:

    /**
     * Return the pointer to the raw bytes buffer containing the
     * register values.  Each byte of this buffer is literally
     * encoded as two hex digits in the g or G RSP packet.
     *
     * @ingroup api_remote_gdb
     */
    virtual char *data() const = 0;

    /**
     * Return the size of the raw buffer, in bytes
     * (i.e., half of the number of digits in the g/G packet).
     *
     * @ingroup api_remote_gdb
     */
    virtual size_t size() const = 0;

    /**
     * Fill the raw buffer from the registers in the ThreadContext.
     *
     * @ingroup api_remote_gdb
     */
    virtual void getRegs(ThreadContext*) = 0;

    /**
     * Set the ThreadContext's registers from the values
     * in the raw buffer.
     *
     * @ingroup api_remote_gdb
     */
    virtual void setRegs(ThreadContext*) const = 0;

    /**
     * Return the name to use in places like DPRINTF.
     * Having each concrete superclass redefine this member
     * is useful in situations where the class of the regCache
     * can change on the fly.
     *
     * @ingroup api_remote_gdb
     */
    virtual const std::string name() const = 0;

    /**
     * @ingroup api_remote_gdb
     */
    BaseGdbRegCache(BaseRemoteGDB *g) : gdb(g)
    {}
    virtual ~BaseGdbRegCache()
    {}

  protected:
    BaseRemoteGDB *gdb;
};

class BaseRemoteGDB
{
    friend class HardBreakpoint;
  public:

    /**
     * @ingroup api_remote_gdb
     * @{
     */

    /**
     * Interface to other parts of the simulator.
     */
    BaseRemoteGDB(System *system, ThreadContext *context, int _port);
    virtual ~BaseRemoteGDB();

    std::string name();

    void listen();
    void connect();

    int port() const;

    void attach(int fd);
    void detach();
    bool isAttached() { return attached; }

    void replaceThreadContext(ThreadContext *_tc) { tc = _tc; }

    bool trap(int type);

    /** @} */ // end of api_remote_gdb

  private:
    /*
     * Connection to the external GDB.
     */
    void incomingData(int revent);
    void connectWrapper(int revent) { connect(); }

    template <void (BaseRemoteGDB::*F)(int revent)>
    class SocketEvent : public PollEvent
    {
      protected:
        BaseRemoteGDB *gdb;

      public:
        SocketEvent(BaseRemoteGDB *gdb, int fd, int e) :
            PollEvent(fd, e), gdb(gdb)
        {}

        void process(int revent) { (gdb->*F)(revent); }
    };

    typedef SocketEvent<&BaseRemoteGDB::connectWrapper> ConnectEvent;
    typedef SocketEvent<&BaseRemoteGDB::incomingData> DataEvent;

    friend ConnectEvent;
    friend DataEvent;

    ConnectEvent *connectEvent;
    DataEvent *dataEvent;

    ListenSocket listener;
    int _port;

    // The socket commands come in through.
    int fd;

    // Transfer data to/from GDB.
    uint8_t getbyte();
    void putbyte(uint8_t b);

    void recv(std::vector<char> &bp);
    void send(const char *data);
    void send(const std::string &data) { send(data.c_str()); }

    template <typename ...Args>
    void
    send(const char *format, const Args &...args)
    {
        send(csprintf(format, args...));
    }

    /*
     * Simulator side debugger state.
     */
    bool active;
    bool attached;

    System *sys;
    ThreadContext *tc;

    BaseGdbRegCache *regCachePtr;

    class TrapEvent : public Event
    {
      protected:
        int _type;
        BaseRemoteGDB *gdb;

      public:
        TrapEvent(BaseRemoteGDB *g) : gdb(g)
        {}

        void type(int t) { _type = t; }
        void process() { gdb->trap(_type); }
    } trapEvent;

    /*
     * The interface to the simulated system.
     */
    // Machine memory.
    bool read(Addr addr, size_t size, char *data);
    bool write(Addr addr, size_t size, const char *data);

    template <class T> T read(Addr addr);
    template <class T> void write(Addr addr, T data);

    // Single step.
    void singleStep();
    EventWrapper<BaseRemoteGDB, &BaseRemoteGDB::singleStep> singleStepEvent;

    void clearSingleStep();
    void setSingleStep();

    /// Schedule an event which will be triggered "delta" instructions later.
    void scheduleInstCommitEvent(Event *ev, int delta);
    /// Deschedule an instruction count based event.
    void descheduleInstCommitEvent(Event *ev);

    // Breakpoints.
    void insertSoftBreak(Addr addr, size_t len);
    void removeSoftBreak(Addr addr, size_t len);
    void insertHardBreak(Addr addr, size_t len);
    void removeHardBreak(Addr addr, size_t len);

    /*
     * GDB commands.
     */
    struct GdbCommand
    {
      public:
        struct Context
        {
            const GdbCommand *cmd;
            char cmdByte;
            int type;
            char *data;
            int len;
        };

        typedef bool (BaseRemoteGDB::*Func)(Context &ctx);

        const char * const name;
        const Func func;

        GdbCommand(const char *_name, Func _func) : name(_name), func(_func) {}
    };

    static std::map<char, GdbCommand> commandMap;

    bool cmdUnsupported(GdbCommand::Context &ctx);

    bool cmdSignal(GdbCommand::Context &ctx);
    bool cmdCont(GdbCommand::Context &ctx);
    bool cmdAsyncCont(GdbCommand::Context &ctx);
    bool cmdDetach(GdbCommand::Context &ctx);
    bool cmdRegR(GdbCommand::Context &ctx);
    bool cmdRegW(GdbCommand::Context &ctx);
    bool cmdSetThread(GdbCommand::Context &ctx);
    bool cmdMemR(GdbCommand::Context &ctx);
    bool cmdMemW(GdbCommand::Context &ctx);
    bool cmdQueryVar(GdbCommand::Context &ctx);
    bool cmdStep(GdbCommand::Context &ctx);
    bool cmdAsyncStep(GdbCommand::Context &ctx);
    bool cmdClrHwBkpt(GdbCommand::Context &ctx);
    bool cmdSetHwBkpt(GdbCommand::Context &ctx);

    struct QuerySetCommand
    {
        struct Context
        {
            const std::string &name;
            std::vector<std::string> args;

            Context(const std::string &_name) : name(_name) {}
        };

        using Func = void (BaseRemoteGDB::*)(Context &ctx);

        const char * const argSep;
        const Func func;

        QuerySetCommand(Func _func, const char *_argSep=nullptr) :
            argSep(_argSep), func(_func)
        {}
    };

    static std::map<std::string, QuerySetCommand> queryMap;

    void queryC(QuerySetCommand::Context &ctx);
    void querySupported(QuerySetCommand::Context &ctx);
    void queryXfer(QuerySetCommand::Context &ctx);
    void queryFThreadInfo(QuerySetCommand::Context &ctx);
    void querySThreadInfo(QuerySetCommand::Context &ctx);

  protected:
    ThreadContext *context() { return tc; }
    System *system() { return sys; }

    void encodeBinaryData(const std::string &unencoded,
            std::string &encoded) const;

    void encodeXferResponse(const std::string &unencoded,
        std::string &encoded, size_t offset, size_t unencoded_length) const;

    // To be implemented by subclasses.
    virtual bool checkBpLen(size_t len);

    virtual BaseGdbRegCache *gdbRegs() = 0;

    virtual bool acc(Addr addr, size_t len) = 0;

    virtual std::vector<std::string> availableFeatures() const;

    /**
     * Get an XML target description.
     *
     * @param[in] annex the XML filename
     * @param[out] output set to the decoded XML
     * @return true if the given annex was found
     */
    virtual bool getXferFeaturesRead(const std::string &annex,
            std::string &output);
};

template <class T>
inline T
BaseRemoteGDB::read(Addr addr)
{
    T temp;
    read(addr, sizeof(T), (char *)&temp);
    return temp;
}

template <class T>
inline void
BaseRemoteGDB::write(Addr addr, T data)
{
    write(addr, sizeof(T), (const char *)&data);
}

#endif /* __REMOTE_GDB_H__ */
<|endoftext|>


<commit_before>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <iostream>

#include <bench/bench.h>
#include <hash.h>
#include <crypto/chacha20.h>

/* Number of bytes to process per iteration */
static const uint64_t BUFFER_SIZE_TINY  = 64;
static const uint64_t BUFFER_SIZE_SMALL = 256;
static const uint64_t BUFFER_SIZE_LARGE = 1024*1024;

static void CHACHA20(benchmark::State& state, size_t buffersize)
{
    std::vector<uint8_t> key(32,0);
    ChaCha20 ctx(key.data(), key.size());
    ctx.SetIV(0);
    ctx.Seek(0);
    std::vector<uint8_t> in(buffersize,0);
    std::vector<uint8_t> out(buffersize,0);
    while (state.KeepRunning()) {
        ctx.Crypt(in.data(), out.data(), in.size());
    }
}

static void CHACHA20_64BYTES(benchmark::State& state)
{
    CHACHA20(state, BUFFER_SIZE_TINY);
}

static void CHACHA20_256BYTES(benchmark::State& state)
{
    CHACHA20(state, BUFFER_SIZE_SMALL);
}

static void CHACHA20_1MB(benchmark::State& state)
{
    CHACHA20(state, BUFFER_SIZE_LARGE);
}

BENCHMARK(CHACHA20_64BYTES, 500000);
BENCHMARK(CHACHA20_256BYTES, 250000);
BENCHMARK(CHACHA20_1MB, 340);
<commit_msg>Use old BENCHMARK setup<commit_after>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <iostream>

#include <bench/bench.h>
#include <hash.h>
#include <crypto/chacha20.h>

/* Number of bytes to process per iteration */
static const uint64_t BUFFER_SIZE_TINY  = 64;
static const uint64_t BUFFER_SIZE_SMALL = 256;
static const uint64_t BUFFER_SIZE_LARGE = 1024*1024;

static void CHACHA20(benchmark::State& state, size_t buffersize)
{
    std::vector<uint8_t> key(32,0);
    ChaCha20 ctx(key.data(), key.size());
    ctx.SetIV(0);
    ctx.Seek(0);
    std::vector<uint8_t> in(buffersize,0);
    std::vector<uint8_t> out(buffersize,0);
    while (state.KeepRunning()) {
        ctx.Crypt(in.data(), out.data(), in.size());
    }
}

static void CHACHA20_64BYTES(benchmark::State& state)
{
    CHACHA20(state, BUFFER_SIZE_TINY);
}

static void CHACHA20_256BYTES(benchmark::State& state)
{
    CHACHA20(state, BUFFER_SIZE_SMALL);
}

static void CHACHA20_1MB(benchmark::State& state)
{
    CHACHA20(state, BUFFER_SIZE_LARGE);
}

//TODO add back below once benchmarking backports are done
//BENCHMARK(CHACHA20_64BYTES, 500000);
//BENCHMARK(CHACHA20_256BYTES, 250000);
//BENCHMARK(CHACHA20_1MB, 340);
BENCHMARK(CHACHA20_64BYTES);
BENCHMARK(CHACHA20_256BYTES);
BENCHMARK(CHACHA20_1MB);<|endoftext|>


<commit_before>
// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_SFM_IO_H
#define OPENMVG_SFM_IO_H

#include "openMVG/numeric/numeric.h"
#include "openMVG/split/split.hpp"

#include <fstream>
#include <iterator>
#include <set>
#include <sstream>
#include <string>
#include <vector>

namespace openMVG{
namespace SfMIO{

struct CameraInfo
{
  std::string m_sImageName;
  size_t m_intrinsicId;
};

struct IntrinsicCameraInfo
{
  size_t m_w, m_h;
  float m_focal;
  Mat3 m_K;
  bool m_bKnownIntrinsic; // true if 11 or 6, else false
  std::string m_sCameraMaker, m_sCameraModel;

  bool operator() (IntrinsicCameraInfo const &ci1, IntrinsicCameraInfo const &ci2)const
  {
    bool bequal = false;
    if ( ci1.m_sCameraMaker.compare("") != 0  && ci1.m_sCameraModel.compare("") != 0 )
    {
      if ( ci1.m_sCameraMaker.compare(ci2.m_sCameraMaker) == 0
          && ci1.m_sCameraModel.compare(ci2.m_sCameraModel) == 0
          && ci1.m_w == ci2.m_w
          && ci1.m_h == ci2.m_h
          && ci1.m_focal == ci2.m_focal )
      {
        bequal = true;
      }
      else
      {
        if(m_bKnownIntrinsic)
          bequal = ci1.m_K == ci2.m_K;
      }
    }
    return !bequal;
  }
};

// Load an image file list
// One basename per line.
// It handle different scenario based on the intrinsic info of the tested image
// - a camera without exif data
// - a camera with exif data found in the database
// - a camera with exif data not found in the database
// - a camera with known intrinsic
static bool loadImageList( std::vector<CameraInfo> & vec_camImageName,
                           std::vector<IntrinsicCameraInfo> & vec_focalGroup,
                           std::string sFileName,
                           bool bVerbose = true )
{
  typedef std::set<IntrinsicCameraInfo, IntrinsicCameraInfo> setIntrinsicCameraInfo;
  setIntrinsicCameraInfo set_focalGroup;

  std::ifstream in(sFileName.c_str());
  if(!in.is_open())  {
    std::cerr << std::endl
      << "Impossible to read the specified file." << std::endl;
  }
  std::string sValue;
  std::vector<std::string> vec_str;
  while(getline( in, sValue ) )
  {
    vec_str.clear();
    IntrinsicCameraInfo intrinsicCamInfo;
    split( sValue, ";", vec_str );
    if (vec_str.size() == 1)
    {
      std::cerr << "Invalid input file" << std::endl;
      in.close();
      return false;
    }
    std::stringstream oss;
    oss.clear(); oss.str(vec_str[1]);
    size_t width, height;
    oss >> width;
    oss.clear(); oss.str(vec_str[2]);
    oss >> height;

    intrinsicCamInfo.m_w = width;
    intrinsicCamInfo.m_h = height;

    switch ( vec_str.size() )
    {
      case 3 : // a camera without exif data
      {
         intrinsicCamInfo.m_focal = -1;
         intrinsicCamInfo.m_bKnownIntrinsic = false;
         intrinsicCamInfo.m_sCameraMaker = "";
         intrinsicCamInfo.m_sCameraModel = "";
      }
      break;
      case 5 : // a camera with exif data found in the database
      {
         intrinsicCamInfo.m_focal = -1;
         intrinsicCamInfo.m_bKnownIntrinsic = false;
         intrinsicCamInfo.m_sCameraMaker = vec_str[3];
         intrinsicCamInfo.m_sCameraModel = vec_str[4];
      }
      break;
      case  6 : // a camera with exif data not found in the database
      {
         oss.clear(); oss.str(vec_str[3]);
         float focal;
         oss >> focal;
         intrinsicCamInfo.m_focal = focal;
         intrinsicCamInfo.m_bKnownIntrinsic = true;
         intrinsicCamInfo.m_sCameraMaker = vec_str[4];
         intrinsicCamInfo.m_sCameraModel = vec_str[5];

         Mat3 K;
         K << focal, 0, float(width) / 2.f,
              0, focal, float(height) / 2.f,
              0, 0, 1;
         intrinsicCamInfo.m_K = K;

      }
      break;
      case 12 : // a camera with known intrinsic
      {
        intrinsicCamInfo.m_bKnownIntrinsic = true;
        intrinsicCamInfo.m_sCameraMaker = intrinsicCamInfo.m_sCameraModel = "";

        Mat3 K = Mat3::Identity();

        oss.clear(); oss.str(vec_str[3]);
        oss >> K(0,0);
        oss.clear(); oss.str(vec_str[4]);
        oss >> K(0,1);
        oss.clear(); oss.str(vec_str[5]);
        oss >> K(0,2);
        oss.clear(); oss.str(vec_str[6]);
        oss >> K(1,0);
        oss.clear(); oss.str(vec_str[7]);
        oss >> K(1,1);
        oss.clear(); oss.str(vec_str[8]);
        oss >> K(1,2);
        oss.clear(); oss.str(vec_str[9]);
        oss >> K(2,0);
        oss.clear(); oss.str(vec_str[10]);
        oss >> K(2,1);
        oss.clear(); oss.str(vec_str[11]);
        oss >> K(2,2);

        intrinsicCamInfo.m_K = K;
        intrinsicCamInfo.m_focal = static_cast<float>(K(0,0)); // unkown sensor size;
      }
      break;
      default :
      {
        std::cerr << "Invalid line : wrong number of arguments" << std::endl;
      }
    }

    std::pair<setIntrinsicCameraInfo::iterator, bool> ret = set_focalGroup.insert(intrinsicCamInfo);
    if ( ret.second )
    {
      vec_focalGroup.push_back(intrinsicCamInfo);
    }
    size_t id = std::distance( ret.first, set_focalGroup.end()) - 1;
    CameraInfo camInfo;
    camInfo.m_sImageName = vec_str[0];
    camInfo.m_intrinsicId = id;
    vec_camImageName.push_back(camInfo);

    vec_str.clear();
  }
  in.close();
  return !(vec_camImageName.empty());
}

//-- Load an image list file but only return camera image names
static bool loadImageList( std::vector<std::string> & vec_camImageName,
                           std::string sListFileName,
                           bool bVerbose = true )
{
  vec_camImageName.clear();
  std::vector<openMVG::SfMIO::CameraInfo> vec_camImageIntrinsicInfo;
  std::vector<openMVG::SfMIO::IntrinsicCameraInfo> vec_focalGroup;
  if (loadImageList( vec_camImageIntrinsicInfo,
                      vec_focalGroup,
                      sListFileName,
                      bVerbose) )
  {
    for ( std::vector<openMVG::SfMIO::CameraInfo>::const_iterator
      iter_camInfo = vec_camImageIntrinsicInfo.begin();
      iter_camInfo != vec_camImageIntrinsicInfo.end();
      iter_camInfo++ )
    {
      vec_camImageName.push_back( iter_camInfo->m_sImageName );
    }
  }
  return (!vec_camImageName.empty());
}

} // namespace SfMIO
} // namespace openMVG

#endif // OPENMVG_SFM_INCREMENTAL_ENGINE_H

<commit_msg>[SfM] better handle bad line reading in lists.txt. #157<commit_after>
// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_SFM_IO_H
#define OPENMVG_SFM_IO_H

#include "openMVG/numeric/numeric.h"
#include "openMVG/split/split.hpp"

#include <fstream>
#include <iterator>
#include <set>
#include <sstream>
#include <string>
#include <vector>

namespace openMVG{
namespace SfMIO{

struct CameraInfo
{
  std::string m_sImageName;
  size_t m_intrinsicId;
};

struct IntrinsicCameraInfo
{
  size_t m_w, m_h;
  float m_focal;
  Mat3 m_K;
  bool m_bKnownIntrinsic; // true if 11 or 6, else false
  std::string m_sCameraMaker, m_sCameraModel;

  bool operator() (IntrinsicCameraInfo const &ci1, IntrinsicCameraInfo const &ci2)const
  {
    bool bequal = false;
    if ( ci1.m_sCameraMaker.compare("") != 0  && ci1.m_sCameraModel.compare("") != 0 )
    {
      if ( ci1.m_sCameraMaker.compare(ci2.m_sCameraMaker) == 0
          && ci1.m_sCameraModel.compare(ci2.m_sCameraModel) == 0
          && ci1.m_w == ci2.m_w
          && ci1.m_h == ci2.m_h
          && ci1.m_focal == ci2.m_focal )
      {
        bequal = true;
      }
      else
      {
        if(m_bKnownIntrinsic)
          bequal = ci1.m_K == ci2.m_K;
      }
    }
    return !bequal;
  }
};

// Load an image file list
// One basename per line.
// It handle different scenario based on the intrinsic info of the tested image
// - a camera without exif data
// - a camera with exif data found in the database
// - a camera with exif data not found in the database
// - a camera with known intrinsic
static bool loadImageList( std::vector<CameraInfo> & vec_camImageName,
                           std::vector<IntrinsicCameraInfo> & vec_focalGroup,
                           std::string sFileName,
                           bool bVerbose = true )
{
  typedef std::set<IntrinsicCameraInfo, IntrinsicCameraInfo> setIntrinsicCameraInfo;
  setIntrinsicCameraInfo set_focalGroup;

  std::ifstream in(sFileName.c_str());
  if(!in.is_open())  {
    std::cerr << std::endl
      << "Impossible to read the specified file." << std::endl;
  }
  std::string sValue;
  std::vector<std::string> vec_str;
  while(getline( in, sValue ) )
  {
    vec_str.clear();
    IntrinsicCameraInfo intrinsicCamInfo;
    split( sValue, ";", vec_str );
    if (vec_str.size() == 1)
    {
      std::cerr << "Invalid input file" << std::endl;
      in.close();
      return false;
    }
    std::stringstream oss;
    oss.clear(); oss.str(vec_str[1]);
    size_t width, height;
    oss >> width;
    oss.clear(); oss.str(vec_str[2]);
    oss >> height;

    intrinsicCamInfo.m_w = width;
    intrinsicCamInfo.m_h = height;

    switch ( vec_str.size() )
    {
      case 3 : // a camera without exif data
      {
         intrinsicCamInfo.m_focal = -1;
         intrinsicCamInfo.m_bKnownIntrinsic = false;
         intrinsicCamInfo.m_sCameraMaker = "";
         intrinsicCamInfo.m_sCameraModel = "";
      }
      break;
      case 5 : // a camera with exif data found in the database
      {
         intrinsicCamInfo.m_focal = -1;
         intrinsicCamInfo.m_bKnownIntrinsic = false;
         intrinsicCamInfo.m_sCameraMaker = vec_str[3];
         intrinsicCamInfo.m_sCameraModel = vec_str[4];
      }
      break;
      case  6 : // a camera with exif data not found in the database
      {
         oss.clear(); oss.str(vec_str[3]);
         float focal;
         oss >> focal;
         intrinsicCamInfo.m_focal = focal;
         intrinsicCamInfo.m_bKnownIntrinsic = true;
         intrinsicCamInfo.m_sCameraMaker = vec_str[4];
         intrinsicCamInfo.m_sCameraModel = vec_str[5];

         Mat3 K;
         K << focal, 0, float(width) / 2.f,
              0, focal, float(height) / 2.f,
              0, 0, 1;
         intrinsicCamInfo.m_K = K;

      }
      break;
      case 12 : // a camera with known intrinsic
      {
        intrinsicCamInfo.m_bKnownIntrinsic = true;
        intrinsicCamInfo.m_sCameraMaker = intrinsicCamInfo.m_sCameraModel = "";

        Mat3 K = Mat3::Identity();

        oss.clear(); oss.str(vec_str[3]);
        oss >> K(0,0);
        oss.clear(); oss.str(vec_str[4]);
        oss >> K(0,1);
        oss.clear(); oss.str(vec_str[5]);
        oss >> K(0,2);
        oss.clear(); oss.str(vec_str[6]);
        oss >> K(1,0);
        oss.clear(); oss.str(vec_str[7]);
        oss >> K(1,1);
        oss.clear(); oss.str(vec_str[8]);
        oss >> K(1,2);
        oss.clear(); oss.str(vec_str[9]);
        oss >> K(2,0);
        oss.clear(); oss.str(vec_str[10]);
        oss >> K(2,1);
        oss.clear(); oss.str(vec_str[11]);
        oss >> K(2,2);

        intrinsicCamInfo.m_K = K;
        intrinsicCamInfo.m_focal = static_cast<float>(K(0,0)); // unkown sensor size;
      }
      break;
      default :
      {
        std::cerr << "Invalid image list line: wrong number of arguments" << std::endl;
        in.close();
        return false;
      }
    }

    std::pair<setIntrinsicCameraInfo::iterator, bool> ret = set_focalGroup.insert(intrinsicCamInfo);
    if ( ret.second )
    {
      vec_focalGroup.push_back(intrinsicCamInfo);
    }
    size_t id = std::distance( ret.first, set_focalGroup.end()) - 1;
    CameraInfo camInfo;
    camInfo.m_sImageName = vec_str[0];
    camInfo.m_intrinsicId = id;
    vec_camImageName.push_back(camInfo);

    vec_str.clear();
  }
  in.close();
  return !(vec_camImageName.empty());
}

//-- Load an image list file but only return camera image names
static bool loadImageList( std::vector<std::string> & vec_camImageName,
                           std::string sListFileName,
                           bool bVerbose = true )
{
  vec_camImageName.clear();
  std::vector<openMVG::SfMIO::CameraInfo> vec_camImageIntrinsicInfo;
  std::vector<openMVG::SfMIO::IntrinsicCameraInfo> vec_focalGroup;
  if (loadImageList( vec_camImageIntrinsicInfo,
                      vec_focalGroup,
                      sListFileName,
                      bVerbose) )
  {
    for ( std::vector<openMVG::SfMIO::CameraInfo>::const_iterator
      iter_camInfo = vec_camImageIntrinsicInfo.begin();
      iter_camInfo != vec_camImageIntrinsicInfo.end();
      iter_camInfo++ )
    {
      vec_camImageName.push_back( iter_camInfo->m_sImageName );
    }
  }
  return (!vec_camImageName.empty());
}

} // namespace SfMIO
} // namespace openMVG

#endif // OPENMVG_SFM_INCREMENTAL_ENGINE_H

<|endoftext|>


<commit_before>/*

This file is part of VROOM.

Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).

*/

#include "vehicle.h"

vehicle_t::vehicle_t(ID_t id,
                     const boost::optional<location_t>& start,
                     const boost::optional<location_t>& end)
  : vehicle_t(id, start, end, boost::none) {
}

vehicle_t::vehicle_t(ID_t id,
                     const boost::optional<location_t>& start,
                     const boost::optional<location_t>& end,
                     const boost::optional<amount_t>& capacity)
  : id(id), start(start), end(end), capacity(capacity) {
  if ((start == boost::none) and (end == boost::none)) {
    throw custom_exception("No start or end specified for vehicle " +
                           std::to_string(id) + '.');
  }
}

bool vehicle_t::has_start() const {
  return start != boost::none;
}

bool vehicle_t::has_end() const {
  return end != boost::none;
}

bool vehicle_t::has_capacity() const {
  return capacity != boost::none;
}
<commit_msg>Remove checks against boost::none.<commit_after>/*

This file is part of VROOM.

Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).

*/

#include "vehicle.h"

vehicle_t::vehicle_t(ID_t id,
                     const boost::optional<location_t>& start,
                     const boost::optional<location_t>& end)
  : vehicle_t(id, start, end, boost::none) {
}

vehicle_t::vehicle_t(ID_t id,
                     const boost::optional<location_t>& start,
                     const boost::optional<location_t>& end,
                     const boost::optional<amount_t>& capacity)
  : id(id), start(start), end(end), capacity(capacity) {
  if (!static_cast<bool>(start) and !static_cast<bool>(end)) {
    throw custom_exception("No start or end specified for vehicle " +
                           std::to_string(id) + '.');
  }
}

bool vehicle_t::has_start() const {
  return static_cast<bool>(start);
}

bool vehicle_t::has_end() const {
  return static_cast<bool>(end);
}

bool vehicle_t::has_capacity() const {
  return static_cast<bool>(capacity);
}
<|endoftext|>


<commit_before>
#include <getopt.h>
#include "subcommand.hpp"
#include "index.hpp"
#include "stream.hpp"
#include "genotyper.hpp"
#include "genotypekit.hpp"
#include "stream.hpp"
/**
* GAM sort main
*/

using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_genotype(char** argv) {
    cerr << "usage: " << argv[0] << " genotype [options] <graph.vg> [reads.index/] > <calls.vcf>" << endl
         << "Compute genotypes from a graph and an indexed collection of reads" << endl
         << endl
         << "options:" << endl
         << "    -j, --json              output in JSON" << endl
         << "    -v, --vcf               output in VCF" << endl
         << "    -G, --gam   GAM         a GAM file to use with variant recall (or in place of index)" << endl
         << "    -V, --recall-vcf VCF    recall variants in a specific VCF file." << endl
         << "    -F, --fasta  FASTA" << endl
         << "    -I, --insertions INS" << endl
         << "    -r, --ref PATH          use the given path name as the reference path" << std::endl
         << "    -c, --contig NAME       use the given name as the VCF contig name" << std::endl
         << "    -s, --sample NAME       name the sample in the VCF with the given name" << std::endl
         << "    -o, --offset INT        offset variant positions by this amount" << std::endl
         << "    -l, --length INT        override total sequence length" << std::endl
         << "    -a, --augmented FILE    dump augmented graph to FILE" << std::endl
         << "    -q, --use_mapq          use mapping qualities" << std::endl
         << "    -S, --subset-graph      only use the reference and areas of the graph with read support" << std::endl
         << "    -i, --realign_indels    realign at indels" << std::endl
         << "    -d, --het_prior_denom   denominator for prior probability of heterozygousness" << std::endl
         << "    -P, --min_per_strand    min consistent reads per strand for an allele" << std::endl
         << "    -p, --progress          show progress" << endl
         << "    -t, --threads N         number of threads to use" << endl;
}

int main_genotype(int argc, char** argv) {

    if (argc <= 2) {
        help_genotype(argv);
        return 1;
    }
    // Should we output genotypes in JSON (true) or Protobuf (false)?
    bool output_json = false;
    // Should we output VCF instead of protobuf?
    bool output_vcf = false;
    // Should we show progress with a progress bar?
    bool show_progress = false;
    // How many threads should we use?
    int thread_count = 0;

    // What reference path should we use
    string ref_path_name;
    // What sample name should we use for output
    string sample_name;
    // What contig name override do we want?
    string contig_name;
    // What offset should we add to coordinates
    int64_t variant_offset = 0;
    // What length override should we use
    int64_t length_override = 0;

    // Should we we just do a quick variant recall,
    // based on this VCF and GAM, then exit?
    string recall_vcf;
    string gam_file;
    string fasta;
    string insertions_file;
    bool useindex = true;

    // Should we use mapping qualities?
    bool use_mapq = false;
    // Should we do indel realignment?
    bool realign_indels = false;

    // Should we dump the augmented graph to a file?
    string augmented_file_name;

    // Should we find superbubbles on the supported subset (true) or the whole graph (false)?
    bool subset_graph = false;
    // What should the heterozygous genotype prior be? (1/this)
    double het_prior_denominator = 10.0;
    // At least how many reads must be consistent per strand for a call?
    size_t min_consistent_per_strand = 2;

    bool just_call = false;
    int c;
    optind = 2; // force optind past command positional arguments
    while (true) {
        static struct option long_options[] =
            {
                {"json", no_argument, 0, 'j'},
                {"vcf", no_argument, 0, 'v'},
                {"ref", required_argument, 0, 'r'},
                {"contig", required_argument, 0, 'c'},
                {"sample", required_argument, 0, 's'},
                {"offset", required_argument, 0, 'o'},
                {"length", required_argument, 0, 'l'},
                {"augmented", required_argument, 0, 'a'},
                {"use_mapq", no_argument, 0, 'q'},
                {"subset-graph", no_argument, 0, 'S'},
                {"realign_indels", no_argument, 0, 'i'},
                {"het_prior_denom", required_argument, 0, 'd'},
                {"min_per_strand", required_argument, 0, 'P'},
                {"progress", no_argument, 0, 'p'},
                {"threads", required_argument, 0, 't'},
                {"recall-vcf", required_argument, 0, 'V'},
                {"gam", required_argument, 0, 'G'},
                {"fasta", required_argument, 0, 'F'},
                {"insertions", required_argument, 0, 'I'},
                {"call", no_argument, 0, 'z'},
                {0, 0, 0, 0}
            };

        int option_index = 0;
        c = getopt_long (argc, argv, "hjvr:c:s:o:l:a:qSid:P:pt:V:I:G:F:z",
                         long_options, &option_index);

        /* Detect the end of the options. */
        if (c == -1)
            break;

        switch (c)
        {
        case 'j':
            output_json = true;
            break;
        case 'v':
            output_vcf = true;
            break;
        case 'r':
            // Set the reference path name
            ref_path_name = optarg;
            break;
        case 'c':
            // Set the contig name for output
            contig_name = optarg;
            break;
        case 's':
            // Set the sample name
            sample_name = optarg;
            break;
        case 'o':
            // Offset variants
            variant_offset = std::stoll(optarg);
            break;
        case 'l':
            // Set a length override
            length_override = std::stoll(optarg);
            break;
        case 'a':
            // Dump augmented graph
            augmented_file_name = optarg;
            break;
        case 'q':
            // Use mapping qualities
            use_mapq = true;
            break;
        case 'S':
            // Find sites on the graph subset with any read support
            subset_graph = true;
            break;
        case 'z':
            just_call = true;
            break;
        case 'i':
            // Do indel realignment
            realign_indels = true;
            break;
        case 'd':
            // Set heterozygous genotype prior denominator
            het_prior_denominator = std::stod(optarg);
            break;
        case 'P':
            // Set min consistent reads per strand required to keep an allele
            min_consistent_per_strand = std::stoll(optarg);
            break;
        case 'p':
            show_progress = true;
            break;
        case 't':
            thread_count = atoi(optarg);
            break;
        case 'V':
            recall_vcf = optarg;
            break;
        case 'I':
            insertions_file = optarg;
            break;
        case 'F':
            fasta = optarg;
            break;
        case 'G':
            gam_file = optarg;
            useindex = false;
            break;
        case 'h':
        case '?':
            /* getopt_long already printed an error message. */
            help_genotype(argv);
            exit(1);
            break;
        default:
          abort ();
        }
    }

    if(thread_count > 0) {
        omp_set_num_threads(thread_count);
    }

    // read the graph
    if (optind >= argc) {
        help_genotype(argv);
        return 1;
    }

    if (show_progress) {
        cerr << "Reading input graph..." << endl;
    }
    VG* graph;
    get_input_file(optind, argc, argv, [&](istream& in) {
        graph = new VG(in);
    });

    if (just_call){
        Genotyper gt;
        string gamfi(gam_file);
        string rstr(ref_path_name);
        gt.genotype_svs(graph, gamfi, rstr);
        exit(0);
    }

      // setup reads index
    if (optind >= argc) {
        help_genotype(argv);
        return 1;
    }

    string reads_index_name = "";
    if (optind < argc){
        reads_index_name = get_input_file_name(optind, argc, argv);

    }
    // This holds the RocksDB index that has all our reads, indexed by the nodes they visit.
    Index index;
    if (useindex){
        index.open_read_only(reads_index_name);
        gam_file = reads_index_name;
    }

    // Build the set of all the node IDs to operate on
    vector<vg::id_t> graph_ids;
    graph->for_each_node([&](Node* node) {
        // Put all the ids in the set
        graph_ids.push_back(node->id());
    });

    if (!(recall_vcf.empty() || fasta.empty())){
        Genotyper gt;
        vcflib::VariantCallFile* vars = new vcflib::VariantCallFile();
        vars->open(recall_vcf);
        FastaReference* lin_ref = new FastaReference();
        lin_ref->open(fasta);

        vector<FastaReference*> insertions;
        if (!insertions_file.empty()){
            FastaReference* ins = new FastaReference();
            insertions.emplace_back(ins);
            ins->open(insertions_file);
        }
        gt.variant_recall(graph, vars, lin_ref, insertions, gam_file, useindex);
        return 0;

    }

    // Load all the reads matching the graph into memory
    vector<Alignment> alignments;

    if(show_progress) {
        cerr << "Loading reads..." << endl;
    }

    function<bool(const Alignment&)> alignment_contained = [&graph](const Alignment& alignment) {
        for(size_t i = 0; i < alignment.path().mapping_size(); i++) {
            if(!graph->has_node(alignment.path().mapping(i).position().node_id())) {
                return false;
            }
        }
        return alignment.path().mapping_size() > 0;
    };

    if (useindex) {
        // Extract all the alignments
        index.for_alignment_to_nodes(graph_ids, [&](const Alignment& alignment) {
                // Only take alignments that don't visit nodes not in the graph
                if (alignment_contained(alignment)) {
                    alignments.push_back(alignment);
                }
            });
    } else {
        // load in all reads (activated by passing GAM directly with -G).
        // This is used by, ex., toil-vg, which has already used the gam index
        // to extract relevant reads
        ifstream gam_reads(gam_file.c_str());
        if (!gam_reads) {
            cerr << "[vg genotype] Error opening gam: " << gam_file << endl;
            return 1;
        }
        stream::for_each<Alignment>(gam_reads, [&alignments, &alignment_contained](Alignment& alignment) {
                if (alignment_contained(alignment)) {
                    alignments.push_back(alignment);
                }
            });
    }

    if(show_progress) {
        cerr << "Loaded " << alignments.size() << " alignments" << endl;
    }

    // Make a Genotyper to do the genotyping
    Genotyper genotyper;
    // Configure it
    genotyper.use_mapq = use_mapq;
    genotyper.realign_indels = realign_indels;
    assert(het_prior_denominator > 0);
    genotyper.het_prior_logprob = prob_to_logprob(1.0/het_prior_denominator);
    genotyper.min_consistent_per_strand = min_consistent_per_strand;
    // TODO: move arguments below up into configuration
    genotyper.run(*graph,
                  alignments,
                  cout,
                  ref_path_name,
                  contig_name,
                  sample_name,
                  augmented_file_name,
                  subset_graph,
                  show_progress,
                  output_vcf,
                  output_json,
                  length_override,
                  variant_offset);

    delete graph;

    return 0;
}

static Subcommand vg_genotype("genotype", "Genotype (or type) graphs, GAMS, and VCFs.", main_genotype);
<commit_msg>make index argument optional<commit_after>
#include <getopt.h>
#include "subcommand.hpp"
#include "index.hpp"
#include "stream.hpp"
#include "genotyper.hpp"
#include "genotypekit.hpp"
#include "stream.hpp"
/**
* GAM sort main
*/

using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_genotype(char** argv) {
    cerr << "usage: " << argv[0] << " genotype [options] <graph.vg> [reads.index/] > <calls.vcf>" << endl
         << "Compute genotypes from a graph and an indexed collection of reads" << endl
         << endl
         << "options:" << endl
         << "    -j, --json              output in JSON" << endl
         << "    -v, --vcf               output in VCF" << endl
         << "    -G, --gam   GAM         a GAM file to use with variant recall (or in place of index)" << endl
         << "    -V, --recall-vcf VCF    recall variants in a specific VCF file." << endl
         << "    -F, --fasta  FASTA" << endl
         << "    -I, --insertions INS" << endl
         << "    -r, --ref PATH          use the given path name as the reference path" << std::endl
         << "    -c, --contig NAME       use the given name as the VCF contig name" << std::endl
         << "    -s, --sample NAME       name the sample in the VCF with the given name" << std::endl
         << "    -o, --offset INT        offset variant positions by this amount" << std::endl
         << "    -l, --length INT        override total sequence length" << std::endl
         << "    -a, --augmented FILE    dump augmented graph to FILE" << std::endl
         << "    -q, --use_mapq          use mapping qualities" << std::endl
         << "    -S, --subset-graph      only use the reference and areas of the graph with read support" << std::endl
         << "    -i, --realign_indels    realign at indels" << std::endl
         << "    -d, --het_prior_denom   denominator for prior probability of heterozygousness" << std::endl
         << "    -P, --min_per_strand    min consistent reads per strand for an allele" << std::endl
         << "    -p, --progress          show progress" << endl
         << "    -t, --threads N         number of threads to use" << endl;
}

int main_genotype(int argc, char** argv) {

    if (argc <= 2) {
        help_genotype(argv);
        return 1;
    }
    // Should we output genotypes in JSON (true) or Protobuf (false)?
    bool output_json = false;
    // Should we output VCF instead of protobuf?
    bool output_vcf = false;
    // Should we show progress with a progress bar?
    bool show_progress = false;
    // How many threads should we use?
    int thread_count = 0;

    // What reference path should we use
    string ref_path_name;
    // What sample name should we use for output
    string sample_name;
    // What contig name override do we want?
    string contig_name;
    // What offset should we add to coordinates
    int64_t variant_offset = 0;
    // What length override should we use
    int64_t length_override = 0;

    // Should we we just do a quick variant recall,
    // based on this VCF and GAM, then exit?
    string recall_vcf;
    string gam_file;
    string fasta;
    string insertions_file;
    bool useindex = true;

    // Should we use mapping qualities?
    bool use_mapq = false;
    // Should we do indel realignment?
    bool realign_indels = false;

    // Should we dump the augmented graph to a file?
    string augmented_file_name;

    // Should we find superbubbles on the supported subset (true) or the whole graph (false)?
    bool subset_graph = false;
    // What should the heterozygous genotype prior be? (1/this)
    double het_prior_denominator = 10.0;
    // At least how many reads must be consistent per strand for a call?
    size_t min_consistent_per_strand = 2;

    bool just_call = false;
    int c;
    optind = 2; // force optind past command positional arguments
    while (true) {
        static struct option long_options[] =
            {
                {"json", no_argument, 0, 'j'},
                {"vcf", no_argument, 0, 'v'},
                {"ref", required_argument, 0, 'r'},
                {"contig", required_argument, 0, 'c'},
                {"sample", required_argument, 0, 's'},
                {"offset", required_argument, 0, 'o'},
                {"length", required_argument, 0, 'l'},
                {"augmented", required_argument, 0, 'a'},
                {"use_mapq", no_argument, 0, 'q'},
                {"subset-graph", no_argument, 0, 'S'},
                {"realign_indels", no_argument, 0, 'i'},
                {"het_prior_denom", required_argument, 0, 'd'},
                {"min_per_strand", required_argument, 0, 'P'},
                {"progress", no_argument, 0, 'p'},
                {"threads", required_argument, 0, 't'},
                {"recall-vcf", required_argument, 0, 'V'},
                {"gam", required_argument, 0, 'G'},
                {"fasta", required_argument, 0, 'F'},
                {"insertions", required_argument, 0, 'I'},
                {"call", no_argument, 0, 'z'},
                {0, 0, 0, 0}
            };

        int option_index = 0;
        c = getopt_long (argc, argv, "hjvr:c:s:o:l:a:qSid:P:pt:V:I:G:F:z",
                         long_options, &option_index);

        /* Detect the end of the options. */
        if (c == -1)
            break;

        switch (c)
        {
        case 'j':
            output_json = true;
            break;
        case 'v':
            output_vcf = true;
            break;
        case 'r':
            // Set the reference path name
            ref_path_name = optarg;
            break;
        case 'c':
            // Set the contig name for output
            contig_name = optarg;
            break;
        case 's':
            // Set the sample name
            sample_name = optarg;
            break;
        case 'o':
            // Offset variants
            variant_offset = std::stoll(optarg);
            break;
        case 'l':
            // Set a length override
            length_override = std::stoll(optarg);
            break;
        case 'a':
            // Dump augmented graph
            augmented_file_name = optarg;
            break;
        case 'q':
            // Use mapping qualities
            use_mapq = true;
            break;
        case 'S':
            // Find sites on the graph subset with any read support
            subset_graph = true;
            break;
        case 'z':
            just_call = true;
            break;
        case 'i':
            // Do indel realignment
            realign_indels = true;
            break;
        case 'd':
            // Set heterozygous genotype prior denominator
            het_prior_denominator = std::stod(optarg);
            break;
        case 'P':
            // Set min consistent reads per strand required to keep an allele
            min_consistent_per_strand = std::stoll(optarg);
            break;
        case 'p':
            show_progress = true;
            break;
        case 't':
            thread_count = atoi(optarg);
            break;
        case 'V':
            recall_vcf = optarg;
            break;
        case 'I':
            insertions_file = optarg;
            break;
        case 'F':
            fasta = optarg;
            break;
        case 'G':
            gam_file = optarg;
            useindex = false;
            break;
        case 'h':
        case '?':
            /* getopt_long already printed an error message. */
            help_genotype(argv);
            exit(1);
            break;
        default:
          abort ();
        }
    }

    if(thread_count > 0) {
        omp_set_num_threads(thread_count);
    }

    // read the graph
    if (optind >= argc) {
        help_genotype(argv);
        return 1;
    }

    if (show_progress) {
        cerr << "Reading input graph..." << endl;
    }
    VG* graph;
    get_input_file(optind, argc, argv, [&](istream& in) {
        graph = new VG(in);
    });

    if (just_call){
        Genotyper gt;
        string gamfi(gam_file);
        string rstr(ref_path_name);
        gt.genotype_svs(graph, gamfi, rstr);
        exit(0);
    }

    // setup reads index
    string reads_index_name = "";
    if (optind < argc){
        reads_index_name = get_input_file_name(optind, argc, argv);

    } else {
        if (gam_file.empty()) {
            cerr << "[vg genotype] Index argument must be specified when not using -G" << endl;
            return 1;
        }
    }

    // This holds the RocksDB index that has all our reads, indexed by the nodes they visit.
    Index index;
    if (useindex){
        index.open_read_only(reads_index_name);
        gam_file = reads_index_name;
    }

    // Build the set of all the node IDs to operate on
    vector<vg::id_t> graph_ids;
    graph->for_each_node([&](Node* node) {
        // Put all the ids in the set
        graph_ids.push_back(node->id());
    });

    if (!(recall_vcf.empty() || fasta.empty())){
        Genotyper gt;
        vcflib::VariantCallFile* vars = new vcflib::VariantCallFile();
        vars->open(recall_vcf);
        FastaReference* lin_ref = new FastaReference();
        lin_ref->open(fasta);

        vector<FastaReference*> insertions;
        if (!insertions_file.empty()){
            FastaReference* ins = new FastaReference();
            insertions.emplace_back(ins);
            ins->open(insertions_file);
        }
        gt.variant_recall(graph, vars, lin_ref, insertions, gam_file, useindex);
        return 0;

    }

    // Load all the reads matching the graph into memory
    vector<Alignment> alignments;

    if(show_progress) {
        cerr << "Loading reads..." << endl;
    }

    function<bool(const Alignment&)> alignment_contained = [&graph](const Alignment& alignment) {
        for(size_t i = 0; i < alignment.path().mapping_size(); i++) {
            if(!graph->has_node(alignment.path().mapping(i).position().node_id())) {
                return false;
            }
        }
        return alignment.path().mapping_size() > 0;
    };

    if (useindex) {
        // Extract all the alignments
        index.for_alignment_to_nodes(graph_ids, [&](const Alignment& alignment) {
                // Only take alignments that don't visit nodes not in the graph
                if (alignment_contained(alignment)) {
                    alignments.push_back(alignment);
                }
            });
    } else {
        // load in all reads (activated by passing GAM directly with -G).
        // This is used by, ex., toil-vg, which has already used the gam index
        // to extract relevant reads
        ifstream gam_reads(gam_file.c_str());
        if (!gam_reads) {
            cerr << "[vg genotype] Error opening gam: " << gam_file << endl;
            return 1;
        }
        stream::for_each<Alignment>(gam_reads, [&alignments, &alignment_contained](Alignment& alignment) {
                if (alignment_contained(alignment)) {
                    alignments.push_back(alignment);
                }
            });
    }

    if(show_progress) {
        cerr << "Loaded " << alignments.size() << " alignments" << endl;
    }

    // Make a Genotyper to do the genotyping
    Genotyper genotyper;
    // Configure it
    genotyper.use_mapq = use_mapq;
    genotyper.realign_indels = realign_indels;
    assert(het_prior_denominator > 0);
    genotyper.het_prior_logprob = prob_to_logprob(1.0/het_prior_denominator);
    genotyper.min_consistent_per_strand = min_consistent_per_strand;
    // TODO: move arguments below up into configuration
    genotyper.run(*graph,
                  alignments,
                  cout,
                  ref_path_name,
                  contig_name,
                  sample_name,
                  augmented_file_name,
                  subset_graph,
                  show_progress,
                  output_vcf,
                  output_json,
                  length_override,
                  variant_offset);

    delete graph;

    return 0;
}

static Subcommand vg_genotype("genotype", "Genotype (or type) graphs, GAMS, and VCFs.", main_genotype);
<|endoftext|>