<commit_before>#include "sdfloader.hpp"

Scene SDFloader::sdfLoad(std::string const& inputFile)
{
	Scene scene;

	std::fstream inputfile;
	inputfile.open(inputFile);

	if(inputfile.is_open())
	{
		std::string line;
		std::string word;

		std::map<std::string, std::shared_ptr<Shape>> tempshapesmap;
		std::map<std::string, std::shared_ptr<Composite>> tempcompmap;

  	std::vector<std::shared_ptr<Composite>> composites;

		while(std::getline(inputfile, line))
		{
			std::stringstream stream;

			stream << line;
			stream >> word;

			if(word == "define")
			{
				stream >> word;

				if(word == "material")
				{
					std::string matname;
					Color ka;
					Color kd;
					Color ks;
					float m;

					stream >> matname;

					stream >> ka.r;
					stream >> ka.g;
					stream >> ka.b;

					stream >> kd.r;
					stream >> kd.g;
					stream >> kd.b;

					stream >> ks.r;
					stream >> ks.g;
					stream >> ks.b;

					stream >> m;

					std::shared_ptr<Material> material = std::make_shared<Material>(matname, ka, kd, ks, m);
					scene.materials_.insert(std::pair<std::string, std::shared_ptr<Material>>(matname, material));
					std::cout << "\nmaterial added to scene " << matname;
				}

				else if(word == "shape")
				{
					stream >> word;

					if(word == "box")
					{
						std::string boxname;
						glm::vec3 min;
						glm::vec3 max;
						std::string matname;

						stream >> boxname;

						stream >> min.x;
						stream >> min.y;
						stream >> min.z;

						stream >> max.x;
						stream >> max.y;
						stream >> max.z;

						stream >> matname;

						std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
						std::shared_ptr<Shape> box = std::make_shared<Box>(min, max , material, boxname);
						tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(boxname, box));
						std::cout << "\nbox added to temshapepmap " << boxname;
					}

					else if (word == "sphere")
					{
						std::string spherename;
						glm::vec3 center;
						float r;
						std::string matname;

						stream >> spherename;

						stream >> center.x;
						stream >> center.y;
						stream >> center.z;

						stream >> r;

						stream >> matname;

						std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
						std::shared_ptr<Shape> sphere = std::make_shared<Sphere>(center, r, material, spherename);
						tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(spherename, sphere));
						std::cout << "\nsphere added to tempshapemap " << spherename;
					}

					else if (word == "cone")
					{
						std::string conename;
						glm::vec3 center;
						float angle;
						float height;
						std::string matname;

						stream >> conename;

						stream >> center.x;
						stream >> center.y;
						stream >> center.z;

						stream >> angle;
						stream >> height;

						stream >> matname;

						std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
						std::shared_ptr<Shape> cone = std::make_shared<Cone>(center, angle, height, material, conename);
						tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(conename, cone));
					}

					else if (word == "cylinder")
					{

					}

					else if (word == "triangle")
					{

					}

					else if (word == "composite")
					{
						std::string compname;
						std::string shapename;

						stream >> compname;

						std::vector<std::shared_ptr<Shape>> shapes;

						while(!stream.eof())
						{
							stream >> shapename;
							auto shape_ptr = tempshapesmap.find(shapename);

							if(shape_ptr != tempshapesmap.end())
							{
								shapes.push_back(shape_ptr->second);
								std::cout << "\nshape added from tempshapemap to tempvector " << shape_ptr->first;
							}

							auto comp_ptr = tempcompmap.find(shapename);

							if(comp_ptr != tempcompmap.end())
							{
								shapes.push_back(comp_ptr->second);
								std::cout << "\ncomp added from tempcompmap to tempvector " << comp_ptr->first;
							}
						}
						std::shared_ptr<Composite> comp = std::make_shared<Composite>(compname, shapes);
						tempcompmap.insert(std::pair<std::string, std::shared_ptr<Composite>>(compname, comp));
						std::cout << "\ncomp added to tempcompmap " << compname;
					}
				}

				else if (word == "light")
				{
					std::string lightname;
					Color color;
					glm::vec3 pos;

					stream >> lightname;

					if(lightname == "ambient")
					{
						stream >> color.r;
						stream >> color.g;
						stream >> color.b;

						scene.ambient_ = color;
						std::cout << "\nambientlight added to scene: " << lightname;
					}
					else
					{
						stream >> pos.x;
						stream >> pos.y;
						stream >> pos.z;

						stream >> color.r;
						stream >> color.g;
						stream >> color.b;

						std::shared_ptr<Light> light = std::make_shared<Light>(lightname, pos, color);
						scene.lights_.push_back(light);
						std::cout << "\nlight added to scene: " << lightname;
					}
				}

				else if (word == "camera")
				{
					std::string cameraname;
					float fov;
					glm::vec3 eye;
					glm::vec3 dir;
					glm::vec3 up;

					stream >> cameraname;

					stream >> fov;

					stream >> eye.x;
					stream >> eye.y;
					stream >> eye.z;

					stream >> dir.x;
					stream >> dir.y;
					stream >> dir.z;

					stream >> up.x;
					stream >> up.y;
					stream >> up.z;

					scene.camera_ = Camera{cameraname, fov, eye, dir, up};
					std::cout << "\ncamera added to scene: " << cameraname;
				}
			}
		}

		for(auto it = tempcompmap.cbegin(); it != tempcompmap.cend(); ++it)
		{
    	composites.push_back(it->second);
			std::cout << "\ncomp pushed from tempcompmap in compvector: " << it->first;
		}

		scene.shapes_ = composites;
		std::cout << "\ncompvector added to scene";
	}

	else
	{
		std::cout << "File not found." << std::endl;
	}

	return scene;
}<commit_msg>sdfloader cylinder added<commit_after>#include "sdfloader.hpp"

Scene SDFloader::sdfLoad(std::string const& inputFile)
{
	Scene scene;

	std::fstream inputfile;
	inputfile.open(inputFile);

	if(inputfile.is_open())
	{
		std::string line;
		std::string word;

		std::map<std::string, std::shared_ptr<Shape>> tempshapesmap;
		std::map<std::string, std::shared_ptr<Composite>> tempcompmap;

  	std::vector<std::shared_ptr<Composite>> composites;

		while(std::getline(inputfile, line))
		{
			std::stringstream stream;

			stream << line;
			stream >> word;

			if(word == "define")
			{
				stream >> word;

				if(word == "material")
				{
					std::string matname;
					Color ka;
					Color kd;
					Color ks;
					float m;

					stream >> matname;

					stream >> ka.r;
					stream >> ka.g;
					stream >> ka.b;

					stream >> kd.r;
					stream >> kd.g;
					stream >> kd.b;

					stream >> ks.r;
					stream >> ks.g;
					stream >> ks.b;

					stream >> m;

					std::shared_ptr<Material> material = std::make_shared<Material>(matname, ka, kd, ks, m);
					scene.materials_.insert(std::pair<std::string, std::shared_ptr<Material>>(matname, material));
					std::cout << "\nmaterial added to scene " << matname;
				}

				else if(word == "shape")
				{
					stream >> word;

					if(word == "box")
					{
						std::string boxname;
						glm::vec3 min;
						glm::vec3 max;
						std::string matname;

						stream >> boxname;

						stream >> min.x;
						stream >> min.y;
						stream >> min.z;

						stream >> max.x;
						stream >> max.y;
						stream >> max.z;

						stream >> matname;

						std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
						std::shared_ptr<Shape> box = std::make_shared<Box>(min, max , material, boxname);
						tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(boxname, box));
						std::cout << "\nbox added to temshapepmap " << boxname;
					}

					else if (word == "sphere")
					{
						std::string spherename;
						glm::vec3 center;
						float r;
						std::string matname;

						stream >> spherename;

						stream >> center.x;
						stream >> center.y;
						stream >> center.z;

						stream >> r;

						stream >> matname;

						std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
						std::shared_ptr<Shape> sphere = std::make_shared<Sphere>(center, r, material, spherename);
						tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(spherename, sphere));
						std::cout << "\nsphere added to tempshapemap " << spherename;
					}

					else if (word == "cone")
					{
						std::string conename;
						glm::vec3 center;
						float angle;
						float height;
						std::string matname;

						stream >> conename;

						stream >> center.x;
						stream >> center.y;
						stream >> center.z;

						stream >> angle;
						stream >> height;

						stream >> matname;

						std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
						std::shared_ptr<Shape> cone = std::make_shared<Cone>(center, angle, height, material, conename);
						tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(conename, cone));
					}

					else if (word == "cylinder")
					{
						std::string cylname;
						glm::vec3 center;
						float r;
						float height;
						std::string matname;

						stream >> cylname;

						stream >> center.x;
						stream >> center.y;
						stream >> center.z;

						stream >> r;
						stream >> height;

						stream >> matname;

						std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
						std::shared_ptr<Shape> cyl = std::make_shared<Cylinder>(center, r, height, material, cylname);
						tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(cylname, cyl));
					}

					else if (word == "triangle")
					{

					}

					else if (word == "composite")
					{
						std::string compname;
						std::string shapename;

						stream >> compname;

						std::vector<std::shared_ptr<Shape>> shapes;

						while(!stream.eof())
						{
							stream >> shapename;
							auto shape_ptr = tempshapesmap.find(shapename);

							if(shape_ptr != tempshapesmap.end())
							{
								shapes.push_back(shape_ptr->second);
								std::cout << "\nshape added from tempshapemap to tempvector " << shape_ptr->first;
							}

							auto comp_ptr = tempcompmap.find(shapename);

							if(comp_ptr != tempcompmap.end())
							{
								shapes.push_back(comp_ptr->second);
								std::cout << "\ncomp added from tempcompmap to tempvector " << comp_ptr->first;
							}
						}
						std::shared_ptr<Composite> comp = std::make_shared<Composite>(compname, shapes);
						tempcompmap.insert(std::pair<std::string, std::shared_ptr<Composite>>(compname, comp));
						std::cout << "\ncomp added to tempcompmap " << compname;
					}
				}

				else if (word == "light")
				{
					std::string lightname;
					Color color;
					glm::vec3 pos;

					stream >> lightname;

					if(lightname == "ambient")
					{
						stream >> color.r;
						stream >> color.g;
						stream >> color.b;

						scene.ambient_ = color;
						std::cout << "\nambientlight added to scene: " << lightname;
					}
					else
					{
						stream >> pos.x;
						stream >> pos.y;
						stream >> pos.z;

						stream >> color.r;
						stream >> color.g;
						stream >> color.b;

						std::shared_ptr<Light> light = std::make_shared<Light>(lightname, pos, color);
						scene.lights_.push_back(light);
						std::cout << "\nlight added to scene: " << lightname;
					}
				}

				else if (word == "camera")
				{
					std::string cameraname;
					float fov;
					glm::vec3 eye;
					glm::vec3 dir;
					glm::vec3 up;

					stream >> cameraname;

					stream >> fov;

					stream >> eye.x;
					stream >> eye.y;
					stream >> eye.z;

					stream >> dir.x;
					stream >> dir.y;
					stream >> dir.z;

					stream >> up.x;
					stream >> up.y;
					stream >> up.z;

					scene.camera_ = Camera{cameraname, fov, eye, dir, up};
					std::cout << "\ncamera added to scene: " << cameraname;
				}
			}
		}

		for(auto it = tempcompmap.cbegin(); it != tempcompmap.cend(); ++it)
		{
    	composites.push_back(it->second);
			std::cout << "\ncomp pushed from tempcompmap in compvector: " << it->first;
		}

		scene.shapes_ = composites;
		std::cout << "\ncompvector added to scene";
	}

	else
	{
		std::cout << "File not found." << std::endl;
	}

	return scene;
}<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2013 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "VTestPlugin.h"
#include "StencilShadowTest.h"
#include "ParticleTest.h"
#include "TransparencyTest.h"
#include "TextureEffectsTest.h"
#include "CubeMappingTest.h"
#include "OgreResourceGroupManager.h"

VTestPlugin::VTestPlugin()
    :SamplePlugin("VTestPlugin")
{
    // add the playpen tests
    addSample(new CubeMappingTest()); // no bg on Win
    addSample(new ParticleTest());
    addSample(new StencilShadowTest()); // should show ogre head, barrel, taurus
    addSample(new TextureEffectsTest());
    addSample(new TransparencyTest());
}
//---------------------------------------------------------------------

VTestPlugin::~VTestPlugin()
{
    for (OgreBites::SampleSet::iterator i = mSamples.begin(); i != mSamples.end(); ++i)
    {
        delete *i;
    }
    mSamples.clear();
}
//---------------------------------------------------------------------

#ifndef OGRE_STATIC_LIB

VTestPlugin* testPlugin = 0;

extern "C" _OgreSampleExport void dllStartPlugin()
{
    testPlugin = OGRE_NEW VTestPlugin();
    Ogre::Root::getSingleton().installPlugin(testPlugin);
}

extern "C" _OgreSampleExport void dllStopPlugin()
{
    Ogre::Root::getSingleton().uninstallPlugin(testPlugin);
    OGRE_DELETE testPlugin;
}

#endif
<commit_msg>[vtests] Disable a stencil shadow test that crashes on Windows<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2013 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "VTestPlugin.h"
#include "StencilShadowTest.h"
#include "ParticleTest.h"
#include "TransparencyTest.h"
#include "TextureEffectsTest.h"
#include "CubeMappingTest.h"
#include "OgreResourceGroupManager.h"

VTestPlugin::VTestPlugin()
    :SamplePlugin("VTestPlugin")
{
    // add the playpen tests
    addSample(new CubeMappingTest()); // no bg on Win
    addSample(new ParticleTest());
    // addSample(new StencilShadowTest()); // crashes on Windows; should show ogre head, barrel, taurus
    addSample(new TextureEffectsTest());
    addSample(new TransparencyTest());
}
//---------------------------------------------------------------------

VTestPlugin::~VTestPlugin()
{
    for (OgreBites::SampleSet::iterator i = mSamples.begin(); i != mSamples.end(); ++i)
    {
        delete *i;
    }
    mSamples.clear();
}
//---------------------------------------------------------------------

#ifndef OGRE_STATIC_LIB

VTestPlugin* testPlugin = 0;

extern "C" _OgreSampleExport void dllStartPlugin()
{
    testPlugin = OGRE_NEW VTestPlugin();
    Ogre::Root::getSingleton().installPlugin(testPlugin);
}

extern "C" _OgreSampleExport void dllStopPlugin()
{
    Ogre::Root::getSingleton().uninstallPlugin(testPlugin);
    OGRE_DELETE testPlugin;
}

#endif
<|endoftext|>


<commit_before>//
//  board.cpp
//  game_of_life
//
//  Created by Chris Powell on 8/24/13.
//  Copyright (c) 2013 Prylis Inc. All rights reserved.
//

#include "board.h"

int Board::getCell(const int x, const int y) const {
    return _cells[x][y];
}

int Board::getLiveNeighborCountForCell(const int x, const int y) const {
    int above = y-1;
    if (above < 0)
        above = BOARD_HEIGHT;

    int below = y+1;
    if (below >= BOARD_HEIGHT)
        below = 0;

    int left = x-1;
    if (left < 0)
        left = BOARD_WIDTH;

    int right = x+1;
    if (right >= BOARD_WIDTH) {
        right = 0;
    }

    int live = 0;
    for (int xx=left; xx<=right; ++xx) {
        for (int yy=above; yy<=below; ++yy) {
            if (xx==x && yy==y)
                continue;

            live += _cells[xx][yy];
        }
    }
    return live;
}

int Board::evolveCell(const int curState, const int numLiveNeigbors) const {
    //TODO bounds checking

//    int state = _cells[x][y];
//    int numNeighbors = getLiveNeighborCountForCell(x, y);

    if (curState==ALIVE) {
        if (numLiveNeigbors < 2 || numLiveNeigbors > 3)
            return DEAD;
    } else {
        if (numLiveNeigbors == 3)
            return ALIVE;
    }
    return curState;
}

void Board::evolve(const Board &previousBoard) {
    for (int x=0; x<BOARD_WIDTH; ++x) {
        for (int y=0; y<BOARD_HEIGHT; ++y) {
            _cells[x][y] = evolveCell(previousBoard.getCell(x, y), previousBoard.getLiveNeighborCountForCell(x, y));
        }
    }
}

void Board::randomize(const int ratio) {
    for (int y=0; y<BOARD_HEIGHT; ++y) {
        for (int x=0; x<BOARD_WIDTH; ++x) {
            if (rand() % 100 < ratio)
                _cells[x][y]=1;
        }
        std::cout << std::endl;
    }
}

void Board::print() {
    for (int y=0; y<BOARD_HEIGHT; ++y) {
        for (int x=0; x<BOARD_WIDTH; ++x) {
            std::cout << _cells[x][y];
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;

}<commit_msg>Nicer output makes it easier to see the shapes.<commit_after>//
//  board.cpp
//  game_of_life
//
//  Created by Chris Powell on 8/24/13.
//  Copyright (c) 2013 Prylis Inc. All rights reserved.
//

#include "board.h"

int Board::getCell(const int x, const int y) const {
    return _cells[x][y];
}

int Board::getLiveNeighborCountForCell(const int x, const int y) const {
    int above = y-1;
    if (above < 0)
        above = BOARD_HEIGHT;

    int below = y+1;
    if (below >= BOARD_HEIGHT)
        below = 0;

    int left = x-1;
    if (left < 0)
        left = BOARD_WIDTH;

    int right = x+1;
    if (right >= BOARD_WIDTH) {
        right = 0;
    }

    int live = 0;
    for (int xx=left; xx<=right; ++xx) {
        for (int yy=above; yy<=below; ++yy) {
            if (xx==x && yy==y)
                continue;

            live += _cells[xx][yy];
        }
    }
    return live;
}

int Board::evolveCell(const int curState, const int numLiveNeigbors) const {
    //TODO bounds checking

//    int state = _cells[x][y];
//    int numNeighbors = getLiveNeighborCountForCell(x, y);

    if (curState==ALIVE) {
        if (numLiveNeigbors < 2 || numLiveNeigbors > 3)
            return DEAD;
    } else {
        if (numLiveNeigbors == 3)
            return ALIVE;
    }
    return curState;
}

void Board::evolve(const Board &previousBoard) {
    for (int x=0; x<BOARD_WIDTH; ++x) {
        for (int y=0; y<BOARD_HEIGHT; ++y) {
            _cells[x][y] = evolveCell(previousBoard.getCell(x, y), previousBoard.getLiveNeighborCountForCell(x, y));
        }
    }
}

void Board::randomize(const int ratio) {
    for (int y=0; y<BOARD_HEIGHT; ++y) {
        for (int x=0; x<BOARD_WIDTH; ++x) {
            if (rand() % 100 < ratio)
                _cells[x][y]=1;
        }
        std::cout << std::endl;
    }
}

void Board::print() {
    for (int y=0; y<BOARD_HEIGHT; ++y) {
        for (int x=0; x<BOARD_WIDTH; ++x) {
            if (_cells[x][y]==1)
                std::cout<< "*";
            else
                std::cout<< " ";
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;

}<|endoftext|>


<commit_before>#include <QtCore/QFile>

#include <QtTest/QtTest>

#include <QMimeDatabase>

class tst_QMimeType : public QObject
{
    Q_OBJECT

public:
    tst_QMimeType();
    ~tst_QMimeType();

private Q_SLOTS:
    void initTestCase();

    void findByName_data();
    void findByName();

    void findByData_data();
    void findByData();

    void findByFile_data();
    void findByFile();

private:
    QMimeDatabase database;
};

tst_QMimeType::tst_QMimeType() :
        database()
{
}

tst_QMimeType::~tst_QMimeType()
{
}

void tst_QMimeType::initTestCase()
{
}

void tst_QMimeType::findByName_data()
{
    QTest::addColumn<QString>("filePath");
    QTest::addColumn<QString>("mimeType");
    QTest::addColumn<QString>("xFail");

    QString prefix = QLatin1String(SRCDIR "testfiles/");

    QFile f(prefix + QLatin1String("list"));
    QVERIFY(f.open(QIODevice::ReadOnly));

    QByteArray line(1024, Qt::Uninitialized);

    while (!f.atEnd()) {
        int len = f.readLine(line.data(), 1023);

        if (len <= 2 || line.at(0) == '#')
            continue;

        QString string = QString::fromLatin1(line.constData(), len - 1).trimmed();
        QStringList list = string.split(QLatin1Char(' '), QString::SkipEmptyParts);
        QVERIFY(list.size() >= 2);

        QString filePath = list.at(0);
        QString mimeType = list.at(1);
        QString xFail;
        if (list.size() == 3)
            xFail = list.at(2);

        QTest::newRow(filePath.toLatin1().constData()) << prefix + filePath << mimeType << xFail;
    }
}

void tst_QMimeType::findByName()
{
    QFETCH(QString, filePath);
    QFETCH(QString, mimeType);
    QFETCH(QString, xFail);

    const QString resultMimeTypeName = database.findByName(filePath).name();

    // Results are ambiguous when multiple MIME types have the same glob
    // -> accept the current result if the found MIME type actually
    // matches the file's extension.
    const QMimeType foundMimeType = database.mimeTypeForName(resultMimeTypeName);
    const QString extension = QFileInfo(filePath).suffix();
    //qDebug() << foundMimeType.globPatterns() << "extension=*." << extension;
    if (foundMimeType.globPatterns().contains("*." + extension))
        return;

    const bool shouldFail = (xFail.length() >= 1 && xFail.at(0) == QLatin1Char('x'));
    if (shouldFail) {
        // Expected to fail
        QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
    } else {
        QCOMPARE(resultMimeTypeName, mimeType);
    }
}

void tst_QMimeType::findByData_data()
{
    findByName_data();
}

void tst_QMimeType::findByData()
{
    QFETCH(QString, filePath);
    QFETCH(QString, mimeType);
    QFETCH(QString, xFail);

    QFile f(filePath);
    QVERIFY(f.open(QIODevice::ReadOnly));
    QByteArray data = f.readAll();

    const QString resultMimeTypeName = database.findByData(data).name();
    if (xFail.length() >= 2 && xFail.at(1) == QLatin1Char('x'))
        // Expected to fail
        QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
    else
        QCOMPARE(resultMimeTypeName, mimeType);
}

void tst_QMimeType::findByFile_data()
{
    findByName_data();
}

void tst_QMimeType::findByFile()
{
    QFETCH(QString, filePath);
    QFETCH(QString, mimeType);
    QFETCH(QString, xFail);

    const QString resultMimeTypeName = database.findByFile(QFileInfo(filePath)).name();
    if (xFail.length() >= 3 && xFail.at(2) == QLatin1Char('x'))
        // Expected to fail
        QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
    else
        QCOMPARE(resultMimeTypeName, mimeType);
}

QTEST_APPLESS_MAIN(tst_QMimeType)

#include "tst_qmimedatabase.moc"
<commit_msg>Updated the debug output.<commit_after>#include <QtCore/QFile>

#include <QtTest/QtTest>

#include <QMimeDatabase>

class tst_QMimeType : public QObject
{
    Q_OBJECT

public:
    tst_QMimeType();
    ~tst_QMimeType();

private Q_SLOTS:
    void initTestCase();

    void findByName_data();
    void findByName();

    void findByData_data();
    void findByData();

    void findByFile_data();
    void findByFile();

private:
    QMimeDatabase database;
};

tst_QMimeType::tst_QMimeType() :
        database()
{
}

tst_QMimeType::~tst_QMimeType()
{
}

void tst_QMimeType::initTestCase()
{
}

void tst_QMimeType::findByName_data()
{
    QTest::addColumn<QString>("filePath");
    QTest::addColumn<QString>("mimeType");
    QTest::addColumn<QString>("xFail");

    QString prefix = QLatin1String(SRCDIR "testfiles/");

    QFile f(prefix + QLatin1String("list"));
    QVERIFY(f.open(QIODevice::ReadOnly));

    QByteArray line(1024, Qt::Uninitialized);

    while (!f.atEnd()) {
        int len = f.readLine(line.data(), 1023);

        if (len <= 2 || line.at(0) == '#')
            continue;

        QString string = QString::fromLatin1(line.constData(), len - 1).trimmed();
        QStringList list = string.split(QLatin1Char(' '), QString::SkipEmptyParts);
        QVERIFY(list.size() >= 2);

        QString filePath = list.at(0);
        QString mimeType = list.at(1);
        QString xFail;
        if (list.size() == 3)
            xFail = list.at(2);

        QTest::newRow(filePath.toLatin1().constData()) << prefix + filePath << mimeType << xFail;
    }
}

void tst_QMimeType::findByName()
{
    QFETCH(QString, filePath);
    QFETCH(QString, mimeType);
    QFETCH(QString, xFail);

    //qDebug() << Q_FUNC_INFO << filePath;

    const QString resultMimeTypeName = database.findByName(filePath).name();
    //qDebug() << Q_FUNC_INFO << "findByName() returned" << resultMimeTypeName;

    // Results are ambiguous when multiple MIME types have the same glob
    // -> accept the current result if the found MIME type actually
    // matches the file's extension.
    const QMimeType foundMimeType = database.mimeTypeForName(resultMimeTypeName);
    const QString extension = QFileInfo(filePath).suffix();
    //qDebug() << Q_FUNC_INFO << "globPatterns:" << foundMimeType.globPatterns() << "- extension:" << QString() + "*." + extension;
    if (foundMimeType.globPatterns().contains("*." + extension))
        return;

    const bool shouldFail = (xFail.length() >= 1 && xFail.at(0) == QLatin1Char('x'));
    if (shouldFail) {
        // Expected to fail
        QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
    } else {
        QCOMPARE(resultMimeTypeName, mimeType);
    }
}

void tst_QMimeType::findByData_data()
{
    findByName_data();
}

void tst_QMimeType::findByData()
{
    QFETCH(QString, filePath);
    QFETCH(QString, mimeType);
    QFETCH(QString, xFail);

    QFile f(filePath);
    QVERIFY(f.open(QIODevice::ReadOnly));
    QByteArray data = f.readAll();

    const QString resultMimeTypeName = database.findByData(data).name();
    if (xFail.length() >= 2 && xFail.at(1) == QLatin1Char('x')) {
        // Expected to fail
        QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
    }
    else {
        QCOMPARE(resultMimeTypeName, mimeType);
    }
}

void tst_QMimeType::findByFile_data()
{
    findByName_data();
}

void tst_QMimeType::findByFile()
{
    QFETCH(QString, filePath);
    QFETCH(QString, mimeType);
    QFETCH(QString, xFail);

    const QString resultMimeTypeName = database.findByFile(QFileInfo(filePath)).name();
    //qDebug() << Q_FUNC_INFO << filePath << "->" << resultMimeTypeName;
    if (xFail.length() >= 3 && xFail.at(2) == QLatin1Char('x')) {
        // Expected to fail
        QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
    }
    else {
        QCOMPARE(resultMimeTypeName, mimeType);
    }
}

QTEST_APPLESS_MAIN(tst_QMimeType)

#include "tst_qmimedatabase.moc"
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/operators/nccl/nccl_gpu_common.h"
#include "paddle/fluid/platform/gpu_info.h"

namespace paddle {
namespace platform {
namespace {
// TODO(panyx0718): Where to destroy them.
std::unique_ptr<std::vector<ncclComm_t>> global_comms;
std::unique_ptr<std::unordered_map<int, int>> comm_id_map;
bool inited = false;
size_t last_num_gpus = -1;
}

int Communicator::GetCommId(int device_id) const {
  return comm_id_map->at(device_id);
}

void Communicator::InitAll(const std::vector<int>& gpus) {
  if (inited && last_num_gpus == gpus.size()) {
    return;
  }
  last_num_gpus = gpus.size();
  if (global_comms) {
    for (size_t i = 0; i < global_comms->size(); ++i) {
      // FIXME(dzh) : PADDLE_ENFORCE return void
      dynload::ncclCommDestroy((*global_comms)[i]);
    }
  }
  global_comms.reset(new std::vector<ncclComm_t>());
  comm_id_map.reset(new std::unordered_map<int, int>());
  global_comms->resize(gpus.size());
  for (size_t i = 0; i < gpus.size(); ++i) {
    (*comm_id_map)[gpus[i]] = i;
  }
  PADDLE_ENFORCE(
      dynload::ncclCommInitAll(global_comms->data(), gpus.size(), gpus.data()));
  inited = true;
}

const std::vector<ncclComm_t>& Communicator::comms() const {
  return *global_comms;
}

}  // namespace platform
}  // namespace paddle
<commit_msg>Add lock<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/operators/nccl/nccl_gpu_common.h"
#include "paddle/fluid/platform/gpu_info.h"

namespace paddle {
namespace platform {
namespace {
// TODO(panyx0718): Where to destroy them.
std::unique_ptr<std::vector<ncclComm_t>> global_comms;
std::unique_ptr<std::unordered_map<int, int>> comm_id_map;
bool inited = false;
size_t last_num_gpus = -1;
// TODO(panyx0718): Need to decide whether Paddle supports parallel
// runs with different number GPUs. If true, current solution is not enough.
std::mutex comm_mu;
}

int Communicator::GetCommId(int device_id) const {
  std::lock_guard<std::mutex> guard(comm_mu);
  return comm_id_map->at(device_id);
}

void Communicator::InitAll(const std::vector<int>& gpus) {
  std::lock_guard<std::mutex> guard(comm_mu);
  if (inited && last_num_gpus == gpus.size()) {
    return;
  }
  last_num_gpus = gpus.size();
  if (global_comms) {
    for (size_t i = 0; i < global_comms->size(); ++i) {
      // FIXME(dzh) : PADDLE_ENFORCE return void
      dynload::ncclCommDestroy((*global_comms)[i]);
    }
  }
  global_comms.reset(new std::vector<ncclComm_t>());
  comm_id_map.reset(new std::unordered_map<int, int>());
  global_comms->resize(gpus.size());
  for (size_t i = 0; i < gpus.size(); ++i) {
    (*comm_id_map)[gpus[i]] = i;
  }
  PADDLE_ENFORCE(
      dynload::ncclCommInitAll(global_comms->data(), gpus.size(), gpus.data()));
  inited = true;
}

const std::vector<ncclComm_t>& Communicator::comms() const {
  std::lock_guard<std::mutex> guard(comm_mu);
  return *global_comms;
}

}  // namespace platform
}  // namespace paddle
<|endoftext|>


<commit_before>/*
 * File:   render.cpp
 * Author: ivan
 *
 * Created on October 12, 2015, 11:04 PM
 */

#include "render.hpp"

#include <cmath>

#include <cairo/cairo.h>

#include <utki/util.hpp>

using namespace svgren;

namespace{

class CairoMatrixPush{
	cairo_matrix_t m;
	cairo_t* cr;
public:
	CairoMatrixPush(cairo_t* cr) :
			cr(cr)
	{
		ASSERT(this->cr)
		cairo_get_matrix(this->cr, &this->m);
	}
	~CairoMatrixPush()noexcept{
		cairo_set_matrix(this->cr, &this->m);
	}
};

class Renderer : public svgdom::Renderer{
	cairo_t* cr;

	void applyTransformations(const svgdom::Transformable& transformable)const{
		for(auto& t : transformable.transformations){
			switch(t.type){
				case svgdom::Transformation::EType::TRANSLATE:
					cairo_translate(this->cr, t.x, t.y);
					break;
				case svgdom::Transformation::EType::MATRIX:
					{
						cairo_matrix_t matrix;
						matrix.xx = t.a;
						matrix.yx = t.b;
						matrix.xy = t.c;
						matrix.yy = t.d;
						matrix.x0 = t.e;
						matrix.y0 = t.f;
						cairo_transform(this->cr, &matrix);
					}
					break;
				case svgdom::Transformation::EType::SCALE:
					cairo_scale(this->cr, t.x, t.y);
					break;
				case svgdom::Transformation::EType::ROTATE:
					cairo_translate(this->cr, t.x, t.y);
					cairo_rotate(this->cr, t.angle);
					cairo_translate(this->cr, -t.x, -t.y);
					break;
				case svgdom::Transformation::EType::SKEWX:
					{
						cairo_matrix_t matrix;
						matrix.xx = 1;
						matrix.yx = 0;
						matrix.xy = std::tan(t.angle);
						matrix.yy = 1;
						matrix.x0 = 0;
						matrix.y0 = 0;
						cairo_transform(this->cr, &matrix);
					}
					break;
				case svgdom::Transformation::EType::SKEWY:
					{
						cairo_matrix_t matrix;
						matrix.xx = 1;
						matrix.yx = std::tan(t.angle);
						matrix.xy = 0;
						matrix.yy = 1;
						matrix.x0 = 0;
						matrix.y0 = 0;
						cairo_transform(this->cr, &matrix);
					}
					break;
				default:
					ASSERT(false)
					break;
			}
		}
	}

public:
	Renderer(cairo_t* cr) :
			cr(cr)
	{}

	void render(const svgdom::GElement& e)override{
		CairoMatrixPush cairoMatrixPush(this->cr);

		this->applyTransformations(e);

		e.Container::render(*this);
	}

	void render(const svgdom::SvgElement& e)override{
		e.Container::render(*this);
	}

	void render(const svgdom::PathElement& e)override{
		CairoMatrixPush cairoMatrixPush(this->cr);

		this->applyTransformations(e);

		cairo_set_source_rgb(cr, 1.0, 0, 0);

//		const svgdom::PathElement::Step* prev = nullptr;
		for(auto& s : e.path){
			switch(s.type){
				case svgdom::PathElement::Step::EType::MOVE_ABS:
					cairo_move_to(this->cr, s.x, s.y);
					break;
				case svgdom::PathElement::Step::EType::MOVE_REL:
					cairo_rel_move_to(this->cr, s.x, s.y);
					break;
				case svgdom::PathElement::Step::EType::LINE_ABS:
					cairo_line_to(this->cr, s.x, s.y);
					break;
				case svgdom::PathElement::Step::EType::LINE_REL:
					cairo_rel_line_to(this->cr, s.x, s.y);
					break;
				case svgdom::PathElement::Step::EType::HORIZONTAL_LINE_ABS:
					{
						double x, y;
						if(cairo_has_current_point(this->cr)){
							cairo_get_current_point(this->cr, &x, &y);
						}else{
							y = 0;
						}
						cairo_line_to(this->cr, s.x, y);
					}
					break;
				case svgdom::PathElement::Step::EType::HORIZONTAL_LINE_REL:
					{
						double x, y;
						if(cairo_has_current_point(this->cr)){
							cairo_get_current_point(this->cr, &x, &y);
						}else{
							y = 0;
						}
						cairo_rel_line_to(this->cr, s.x, y);
					}
					break;
				case svgdom::PathElement::Step::EType::VERTICAL_LINE_ABS:
					{
						double x, y;
						if(cairo_has_current_point(this->cr)){
							cairo_get_current_point(this->cr, &x, &y);
						}else{
							x = 0;
						}
						cairo_line_to(this->cr, x, s.y);
					}
					break;
				case svgdom::PathElement::Step::EType::VERTICAL_LINE_REL:
					{
						double x, y;
						if(cairo_has_current_point(this->cr)){
							cairo_get_current_point(this->cr, &x, &y);
						}else{
							x = 0;
						}
						cairo_rel_line_to(this->cr, x, s.y);
					}
					break;
				case svgdom::PathElement::Step::EType::CLOSE:
					cairo_close_path(this->cr);
					break;
				case svgdom::PathElement::Step::EType::CUBIC_ABS:
					cairo_curve_to(this->cr, s.x1, s.y1, s.x2, s.y2, s.x, s.y);
					break;
				case svgdom::PathElement::Step::EType::CUBIC_REL:
					cairo_rel_curve_to(this->cr, s.x1, s.y1, s.x2, s.y2, s.x, s.y);
					break;
//				case svgdom::PathElement::Step::EType::CUBIC_SMOOTH_ABS:
//					{
//						double x, y;
//						if(cairo_has_current_point(this->cr)){
//							cairo_get_current_point(this->cr, &x, &y);
//						}else{
//							x = 0;
//							y = 0;
//						}
//						double x1, y1;
//						if(prev){
//							x1 = -(prev->x2 - x) + x;
//							y1 = -(prev->y2 - y) + y;
//						}else{
//							x1 = x;
//							y1 = y;
//						}
//						cairo_curve_to(this->cr, x1, y1, s.x2, s.y2, s.x, s.y);
//					}
//					break;
				default:
					ASSERT(false)
					break;
			}
//			prev = &s;
		}

		cairo_set_line_width (cr, 1);
		cairo_stroke (cr);
	}
};

}

std::vector<std::uint32_t> svgren::render(const svgdom::SvgElement& svg, unsigned width, unsigned height){
//	int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width);
	int stride = width * 4;

	TRACE(<< "width = " << width << " stride = " << stride / 4 << std::endl)

	std::vector<std::uint32_t> ret((stride / sizeof(std::uint32_t)) * height);

	cairo_surface_t* surface = cairo_image_surface_create_for_data(
			reinterpret_cast<unsigned char*>(&*ret.begin()),
			CAIRO_FORMAT_ARGB32,
			width,
			height,
			stride
		);
	if(!surface){
		ret.clear();
		return ret;
	}
	utki::ScopeExit scopeExitSurface([&surface](){
		cairo_surface_destroy(surface);
	});

	cairo_t* cr = cairo_create(surface);
	if(!cr){
		ret.clear();
		return ret;
	}
	utki::ScopeExit scopeExitContext([&cr](){
		cairo_destroy(cr);
	});

	Renderer r(cr);

	svg.render(r);

	return ret;
}
<commit_msg>stuff<commit_after>/*
 * File:   render.cpp
 * Author: ivan
 *
 * Created on October 12, 2015, 11:04 PM
 */

#include "render.hpp"

#include <cmath>

#include <cairo/cairo.h>

#include <utki/util.hpp>

using namespace svgren;

namespace{

class CairoMatrixPush{
	cairo_matrix_t m;
	cairo_t* cr;
public:
	CairoMatrixPush(cairo_t* cr) :
			cr(cr)
	{
		ASSERT(this->cr)
		cairo_get_matrix(this->cr, &this->m);
	}
	~CairoMatrixPush()noexcept{
		cairo_set_matrix(this->cr, &this->m);
	}
};

class Renderer : public svgdom::Renderer{
	cairo_t* cr;

	void applyTransformations(const svgdom::Transformable& transformable)const{
		for(auto& t : transformable.transformations){
			switch(t.type){
				case svgdom::Transformation::EType::TRANSLATE:
					cairo_translate(this->cr, t.x, t.y);
					break;
				case svgdom::Transformation::EType::MATRIX:
					{
						cairo_matrix_t matrix;
						matrix.xx = t.a;
						matrix.yx = t.b;
						matrix.xy = t.c;
						matrix.yy = t.d;
						matrix.x0 = t.e;
						matrix.y0 = t.f;
						cairo_transform(this->cr, &matrix);
					}
					break;
				case svgdom::Transformation::EType::SCALE:
					cairo_scale(this->cr, t.x, t.y);
					break;
				case svgdom::Transformation::EType::ROTATE:
					cairo_translate(this->cr, t.x, t.y);
					cairo_rotate(this->cr, t.angle);
					cairo_translate(this->cr, -t.x, -t.y);
					break;
				case svgdom::Transformation::EType::SKEWX:
					{
						cairo_matrix_t matrix;
						matrix.xx = 1;
						matrix.yx = 0;
						matrix.xy = std::tan(t.angle);
						matrix.yy = 1;
						matrix.x0 = 0;
						matrix.y0 = 0;
						cairo_transform(this->cr, &matrix);
					}
					break;
				case svgdom::Transformation::EType::SKEWY:
					{
						cairo_matrix_t matrix;
						matrix.xx = 1;
						matrix.yx = std::tan(t.angle);
						matrix.xy = 0;
						matrix.yy = 1;
						matrix.x0 = 0;
						matrix.y0 = 0;
						cairo_transform(this->cr, &matrix);
					}
					break;
				default:
					ASSERT(false)
					break;
			}
		}
	}

public:
	Renderer(cairo_t* cr) :
			cr(cr)
	{}

	void render(const svgdom::GElement& e)override{
		CairoMatrixPush cairoMatrixPush(this->cr);

		this->applyTransformations(e);

		e.Container::render(*this);
	}

	void render(const svgdom::SvgElement& e)override{
		e.Container::render(*this);
	}

	void render(const svgdom::PathElement& e)override{
		CairoMatrixPush cairoMatrixPush(this->cr);

		this->applyTransformations(e);

//		const svgdom::PathElement::Step* prev = nullptr;
		for(auto& s : e.path){
			switch(s.type){
				case svgdom::PathElement::Step::EType::MOVE_ABS:
					cairo_move_to(this->cr, s.x, s.y);
					break;
				case svgdom::PathElement::Step::EType::MOVE_REL:
					cairo_rel_move_to(this->cr, s.x, s.y);
					break;
				case svgdom::PathElement::Step::EType::LINE_ABS:
					cairo_line_to(this->cr, s.x, s.y);
					break;
				case svgdom::PathElement::Step::EType::LINE_REL:
					cairo_rel_line_to(this->cr, s.x, s.y);
					break;
				case svgdom::PathElement::Step::EType::HORIZONTAL_LINE_ABS:
					{
						double x, y;
						if(cairo_has_current_point(this->cr)){
							cairo_get_current_point(this->cr, &x, &y);
						}else{
							y = 0;
						}
						cairo_line_to(this->cr, s.x, y);
					}
					break;
				case svgdom::PathElement::Step::EType::HORIZONTAL_LINE_REL:
					{
						double x, y;
						if(cairo_has_current_point(this->cr)){
							cairo_get_current_point(this->cr, &x, &y);
						}else{
							y = 0;
						}
						cairo_rel_line_to(this->cr, s.x, y);
					}
					break;
				case svgdom::PathElement::Step::EType::VERTICAL_LINE_ABS:
					{
						double x, y;
						if(cairo_has_current_point(this->cr)){
							cairo_get_current_point(this->cr, &x, &y);
						}else{
							x = 0;
						}
						cairo_line_to(this->cr, x, s.y);
					}
					break;
				case svgdom::PathElement::Step::EType::VERTICAL_LINE_REL:
					{
						double x, y;
						if(cairo_has_current_point(this->cr)){
							cairo_get_current_point(this->cr, &x, &y);
						}else{
							x = 0;
						}
						cairo_rel_line_to(this->cr, x, s.y);
					}
					break;
				case svgdom::PathElement::Step::EType::CLOSE:
					cairo_close_path(this->cr);
					break;
				case svgdom::PathElement::Step::EType::CUBIC_ABS:
					cairo_curve_to(this->cr, s.x1, s.y1, s.x2, s.y2, s.x, s.y);
					break;
				case svgdom::PathElement::Step::EType::CUBIC_REL:
					cairo_rel_curve_to(this->cr, s.x1, s.y1, s.x2, s.y2, s.x, s.y);
					break;
//				case svgdom::PathElement::Step::EType::CUBIC_SMOOTH_ABS:
//					{
//						double x, y;
//						if(cairo_has_current_point(this->cr)){
//							cairo_get_current_point(this->cr, &x, &y);
//						}else{
//							x = 0;
//							y = 0;
//						}
//						double x1, y1;
//						if(prev){
//							x1 = -(prev->x2 - x) + x;
//							y1 = -(prev->y2 - y) + y;
//						}else{
//							x1 = x;
//							y1 = y;
//						}
//						cairo_curve_to(this->cr, x1, y1, s.x2, s.y2, s.x, s.y);
//					}
//					break;
				default:
					ASSERT(false)
					break;
			}
//			prev = &s;
		}

		auto fill = e.getStyleProperty(svgdom::EStyleProperty::FILL);
		auto stroke = e.getStyleProperty(svgdom::EStyleProperty::STROKE);

		if(fill && fill->effective){
			svgdom::real opacity;
			if(auto fillOpacity = e.getStyleProperty(svgdom::EStyleProperty::FILL_OPACITY)){
				opacity = fillOpacity->floating;
			}else{
				opacity = 1;
			}

			auto fillRgb = fill->getRgb();

			cairo_set_source_rgba(this->cr, fillRgb.r, fillRgb.g, fillRgb.b, opacity);
			if(stroke && stroke->effective){
				cairo_fill_preserve(this->cr);
			}else{
				cairo_fill(this->cr);
			}
		}

		if(stroke && stroke->effective){
			if(auto strokeWidth = e.getStyleProperty(svgdom::EStyleProperty::STROKE_WIDTH)){
				cairo_set_line_width(cr, strokeWidth->length.value);
			}else{
				cairo_set_line_width(cr, 1);
			}

			auto rgb = stroke->getRgb();

			cairo_set_source_rgb(this->cr, rgb.r, rgb.g, rgb.b);
			cairo_stroke(this->cr);
		}
	}
};

}

std::vector<std::uint32_t> svgren::render(const svgdom::SvgElement& svg, unsigned width, unsigned height){
//	int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width);
	int stride = width * 4;

	TRACE(<< "width = " << width << " stride = " << stride / 4 << std::endl)

	std::vector<std::uint32_t> ret((stride / sizeof(std::uint32_t)) * height);

	for(auto& c : ret){
		c = 0xffffffff;//TODO: fill 0
	}

	cairo_surface_t* surface = cairo_image_surface_create_for_data(
			reinterpret_cast<unsigned char*>(&*ret.begin()),
			CAIRO_FORMAT_ARGB32,
			width,
			height,
			stride
		);
	if(!surface){
		ret.clear();
		return ret;
	}
	utki::ScopeExit scopeExitSurface([&surface](){
		cairo_surface_destroy(surface);
	});

	cairo_t* cr = cairo_create(surface);
	if(!cr){
		ret.clear();
		return ret;
	}
	utki::ScopeExit scopeExitContext([&cr](){
		cairo_destroy(cr);
	});

	Renderer r(cr);

	svg.render(r);

	return ret;
}
<|endoftext|>


<commit_before>/*
 * Tests for the scalar example solving the test equation
 */
#include <cmath>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

using namespace ::testing;

#include <pfasst/quadrature.hpp>

#define PFASST_UNIT_TESTING
#include "../examples/scalar/scalar_sdc.cpp"
#undef PFASST_UNIT_TESTING

/*
 * parameterized test that verifies that given sufficiently many nodes and iterations,
 * SDC can reproduce the analytic solution with very high precision
 */
class HighPrecisionTest
  : public TestWithParam<pfasst::QuadratureType>
{
  protected:
    pfasst::QuadratureType nodetype; // parameter

    complex<double> lambda;
    double Tend = 0.5;
    size_t nsteps = 1;
    size_t niters = 30;
    size_t nnodes = 8;
    size_t nnodes_in_call;

    void set_parameters()
    {
      switch (this->nodetype)
      {
        case pfasst::QuadratureType::GaussLobatto:
          break;

        default:
          break;
      }

    }

  public:
    virtual void SetUp()
    {
      this->nodetype = GetParam();
      this->set_parameters();
    }

    virtual void TearDown()
    {}
};

TEST_P(HighPrecisionTest, AllNodes)
{
}

INSTANTIATE_TEST_CASE_P(ScalarSDC, HighPrecisionTest,
                                Values(pfasst::QuadratureType::GaussLobatto,
                                       pfasst::QuadratureType::GaussLegendre,
                                       pfasst::QuadratureType::GaussRadau,
                                       pfasst::QuadratureType::ClenshawCurtis,
                                       pfasst::QuadratureType::Uniform)
);

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}<commit_msg>high precision test for scalar now running: tolerance set to 5e-12<commit_after>/*
 * Tests for the scalar example solving the test equation
 */
#include <cmath>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

using namespace ::testing;

#include <pfasst/quadrature.hpp>

#define PFASST_UNIT_TESTING
#include "../examples/scalar/scalar_sdc.cpp"
#undef PFASST_UNIT_TESTING

/*
 * parameterized test that verifies that given sufficiently many nodes and iterations,
 * SDC can reproduce the analytic solution with very high precision
 */
class HighPrecisionTest
  : public TestWithParam<pfasst::QuadratureType>
{
  protected:
    pfasst::QuadratureType nodetype; // parameter

    const complex<double> lambda = complex<double>(-1.0,1.0);
    const double dt = 0.2; // = Tend for single step
    const size_t nsteps = 1;
    const size_t niters = 30;
    const size_t nnodes = 8;
    size_t nnodes_in_call;
    double err;

    void set_parameters()
    {
      switch (this->nodetype)
      {
        case pfasst::QuadratureType::GaussLobatto:
          this->nnodes_in_call = this->nnodes;
          break;

        case pfasst::QuadratureType::GaussLegendre:
          this->nnodes_in_call = this->nnodes + 2;
          break;

        case pfasst::QuadratureType::GaussRadau:
          this->nnodes_in_call = this->nnodes + 1;
          break;

        case pfasst::QuadratureType::ClenshawCurtis:
          this->nnodes_in_call = this->nnodes + 1;
          break;

        case pfasst::QuadratureType::Uniform:
          this->nnodes_in_call = this->nnodes + 1;
          break;

        default:
          break;
      }

    }

  public:
    virtual void SetUp()
    {
      this->nodetype = GetParam();
      this->set_parameters();
      this->err = run_scalar_sdc(this->nsteps, this->dt, this->nnodes_in_call,
                                 this->niters, this->lambda, this->nodetype);
    }

    virtual void TearDown()
    {}
};

TEST_P(HighPrecisionTest, AllNodes)
{
  EXPECT_THAT(err, Le<double>(5e-12)) << "Failed to bring relative error below 5e-12";
}

INSTANTIATE_TEST_CASE_P(ScalarSDC, HighPrecisionTest,
                                Values(pfasst::QuadratureType::GaussLobatto,
                                       pfasst::QuadratureType::GaussLegendre,
                                       pfasst::QuadratureType::GaussRadau,
                                       pfasst::QuadratureType::ClenshawCurtis,
                                       pfasst::QuadratureType::Uniform)
);

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Matias Fontanini
 * 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.
 *
 * 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 "tcp_ip/stream.h"

#ifdef TINS_HAVE_TCPIP

#include <limits>
#include <algorithm>
#include "memory.h"
#include "ip_address.h"
#include "ipv6_address.h"
#include "tcp.h"
#include "ip.h"
#include "ipv6.h"
#include "ethernetII.h"
#include "rawpdu.h"
#include "exceptions.h"
#include "memory_helpers.h"

using std::make_pair;
using std::bind;
using std::pair;
using std::runtime_error;
using std::numeric_limits;
using std::max;
using std::swap;

using Tins::Memory::OutputMemoryStream;
using Tins::Memory::InputMemoryStream;

namespace Tins {
namespace TCPIP {

Stream::Stream(PDU& packet, const timestamp_type& ts)
: client_flow_(extract_client_flow(packet)),
  server_flow_(extract_server_flow(packet)), create_time_(ts),
  last_seen_(ts), auto_cleanup_client_(true), auto_cleanup_server_(true),
  is_partial_stream_(false), directions_recovery_mode_enabled_(0) {
    const EthernetII* eth = packet.find_pdu<EthernetII>();
    if (eth) {
        client_hw_addr_ = eth->src_addr();
        server_hw_addr_ = eth->dst_addr();
    }
    const TCP& tcp = packet.rfind_pdu<TCP>();
    // If this is not the first packet of a stream (SYN), then it's a partial stream
    is_partial_stream_ = tcp.flags() != TCP::SYN;
}

void Stream::process_packet(PDU& packet, const timestamp_type& ts) {
    last_seen_ = ts;
    if (client_flow_.packet_belongs(packet)) {
        client_flow_.process_packet(packet);
    }
    else if (server_flow_.packet_belongs(packet)) {
        server_flow_.process_packet(packet);
    }
    if (is_finished() && on_stream_closed_) {
        on_stream_closed_(*this);
    }
}

void Stream::process_packet(PDU& packet) {
    return process_packet(packet, timestamp_type(0));
}

Flow& Stream::client_flow() {
    return client_flow_;
}

const Flow& Stream::client_flow() const {
    return client_flow_;
}

Flow& Stream::server_flow() {
    return server_flow_;
}

const Flow& Stream::server_flow() const {
    return server_flow_;
}

void Stream::stream_closed_callback(const stream_callback_type& callback) {
    on_stream_closed_ = callback;
}

void Stream::client_data_callback(const stream_callback_type& callback) {
    on_client_data_callback_ = callback;
}

void Stream::server_data_callback(const stream_callback_type& callback) {
    on_server_data_callback_ = callback;
}

void Stream::client_out_of_order_callback(const stream_packet_callback_type& callback) {
    on_client_out_of_order_callback_ = callback;
}

void Stream::server_out_of_order_callback(const stream_packet_callback_type& callback) {
    on_server_out_of_order_callback_ = callback;
}

void Stream::ignore_client_data() {
    client_flow().ignore_data_packets();
}

void Stream::ignore_server_data() {
    server_flow().ignore_data_packets();
}

bool Stream::is_finished() const {
    const Flow::State client_state = client_flow_.state();
    const Flow::State server_state = server_flow_.state();
    // If either peer sent a RST then the stream is done
    if (client_state == Flow::RST_SENT || server_state == Flow::RST_SENT) {
        return true;
    }
    else {
        // Otherwise, only finish if both sent a FIN
        return client_state == Flow::FIN_SENT && server_state == Flow::FIN_SENT;
    }
}

bool Stream::is_v6() const {
    return server_flow().is_v6();
}

IPv4Address Stream::client_addr_v4() const {
    return server_flow().dst_addr_v4();
}

IPv6Address Stream::client_addr_v6() const {
    return server_flow().dst_addr_v6();
}

const Stream::hwaddress_type& Stream::client_hw_addr() const {
    return client_hw_addr_;
}

const Stream::hwaddress_type& Stream::server_hw_addr() const {
    return server_hw_addr_;
}

IPv4Address Stream::server_addr_v4() const {
    return client_flow().dst_addr_v4();
}

IPv6Address Stream::server_addr_v6() const {
    return client_flow().dst_addr_v6();
}

uint16_t Stream::client_port() const {
    return server_flow().dport();
}

uint16_t Stream::server_port() const {
    return client_flow().dport();
}

const Stream::payload_type& Stream::client_payload() const {
    return client_flow().payload();
}

Stream::payload_type& Stream::client_payload() {
    return client_flow().payload();
}

const Stream::payload_type& Stream::server_payload() const {
    return server_flow().payload();
}

Stream::payload_type& Stream::server_payload() {
    return server_flow().payload();
}

const Stream::timestamp_type& Stream::create_time() const {
    return create_time_;
}

const Stream::timestamp_type& Stream::last_seen() const {
    return last_seen_;
}

Flow Stream::extract_client_flow(const PDU& packet) {
    const TCP* tcp = packet.find_pdu<TCP>();
    if (!tcp) {
        throw invalid_packet();
    }
    if (const IP* ip = packet.find_pdu<IP>()) {
        return Flow(ip->dst_addr(), tcp->dport(), tcp->seq());
    }
    else if (const IPv6* ip = packet.find_pdu<IPv6>()) {
        return Flow(ip->dst_addr(), tcp->dport(), tcp->seq());
    }
    else {
        throw invalid_packet();
    }
}

Flow Stream::extract_server_flow(const PDU& packet) {
    const TCP* tcp = packet.find_pdu<TCP>();
    if (!tcp) {
        throw invalid_packet();
    }
    if (const IP* ip = packet.find_pdu<IP>()) {
        return Flow(ip->src_addr(), tcp->sport(), tcp->ack_seq());
    }
    else if (const IPv6* ip = packet.find_pdu<IPv6>()) {
        return Flow(ip->src_addr(), tcp->sport(), tcp->ack_seq());
    }
    else {
        throw invalid_packet();
    }
}

void Stream::setup_flows_callbacks() {
    using namespace std::placeholders;

    client_flow_.data_callback(bind(&Stream::on_client_flow_data, this, _1));
    server_flow_.data_callback(bind(&Stream::on_server_flow_data, this, _1));
    client_flow_.out_of_order_callback(bind(&Stream::on_client_out_of_order,
                                            this, _1, _2, _3));
    server_flow_.out_of_order_callback(bind(&Stream::on_server_out_of_order,
                                            this, _1, _2, _3));
}

void Stream::auto_cleanup_payloads(bool value) {
    auto_cleanup_client_data(value);
    auto_cleanup_server_data(value);
}

void Stream::auto_cleanup_client_data(bool value) {
    auto_cleanup_client_ = value;
}

void Stream::auto_cleanup_server_data(bool value) {
    auto_cleanup_server_ = value;
}

void Stream::enable_ack_tracking() {
    client_flow().enable_ack_tracking();
    server_flow().enable_ack_tracking();
}

bool Stream::ack_tracking_enabled() const {
    return client_flow().ack_tracking_enabled() && server_flow().ack_tracking_enabled();
}

bool Stream::is_partial_stream() const {
    return is_partial_stream_;
}

void Stream::enable_recovery_mode(uint32_t recovery_window) {
    using namespace std::placeholders;
    client_out_of_order_callback(bind(&Stream::client_recovery_mode_handler, _1, _2, _3,
                                 client_flow_.sequence_number() + recovery_window,
                                 on_client_out_of_order_callback_));
    server_out_of_order_callback(bind(&Stream::server_recovery_mode_handler, _1, _2, _3,
                                 server_flow_.sequence_number() + recovery_window,
                                 on_server_out_of_order_callback_));
    directions_recovery_mode_enabled_ = 2;
}

bool Stream::is_recovery_mode_enabled() const {
    return directions_recovery_mode_enabled_ > 0;
}

void Stream::on_client_flow_data(const Flow& /*flow*/) {
    if (on_client_data_callback_) {
        on_client_data_callback_(*this);
    }
    if (auto_cleanup_client_) {
        client_payload().clear();
    }
}

void Stream::on_server_flow_data(const Flow& /*flow*/) {
    if (on_server_data_callback_) {
        on_server_data_callback_(*this);
    }
    if (auto_cleanup_server_) {
        server_payload().clear();
    }
}

void Stream::on_client_out_of_order(const Flow& flow, uint32_t seq, const payload_type& payload) {
    if (on_client_out_of_order_callback_) {
        on_client_out_of_order_callback_(*this, seq, payload);
    }
}

void Stream::on_server_out_of_order(const Flow& flow, uint32_t seq, const payload_type& payload) {
    if (on_server_out_of_order_callback_) {
        on_server_out_of_order_callback_(*this, seq, payload);
    }
}

void Stream::client_recovery_mode_handler(Stream& stream, uint32_t sequence_number,
                                          const payload_type& payload,
                                          uint32_t recovery_sequence_number_end,
                                          const stream_packet_callback_type& original_callback) {
    if (!recovery_mode_handler(stream.client_flow(), sequence_number,
                               recovery_sequence_number_end)) {
        stream.client_out_of_order_callback(original_callback);
        stream.directions_recovery_mode_enabled_--;
    }
    if (original_callback) {
        original_callback(stream, sequence_number, payload);
    }
}

void Stream::server_recovery_mode_handler(Stream& stream, uint32_t sequence_number,
                                          const payload_type& payload,
                                          uint32_t recovery_sequence_number_end,
                                          const stream_packet_callback_type& original_callback) {
    if (!recovery_mode_handler(stream.server_flow(), sequence_number,
                               recovery_sequence_number_end)) {
        stream.server_out_of_order_callback(original_callback);
        stream.directions_recovery_mode_enabled_--;
    }
    if (original_callback) {
        original_callback(stream, sequence_number, payload);
    }
}

bool Stream::recovery_mode_handler(Flow& flow, uint32_t sequence_number,
                                   uint32_t recovery_sequence_number_end) {
    // If this packet comes after our sequence number (would create a hole), skip it
    if (sequence_number > flow.sequence_number() &&
        sequence_number <= recovery_sequence_number_end) {
        flow.advance_sequence(sequence_number);
    }
    // Return true iff we need to keep being in recovery mode
    return recovery_sequence_number_end > sequence_number;
}

} // TCPIP
} // Tins

#endif // TINS_HAVE_TCPIP
<commit_msg>Execute original ooo callback first on recovery mode<commit_after>/*
 * Copyright (c) 2016, Matias Fontanini
 * 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.
 *
 * 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 "tcp_ip/stream.h"

#ifdef TINS_HAVE_TCPIP

#include <limits>
#include <algorithm>
#include "memory.h"
#include "ip_address.h"
#include "ipv6_address.h"
#include "tcp.h"
#include "ip.h"
#include "ipv6.h"
#include "ethernetII.h"
#include "rawpdu.h"
#include "exceptions.h"
#include "memory_helpers.h"

using std::make_pair;
using std::bind;
using std::pair;
using std::runtime_error;
using std::numeric_limits;
using std::max;
using std::swap;

using Tins::Memory::OutputMemoryStream;
using Tins::Memory::InputMemoryStream;

namespace Tins {
namespace TCPIP {

Stream::Stream(PDU& packet, const timestamp_type& ts)
: client_flow_(extract_client_flow(packet)),
  server_flow_(extract_server_flow(packet)), create_time_(ts),
  last_seen_(ts), auto_cleanup_client_(true), auto_cleanup_server_(true),
  is_partial_stream_(false), directions_recovery_mode_enabled_(0) {
    const EthernetII* eth = packet.find_pdu<EthernetII>();
    if (eth) {
        client_hw_addr_ = eth->src_addr();
        server_hw_addr_ = eth->dst_addr();
    }
    const TCP& tcp = packet.rfind_pdu<TCP>();
    // If this is not the first packet of a stream (SYN), then it's a partial stream
    is_partial_stream_ = tcp.flags() != TCP::SYN;
}

void Stream::process_packet(PDU& packet, const timestamp_type& ts) {
    last_seen_ = ts;
    if (client_flow_.packet_belongs(packet)) {
        client_flow_.process_packet(packet);
    }
    else if (server_flow_.packet_belongs(packet)) {
        server_flow_.process_packet(packet);
    }
    if (is_finished() && on_stream_closed_) {
        on_stream_closed_(*this);
    }
}

void Stream::process_packet(PDU& packet) {
    return process_packet(packet, timestamp_type(0));
}

Flow& Stream::client_flow() {
    return client_flow_;
}

const Flow& Stream::client_flow() const {
    return client_flow_;
}

Flow& Stream::server_flow() {
    return server_flow_;
}

const Flow& Stream::server_flow() const {
    return server_flow_;
}

void Stream::stream_closed_callback(const stream_callback_type& callback) {
    on_stream_closed_ = callback;
}

void Stream::client_data_callback(const stream_callback_type& callback) {
    on_client_data_callback_ = callback;
}

void Stream::server_data_callback(const stream_callback_type& callback) {
    on_server_data_callback_ = callback;
}

void Stream::client_out_of_order_callback(const stream_packet_callback_type& callback) {
    on_client_out_of_order_callback_ = callback;
}

void Stream::server_out_of_order_callback(const stream_packet_callback_type& callback) {
    on_server_out_of_order_callback_ = callback;
}

void Stream::ignore_client_data() {
    client_flow().ignore_data_packets();
}

void Stream::ignore_server_data() {
    server_flow().ignore_data_packets();
}

bool Stream::is_finished() const {
    const Flow::State client_state = client_flow_.state();
    const Flow::State server_state = server_flow_.state();
    // If either peer sent a RST then the stream is done
    if (client_state == Flow::RST_SENT || server_state == Flow::RST_SENT) {
        return true;
    }
    else {
        // Otherwise, only finish if both sent a FIN
        return client_state == Flow::FIN_SENT && server_state == Flow::FIN_SENT;
    }
}

bool Stream::is_v6() const {
    return server_flow().is_v6();
}

IPv4Address Stream::client_addr_v4() const {
    return server_flow().dst_addr_v4();
}

IPv6Address Stream::client_addr_v6() const {
    return server_flow().dst_addr_v6();
}

const Stream::hwaddress_type& Stream::client_hw_addr() const {
    return client_hw_addr_;
}

const Stream::hwaddress_type& Stream::server_hw_addr() const {
    return server_hw_addr_;
}

IPv4Address Stream::server_addr_v4() const {
    return client_flow().dst_addr_v4();
}

IPv6Address Stream::server_addr_v6() const {
    return client_flow().dst_addr_v6();
}

uint16_t Stream::client_port() const {
    return server_flow().dport();
}

uint16_t Stream::server_port() const {
    return client_flow().dport();
}

const Stream::payload_type& Stream::client_payload() const {
    return client_flow().payload();
}

Stream::payload_type& Stream::client_payload() {
    return client_flow().payload();
}

const Stream::payload_type& Stream::server_payload() const {
    return server_flow().payload();
}

Stream::payload_type& Stream::server_payload() {
    return server_flow().payload();
}

const Stream::timestamp_type& Stream::create_time() const {
    return create_time_;
}

const Stream::timestamp_type& Stream::last_seen() const {
    return last_seen_;
}

Flow Stream::extract_client_flow(const PDU& packet) {
    const TCP* tcp = packet.find_pdu<TCP>();
    if (!tcp) {
        throw invalid_packet();
    }
    if (const IP* ip = packet.find_pdu<IP>()) {
        return Flow(ip->dst_addr(), tcp->dport(), tcp->seq());
    }
    else if (const IPv6* ip = packet.find_pdu<IPv6>()) {
        return Flow(ip->dst_addr(), tcp->dport(), tcp->seq());
    }
    else {
        throw invalid_packet();
    }
}

Flow Stream::extract_server_flow(const PDU& packet) {
    const TCP* tcp = packet.find_pdu<TCP>();
    if (!tcp) {
        throw invalid_packet();
    }
    if (const IP* ip = packet.find_pdu<IP>()) {
        return Flow(ip->src_addr(), tcp->sport(), tcp->ack_seq());
    }
    else if (const IPv6* ip = packet.find_pdu<IPv6>()) {
        return Flow(ip->src_addr(), tcp->sport(), tcp->ack_seq());
    }
    else {
        throw invalid_packet();
    }
}

void Stream::setup_flows_callbacks() {
    using namespace std::placeholders;

    client_flow_.data_callback(bind(&Stream::on_client_flow_data, this, _1));
    server_flow_.data_callback(bind(&Stream::on_server_flow_data, this, _1));
    client_flow_.out_of_order_callback(bind(&Stream::on_client_out_of_order,
                                            this, _1, _2, _3));
    server_flow_.out_of_order_callback(bind(&Stream::on_server_out_of_order,
                                            this, _1, _2, _3));
}

void Stream::auto_cleanup_payloads(bool value) {
    auto_cleanup_client_data(value);
    auto_cleanup_server_data(value);
}

void Stream::auto_cleanup_client_data(bool value) {
    auto_cleanup_client_ = value;
}

void Stream::auto_cleanup_server_data(bool value) {
    auto_cleanup_server_ = value;
}

void Stream::enable_ack_tracking() {
    client_flow().enable_ack_tracking();
    server_flow().enable_ack_tracking();
}

bool Stream::ack_tracking_enabled() const {
    return client_flow().ack_tracking_enabled() && server_flow().ack_tracking_enabled();
}

bool Stream::is_partial_stream() const {
    return is_partial_stream_;
}

void Stream::enable_recovery_mode(uint32_t recovery_window) {
    using namespace std::placeholders;
    client_out_of_order_callback(bind(&Stream::client_recovery_mode_handler, _1, _2, _3,
                                 client_flow_.sequence_number() + recovery_window,
                                 on_client_out_of_order_callback_));
    server_out_of_order_callback(bind(&Stream::server_recovery_mode_handler, _1, _2, _3,
                                 server_flow_.sequence_number() + recovery_window,
                                 on_server_out_of_order_callback_));
    directions_recovery_mode_enabled_ = 2;
}

bool Stream::is_recovery_mode_enabled() const {
    return directions_recovery_mode_enabled_ > 0;
}

void Stream::on_client_flow_data(const Flow& /*flow*/) {
    if (on_client_data_callback_) {
        on_client_data_callback_(*this);
    }
    if (auto_cleanup_client_) {
        client_payload().clear();
    }
}

void Stream::on_server_flow_data(const Flow& /*flow*/) {
    if (on_server_data_callback_) {
        on_server_data_callback_(*this);
    }
    if (auto_cleanup_server_) {
        server_payload().clear();
    }
}

void Stream::on_client_out_of_order(const Flow& flow, uint32_t seq, const payload_type& payload) {
    if (on_client_out_of_order_callback_) {
        on_client_out_of_order_callback_(*this, seq, payload);
    }
}

void Stream::on_server_out_of_order(const Flow& flow, uint32_t seq, const payload_type& payload) {
    if (on_server_out_of_order_callback_) {
        on_server_out_of_order_callback_(*this, seq, payload);
    }
}

void Stream::client_recovery_mode_handler(Stream& stream, uint32_t sequence_number,
                                          const payload_type& payload,
                                          uint32_t recovery_sequence_number_end,
                                          const stream_packet_callback_type& original_callback) {
    if (original_callback) {
        original_callback(stream, sequence_number, payload);
    }
    if (!recovery_mode_handler(stream.client_flow(), sequence_number,
                               recovery_sequence_number_end)) {
        stream.directions_recovery_mode_enabled_--;
        stream.client_out_of_order_callback(original_callback);
    }
}

void Stream::server_recovery_mode_handler(Stream& stream, uint32_t sequence_number,
                                          const payload_type& payload,
                                          uint32_t recovery_sequence_number_end,
                                          const stream_packet_callback_type& original_callback) {
    if (original_callback) {
        original_callback(stream, sequence_number, payload);
    }
    if (!recovery_mode_handler(stream.server_flow(), sequence_number,
                               recovery_sequence_number_end)) {
        stream.directions_recovery_mode_enabled_--;
        stream.server_out_of_order_callback(original_callback);
    }
}

bool Stream::recovery_mode_handler(Flow& flow, uint32_t sequence_number,
                                   uint32_t recovery_sequence_number_end) {
    // If this packet comes after our sequence number (would create a hole), skip it
    if (sequence_number > flow.sequence_number() &&
        sequence_number <= recovery_sequence_number_end) {
        flow.advance_sequence(sequence_number);
    }
    // Return true iff we need to keep being in recovery mode
    return recovery_sequence_number_end > sequence_number;
}

} // TCPIP
} // Tins

#endif // TINS_HAVE_TCPIP
<|endoftext|>


<commit_before>#include <chrono>
#include <cinttypes>
#include <memory>
#include <rclcpp/rclcpp.hpp>
#include "myworkcell_core/srv/localize_part.hpp"

// The ScanNPlan inherits from node, allowing it to act as a Node to do things like create clients
class ScanNPlan : public rclcpp::Node
{
public:
  explicit ScanNPlan()
  : Node("scan_n_plan")
  {
    vision_client_ = this->create_client<myworkcell_core::srv::LocalizePart>("localize_part");
  }

  void start(const std::string& base_frame)
  {
    // Need to wait until vision node has data
    rclcpp::Rate rate(std::chrono::duration<int, std::milli>(1000));
    rate.sleep();

    RCLCPP_INFO(this->get_logger(), "Attempting to localize part in frame: %s", base_frame.c_str());

    // The vision client needs to wait until the service appears
    while (!vision_client_->wait_for_service(std::chrono::duration<int, std::milli>(500))) {
      if (!rclcpp::ok()) {
        RCLCPP_ERROR(this->get_logger(), "client interrupted while waiting for service to appear.");
        return;
      }
      RCLCPP_INFO(this->get_logger(), "waiting for service to appear...");
    }

    // Create a request for the LocalizePart service call
    auto request = std::make_shared<myworkcell_core::srv::LocalizePart::Request>();
    // The base_frame that is passed in is used to fill the request
    request->base_frame = base_frame;

    using ServiceResponseFuture =
      rclcpp::Client<myworkcell_core::srv::LocalizePart>::SharedFuture; //holds results of async call

    auto response_received_callback = [this](ServiceResponseFuture future) {
        auto result = future.get();
        RCLCPP_INFO(this->get_logger(), "Part Localized:  w: %f, x: %f, y: %f, z: %f",
                                      result->pose.orientation.w,
                                      result->pose.position.x,
                                      result->pose.position.y,
                                      result->pose.position.z);
        rclcpp::shutdown();
      };

    auto future = vision_client_->async_send_request(request, response_received_callback);

    //auto larry = rclcpp::Node::get_node_base_interface();
    rclcpp::spin(rclcpp::Node::get_node_base_interface()); //this needs to be tested
    }

private:
  //
  rclcpp::Client<myworkcell_core::srv::LocalizePart>::SharedPtr vision_client_;

};

int main(int argc, char **argv)
{
  // This must be called before anything else ROS-related
  rclcpp::init(argc, argv);

  // Create the ScanNPlan object and node
  auto app = std::make_shared<ScanNPlan>();

  // Create client to get parameters
  auto parameters_client = std::make_shared<rclcpp::SyncParametersClient>(app);

  // String to store the base_frame parameter after getting it from the Node's parameter client
  std::string base_frame;
  app->declare_parameter("base_frame");
  app->get_parameter("base_frame", base_frame);

  RCLCPP_INFO(app->get_logger(), "ScanNPlan node has been initialized");

  // Call the vision client's LocalizePart service using base_frame as a parameter
  app->start(base_frame);
  // Spin on the node so we don't exit the program
  rclcpp::spin(app);
  rclcpp::shutdown();
  return 0;
}
<commit_msg>Add spin on node base interface inside start<commit_after>#include <chrono>
#include <cinttypes>
#include <memory>
#include <rclcpp/rclcpp.hpp>
#include "myworkcell_core/srv/localize_part.hpp"

// The ScanNPlan inherits from node, allowing it to act as a Node to do things like create clients
class ScanNPlan : public rclcpp::Node
{
public:
  explicit ScanNPlan()
  : Node("scan_n_plan")
  {
    vision_client_ = this->create_client<myworkcell_core::srv::LocalizePart>("localize_part");
  }

  void start(const std::string& base_frame)
  {
    // Need to wait until vision node has data
    rclcpp::Rate rate(std::chrono::duration<int, std::milli>(1000));
    rate.sleep();

    RCLCPP_INFO(this->get_logger(), "Attempting to localize part in frame: %s", base_frame.c_str());

    // The vision client needs to wait until the service appears
    while (!vision_client_->wait_for_service(std::chrono::duration<int, std::milli>(500))) {
      if (!rclcpp::ok()) {
        RCLCPP_ERROR(this->get_logger(), "client interrupted while waiting for service to appear.");
        return;
      }
      RCLCPP_INFO(this->get_logger(), "waiting for service to appear...");
    }

    // Create a request for the LocalizePart service call
    auto request = std::make_shared<myworkcell_core::srv::LocalizePart::Request>();
    // The base_frame that is passed in is used to fill the request
    request->base_frame = base_frame;

    using ServiceResponseFuture =
      rclcpp::Client<myworkcell_core::srv::LocalizePart>::SharedFuture; //holds results of async call

    auto response_received_callback = [this](ServiceResponseFuture future) {
        auto result = future.get();
        RCLCPP_INFO(this->get_logger(), "Part Localized:  w: %f, x: %f, y: %f, z: %f",
                                      result->pose.orientation.w,
                                      result->pose.position.x,
                                      result->pose.position.y,
                                      result->pose.position.z);
        rclcpp::shutdown();
      };

    auto future = vision_client_->async_send_request(request, response_received_callback);

    // Make sure node doesn't exit using the node interface to spin
    rclcpp::spin(rclcpp::Node::get_node_base_interface());
    }

private:
  //
  rclcpp::Client<myworkcell_core::srv::LocalizePart>::SharedPtr vision_client_;

};

int main(int argc, char **argv)
{
  // This must be called before anything else ROS-related
  rclcpp::init(argc, argv);

  // Create the ScanNPlan object and node
  auto app = std::make_shared<ScanNPlan>();

  // Create client to get parameters
  auto parameters_client = std::make_shared<rclcpp::SyncParametersClient>(app);

  // String to store the base_frame parameter after getting it from the Node's parameter client
  std::string base_frame;
  app->declare_parameter("base_frame");
  app->get_parameter("base_frame", base_frame);

  RCLCPP_INFO(app->get_logger(), "ScanNPlan node has been initialized");

  // Call the vision client's LocalizePart service using base_frame as a parameter
  app->start(base_frame);
  rclcpp::shutdown();
  return 0;
}
<|endoftext|>