<commit_before>#include "roomsreader.h"

RRNode::RRNode(TiXmlElement *root)
{
    this->root = root;
    parent = 0;
    gotoRoot();
}

RRNode::~RRNode()
{

}

RRNode *RRNode::gotoElement(string name)
{
    cursor = findElement(root, name);
    if (!isNull())
        parent = cursor->Parent()->ToElement();
    else
        parent = 0;
    return this;
}

RRNode *RRNode::gotoRoot()
{
    cursor = root;
    parent = 0;
    return this;
}

RRNode *RRNode::gotoChild(string name)
{
    if(!isNull())
    {
        parent = cursor;
        cursor = cursor->FirstChildElement(name.c_str());
    }
    return this;
}

RRNode *RRNode::gotoParent()
{
    cursor = parent;
    if(!isNull())
    {
        parent = cursor->Parent()->ToElement();
    }
    return this;
}

RRNode *RRNode::gotoNext()
{
    if(!isNull())
        cursor = cursor->NextSiblingElement(cursor->Value());
    return this;
}

RRNode *RRNode::appendElement(string name)
{
    if(!isNull())
    {
        TiXmlElement *new_elem = new TiXmlElement(name.c_str());
        cursor->LinkEndChild(new_elem);
        parent = cursor;
        cursor = new_elem;
    }
    return this;
}

bool RRNode::isNull()
{
    bool result = cursor;
    return !result;
}

int RRNode::attrInt(string name)
{
    int tmp = 0;
    cursor->QueryIntAttribute(name.c_str(), &tmp);
    return tmp;
}

float RRNode::attrFloat(string name)
{
    float tmp = 0.0;
    cursor->QueryFloatAttribute(name.c_str(), &tmp);
    return tmp;
}

string RRNode::attrStr(string name)
{
    return cursor->Attribute(name.c_str());
}

void RRNode::setAttr(string name, string value)
{
    cursor->SetAttribute(name.c_str(), value.c_str());
}

Event *RRNode::fetchEvent()
{
    if (isNull()) return 0;
    Event *event = new Event(attrStr("id"));
    for (gotoChild("item_req"); !isNull(); gotoNext())
        event->addItemReq(attrStr("id"), attrStr("value"));
    gotoParent();
    for (gotoChild("var_req"); !isNull(); gotoNext())
        event->addVarReq(attrStr("id"), attrInt("value"));
    gotoParent();
    for (gotoChild("action"); !isNull(); gotoNext())
    {
        Action *act = event->addAction(attrStr("id"));
        for (gotoChild("param"); !isNull(); gotoNext())
            act->pushParam(attrStr("value"));
        gotoParent();
    }
    gotoParent();
    return event;
}

Room *RRNode::fetchRoom()
{
    if (isNull()) return 0;
    Room *room = new Room(attrStr("id"));
    room->bg(attrStr("bg"));
    for (gotoChild("area"); !isNull(); gotoNext())
    {
        Area *area = room->addArea(attrStr("id"));
        area->size(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height"));
        area->setEvent(attrStr("event"));
    }
    gotoParent();
    return room;
}

Item *RRNode::fetchItem()
{
    if (isNull()) return 0;
    Item *item = new Item(attrStr("id"));
    item->size(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height"));
    item->setEvent(attrStr("event"));
    item->setImage(attrStr("image"));
    item->move(attrStr("room"));
    return item;
}

Dialog *RRNode::fetchDialog()
{
    if (isNull()) return 0;
    Dialog *d = new Dialog(attrStr("id"), attrStr("start"));
    for (gotoChild("step"); !isNull(); gotoNext())
    {
        DialogStep *step = d->addStep(attrStr("id"), attrStr("text"));
        step->event = fetchEvent();
        for (gotoChild("link"); !isNull(); gotoNext())
            d->addLink(step->id, attrStr("id"), attrStr("text"));
         gotoParent();
    }
    gotoParent();
    return d;
}

TiXmlElement *RRNode::findElement(TiXmlElement *elem, string name)
{
    if (elem == 0)
        return 0;
    if (string(elem->Value()) == name)
        return elem;
    TiXmlElement *result = findElement(elem->NextSiblingElement(), name);
    if (result != 0)
        return result;
    result = findElement(elem->FirstChildElement(), name);
    if (result != 0)
        return result;
    return 0;
}

string floatToStr(const float f)
{
    std::ostringstream os;
    os << f;
    return os.str();
}

string upgradeFrom1To2(string content)
{
    TiXmlDocument doc;
    doc.Parse(content.c_str());
    RRNode node(doc.RootElement());
    node.gotoElement("world");
    int w = node.attrInt("width");
    int h = node.attrInt("height");
    node.setAttr("version", "2");
    for (node.gotoElement("items")->gotoChild("item"); !node.isNull(); node.gotoNext())
    {
        node.setAttr("x", floatToStr(node.attrFloat("x") / w));
        node.setAttr("y", floatToStr(node.attrFloat("y") / h));
        node.setAttr("width", floatToStr(node.attrFloat("width") / w));
        node.setAttr("height", floatToStr(node.attrFloat("height") / h));
    }

    for (node.gotoElement("rooms")->gotoChild("room"); !node.isNull(); node.gotoNext())
    {
        for (node.gotoChild("area"); !node.isNull(); node.gotoNext())
        {
            node.setAttr("x", floatToStr(node.attrFloat("x") / w));
            node.setAttr("y", floatToStr(node.attrFloat("y") / h));
            node.setAttr("width", floatToStr(node.attrFloat("width") / w));
            node.setAttr("height", floatToStr(node.attrFloat("height") / h));
        }
        node.gotoParent();
    }
    TiXmlPrinter printer;
    doc.Accept(&printer);
    return printer.CStr();
}

const int RoomsReader::VERSION = 2;

RoomsReader::RoomsReader()
{
    crawler = 0;
    doc = new TiXmlDocument;
    parse_map["world"] = &RoomsReader::parseWorld;
    parse_map["room"] = &RoomsReader::parseRoom;
    parse_map["area"] = &RoomsReader::parseArea;
    parse_map["action"] = &RoomsReader::parseAction;
    parse_map["event"] = &RoomsReader::parseEvent;
    parse_map["dialog"] = &RoomsReader::parseDialog;
    parse_map["step"] = &RoomsReader::parseDialogStep;
    parse_map["var"] = &RoomsReader::parseVar;
    parse_map["item"] = &RoomsReader::parseItem;
    parse_map["param"] = &RoomsReader::parseParam;
    parse_map["item_req"] = &RoomsReader::parseItemReq;
    parse_map["var_req"] = &RoomsReader::parseVarReq;
    parse_map["img"] = &RoomsReader::parseImages;
}

RoomsReader::~RoomsReader()
{
    if(crawler)
        delete crawler;
    if (doc)
        delete doc;
}

RoomsReader::UpgradeFunc RoomsReader::upgrade_funcs[] = {upgradeFrom1To2};

bool RoomsReader::loadFromFile(const string filename)
{
    std::ifstream xml(filename.c_str(), std::ios::binary);
    if (!xml.good()) return false;
    xml.seekg (0, std::ios::end);
    long length = xml.tellg();
    if (length == 0) return false;
    char *buffer = new char [length];
    xml.seekg (0, std::ios::beg);
    xml.read(buffer, length);
    bool res = loadFromStr(buffer);
    xml.close();
    delete [] buffer;
    return res;
}

bool RoomsReader::loadFromStr(const string content)
{
    doc->Parse(content.c_str());
    if (!parse())
    {
        delete doc;
        doc = 0;
        if (file_version < VERSION)
        {
            logger.write("Old version detected: " + floatToStr(file_version) + ". Upgrading...", Log::WARNING);
            string new_content = upgrade(content);
            return loadFromStr(new_content);
        }
        return false;
    }
    crawler = new RRNode(doc->RootElement());
    return true;
}

void RoomsReader::loadEmptyDoc()
{
    TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "", "");
    TiXmlElement *element = new TiXmlElement("world");
    doc->LinkEndChild(decl);
    doc->LinkEndChild(element);
    crawler = new RRNode(doc->RootElement());
}

void RoomsReader::saveDoc(string filename)
{
    if (!doc->SaveFile(filename.c_str()))
        logger.write("Cannot save to " + filename, Log::ERROR);
}

string RoomsReader::upgrade(string content)
{
    for (int i = file_version; i < VERSION; ++i)
    {
        content = upgrade_funcs[i - 1](content);
    }
    return content;
}

bool RoomsReader::parse()
{
    return parseElement(doc->RootElement());
}

RRNode *RoomsReader::getCrawler()
{
    return crawler;
}

bool RoomsReader::checkUniqueId(std::set<string> &ids, const string id)
{
    if (ids.count(id) != 0)
        return false;
    ids.insert(id);
    return true;
}

bool RoomsReader::checkParent(TiXmlElement *elem, string name)
{
    return (elem->Parent() != 0 &&
            string(elem->Parent()->Value()) == name);
}

bool RoomsReader::parseElement(TiXmlElement *elem)
{
    if (elem == 0)
        return true;
    bool value = true;
    if (parse_map.find(elem->Value()) != parse_map.end())
    {
        ParseMethod method = parse_map.find(elem->Value())->second;
        value = (this->*method)(elem);
    }
    return (value && parseElement(elem->FirstChildElement()) && parseElement(elem->NextSiblingElement()));
}

bool RoomsReader::parseArea(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "x", ATTR_FLOAT) &&
          parseAttr(elem, "y", ATTR_FLOAT) &&
          parseAttr(elem, "width", ATTR_FLOAT) &&
          parseAttr(elem, "height", ATTR_FLOAT)))
        return false;
    if (!(checkUniqueId(unique_ids_areas, elem->Attribute("id")) &&
        checkParent(elem, "room")))
        return false;
    return true;
}

bool RoomsReader::parseItem(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "room", ATTR_STR) &&
          parseAttr(elem, "image", ATTR_STR) &&
          parseAttr(elem, "x", ATTR_FLOAT) &&
          parseAttr(elem, "y", ATTR_FLOAT) &&
          parseAttr(elem, "width", ATTR_FLOAT) &&
          parseAttr(elem, "height", ATTR_FLOAT)))
        return false;
    if (!(checkUniqueId(unique_ids_items, elem->Attribute("id")) &&
        checkParent(elem, "items") &&
        !checkUniqueId(unique_ids_images, elem->Attribute("image"))))
        return false;
    return true;
}

bool RoomsReader::parseRoom(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "bg", ATTR_STR)))
        return false;
    if (!(checkUniqueId(unique_ids_rooms, elem->Attribute("id")) &&
          checkParent(elem, "rooms")))
        return false;
    return true;
}

bool RoomsReader::parseAction(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
         (checkParent(elem, "event") || checkParent(elem, "step"))))
        return false;
    return true;
}

bool RoomsReader::parseWorld(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "version", ATTR_INT) &&
          parseAttr(elem, "name", ATTR_STR) &&
          parseAttr(elem, "start", ATTR_STR) &&
          parseAttr(elem, "width", ATTR_INT) &&
          parseAttr(elem, "height", ATTR_INT)))
        return false;
    elem->QueryIntAttribute("version", &file_version);
    if (file_version != VERSION)
        return false;
    return true;
}

bool RoomsReader::parseEvent(TiXmlElement *elem)
{
    if (!parseAttr(elem, "id", ATTR_STR))
        return false;
    if (!(checkUniqueId(unique_ids_events, elem->Attribute("id")) &&
        checkParent(elem, "events")))
        return false;
    return true;
}

bool RoomsReader::parseVar(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "value", ATTR_STR) &&
          checkParent(elem, "vars")))
        return false;
    return true;
}

bool RoomsReader::parseImages(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "file", ATTR_STR) &&
        checkParent(elem, "images")))
        return false;
    if (!checkUniqueId(unique_ids_images, elem->Attribute("file")))
        return false;
    return true;
}

bool RoomsReader::parseItemReq(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "value", ATTR_STR)))
        return false;
    if (!(!checkUniqueId(unique_ids_items, elem->Attribute("id")) &&
        (checkParent(elem, "event") || checkParent(elem, "step"))))
        return false;
    return true;
}

bool RoomsReader::parseVarReq(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "value", ATTR_INT)))
        return false;
    if (!(checkParent(elem, "event") || checkParent(elem, "step")))
        return false;
    return true;
}

bool RoomsReader::parseParam(TiXmlElement *elem)
{
    if (!parseAttr(elem, "value", ATTR_STR))
        return false;
    return true;
}

bool RoomsReader::parseDialog(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "start", ATTR_STR)))
        return false;
    if (!(checkUniqueId(unique_ids_dialogs, elem->Attribute("id")) &&
        checkParent(elem, "dialogs")))
        return false;
    return true;
}

bool RoomsReader::parseDialogStep(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "text", ATTR_STR) &&
          checkParent(elem, "dialog")))
        return false;
    return true;
}

bool RoomsReader::parseAttr(TiXmlElement *elem, string name, AttributeType type)
{
    switch (type)
    {
        case ATTR_FLOAT:
        {
            float tmp;
            return (elem->QueryFloatAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);
            break;
        }
        case ATTR_INT:
        {
            int tmp;
            return (elem->QueryIntAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);
            break;
        }
        case ATTR_STR:
        {
            return (elem->Attribute(name.c_str()));
            break;
        }
        default:
        {
            return false;
            break;
        }
    }
}
<commit_msg>Added some logs<commit_after>#include "roomsreader.h"

RRNode::RRNode(TiXmlElement *root)
{
    this->root = root;
    parent = 0;
    gotoRoot();
}

RRNode::~RRNode()
{

}

RRNode *RRNode::gotoElement(string name)
{
    cursor = findElement(root, name);
    if (!isNull())
        parent = cursor->Parent()->ToElement();
    else
        parent = 0;
    return this;
}

RRNode *RRNode::gotoRoot()
{
    cursor = root;
    parent = 0;
    return this;
}

RRNode *RRNode::gotoChild(string name)
{
    if(!isNull())
    {
        parent = cursor;
        cursor = cursor->FirstChildElement(name.c_str());
    }
    return this;
}

RRNode *RRNode::gotoParent()
{
    cursor = parent;
    if(!isNull())
    {
        parent = cursor->Parent()->ToElement();
    }
    return this;
}

RRNode *RRNode::gotoNext()
{
    if(!isNull())
        cursor = cursor->NextSiblingElement(cursor->Value());
    return this;
}

RRNode *RRNode::appendElement(string name)
{
    if(!isNull())
    {
        TiXmlElement *new_elem = new TiXmlElement(name.c_str());
        cursor->LinkEndChild(new_elem);
        parent = cursor;
        cursor = new_elem;
    }
    return this;
}

bool RRNode::isNull()
{
    bool result = cursor;
    return !result;
}

int RRNode::attrInt(string name)
{
    int tmp = 0;
    cursor->QueryIntAttribute(name.c_str(), &tmp);
    return tmp;
}

float RRNode::attrFloat(string name)
{
    float tmp = 0.0;
    cursor->QueryFloatAttribute(name.c_str(), &tmp);
    return tmp;
}

string RRNode::attrStr(string name)
{
    return cursor->Attribute(name.c_str());
}

void RRNode::setAttr(string name, string value)
{
    cursor->SetAttribute(name.c_str(), value.c_str());
}

Event *RRNode::fetchEvent()
{
    if (isNull()) return 0;
    Event *event = new Event(attrStr("id"));
    for (gotoChild("item_req"); !isNull(); gotoNext())
        event->addItemReq(attrStr("id"), attrStr("value"));
    gotoParent();
    for (gotoChild("var_req"); !isNull(); gotoNext())
        event->addVarReq(attrStr("id"), attrInt("value"));
    gotoParent();
    for (gotoChild("action"); !isNull(); gotoNext())
    {
        Action *act = event->addAction(attrStr("id"));
        for (gotoChild("param"); !isNull(); gotoNext())
            act->pushParam(attrStr("value"));
        gotoParent();
    }
    gotoParent();
    return event;
}

Room *RRNode::fetchRoom()
{
    if (isNull()) return 0;
    Room *room = new Room(attrStr("id"));
    room->bg(attrStr("bg"));
    for (gotoChild("area"); !isNull(); gotoNext())
    {
        Area *area = room->addArea(attrStr("id"));
        area->size(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height"));
        area->setEvent(attrStr("event"));
    }
    gotoParent();
    return room;
}

Item *RRNode::fetchItem()
{
    if (isNull()) return 0;
    Item *item = new Item(attrStr("id"));
    item->size(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height"));
    item->setEvent(attrStr("event"));
    item->setImage(attrStr("image"));
    item->move(attrStr("room"));
    return item;
}

Dialog *RRNode::fetchDialog()
{
    if (isNull()) return 0;
    Dialog *d = new Dialog(attrStr("id"), attrStr("start"));
    for (gotoChild("step"); !isNull(); gotoNext())
    {
        DialogStep *step = d->addStep(attrStr("id"), attrStr("text"));
        step->event = fetchEvent();
        for (gotoChild("link"); !isNull(); gotoNext())
            d->addLink(step->id, attrStr("id"), attrStr("text"));
         gotoParent();
    }
    gotoParent();
    return d;
}

TiXmlElement *RRNode::findElement(TiXmlElement *elem, string name)
{
    if (elem == 0)
        return 0;
    if (string(elem->Value()) == name)
        return elem;
    TiXmlElement *result = findElement(elem->NextSiblingElement(), name);
    if (result != 0)
        return result;
    result = findElement(elem->FirstChildElement(), name);
    if (result != 0)
        return result;
    return 0;
}

string floatToStr(const float f)
{
    std::ostringstream os;
    os << f;
    return os.str();
}

string upgradeFrom1To2(string content)
{
    TiXmlDocument doc;
    doc.Parse(content.c_str());
    RRNode node(doc.RootElement());
    node.gotoElement("world");
    int w = node.attrInt("width");
    int h = node.attrInt("height");
    node.setAttr("version", "2");
    for (node.gotoElement("items")->gotoChild("item"); !node.isNull(); node.gotoNext())
    {
        node.setAttr("x", floatToStr(node.attrFloat("x") / w));
        node.setAttr("y", floatToStr(node.attrFloat("y") / h));
        node.setAttr("width", floatToStr(node.attrFloat("width") / w));
        node.setAttr("height", floatToStr(node.attrFloat("height") / h));
    }

    for (node.gotoElement("rooms")->gotoChild("room"); !node.isNull(); node.gotoNext())
    {
        for (node.gotoChild("area"); !node.isNull(); node.gotoNext())
        {
            node.setAttr("x", floatToStr(node.attrFloat("x") / w));
            node.setAttr("y", floatToStr(node.attrFloat("y") / h));
            node.setAttr("width", floatToStr(node.attrFloat("width") / w));
            node.setAttr("height", floatToStr(node.attrFloat("height") / h));
        }
        node.gotoParent();
    }
    TiXmlPrinter printer;
    doc.Accept(&printer);
    return printer.CStr();
}

const int RoomsReader::VERSION = 2;

RoomsReader::RoomsReader()
{
    crawler = 0;
    doc = new TiXmlDocument;
    parse_map["world"] = &RoomsReader::parseWorld;
    parse_map["room"] = &RoomsReader::parseRoom;
    parse_map["area"] = &RoomsReader::parseArea;
    parse_map["action"] = &RoomsReader::parseAction;
    parse_map["event"] = &RoomsReader::parseEvent;
    parse_map["dialog"] = &RoomsReader::parseDialog;
    parse_map["step"] = &RoomsReader::parseDialogStep;
    parse_map["var"] = &RoomsReader::parseVar;
    parse_map["item"] = &RoomsReader::parseItem;
    parse_map["param"] = &RoomsReader::parseParam;
    parse_map["item_req"] = &RoomsReader::parseItemReq;
    parse_map["var_req"] = &RoomsReader::parseVarReq;
    parse_map["img"] = &RoomsReader::parseImages;
}

RoomsReader::~RoomsReader()
{
    if(crawler)
        delete crawler;
    if (doc)
        delete doc;
}

RoomsReader::UpgradeFunc RoomsReader::upgrade_funcs[] = {upgradeFrom1To2};

bool RoomsReader::loadFromFile(const string filename)
{
    std::ifstream xml(filename.c_str(), std::ios::binary);
    if (!xml.good()) return false;
    xml.seekg (0, std::ios::end);
    long length = xml.tellg();
    if (length == 0) return false;
    char *buffer = new char [length];
    xml.seekg (0, std::ios::beg);
    xml.read(buffer, length);
    bool res = loadFromStr(buffer);
    xml.close();
    delete [] buffer;
    return res;
}

bool RoomsReader::loadFromStr(const string content)
{
    doc->Parse(content.c_str());
    if (!parse())
    {
        delete doc;
        doc = 0;
        if (file_version < VERSION)
        {
            logger.write("Old version detected: " + floatToStr(file_version) + ". Upgrading...", Log::WARNING);
            string new_content = upgrade(content);
            return loadFromStr(new_content);
        }
        return false;
    }
    crawler = new RRNode(doc->RootElement());
    return true;
}

void RoomsReader::loadEmptyDoc()
{
    TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "", "");
    TiXmlElement *element = new TiXmlElement("world");
    doc->LinkEndChild(decl);
    doc->LinkEndChild(element);
    crawler = new RRNode(doc->RootElement());
}

void RoomsReader::saveDoc(string filename)
{
    if (!doc->SaveFile(filename.c_str()))
        logger.write("Cannot save to " + filename, Log::ERROR);
}

string RoomsReader::upgrade(string content)
{
    for (int i = file_version; i < VERSION; ++i)
    {
        logger.write("Updating from v." + floatToStr(i) + " to v." + floatToStr(i + 1), Log::NOTE);
        content = upgrade_funcs[i - 1](content);
    }
    logger.write("Upgrade successful!", Log::WARNING);
    return content;
}

bool RoomsReader::parse()
{
    return parseElement(doc->RootElement());
}

RRNode *RoomsReader::getCrawler()
{
    return crawler;
}

bool RoomsReader::checkUniqueId(std::set<string> &ids, const string id)
{
    if (ids.count(id) != 0)
        return false;
    ids.insert(id);
    return true;
}

bool RoomsReader::checkParent(TiXmlElement *elem, string name)
{
    return (elem->Parent() != 0 &&
            string(elem->Parent()->Value()) == name);
}

bool RoomsReader::parseElement(TiXmlElement *elem)
{
    if (elem == 0)
        return true;
    bool value = true;
    if (parse_map.find(elem->Value()) != parse_map.end())
    {
        ParseMethod method = parse_map.find(elem->Value())->second;
        value = (this->*method)(elem);
    }
    return (value && parseElement(elem->FirstChildElement()) && parseElement(elem->NextSiblingElement()));
}

bool RoomsReader::parseArea(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "x", ATTR_FLOAT) &&
          parseAttr(elem, "y", ATTR_FLOAT) &&
          parseAttr(elem, "width", ATTR_FLOAT) &&
          parseAttr(elem, "height", ATTR_FLOAT)))
        return false;
    if (!(checkUniqueId(unique_ids_areas, elem->Attribute("id")) &&
        checkParent(elem, "room")))
        return false;
    return true;
}

bool RoomsReader::parseItem(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "room", ATTR_STR) &&
          parseAttr(elem, "image", ATTR_STR) &&
          parseAttr(elem, "x", ATTR_FLOAT) &&
          parseAttr(elem, "y", ATTR_FLOAT) &&
          parseAttr(elem, "width", ATTR_FLOAT) &&
          parseAttr(elem, "height", ATTR_FLOAT)))
        return false;
    if (!(checkUniqueId(unique_ids_items, elem->Attribute("id")) &&
        checkParent(elem, "items") &&
        !checkUniqueId(unique_ids_images, elem->Attribute("image"))))
        return false;
    return true;
}

bool RoomsReader::parseRoom(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "bg", ATTR_STR)))
        return false;
    if (!(checkUniqueId(unique_ids_rooms, elem->Attribute("id")) &&
          checkParent(elem, "rooms")))
        return false;
    return true;
}

bool RoomsReader::parseAction(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
         (checkParent(elem, "event") || checkParent(elem, "step"))))
        return false;
    return true;
}

bool RoomsReader::parseWorld(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "version", ATTR_INT) &&
          parseAttr(elem, "name", ATTR_STR) &&
          parseAttr(elem, "start", ATTR_STR) &&
          parseAttr(elem, "width", ATTR_INT) &&
          parseAttr(elem, "height", ATTR_INT)))
        return false;
    elem->QueryIntAttribute("version", &file_version);
    if (file_version != VERSION)
        return false;
    return true;
}

bool RoomsReader::parseEvent(TiXmlElement *elem)
{
    if (!parseAttr(elem, "id", ATTR_STR))
        return false;
    if (!(checkUniqueId(unique_ids_events, elem->Attribute("id")) &&
        checkParent(elem, "events")))
        return false;
    return true;
}

bool RoomsReader::parseVar(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "value", ATTR_STR) &&
          checkParent(elem, "vars")))
        return false;
    return true;
}

bool RoomsReader::parseImages(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "file", ATTR_STR) &&
        checkParent(elem, "images")))
        return false;
    if (!checkUniqueId(unique_ids_images, elem->Attribute("file")))
        return false;
    return true;
}

bool RoomsReader::parseItemReq(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "value", ATTR_STR)))
        return false;
    if (!(!checkUniqueId(unique_ids_items, elem->Attribute("id")) &&
        (checkParent(elem, "event") || checkParent(elem, "step"))))
        return false;
    return true;
}

bool RoomsReader::parseVarReq(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "value", ATTR_INT)))
        return false;
    if (!(checkParent(elem, "event") || checkParent(elem, "step")))
        return false;
    return true;
}

bool RoomsReader::parseParam(TiXmlElement *elem)
{
    if (!parseAttr(elem, "value", ATTR_STR))
        return false;
    return true;
}

bool RoomsReader::parseDialog(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "start", ATTR_STR)))
        return false;
    if (!(checkUniqueId(unique_ids_dialogs, elem->Attribute("id")) &&
        checkParent(elem, "dialogs")))
        return false;
    return true;
}

bool RoomsReader::parseDialogStep(TiXmlElement *elem)
{
    if (!(parseAttr(elem, "id", ATTR_STR) &&
          parseAttr(elem, "text", ATTR_STR) &&
          checkParent(elem, "dialog")))
        return false;
    return true;
}

bool RoomsReader::parseAttr(TiXmlElement *elem, string name, AttributeType type)
{
    switch (type)
    {
        case ATTR_FLOAT:
        {
            float tmp;
            return (elem->QueryFloatAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);
            break;
        }
        case ATTR_INT:
        {
            int tmp;
            return (elem->QueryIntAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);
            break;
        }
        case ATTR_STR:
        {
            return (elem->Attribute(name.c_str()));
            break;
        }
        default:
        {
            return false;
            break;
        }
    }
}
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          renderer.cpp
* Purpose:       Implementation of wxExRenderer class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2007-2008, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/extension/renderer.h>

#if wxUSE_GUI
#if wxUSE_GRID

wxExRenderer::wxExRenderer(
  long flags,
  const wxPen& pen,
  const wxPen& pen_outer,
  const wxBrush& brush)
  : m_Brush(brush)
  , m_Pen(pen)
  , m_PenOuter(pen_outer)
  , m_Flags(flags)
{
}

void wxExRenderer::Draw(
  wxGrid& grid,
  wxGridCellAttr& attr,
  wxDC& dc,
  const wxRect& rect,
  int row,
  int col,
  bool isSelected)
{
  wxGridCellStringRenderer::Draw(grid, attr, dc, rect, row, col, isSelected);

  bool left = false;
  bool right = false;
  bool up = false;
  bool down = false;

  // These are drawn using m_PenOuter.
  if (m_PenOuter.GetWidth() > 0)
  {
    dc.SetPen(m_PenOuter);

    if (m_Flags & CELL_RECT_OUTER_UP)
    {
      up = true;
      dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());
    }

    if (m_Flags & CELL_RECT_OUTER_DOWN)
    {
      down = true;
      dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());
    }

    if (m_Flags & CELL_RECT_OUTER_LEFT)
    {
      left = true;
      dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());
    }

    if (m_Flags & CELL_RECT_OUTER_RIGHT)
    {
      right = true;
      dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());
    }

    if (m_Flags & CELL_RECT)
    {
      dc.SetBrush(m_Brush);
      dc.DrawRectangle(rect);
    }
  }

  // Rest is drawn using normal pen.
  if (m_Pen.GetWidth() == 0) return;

  dc.SetPen(m_Pen);

  if (up || down || left || right)
  {
    if (!up)    dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());
    if (!down)  dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());
    if (!left)  dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());
    if (!right) dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());
  }

  if (m_Flags & CELL_UP)
  {
    dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());
  }

  if (m_Flags & CELL_DOWN)
  {
    dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());
  }

  if (m_Flags & CELL_LEFT)
  {
    dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());
  }

  if (m_Flags & CELL_RIGHT)
  {
    dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());
  }

  if (m_Flags & CELL_CROSS)
  {
    dc.DrawLine(rect.GetTopLeft(), rect.GetBottomRight());
    dc.DrawLine(rect.GetBottomLeft(), rect.GetTopRight());
  }
}

#endif // wxUSE_GRID
#endif // wxUSE_GUI
<commit_msg>changed to unix eol<commit_after>/******************************************************************************\
* File:          renderer.cpp
* Purpose:       Implementation of wxExRenderer class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2007-2008, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/extension/renderer.h>

#if wxUSE_GUI
#if wxUSE_GRID

wxExRenderer::wxExRenderer(
  long flags,
  const wxPen& pen,
  const wxPen& pen_outer,
  const wxBrush& brush)
  : m_Brush(brush)
  , m_Pen(pen)
  , m_PenOuter(pen_outer)
  , m_Flags(flags)
{
}

void wxExRenderer::Draw(
  wxGrid& grid,
  wxGridCellAttr& attr,
  wxDC& dc,
  const wxRect& rect,
  int row,
  int col,
  bool isSelected)
{
  wxGridCellStringRenderer::Draw(grid, attr, dc, rect, row, col, isSelected);

  bool left = false;
  bool right = false;
  bool up = false;
  bool down = false;

  // These are drawn using m_PenOuter.
  if (m_PenOuter.GetWidth() > 0)
  {
    dc.SetPen(m_PenOuter);

    if (m_Flags & CELL_RECT_OUTER_UP)
    {
      up = true;
      dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());
    }

    if (m_Flags & CELL_RECT_OUTER_DOWN)
    {
      down = true;
      dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());
    }

    if (m_Flags & CELL_RECT_OUTER_LEFT)
    {
      left = true;
      dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());
    }

    if (m_Flags & CELL_RECT_OUTER_RIGHT)
    {
      right = true;
      dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());
    }

    if (m_Flags & CELL_RECT)
    {
      dc.SetBrush(m_Brush);
      dc.DrawRectangle(rect);
    }
  }

  // Rest is drawn using normal pen.
  if (m_Pen.GetWidth() == 0) return;

  dc.SetPen(m_Pen);

  if (up || down || left || right)
  {
    if (!up)    dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());
    if (!down)  dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());
    if (!left)  dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());
    if (!right) dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());
  }

  if (m_Flags & CELL_UP)
  {
    dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight());
  }

  if (m_Flags & CELL_DOWN)
  {
    dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight());
  }

  if (m_Flags & CELL_LEFT)
  {
    dc.DrawLine(rect.GetTopLeft(), rect.GetBottomLeft());
  }

  if (m_Flags & CELL_RIGHT)
  {
    dc.DrawLine(rect.GetTopRight(), rect.GetBottomRight());
  }

  if (m_Flags & CELL_CROSS)
  {
    dc.DrawLine(rect.GetTopLeft(), rect.GetBottomRight());
    dc.DrawLine(rect.GetBottomLeft(), rect.GetTopRight());
  }
}

#endif // wxUSE_GRID
#endif // wxUSE_GUI
<|endoftext|>


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

#include <modules/cimg/cimglayerreader.h>
#include <modules/cimg/cimgutils.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/datastructures/image/layerdisk.h>

namespace inviwo {

CImgLayerReader::CImgLayerReader()
    : DataReaderType<Layer>() {
    addExtension(FileExtension("raw", "RAW"));
#ifdef cimg_use_png
    addExtension(FileExtension("png", "Portable Network Graphics"));
#endif
#ifdef cimg_use_jpeg
    addExtension(FileExtension("jpg", "Joint Photographic Experts Group"));
    addExtension(FileExtension("jpeg", "Joint Photographic Experts Group"));
#endif
    addExtension(FileExtension("bmp", "Windows bitmap"));
#ifdef cimg_use_openexr
    addExtension(FileExtension("exr", "OpenEXR"));
#endif
    addExtension(FileExtension("hdr", "Analyze 7.5"));
}

CImgLayerReader::CImgLayerReader(const CImgLayerReader& rhs)
    : DataReaderType<Layer>(rhs) {};

CImgLayerReader& CImgLayerReader::operator=(const CImgLayerReader& that) {
    if (this != &that) {
        DataReaderType<Layer>::operator=(that);
    }

    return *this;
}

CImgLayerReader* CImgLayerReader::clone() const { return new CImgLayerReader(*this); }

Layer* CImgLayerReader::readMetaData(std::string filePath) {
    if (!filesystem::fileExists(filePath)) {
        std::string newPath = filesystem::addBasePath(filePath);

        if (filesystem::fileExists(newPath)) {
            filePath = newPath;
        } else {
            throw DataReaderException("Error could not find input file: " + filePath, IvwContext);
        }
    }

    Layer* layer = new Layer();

    LayerDisk* layerDisk = new LayerDisk(filePath);
    layerDisk->setDataReader(this->clone());

    layer->addRepresentation(layerDisk);

    return layer;
}

void CImgLayerReader::readDataInto(void* destination) const {
    LayerDisk* layerDisk = dynamic_cast<LayerDisk*>(owner_);
    if(layerDisk){
        uvec2 dimensions = layerDisk->getDimensions();
        DataFormatEnums::Id formatId = DataFormatEnums::NOT_SPECIALIZED;

        std::string filePath = layerDisk->getSourceFile();

        if (!filesystem::fileExists(filePath)) {
            std::string newPath = filesystem::addBasePath(filePath);

            if (filesystem::fileExists(newPath)) {
                filePath = newPath;
            }
            else {
                throw DataReaderException("Error could not find input file: " + filePath, IvwContext);
            }
        }

        if (dimensions != uvec2(0)){
            // Load and rescale to input dimensions
            CImgUtils::loadLayerData(destination, filePath, dimensions, formatId, true);
        }
        else{
            // Load to original dimensions
            CImgUtils::loadLayerData(destination, filePath, dimensions, formatId, false);
            layerDisk->setDimensions(dimensions);
        }

        layerDisk->updateDataFormat(DataFormatBase::get(formatId));
    }
}

void* CImgLayerReader::readData() const {
    void* data = nullptr;

    LayerDisk* layerDisk = dynamic_cast<LayerDisk*>(owner_);
    if(layerDisk){
        uvec2 dimensions = layerDisk->getDimensions();
        DataFormatEnums::Id formatId = DataFormatEnums::NOT_SPECIALIZED;

        std::string filePath = layerDisk->getSourceFile();

        if (!filesystem::fileExists(filePath)) {
            std::string newPath = filesystem::addBasePath(filePath);

            if (filesystem::fileExists(newPath)) {
                filePath = newPath;
            }
            else {
                throw DataReaderException("Error could not find input file: " + filePath, IvwContext);
            }
        }

        if (dimensions != uvec2(0)){
            // Load and rescale to input dimensions
            data = CImgUtils::loadLayerData(nullptr, filePath, dimensions, formatId, true);
        }
        else{
            // Load to original dimensions
            data = CImgUtils::loadLayerData(nullptr, filePath, dimensions, formatId, false);
            layerDisk->setDimensions(dimensions);
        }

        layerDisk->updateDataFormat(DataFormatBase::get(formatId));
    }

    return data;
}

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

#include <modules/cimg/cimglayerreader.h>
#include <modules/cimg/cimgutils.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/datastructures/image/layerdisk.h>

namespace inviwo {

CImgLayerReader::CImgLayerReader()
    : DataReaderType<Layer>() {
    addExtension(FileExtension("raw", "RAW"));
#ifdef cimg_use_png
    addExtension(FileExtension("png", "Portable Network Graphics"));
#endif
#ifdef cimg_use_jpeg
    addExtension(FileExtension("jpg", "Joint Photographic Experts Group"));
    addExtension(FileExtension("jpeg", "Joint Photographic Experts Group"));
#endif
    addExtension(FileExtension("bmp", "Windows bitmap"));
#ifdef cimg_use_openexr
    addExtension(FileExtension("exr", "OpenEXR"));
#endif
}

CImgLayerReader::CImgLayerReader(const CImgLayerReader& rhs)
    : DataReaderType<Layer>(rhs) {};

CImgLayerReader& CImgLayerReader::operator=(const CImgLayerReader& that) {
    if (this != &that) {
        DataReaderType<Layer>::operator=(that);
    }

    return *this;
}

CImgLayerReader* CImgLayerReader::clone() const { return new CImgLayerReader(*this); }

Layer* CImgLayerReader::readMetaData(std::string filePath) {
    if (!filesystem::fileExists(filePath)) {
        std::string newPath = filesystem::addBasePath(filePath);

        if (filesystem::fileExists(newPath)) {
            filePath = newPath;
        } else {
            throw DataReaderException("Error could not find input file: " + filePath, IvwContext);
        }
    }

    Layer* layer = new Layer();

    LayerDisk* layerDisk = new LayerDisk(filePath);
    layerDisk->setDataReader(this->clone());

    layer->addRepresentation(layerDisk);

    return layer;
}

void CImgLayerReader::readDataInto(void* destination) const {
    LayerDisk* layerDisk = dynamic_cast<LayerDisk*>(owner_);
    if(layerDisk){
        uvec2 dimensions = layerDisk->getDimensions();
        DataFormatEnums::Id formatId = DataFormatEnums::NOT_SPECIALIZED;

        std::string filePath = layerDisk->getSourceFile();

        if (!filesystem::fileExists(filePath)) {
            std::string newPath = filesystem::addBasePath(filePath);

            if (filesystem::fileExists(newPath)) {
                filePath = newPath;
            }
            else {
                throw DataReaderException("Error could not find input file: " + filePath, IvwContext);
            }
        }

        if (dimensions != uvec2(0)){
            // Load and rescale to input dimensions
            CImgUtils::loadLayerData(destination, filePath, dimensions, formatId, true);
        }
        else{
            // Load to original dimensions
            CImgUtils::loadLayerData(destination, filePath, dimensions, formatId, false);
            layerDisk->setDimensions(dimensions);
        }

        layerDisk->updateDataFormat(DataFormatBase::get(formatId));
    }
}

void* CImgLayerReader::readData() const {
    void* data = nullptr;

    LayerDisk* layerDisk = dynamic_cast<LayerDisk*>(owner_);
    if(layerDisk){
        uvec2 dimensions = layerDisk->getDimensions();
        DataFormatEnums::Id formatId = DataFormatEnums::NOT_SPECIALIZED;

        std::string filePath = layerDisk->getSourceFile();

        if (!filesystem::fileExists(filePath)) {
            std::string newPath = filesystem::addBasePath(filePath);

            if (filesystem::fileExists(newPath)) {
                filePath = newPath;
            }
            else {
                throw DataReaderException("Error could not find input file: " + filePath, IvwContext);
            }
        }

        if (dimensions != uvec2(0)){
            // Load and rescale to input dimensions
            data = CImgUtils::loadLayerData(nullptr, filePath, dimensions, formatId, true);
        }
        else{
            // Load to original dimensions
            data = CImgUtils::loadLayerData(nullptr, filePath, dimensions, formatId, false);
            layerDisk->setDimensions(dimensions);
        }

        layerDisk->updateDataFormat(DataFormatBase::get(formatId));
    }

    return data;
}

}  // namespace
<|endoftext|>


<commit_before>#ifndef WIGWAG_DETAIL_CREATION_STORAGE_ADAPTER_HPP
#define WIGWAG_DETAIL_CREATION_STORAGE_ADAPTER_HPP

#include <utility>

namespace wigwag {
namespace detail
{

	template < typename Storage_ >
	class creation_storage_adapter
	{
	private:
		Storage_		_s;

	public:
		creation_storage_adapter()
			: _s()
		{ }

		template < typename T_, typename... Args_ >
		void create(Args_&&... args)
		{ _s.template create<T_>(std::forward<Args_>(args)...); }

		explicit operator bool() const
		{ return _s.constructed(); }

		auto get_ptr() const -> decltype(_s.get_ptr())
		{ return _s.get_ptr(); }

		auto operator -> () const -> decltype(&*get_ptr())
		{ return &*get_ptr(); }
	};

}}

#endif
<commit_msg>Added license plate<commit_after>#ifndef WIGWAG_DETAIL_CREATION_STORAGE_ADAPTER_HPP
#define WIGWAG_DETAIL_CREATION_STORAGE_ADAPTER_HPP

// Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <utility>

namespace wigwag {
namespace detail
{

	template < typename Storage_ >
	class creation_storage_adapter
	{
	private:
		Storage_		_s;

	public:
		creation_storage_adapter()
			: _s()
		{ }

		template < typename T_, typename... Args_ >
		void create(Args_&&... args)
		{ _s.template create<T_>(std::forward<Args_>(args)...); }

		explicit operator bool() const
		{ return _s.constructed(); }

		auto get_ptr() const -> decltype(_s.get_ptr())
		{ return _s.get_ptr(); }

		auto operator -> () const -> decltype(&*get_ptr())
		{ return &*get_ptr(); }
	};

}}

#endif
<|endoftext|>


<commit_before>/*--------------------------------------------------------------------------*\
 |                                                                          |
 |  Copyright (C) 1998                                                      |
 |                                                                          |
 |         , __                 , __                                        |
 |        /|/  \               /|/  \                                       |
 |         | __/ _   ,_         | __/ _   ,_                                |
 |         |   \|/  /  |  |   | |   \|/  /  |  |   |                        |
 |         |(__/|__/   |_/ \_/|/|(__/|__/   |_/ \_/|/                       |
 |                           /|                   /|                        |
 |                           \|                   \|                        |
 |                                                                          |
 |      Enrico Bertolazzi                                                   |
 |      Dipartimento di Ingegneria Industriale                              |
 |      Universita` degli Studi di Trento                                   |
 |      email: enrico.bertolazzi@unitn.it                                   |
 |                                                                          |
\*--------------------------------------------------------------------------*/

#include "Splines.hh"
#include <cmath>
#include <iomanip>

/**
 *
 */

#ifndef isnan
#define isnan(A) ((A) != (A))
#endif

#ifndef isfinite
#define isfinite(A) ((A*0.0) == 0.0)
#endif

#ifndef isregular
#define isregular(A) ( !isnan(A) && isfinite(A) )
#endif

namespace Splines {

  /*       _               _    _   _       _   _
  //   ___| |__   ___  ___| | _| \ | | __ _| \ | |
  //  / __| '_ \ / _ \/ __| |/ /  \| |/ _` |  \| |
  // | (__| | | |  __/ (__|   <| |\  | (_| | |\  |
  //  \___|_| |_|\___|\___|_|\_\_| \_|\__,_|_| \_|
  */
  //! check if the vector `pv` os size `DIM` contains only regular floats. If not an error is issued
  void
  checkNaN( valueType const pv[],
            char      const v_name[],
            sizeType  const DIM ) {
    for ( indexType i = 0 ; i < DIM ; ++i ) {
      if ( isnan(pv[i]) ) {
        std::ostringstream ost ;
        ost << "\nfound NaN at " << v_name << "[" << i << "]" ;
        throw std::runtime_error(ost.str()) ;
      }
      if ( !isfinite(pv[i]) ) {
        std::ostringstream ost ;
        ost << "\nfound Infinity at " << v_name << "[" << i << "]" ;
        throw std::runtime_error(ost.str()) ;
      }
    }
  }

  void
  Spline::pushBack( valueType x, valueType y ) {
    if ( npts > 0 ) {
      //// DA RISCRIVERE @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
      if ( std::abs(x-X.back()) < 1e-9 ) return ; // workaround per punti doppi
      SPLINE_ASSERT( x > X.back(),
                     "Spline::pushBack, non monotone insert at insert N. " << npts <<
                     "\nX[ " << npts-1 << "] = " << X.back() <<
                     "\nX[ " << npts   << "] = " << x ) ;
    }
    X . push_back( x ) ;
    Y . push_back( y ) ;
    ++npts ;
  }

  ///////////////////////////////////////////////////////////////////////////

  void
  Spline::dropBack() {
    if ( npts > 0 ) {
      --npts ;
      X . pop_back() ;
      Y . pop_back() ;
    }
  }

  ///////////////////////////////////////////////////////////////////////////
  void
  Spline::setOrigin( valueType x0 ) {
    valueType Tx = x0 - X.front() ;
    for ( VectorOfValues::iterator ix = X.begin() ; ix != X.end() ; ++ix ) *ix += Tx ;
  }

  void
  Spline::setRange( valueType xmin, valueType xmax ) {
    SPLINE_ASSERT( xmax > xmin, "Spline::setRange( " << xmin << " , " << xmax << " ) bad range ") ;
    valueType S  = (xmax - xmin) / ( X.back() - X.front() ) ;
    valueType Tx = xmin - S * X.front() ;
    for ( VectorOfValues::iterator ix = X.begin() ; ix != X.end() ; ++ix ) *ix = *ix * S + Tx ;
  }

  //! change X-range of the spline
  void
  CubicSplineBase::setRange( valueType xmin, valueType xmax ) {
    Spline::setRange( xmin, xmax ) ;
    valueType recS = ( X.back() - X.front() ) / (xmax - xmin) ;
    for ( VectorOfValues::iterator iy = Y.begin() ; iy != Y.end() ; ++iy ) *iy *= recS ;
  }

  void
  ConstantsSpline::writeToStream( ostream & s ) const {
    sizeType nseg = sizeType(Y.size()) ;
    for ( sizeType i = 0 ; i < nseg ; ++i )
      s << "segment N." << setw(4) << i
        << " X:[ " << X[i] << ", " << X[i+1] << " ] Y:" << Y[i]
        << '\n' ;
  }

  void
  LinearSpline::writeToStream( ostream & s ) const {
    sizeType nseg = sizeType(Y.size()-1) ;
    for ( sizeType i = 0 ; i < nseg ; ++i )
      s << "segment N." << setw(4) << i
        << " X:[ " << X[i] << ", " << X[i+1] << " ] Y:[ " << Y[i] << ", " << Y[i+1]
        << " ] slope: " << (Y[i+1]-Y[i])/(X[i+1]-X[i])
        << '\n' ;
  }

}
<commit_msg>Removed a warning<commit_after>/*--------------------------------------------------------------------------*\
 |                                                                          |
 |  Copyright (C) 1998                                                      |
 |                                                                          |
 |         , __                 , __                                        |
 |        /|/  \               /|/  \                                       |
 |         | __/ _   ,_         | __/ _   ,_                                |
 |         |   \|/  /  |  |   | |   \|/  /  |  |   |                        |
 |         |(__/|__/   |_/ \_/|/|(__/|__/   |_/ \_/|/                       |
 |                           /|                   /|                        |
 |                           \|                   \|                        |
 |                                                                          |
 |      Enrico Bertolazzi                                                   |
 |      Dipartimento di Ingegneria Industriale                              |
 |      Universita` degli Studi di Trento                                   |
 |      email: enrico.bertolazzi@unitn.it                                   |
 |                                                                          |
\*--------------------------------------------------------------------------*/

#include "Splines.hh"
#include <cmath>
#include <iomanip>

/**
 *
 */

#ifndef isnan
#define isnan(A) ((A) != (A))
#endif

#ifndef isfinite
#define isfinite(A) ((A*0.0) == 0.0)
#endif

#ifndef isregular
#define isregular(A) ( !isnan(A) && isfinite(A) )
#endif

namespace Splines {

  /*       _               _    _   _       _   _
  //   ___| |__   ___  ___| | _| \ | | __ _| \ | |
  //  / __| '_ \ / _ \/ __| |/ /  \| |/ _` |  \| |
  // | (__| | | |  __/ (__|   <| |\  | (_| | |\  |
  //  \___|_| |_|\___|\___|_|\_\_| \_|\__,_|_| \_|
  */
  //! check if the vector `pv` os size `DIM` contains only regular floats. If not an error is issued
  void
  checkNaN( valueType const pv[],
            char      const v_name[],
            sizeType  const DIM ) {
    for ( sizeType i = 0 ; i < DIM ; ++i ) {
      if ( isnan(pv[i]) ) {
        std::ostringstream ost ;
        ost << "\nfound NaN at " << v_name << "[" << i << "]" ;
        throw std::runtime_error(ost.str()) ;
      }
      if ( !isfinite(pv[i]) ) {
        std::ostringstream ost ;
        ost << "\nfound Infinity at " << v_name << "[" << i << "]" ;
        throw std::runtime_error(ost.str()) ;
      }
    }
  }

  void
  Spline::pushBack( valueType x, valueType y ) {
    if ( npts > 0 ) {
      //// DA RISCRIVERE @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
      if ( std::abs(x-X.back()) < 1e-9 ) return ; // workaround per punti doppi
      SPLINE_ASSERT( x > X.back(),
                     "Spline::pushBack, non monotone insert at insert N. " << npts <<
                     "\nX[ " << npts-1 << "] = " << X.back() <<
                     "\nX[ " << npts   << "] = " << x ) ;
    }
    X . push_back( x ) ;
    Y . push_back( y ) ;
    ++npts ;
  }

  ///////////////////////////////////////////////////////////////////////////

  void
  Spline::dropBack() {
    if ( npts > 0 ) {
      --npts ;
      X . pop_back() ;
      Y . pop_back() ;
    }
  }

  ///////////////////////////////////////////////////////////////////////////
  void
  Spline::setOrigin( valueType x0 ) {
    valueType Tx = x0 - X.front() ;
    for ( VectorOfValues::iterator ix = X.begin() ; ix != X.end() ; ++ix ) *ix += Tx ;
  }

  void
  Spline::setRange( valueType xmin, valueType xmax ) {
    SPLINE_ASSERT( xmax > xmin, "Spline::setRange( " << xmin << " , " << xmax << " ) bad range ") ;
    valueType S  = (xmax - xmin) / ( X.back() - X.front() ) ;
    valueType Tx = xmin - S * X.front() ;
    for ( VectorOfValues::iterator ix = X.begin() ; ix != X.end() ; ++ix ) *ix = *ix * S + Tx ;
  }

  //! change X-range of the spline
  void
  CubicSplineBase::setRange( valueType xmin, valueType xmax ) {
    Spline::setRange( xmin, xmax ) ;
    valueType recS = ( X.back() - X.front() ) / (xmax - xmin) ;
    for ( VectorOfValues::iterator iy = Y.begin() ; iy != Y.end() ; ++iy ) *iy *= recS ;
  }

  void
  ConstantsSpline::writeToStream( ostream & s ) const {
    sizeType nseg = sizeType(Y.size()) ;
    for ( sizeType i = 0 ; i < nseg ; ++i )
      s << "segment N." << setw(4) << i
        << " X:[ " << X[i] << ", " << X[i+1] << " ] Y:" << Y[i]
        << '\n' ;
  }

  void
  LinearSpline::writeToStream( ostream & s ) const {
    sizeType nseg = sizeType(Y.size()-1) ;
    for ( sizeType i = 0 ; i < nseg ; ++i )
      s << "segment N." << setw(4) << i
        << " X:[ " << X[i] << ", " << X[i+1] << " ] Y:[ " << Y[i] << ", " << Y[i+1]
        << " ] slope: " << (Y[i+1]-Y[i])/(X[i+1]-X[i])
        << '\n' ;
  }

}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QSplashScreen>
#include <QDebug>
#include <QFontDatabase>

#include "app.h"

void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)
{
    Q_UNUSED(context)

    QString level;

    switch (type) {
    case QtDebugMsg:
        level = "DEBUG"; break;
    case QtInfoMsg:
        level = "INFO"; break;
    case QtWarningMsg:
        level = "WARNING"; break;
    case QtCriticalMsg:
        level = "CRITICAL"; break;
    case QtFatalMsg:
        level = "FATAL"; break;
    default:
        level = "UNDEFIEND"; break;
    }

    if (type != QtWarningMsg) {

        QString text = QString("[%1] [%2] %3")
                                .arg(QDateTime::currentDateTime().toString("dd-MM-yyyy hh:mm:ss"))
                                .arg(level)
                                .arg(message);

        static QString logPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);

        QFile file(logPath + "/stacer.log");

        QIODevice::OpenMode openMode = file.size() > (1L << 20) ? QIODevice::Truncate : QIODevice::Append;

        if (file.open(QIODevice::WriteOnly | openMode)) {
            QTextStream stream(&file);
            stream << text << endl;

            file.close();
        }
    }
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    qApp->setApplicationName("stacer");
    qApp->setApplicationDisplayName("Stacer");
    qApp->setApplicationVersion("1.0.9");
    qApp->setWindowIcon(QIcon(":/static/logo.png"));

    QFontDatabase::addApplicationFont(":/static/font/Ubuntu-R.ttf");

    QPixmap pixSplash(":/static/splashscreen.png");

    QSplashScreen *splash = new QSplashScreen(pixSplash);

    splash->show();

    app.processEvents();

//    QThread::sleep(4);

//    qInstallMessageHandler(messageHandler);

    App w;

    QLatin1String hideOption("--hide");

    if (argc < 2 || QString(argv[1]) != hideOption) {
        w.show();
    }

    splash->finish(&w);

    delete splash;

    return app.exec();
}
<commit_msg>added message handler<commit_after>#include <QApplication>
#include <QSplashScreen>
#include <QDebug>
#include <QFontDatabase>

#include "app.h"

void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)
{
    Q_UNUSED(context)

    QString level;

    switch (type) {
    case QtDebugMsg:
        level = "DEBUG"; break;
    case QtInfoMsg:
        level = "INFO"; break;
    case QtWarningMsg:
        level = "WARNING"; break;
    case QtCriticalMsg:
        level = "CRITICAL"; break;
    case QtFatalMsg:
        level = "FATAL"; break;
    default:
        level = "UNDEFIEND"; break;
    }

    if (type != QtWarningMsg) {

        QString text = QString("[%1] [%2] %3")
                                .arg(QDateTime::currentDateTime().toString("dd-MM-yyyy hh:mm:ss"))
                                .arg(level)
                                .arg(message);

        static QString logPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);

        QFile file(logPath + "/stacer.log");

        QIODevice::OpenMode openMode = file.size() > (1L << 20) ? QIODevice::Truncate : QIODevice::Append;

        if (file.open(QIODevice::WriteOnly | openMode)) {
            QTextStream stream(&file);
            stream << text << endl;

            file.close();
        }
    }
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    qApp->setApplicationName("stacer");
    qApp->setApplicationDisplayName("Stacer");
    qApp->setApplicationVersion("1.0.9");
    qApp->setWindowIcon(QIcon(":/static/logo.png"));

    QFontDatabase::addApplicationFont(":/static/font/Ubuntu-R.ttf");

    QPixmap pixSplash(":/static/splashscreen.png");

    QSplashScreen *splash = new QSplashScreen(pixSplash);

    splash->show();

    app.processEvents();

    qInstallMessageHandler(messageHandler);

    App w;

    QLatin1String hideOption("--hide");

    if (argc < 2 || QString(argv[1]) != hideOption) {
        w.show();
    }

    splash->finish(&w);

    delete splash;

    return app.exec();
}
<|endoftext|>


<commit_before>#include <QApplication>
#include "pdfview.h"

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  if (argc != 2) {
    fprintf(stderr, "Usage: runcible-view-pdf <file>\n");
    return 1;
  }

  PdfView widget;
  widget.setDocument(argv[1]);
  widget.resize(600, 800);

  QObject::connect(&widget, SIGNAL(back()), &app, SLOT(quit()));

  widget.show();
  return app.exec();
}
<commit_msg>Fixed include mistake in view-pdf<commit_after>#include <QApplication>
#include <stdio.h>
#include "pdfview.h"

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  if (argc != 2) {
    fprintf(stderr, "Usage: runcible-view-pdf <file>\n");
    return 1;
  }

  PdfView widget;
  widget.setDocument(argv[1]);
  widget.resize(600, 800);

  QObject::connect(&widget, SIGNAL(back()), &app, SLOT(quit()));

  widget.show();
  return app.exec();
}
<|endoftext|>


<commit_before>#include <cassert>
#include <cstring>  // memcpy
#include <utility>  // swap
#include <iostream> // cout, endl

template <typename T, int INIT_CAP, int CAP_MULT>
Vector<T, INIT_CAP, CAP_MULT>::Vector() : items(0), cap(0), data(nullptr) { }

template <typename T, int INIT_CAP, int CAP_MULT>
Vector<T, INIT_CAP, CAP_MULT>::Vector(int size, T val) : Vector() {
  alloc(size);
  for (decltype(size) i = 0; i < size; i++) {
    // Don't check capacity because we just allocated all. Will speed up a lot.
    _append(val, false);
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
Vector<T, INIT_CAP, CAP_MULT>::Vector(int size, T *values) : Vector() {
  alloc(size);
  for (decltype(size) i = 0; i < size; i++) {
    _append(values[i], false);
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
template <typename Iterator>
Vector<T, INIT_CAP, CAP_MULT>::Vector(Iterator first, Iterator last) : Vector() {
  for (; first != last; first++) {
    append(*first);
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
Vector<T, INIT_CAP, CAP_MULT>::~Vector() {
  clear();
}

template <typename T, int INIT_CAP, int CAP_MULT>
bool Vector<T, INIT_CAP, CAP_MULT>::isEmpty() const {
  return items == 0;
}

template <typename T, int INIT_CAP, int CAP_MULT>
int Vector<T, INIT_CAP, CAP_MULT>::size() const {
  return items;
}

template <typename T, int INIT_CAP, int CAP_MULT>
int Vector<T, INIT_CAP, CAP_MULT>::capacity() const {
  return cap;
}

/// Insert value at the end.
template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::append(const T &val) {
  _append(val);
}

/// Insert value at the beginning.
template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::prepend(const T &val) {
  insert(0, val);
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::insert(int pos, const T &val) {
  assert(pos >= 0 && pos < cap && "Position out of bounds!");
  checkAlloc();
  shiftLeft(pos); // Effectively moving right.
  data[pos] = val;
  items++;
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::print() const {
  using namespace std;
  cout << "[ ";
  if (isEmpty()) {
    cout << "empty";
  }
  for (decltype(cap) i = 0; i < cap; i++) {
    cout << convert(data[i]);
    if (i < cap - 1) {
      cout << ", ";
    }
  }
  cout << " ]" << endl;
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::clear() {
  if (data) {
    delete[] data;
    data = nullptr;
  }
  items = cap = 0;
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::shrinkToFit() {
  if (items == cap) return;
  alloc(items);
}

template <typename T, int INIT_CAP, int CAP_MULT>
T Vector<T, INIT_CAP, CAP_MULT>::operator[](int pos) {
  assert(pos >= 0 && pos < cap && "Position out of bounds!");
  return data[pos];
}

template <typename T, int INIT_CAP, int CAP_MULT>
const T &Vector<T, INIT_CAP, CAP_MULT>::operator[](int pos) const {
  assert(pos >= 0 && pos < cap && "Position out of bounds!");
  return data[pos];
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::remove(const T &val) {
  removeFrom(val);
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::removeAt(int pos) {
  assert(pos >= 0 && pos < cap && "Position out of bounds!");
  data[pos] = T();
  items--;
  shiftRight(pos); // Effectively moving left.
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::fillDefault(T *ptr, int n) {
  for (decltype(n) i = 0; i < n; i++) {
    ptr[i] = T();
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::alloc(int size) {
  auto newCap = size;
  auto *newData = new T[newCap];
  if (newCap > cap) {
    fillDefault(newData, newCap);
  }
  if (items > 0) {
    memcpy(newData, data, items * sizeof(T));
    delete[] data;
  }
  data = newData;
  cap = newCap;
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::checkAlloc() {
  if (items != cap) return;
  alloc(cap == 0 ? INIT_CAP : cap * CAP_MULT);
}

/// Appends value but only checks capacity if check is set.
/** This saves processing time when appending very many items. */
template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::_append(const T &val, bool check) {
  if (check) {
    checkAlloc();
  }
  data[items++] = val;
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::shiftRight(int pos) {
  for (decltype(pos) i = pos; i < items; i++) {
    std::swap(data[i], data[i+1]);
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::shiftLeft(int pos) {
  for (decltype(pos) i = items; i >= pos; i--) {
    std::swap(data[i], data[i+1]);
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::removeFrom(const T &val, int pos) {
  for (decltype(pos) i = pos; i < items; i++) {
    auto &item = data[i];
    if (item == val) {
      item = T(); // Clear.
      items--;
      shiftRight(i); // Effectively moving left.
      removeFrom(val, i);
      break;
    }
  }
}
<commit_msg>Vector: Moved assert() after checkAlloc().<commit_after>#include <cassert>
#include <cstring>  // memcpy
#include <utility>  // swap
#include <iostream> // cout, endl

template <typename T, int INIT_CAP, int CAP_MULT>
Vector<T, INIT_CAP, CAP_MULT>::Vector() : items(0), cap(0), data(nullptr) { }

template <typename T, int INIT_CAP, int CAP_MULT>
Vector<T, INIT_CAP, CAP_MULT>::Vector(int size, T val) : Vector() {
  alloc(size);
  for (decltype(size) i = 0; i < size; i++) {
    // Don't check capacity because we just allocated all. Will speed up a lot.
    _append(val, false);
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
Vector<T, INIT_CAP, CAP_MULT>::Vector(int size, T *values) : Vector() {
  alloc(size);
  for (decltype(size) i = 0; i < size; i++) {
    _append(values[i], false);
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
template <typename Iterator>
Vector<T, INIT_CAP, CAP_MULT>::Vector(Iterator first, Iterator last) : Vector() {
  for (; first != last; first++) {
    append(*first);
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
Vector<T, INIT_CAP, CAP_MULT>::~Vector() {
  clear();
}

template <typename T, int INIT_CAP, int CAP_MULT>
bool Vector<T, INIT_CAP, CAP_MULT>::isEmpty() const {
  return items == 0;
}

template <typename T, int INIT_CAP, int CAP_MULT>
int Vector<T, INIT_CAP, CAP_MULT>::size() const {
  return items;
}

template <typename T, int INIT_CAP, int CAP_MULT>
int Vector<T, INIT_CAP, CAP_MULT>::capacity() const {
  return cap;
}

/// Insert value at the end.
template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::append(const T &val) {
  _append(val);
}

/// Insert value at the beginning.
template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::prepend(const T &val) {
  insert(0, val);
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::insert(int pos, const T &val) {
  checkAlloc();
  assert(pos >= 0 && pos < cap && "Position out of bounds!");
  shiftLeft(pos); // Effectively moving right.
  data[pos] = val;
  items++;
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::print() const {
  using namespace std;
  cout << "[ ";
  if (isEmpty()) {
    cout << "empty";
  }
  for (decltype(cap) i = 0; i < cap; i++) {
    cout << convert(data[i]);
    if (i < cap - 1) {
      cout << ", ";
    }
  }
  cout << " ]" << endl;
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::clear() {
  if (data) {
    delete[] data;
    data = nullptr;
  }
  items = cap = 0;
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::shrinkToFit() {
  if (items == cap) return;
  alloc(items);
}

template <typename T, int INIT_CAP, int CAP_MULT>
T Vector<T, INIT_CAP, CAP_MULT>::operator[](int pos) {
  assert(pos >= 0 && pos < cap && "Position out of bounds!");
  return data[pos];
}

template <typename T, int INIT_CAP, int CAP_MULT>
const T &Vector<T, INIT_CAP, CAP_MULT>::operator[](int pos) const {
  assert(pos >= 0 && pos < cap && "Position out of bounds!");
  return data[pos];
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::remove(const T &val) {
  removeFrom(val);
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::removeAt(int pos) {
  assert(pos >= 0 && pos < cap && "Position out of bounds!");
  data[pos] = T();
  items--;
  shiftRight(pos); // Effectively moving left.
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::fillDefault(T *ptr, int n) {
  for (decltype(n) i = 0; i < n; i++) {
    ptr[i] = T();
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::alloc(int size) {
  auto newCap = size;
  auto *newData = new T[newCap];
  if (newCap > cap) {
    fillDefault(newData, newCap);
  }
  if (items > 0) {
    memcpy(newData, data, items * sizeof(T));
    delete[] data;
  }
  data = newData;
  cap = newCap;
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::checkAlloc() {
  if (items != cap) return;
  alloc(cap == 0 ? INIT_CAP : cap * CAP_MULT);
}

/// Appends value but only checks capacity if check is set.
/** This saves processing time when appending very many items. */
template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::_append(const T &val, bool check) {
  if (check) {
    checkAlloc();
  }
  data[items++] = val;
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::shiftRight(int pos) {
  for (decltype(pos) i = pos; i < items; i++) {
    std::swap(data[i], data[i+1]);
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::shiftLeft(int pos) {
  for (decltype(pos) i = items; i >= pos; i--) {
    std::swap(data[i], data[i+1]);
  }
}

template <typename T, int INIT_CAP, int CAP_MULT>
void Vector<T, INIT_CAP, CAP_MULT>::removeFrom(const T &val, int pos) {
  for (decltype(pos) i = pos; i < items; i++) {
    auto &item = data[i];
    if (item == val) {
      item = T(); // Clear.
      items--;
      shiftRight(i); // Effectively moving left.
      removeFrom(val, i);
      break;
    }
  }
}
<|endoftext|>


<commit_before>#include "rosplan_planning_system/PlanParser.h"
#include <sstream>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>

namespace KCL_rosplan {

	void PlanParser::reset() {
		filter_objects.clear();
		filter_attributes.clear();
		knowledge_filter.clear();
		action_list.clear();
	}

	/*----------------------*/
	/* Post processing plan */
	/*----------------------*/

	/**
	 * parses the output of popf, generating a list of action messages.
	 */
	void PlanParser::preparePlan(std::string &dataPath, PlanningEnvironment &environment, size_t freeActionID) {

		// trim the end of any existing plan
		while(action_list.size() > freeActionID)
			action_list.pop_back();

		// popf output
		std::ifstream planfile;
		planfile.open((dataPath + "plan.pddl").c_str());

		int curr, next;
		std::string line;
		std::vector<rosplan_dispatch_msgs::ActionDispatch> potentialPlan;
		double planDuration;
		double expectedPlanDuration = 0;

		while(!planfile.eof()) {

			getline(planfile, line);

			if (line.substr(0,6).compare("; Plan") == 0) {
				expectedPlanDuration = atof(line.substr(25).c_str());
			} else if (line.substr(0,6).compare("; Time")!=0) {
				//consume useless lines
			} else {

				potentialPlan.clear();
				size_t planFreeActionID = freeActionID;
				planDuration = 0;

				while(!planfile.eof() && line.compare("")!=0) {

					getline(planfile, line);
					if (line.length()<2)
						break;

					rosplan_dispatch_msgs::ActionDispatch msg;

					// action ID
					msg.action_id = planFreeActionID;
					planFreeActionID++;

					// dispatchTime
					curr=line.find(":");
					double dispatchTime = (double)atof(line.substr(0,curr).c_str());
					msg.dispatch_time = dispatchTime;

					// name
					curr=line.find("(")+1;
					next=line.find(" ",curr);
					std::string name = line.substr(curr,next-curr).c_str();
					msg.name = name;

					// parameters
					std::vector<std::string> params;
					curr=next+1;
					next=line.find(")",curr);
					int at = curr;
					while(at < next) {
						int cc = line.find(" ",curr);
						int cc1 = line.find(")",curr);
						curr = cc<cc1?cc:cc1;
						std::string param = environment.name_map[line.substr(at,curr-at)];
						params.push_back(param);
						++curr;
						at = curr;
					}
					processPDDLParameters(msg, params, environment);

					// duration
					curr=line.find("[",curr)+1;
					next=line.find("]",curr);
					msg.duration = (double)atof(line.substr(curr,next-curr).c_str());

					potentialPlan.push_back(msg);

					// update plan duration
					curr=line.find(":");
					planDuration = msg.duration + atof(line.substr(0,curr).c_str());
				}

				if(planDuration - expectedPlanDuration < 0.01)  {

					// trim any previously read plan
					while(action_list.size() > freeActionID) {
						action_list.pop_back();
					}

					// save better optimised plan
					for(size_t i=0;i<potentialPlan.size();i++) {
						action_list.push_back(potentialPlan[i]);
						generateFilter(environment);
					}

					total_plan_duration = planDuration;

				} else {
					ROS_INFO("Duration: %f, expected %f; plan discarded", planDuration, expectedPlanDuration);
				}
			}
		}
		planfile.close();
	}

	/**
	 * processes the parameters of a single PDDL action into an ActionDispatch message
	 */
	void PlanParser::processPDDLParameters(rosplan_dispatch_msgs::ActionDispatch &msg, std::vector<std::string> &params, PlanningEnvironment &environment) {

		// find the correct PDDL operator definition
		std::map<std::string,std::vector<std::string> >::iterator ait;
		ait = environment.domain_operators.find(msg.name);
		if(ait != environment.domain_operators.end()) {

			// add the PDDL parameters to the action dispatch
			for(size_t i=0; i<ait->second.size(); i++) {
				diagnostic_msgs::KeyValue pair;
				pair.key = ait->second[i];
				pair.value = params[i];
				msg.parameters.push_back(pair);

				// prepare object existence for the knowledge filter
				bool add = true;
				for(size_t j=0; j<filter_objects.size(); j++)
					if(0==filter_objects[j].compare(params[i])) add = false;
				if(add) filter_objects.push_back(params[i]);
			}

			// prepare object attributes for the knowledge filter
			for(size_t i=0; i<environment.domain_operator_precondition_map[msg.name].size(); i++) {
				std::vector<std::string> filterAttribute;
				std::vector<std::string> precondition = environment.domain_operator_precondition_map[msg.name][i];
				filterAttribute.push_back(precondition[0]);
				for(size_t j=1; j<precondition.size(); j++) {
					// label
					if(j>1) filterAttribute.push_back(precondition[j]);
					// instance name
					for(size_t k=0;k<ait->second.size();k++) {
						if(0==ait->second[k].compare(precondition[j]))
							filterAttribute.push_back(params[k]);
					}
				}
				filter_attributes.push_back(filterAttribute);
			}

			// add non-PDDL knowledge items to action dispatch
			std::map<std::string,std::vector<std::string> >::iterator pit;
			for(size_t i=0; i<params.size(); i++) {
				pit = environment.domain_predicates.find(ait->second[i]);
				for(size_t j=0; j<environment.instance_attributes.size(); j++) {
					// TODO have knowledge items be passed more cleanly in dispatch
					if(0==environment.instance_attributes[j].instance_name.compare(params[i])
							&& environment.instance_attributes[j].knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE) {
						for(size_t k=0; k<environment.instance_attributes[j].values.size(); k++) {
							diagnostic_msgs::KeyValue pair;
							pair.key = environment.instance_attributes[j].instance_name
									+ "_" + environment.instance_attributes[j].attribute_name
									 + "_" + environment.instance_attributes[j].values[k].key;
							pair.value = environment.instance_attributes[j].values[k].value;
							msg.parameters.push_back(pair);
						}
					}
				}
			}
		} // end of operator
	}

	/*-----------------*/
	/* Planning filter */
	/*-----------------*/

	/**
	 * populates the knowledge filter messages
	 */
	void PlanParser::generateFilter(PlanningEnvironment &environment) {

		knowledge_filter.clear();

		// populate filter message with objects
		for(size_t i=0; i<filter_objects.size(); i++) {
			rosplan_knowledge_msgs::KnowledgeItem filterItem;
			filterItem.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::INSTANCE;
			filterItem.instance_type = environment.object_type_map[filter_objects[i]];
			filterItem.instance_name = filter_objects[i];
			knowledge_filter.push_back(filterItem);
		}

		// populate filter message with attributes
		// TODO only statics, not all preconditions.
		for(size_t i=0; i<filter_attributes.size(); i++) {
			rosplan_knowledge_msgs::KnowledgeItem filterItem;
			filterItem.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;
			filterItem.attribute_name = filter_attributes[i][0];
			filterItem.instance_type = environment.object_type_map[filter_attributes[i][1]];
			filterItem.instance_name = filter_attributes[i][1];
			for(size_t j=2; j<filter_attributes[i].size()-1; j+=2) {
				diagnostic_msgs::KeyValue pair;
				pair.key = filter_attributes[i][j];
				pair.value = filter_attributes[i][j+1];
				filterItem.values.push_back(pair);
			}
			knowledge_filter.push_back(filterItem);
		}
	}
} // close namespace
<commit_msg>Fixed bug in parser when action has no parameters<commit_after>#include "rosplan_planning_system/PlanParser.h"
#include <sstream>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>

namespace KCL_rosplan {

	void PlanParser::reset() {
		filter_objects.clear();
		filter_attributes.clear();
		knowledge_filter.clear();
		action_list.clear();
	}

	/*----------------------*/
	/* Post processing plan */
	/*----------------------*/

	/**
	 * parses the output of popf, generating a list of action messages.
	 */
	void PlanParser::preparePlan(std::string &dataPath, PlanningEnvironment &environment, size_t freeActionID) {

		// trim the end of any existing plan
		while(action_list.size() > freeActionID)
			action_list.pop_back();

		// popf output
		std::ifstream planfile;
		planfile.open((dataPath + "plan.pddl").c_str());

		int curr, next;
		std::string line;
		std::vector<rosplan_dispatch_msgs::ActionDispatch> potentialPlan;
		double planDuration;
		double expectedPlanDuration = 0;

		while(!planfile.eof()) {

			getline(planfile, line);

			if (line.substr(0,6).compare("; Plan") == 0) {
				expectedPlanDuration = atof(line.substr(25).c_str());
			} else if (line.substr(0,6).compare("; Time")!=0) {
				//consume useless lines
			} else {

				potentialPlan.clear();
				size_t planFreeActionID = freeActionID;
				planDuration = 0;

				while(!planfile.eof() && line.compare("")!=0) {

					getline(planfile, line);
					if (line.length()<2)
						break;

					rosplan_dispatch_msgs::ActionDispatch msg;

					// action ID
					msg.action_id = planFreeActionID;
					planFreeActionID++;

					// dispatchTime
					curr=line.find(":");
					double dispatchTime = (double)atof(line.substr(0,curr).c_str());
					msg.dispatch_time = dispatchTime;

					// check for parameters
					curr=line.find("(")+1;
					bool paramsExist = (line.find(" ",curr) > line.find(")",curr));

					if(paramsExist) {

						// name
						next=line.find(" ",curr);
						std::string name = line.substr(curr,next-curr).c_str();
						msg.name = name;

						// parameters
						std::vector<std::string> params;
						curr=next+1;
						next=line.find(")",curr);
						int at = curr;
						while(at < next) {
							int cc = line.find(" ",curr);
							int cc1 = line.find(")",curr);
							curr = cc<cc1?cc:cc1;
							std::string param = environment.name_map[line.substr(at,curr-at)];
							params.push_back(param);
							++curr;
							at = curr;
						}
						processPDDLParameters(msg, params, environment);

					} else {

						// name
						next=line.find(")",curr);
						std::string name = line.substr(curr,next-curr).c_str();
						msg.name = name;

					}

					// duration
					curr=line.find("[",curr)+1;
					next=line.find("]",curr);
					msg.duration = (double)atof(line.substr(curr,next-curr).c_str());

					potentialPlan.push_back(msg);

					// update plan duration
					curr=line.find(":");
					planDuration = msg.duration + atof(line.substr(0,curr).c_str());
				}

				if(planDuration - expectedPlanDuration < 0.01)  {

					// trim any previously read plan
					while(action_list.size() > freeActionID) {
						action_list.pop_back();
					}

					// save better optimised plan
					for(size_t i=0;i<potentialPlan.size();i++) {
						action_list.push_back(potentialPlan[i]);
						generateFilter(environment);
					}

					total_plan_duration = planDuration;

				} else {
					ROS_INFO("Duration: %f, expected %f; plan discarded", planDuration, expectedPlanDuration);
				}
			}
		}
		planfile.close();
	}

	/**
	 * processes the parameters of a single PDDL action into an ActionDispatch message
	 */
	void PlanParser::processPDDLParameters(rosplan_dispatch_msgs::ActionDispatch &msg, std::vector<std::string> &params, PlanningEnvironment &environment) {

		// find the correct PDDL operator definition
		std::map<std::string,std::vector<std::string> >::iterator ait;
		ait = environment.domain_operators.find(msg.name);
		if(ait != environment.domain_operators.end()) {

			// add the PDDL parameters to the action dispatch
			for(size_t i=0; i<ait->second.size(); i++) {
				diagnostic_msgs::KeyValue pair;
				pair.key = ait->second[i];
				pair.value = params[i];
				msg.parameters.push_back(pair);

				// prepare object existence for the knowledge filter
				bool add = true;
				for(size_t j=0; j<filter_objects.size(); j++)
					if(0==filter_objects[j].compare(params[i])) add = false;
				if(add) filter_objects.push_back(params[i]);
			}

			// prepare object attributes for the knowledge filter
			for(size_t i=0; i<environment.domain_operator_precondition_map[msg.name].size(); i++) {
				std::vector<std::string> filterAttribute;
				std::vector<std::string> precondition = environment.domain_operator_precondition_map[msg.name][i];
				filterAttribute.push_back(precondition[0]);
				for(size_t j=1; j<precondition.size(); j++) {
					// label
					if(j>1) filterAttribute.push_back(precondition[j]);
					// instance name
					for(size_t k=0;k<ait->second.size();k++) {
						if(0==ait->second[k].compare(precondition[j]))
							filterAttribute.push_back(params[k]);
					}
				}
				filter_attributes.push_back(filterAttribute);
			}

			// add non-PDDL knowledge items to action dispatch
			std::map<std::string,std::vector<std::string> >::iterator pit;
			for(size_t i=0; i<params.size(); i++) {
				pit = environment.domain_predicates.find(ait->second[i]);
				for(size_t j=0; j<environment.instance_attributes.size(); j++) {
					// TODO have knowledge items be passed more cleanly in dispatch
					if(0==environment.instance_attributes[j].instance_name.compare(params[i])
							&& environment.instance_attributes[j].knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE) {
						for(size_t k=0; k<environment.instance_attributes[j].values.size(); k++) {
							diagnostic_msgs::KeyValue pair;
							pair.key = environment.instance_attributes[j].instance_name
									+ "_" + environment.instance_attributes[j].attribute_name
									 + "_" + environment.instance_attributes[j].values[k].key;
							pair.value = environment.instance_attributes[j].values[k].value;
							msg.parameters.push_back(pair);
						}
					}
				}
			}
		} // end of operator
	}

	/*-----------------*/
	/* Planning filter */
	/*-----------------*/

	/**
	 * populates the knowledge filter messages
	 */
	void PlanParser::generateFilter(PlanningEnvironment &environment) {

		knowledge_filter.clear();

		// populate filter message with objects
		for(size_t i=0; i<filter_objects.size(); i++) {
			rosplan_knowledge_msgs::KnowledgeItem filterItem;
			filterItem.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::INSTANCE;
			filterItem.instance_type = environment.object_type_map[filter_objects[i]];
			filterItem.instance_name = filter_objects[i];
			knowledge_filter.push_back(filterItem);
		}

		// populate filter message with attributes
		// TODO only statics, not all preconditions.
		for(size_t i=0; i<filter_attributes.size(); i++) {
			rosplan_knowledge_msgs::KnowledgeItem filterItem;
			filterItem.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;
			filterItem.attribute_name = filter_attributes[i][0];
			filterItem.instance_type = environment.object_type_map[filter_attributes[i][1]];
			filterItem.instance_name = filter_attributes[i][1];
			for(size_t j=2; j<filter_attributes[i].size()-1; j+=2) {
				diagnostic_msgs::KeyValue pair;
				pair.key = filter_attributes[i][j];
				pair.value = filter_attributes[i][j+1];
				filterItem.values.push_back(pair);
			}
			knowledge_filter.push_back(filterItem);
		}
	}
} // close namespace
<|endoftext|>


<commit_before>#include <iostream>
#include "Board.h"

using namespace std;

Board::Board() {
	Pposition = new char[n];
	for (int i = 0; i<n; i++)
		Pposition[i] = ' ';
}
Board::~Board() {
	delete[] Pposition;
}
Board::Board(const Board &obj) {
	Pposition = new char[n];
	for (int i = 0; i<n; i++)
		Pposition[i] = obj.Pposition[i];

}
Board & Board::operator = (const Board & obj)
// assignment operator
{
	if (this != &obj)
	{
		delete Pposition;
		Pposition = new char[n];
		for (int i = 0; i < n; i++)
			Pposition[i] = obj.Pposition[i];
	}
	return *this;
}
void Board::PrintBoard() {//print the board
	cout << "+---+---+---+" << endl;
	cout << "|" << Pposition[0] << "  |" << Pposition[1] << "  |" << Pposition[2] << "  |" << endl;
	cout << "+---+---+---+" << endl;
	cout << "|" << Pposition[3] << "  |" << Pposition[4] << "  |" << Pposition[5] << "  |" << endl;
	cout << "+---+---+---+" << endl;
	cout << "|" << Pposition[6] << "  |" << Pposition[7] << "  |" << Pposition[8] << "  |" << endl;
	cout << "+---+---+---+" << endl;

}
char Board::getposition(int p)const {
	return Pposition[p];

}
bool Board::DetermineWinner() {//return true if we have winner function printwinner determine we have winner or not
	if (Pposition[0] == Pposition[1] && Pposition[0] == Pposition[2] && Pposition[0] != ' ')
		return true;
	else if (Pposition[3] == Pposition[4] && Pposition[3] == Pposition[5] && Pposition[3] != ' ')
		return true;
	else if (Pposition[6] == Pposition[7] && Pposition[6] == Pposition[8] && Pposition[6] != ' ')
		return true;
	else if (Pposition[0] == Pposition[4] && Pposition[0] == Pposition[8] && Pposition[0] != ' ')
		return true;
	else if (Pposition[2] == Pposition[4] && Pposition[2] == Pposition[6] && Pposition[2] != ' ')
		return true;
	else if (Pposition[0] == Pposition[3] && Pposition[0] == Pposition[6] && Pposition[0] != ' ')
		return true;
	else if (Pposition[1] == Pposition[4] && Pposition[1] == Pposition[7] && Pposition[1] != ' ')
		return true;
	else if (Pposition[2] == Pposition[5] && Pposition[2] == Pposition[8] && Pposition[2] != ' ')
		return true;

	return false;
}

int Board::printwinner(int count,  Board *s)//determine we have winner or not
{
	if (s->DetermineWinner() != true) {
		/*cout << "No winner." << endl;*/
		return 0;
	}
	else if (s->DetermineWinner() == true) {
		if (count % 2 == 0)
			return 1;/* cout << "winner is:" << objB->getsymbol() << endl;*/
		else if (count % 2 != 0)
			return 2; /*cout << "winner is:" << objA->getsymbol() << endl;*/
	}
}

void Board::SetPosition(int position,char player) const{//set symbol to the board

	if (Pposition[position] == ' ') {
		Pposition[position] = player;
	}
	else if (Pposition[position] != ' ') {
		cout << "error" << endl;
	}
}

<commit_msg>Delete Board.cpp<commit_after><|endoftext|>