<commit_before>/*
This file is part of cpp-ethereum.

cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file whisperMessage.cpp
* @author Vladislav Gluhovsky <vlad@ethdev.com>
* @date June 2015
*/

#include <boost/test/unit_test.hpp>
#include <libdevcore/SHA3.h>
#include <libwhisper/BloomFilter.h>

using namespace std;
using namespace dev;
using namespace dev::shh;

using TopicBloomFilterShort = TopicBloomFilterBase<4>;
using TopicBloomFilterTest = TopicBloomFilterBase<c_topicBloomFilterSize>;

void testAddNonExisting(TopicBloomFilterShort& _f, AbridgedTopic const& _h)
{
	BOOST_REQUIRE(!_f.containsRaw(_h));
	_f.addRaw(_h);
	BOOST_REQUIRE(_f.containsRaw(_h));
}

void testRemoveExisting(TopicBloomFilterShort& _f, AbridgedTopic const& _h)
{
	BOOST_REQUIRE(_f.containsRaw(_h));
	_f.removeRaw(_h);
	BOOST_REQUIRE(!_f.containsRaw(_h));
}

void testAddNonExistingBloom(TopicBloomFilterShort& _f, AbridgedTopic const& _h)
{
	BOOST_REQUIRE(!_f.containsBloom(_h));
	_f.addBloom(_h);
	BOOST_REQUIRE(_f.containsBloom(_h));
}

void testRemoveExistingBloom(TopicBloomFilterShort& _f, AbridgedTopic const& _h)
{
	BOOST_REQUIRE(_f.containsBloom(_h));
	_f.removeBloom(_h);
	BOOST_REQUIRE(!_f.containsBloom(_h));
}

double calculateExpected(TopicBloomFilterTest const& f, int n)
{
	int const m = f.size * 8; // number of bits in the bloom
	int const k = f.BitsPerBloom; // number of hash functions (e.g. bits set to 1 in every bloom)

	double singleBitSet = 1.0 / m; // probability of any bit being set after inserting a single bit
	double singleBitNotSet = (1.0 - singleBitSet);

	double singleNot = 1; // single bit not set after inserting N elements in the bloom filter
	for (int i = 0; i < k * n; ++i)
		singleNot *= singleBitNotSet;

	double single = 1.0 - singleNot; // probability of a single bit being set after inserting N elements in the bloom filter

	double kBitsSet = 1; // probability of K bits being set after inserting N elements in the bloom filter
	for (int i = 0; i < k; ++i)
		kBitsSet *= single;

	return kBitsSet;
}

double testFalsePositiveRate(TopicBloomFilterTest const& f, int inserted, Topic& x)
{
	int const c_sampleSize = 1000;
	int falsePositive = 0;

	for (int i = 0; i < c_sampleSize; ++i)
	{
		x = sha3(x);
		AbridgedTopic a(x);
		if (f.containsBloom(a))
			++falsePositive;
	}

	double res = double(falsePositive) / double(c_sampleSize);

	double expected = calculateExpected(f, inserted);
	double allowed = expected * 1.2 + 0.05; // allow deviations ~25%

	//cnote << "Inserted: " << inserted << ", False Positive Rate: " << res << ", Expected: " << expected;
	BOOST_REQUIRE(res <= allowed);
	return expected;
}

BOOST_AUTO_TEST_SUITE(bloomFilter)

BOOST_AUTO_TEST_CASE(falsePositiveRate)
{
	VerbosityHolder setTemporaryLevel(10);
	cnote << "Testing Bloom Filter False Positive Rate...";

	TopicBloomFilterTest f;
	Topic x(0xC0DEFEED); // deterministic pseudorandom value

	double expectedRate = 0;

	for (int i = 1; i < 50 && isless(expectedRate, 0.5); ++i)
	{
		x = sha3(x);
		f.addBloom(AbridgedTopic(x));
		expectedRate = testFalsePositiveRate(f, i, x);
	}
}

BOOST_AUTO_TEST_CASE(bloomFilterRandom)
{
	VerbosityHolder setTemporaryLevel(10);
	cnote << "Testing Bloom Filter matching...";

	TopicBloomFilterShort f;
	vector<AbridgedTopic> vec;
	Topic x(0xDEADBEEF);
	int const c_rounds = 4;

	for (int i = 0; i < c_rounds; ++i, x = sha3(x))
		vec.push_back(abridge(x));

	for (int i = 0; i < c_rounds; ++i)
		testAddNonExisting(f, vec[i]);

	for (int i = 0; i < c_rounds; ++i)
		testRemoveExisting(f, vec[i]);

	for (int i = 0; i < c_rounds; ++i)
		testAddNonExistingBloom(f, vec[i]);

	for (int i = 0; i < c_rounds; ++i)
		testRemoveExistingBloom(f, vec[i]);
}

BOOST_AUTO_TEST_CASE(bloomFilterRaw)
{
	VerbosityHolder setTemporaryLevel(10);
	cnote << "Testing Raw Bloom matching...";

	TopicBloomFilterShort f;

	AbridgedTopic b00000001(0x01);
	AbridgedTopic b00010000(0x10);
	AbridgedTopic b00011000(0x18);
	AbridgedTopic b00110000(0x30);
	AbridgedTopic b00110010(0x32);
	AbridgedTopic b00111000(0x38);
	AbridgedTopic b00000110(0x06);
	AbridgedTopic b00110110(0x36);
	AbridgedTopic b00110111(0x37);

	testAddNonExisting(f, b00000001);
	testAddNonExisting(f, b00010000);
	testAddNonExisting(f, b00011000);
	testAddNonExisting(f, b00110000);
	BOOST_REQUIRE(f.contains(b00111000));
	testAddNonExisting(f, b00110010);
	testAddNonExisting(f, b00000110);
	BOOST_REQUIRE(f.contains(b00110110));
	BOOST_REQUIRE(f.contains(b00110111));

	f.removeRaw(b00000001);
	f.removeRaw(b00000001);
	f.removeRaw(b00000001);
	BOOST_REQUIRE(!f.contains(b00000001));
	BOOST_REQUIRE(f.contains(b00010000));
	BOOST_REQUIRE(f.contains(b00011000));
	BOOST_REQUIRE(f.contains(b00110000));
	BOOST_REQUIRE(f.contains(b00110010));
	BOOST_REQUIRE(f.contains(b00111000));
	BOOST_REQUIRE(f.contains(b00000110));
	BOOST_REQUIRE(f.contains(b00110110));
	BOOST_REQUIRE(!f.contains(b00110111));

	f.removeRaw(b00010000);
	BOOST_REQUIRE(!f.contains(b00000001));
	BOOST_REQUIRE(f.contains(b00010000));
	BOOST_REQUIRE(f.contains(b00011000));
	BOOST_REQUIRE(f.contains(b00110000));
	BOOST_REQUIRE(f.contains(b00110010));
	BOOST_REQUIRE(f.contains(b00111000));
	BOOST_REQUIRE(f.contains(b00000110));
	BOOST_REQUIRE(f.contains(b00110110));
	BOOST_REQUIRE(!f.contains(b00110111));

	f.removeRaw(b00111000);
	BOOST_REQUIRE(!f.contains(b00000001));
	BOOST_REQUIRE(f.contains(b00010000));
	BOOST_REQUIRE(!f.contains(b00011000));
	BOOST_REQUIRE(f.contains(b00110000));
	BOOST_REQUIRE(f.contains(b00110010));
	BOOST_REQUIRE(!f.contains(b00111000));
	BOOST_REQUIRE(f.contains(b00000110));
	BOOST_REQUIRE(f.contains(b00110110));
	BOOST_REQUIRE(!f.contains(b00110111));

	f.addRaw(b00000001);
	BOOST_REQUIRE(f.contains(b00000001));
	BOOST_REQUIRE(f.contains(b00010000));
	BOOST_REQUIRE(!f.contains(b00011000));
	BOOST_REQUIRE(f.contains(b00110000));
	BOOST_REQUIRE(f.contains(b00110010));
	BOOST_REQUIRE(!f.contains(b00111000));
	BOOST_REQUIRE(f.contains(b00000110));
	BOOST_REQUIRE(f.contains(b00110110));
	BOOST_REQUIRE(f.contains(b00110111));

	f.removeRaw(b00110111);
	BOOST_REQUIRE(!f.contains(b00000001));
	BOOST_REQUIRE(f.contains(b00010000));
	BOOST_REQUIRE(!f.contains(b00011000));
	BOOST_REQUIRE(!f.contains(b00110000));
	BOOST_REQUIRE(!f.contains(b00110010));
	BOOST_REQUIRE(!f.contains(b00111000));
	BOOST_REQUIRE(!f.contains(b00000110));
	BOOST_REQUIRE(!f.contains(b00110110));
	BOOST_REQUIRE(!f.contains(b00110111));

	f.removeRaw(b00110111);
	BOOST_REQUIRE(!f.contains(b00000001));
	BOOST_REQUIRE(!f.contains(b00010000));
	BOOST_REQUIRE(!f.contains(b00011000));
	BOOST_REQUIRE(!f.contains(b00110000));
	BOOST_REQUIRE(!f.contains(b00110010));
	BOOST_REQUIRE(!f.contains(b00111000));
	BOOST_REQUIRE(!f.contains(b00000110));
	BOOST_REQUIRE(!f.contains(b00110110));
	BOOST_REQUIRE(!f.contains(b00110111));
}

static const unsigned DistributionTestSize = 8;

void updateDistribution(FixedHash<DistributionTestSize> const& _h, unsigned* _distribution)
{
	unsigned bits = 0;
	for (unsigned i = 0; i < DistributionTestSize; ++i)
		if (_h[i])
			for (unsigned j = 0; j < 8; ++j)
				if (_h[i] & c_powerOfTwoBitMmask[j])
				{
					_distribution[i * 8 + j]++;
					if (++bits >= TopicBloomFilterTest::BitsPerBloom)
						return;
				}
}

BOOST_AUTO_TEST_CASE(distributionRate)
{
	cnote << "Testing Bloom Filter Distribution Rate...";

	unsigned const c_arrSize = DistributionTestSize * 8;
	unsigned distribution[c_arrSize];
	memset(distribution, 0, c_arrSize * sizeof(unsigned));
	Topic x(0xC0FFEE); // deterministic pseudorandom value

	for (unsigned i = 0; i < 22000; ++i)
	{
		x = sha3(x);
		FixedHash<DistributionTestSize> h = x.template bloomPart<TopicBloomFilterTest::BitsPerBloom, DistributionTestSize>();
		updateDistribution(h, distribution);
	}

	unsigned average = 0;
	for (unsigned i = 0; i < c_arrSize; ++i)
		average += distribution[i];

	average /= c_arrSize;
	unsigned deviation = average / 10; // approx. 10%
	unsigned maxAllowed = average + deviation;
	unsigned minAllowed = average - deviation;

	for (unsigned i = 0; i < c_arrSize; ++i)
	{
		//cnote << i << ":" << distribution[i];
		BOOST_REQUIRE(distribution[i] > minAllowed);
		BOOST_REQUIRE(distribution[i] < maxAllowed);
	}
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>super mega enhanced update<commit_after>/*
This file is part of cpp-ethereum.

cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file whisperMessage.cpp
* @author Vladislav Gluhovsky <vlad@ethdev.com>
* @date June 2015
*/

#include <boost/test/unit_test.hpp>
#include <libdevcore/SHA3.h>
#include <libwhisper/BloomFilter.h>

using namespace std;
using namespace dev;
using namespace dev::shh;

using TopicBloomFilterShort = TopicBloomFilterBase<4>;
using TopicBloomFilterTest = TopicBloomFilterBase<c_topicBloomFilterSize>;

void testAddNonExisting(TopicBloomFilterShort& _f, AbridgedTopic const& _h)
{
	BOOST_REQUIRE(!_f.containsRaw(_h));
	_f.addRaw(_h);
	BOOST_REQUIRE(_f.containsRaw(_h));
}

void testRemoveExisting(TopicBloomFilterShort& _f, AbridgedTopic const& _h)
{
	BOOST_REQUIRE(_f.containsRaw(_h));
	_f.removeRaw(_h);
	BOOST_REQUIRE(!_f.containsRaw(_h));
}

void testAddNonExistingBloom(TopicBloomFilterShort& _f, AbridgedTopic const& _h)
{
	BOOST_REQUIRE(!_f.containsBloom(_h));
	_f.addBloom(_h);
	BOOST_REQUIRE(_f.containsBloom(_h));
}

void testRemoveExistingBloom(TopicBloomFilterShort& _f, AbridgedTopic const& _h)
{
	BOOST_REQUIRE(_f.containsBloom(_h));
	_f.removeBloom(_h);
	BOOST_REQUIRE(!_f.containsBloom(_h));
}

double calculateExpected(TopicBloomFilterTest const& f, int n)
{
	int const m = f.size * 8; // number of bits in the bloom
	int const k = f.BitsPerBloom; // number of hash functions (e.g. bits set to 1 in every bloom)

	double singleBitSet = 1.0 / m; // probability of any bit being set after inserting a single bit
	double singleBitNotSet = (1.0 - singleBitSet);

	double singleNot = 1; // single bit not set after inserting N elements in the bloom filter
	for (int i = 0; i < k * n; ++i)
		singleNot *= singleBitNotSet;

	double single = 1.0 - singleNot; // probability of a single bit being set after inserting N elements in the bloom filter

	double kBitsSet = 1; // probability of K bits being set after inserting N elements in the bloom filter
	for (int i = 0; i < k; ++i)
		kBitsSet *= single;

	return kBitsSet;
}

double testFalsePositiveRate(TopicBloomFilterTest const& f, int inserted, Topic& x)
{
	int const c_sampleSize = 1000;
	int falsePositive = 0;

	for (int i = 0; i < c_sampleSize; ++i)
	{
		x = sha3(x);
		AbridgedTopic a(x);
		if (f.containsBloom(a))
			++falsePositive;
	}

	double res = double(falsePositive) / double(c_sampleSize);

	double expected = calculateExpected(f, inserted);
	double allowed = expected * 1.2 + 0.05; // allow deviations ~25%

	//cnote << "Inserted: " << inserted << ", False Positive Rate: " << res << ", Expected: " << expected;
	BOOST_REQUIRE(res <= allowed);
	return expected;
}

BOOST_AUTO_TEST_SUITE(bloomFilter)

BOOST_AUTO_TEST_CASE(falsePositiveRate)
{
	VerbosityHolder setTemporaryLevel(10);
	cnote << "Testing Bloom Filter False Positive Rate...";

	TopicBloomFilterTest f;
	Topic x(0xC0DEFEED); // deterministic pseudorandom value

	double expectedRate = 0;

	for (int i = 1; i < 50 && isless(expectedRate, 0.5); ++i)
	{
		x = sha3(x);
		f.addBloom(AbridgedTopic(x));
		expectedRate = testFalsePositiveRate(f, i, x);
	}
}

BOOST_AUTO_TEST_CASE(bloomFilterRandom)
{
	VerbosityHolder setTemporaryLevel(10);
	cnote << "Testing Bloom Filter matching...";

	TopicBloomFilterShort f;
	vector<AbridgedTopic> vec;
	Topic x(0xDEADBEEF);
	int const c_rounds = 4;

	for (int i = 0; i < c_rounds; ++i, x = sha3(x))
		vec.push_back(abridge(x));

	for (int i = 0; i < c_rounds; ++i)
		testAddNonExisting(f, vec[i]);

	for (int i = 0; i < c_rounds; ++i)
		testRemoveExisting(f, vec[i]);

	for (int i = 0; i < c_rounds; ++i)
		testAddNonExistingBloom(f, vec[i]);

	for (int i = 0; i < c_rounds; ++i)
		testRemoveExistingBloom(f, vec[i]);
}

BOOST_AUTO_TEST_CASE(bloomFilterRaw)
{
	VerbosityHolder setTemporaryLevel(10);
	cnote << "Testing Raw Bloom matching...";

	TopicBloomFilterShort f;

	AbridgedTopic b00000001(0x01);
	AbridgedTopic b00010000(0x10);
	AbridgedTopic b00011000(0x18);
	AbridgedTopic b00110000(0x30);
	AbridgedTopic b00110010(0x32);
	AbridgedTopic b00111000(0x38);
	AbridgedTopic b00000110(0x06);
	AbridgedTopic b00110110(0x36);
	AbridgedTopic b00110111(0x37);

	testAddNonExisting(f, b00000001);
	testAddNonExisting(f, b00010000);
	testAddNonExisting(f, b00011000);
	testAddNonExisting(f, b00110000);
	BOOST_REQUIRE(f.contains(b00111000));
	testAddNonExisting(f, b00110010);
	testAddNonExisting(f, b00000110);
	BOOST_REQUIRE(f.contains(b00110110));
	BOOST_REQUIRE(f.contains(b00110111));

	f.removeRaw(b00000001);
	f.removeRaw(b00000001);
	f.removeRaw(b00000001);
	BOOST_REQUIRE(!f.contains(b00000001));
	BOOST_REQUIRE(f.contains(b00010000));
	BOOST_REQUIRE(f.contains(b00011000));
	BOOST_REQUIRE(f.contains(b00110000));
	BOOST_REQUIRE(f.contains(b00110010));
	BOOST_REQUIRE(f.contains(b00111000));
	BOOST_REQUIRE(f.contains(b00000110));
	BOOST_REQUIRE(f.contains(b00110110));
	BOOST_REQUIRE(!f.contains(b00110111));

	f.removeRaw(b00010000);
	BOOST_REQUIRE(!f.contains(b00000001));
	BOOST_REQUIRE(f.contains(b00010000));
	BOOST_REQUIRE(f.contains(b00011000));
	BOOST_REQUIRE(f.contains(b00110000));
	BOOST_REQUIRE(f.contains(b00110010));
	BOOST_REQUIRE(f.contains(b00111000));
	BOOST_REQUIRE(f.contains(b00000110));
	BOOST_REQUIRE(f.contains(b00110110));
	BOOST_REQUIRE(!f.contains(b00110111));

	f.removeRaw(b00111000);
	BOOST_REQUIRE(!f.contains(b00000001));
	BOOST_REQUIRE(f.contains(b00010000));
	BOOST_REQUIRE(!f.contains(b00011000));
	BOOST_REQUIRE(f.contains(b00110000));
	BOOST_REQUIRE(f.contains(b00110010));
	BOOST_REQUIRE(!f.contains(b00111000));
	BOOST_REQUIRE(f.contains(b00000110));
	BOOST_REQUIRE(f.contains(b00110110));
	BOOST_REQUIRE(!f.contains(b00110111));

	f.addRaw(b00000001);
	BOOST_REQUIRE(f.contains(b00000001));
	BOOST_REQUIRE(f.contains(b00010000));
	BOOST_REQUIRE(!f.contains(b00011000));
	BOOST_REQUIRE(f.contains(b00110000));
	BOOST_REQUIRE(f.contains(b00110010));
	BOOST_REQUIRE(!f.contains(b00111000));
	BOOST_REQUIRE(f.contains(b00000110));
	BOOST_REQUIRE(f.contains(b00110110));
	BOOST_REQUIRE(f.contains(b00110111));

	f.removeRaw(b00110111);
	BOOST_REQUIRE(!f.contains(b00000001));
	BOOST_REQUIRE(f.contains(b00010000));
	BOOST_REQUIRE(!f.contains(b00011000));
	BOOST_REQUIRE(!f.contains(b00110000));
	BOOST_REQUIRE(!f.contains(b00110010));
	BOOST_REQUIRE(!f.contains(b00111000));
	BOOST_REQUIRE(!f.contains(b00000110));
	BOOST_REQUIRE(!f.contains(b00110110));
	BOOST_REQUIRE(!f.contains(b00110111));

	f.removeRaw(b00110111);
	BOOST_REQUIRE(!f.contains(b00000001));
	BOOST_REQUIRE(!f.contains(b00010000));
	BOOST_REQUIRE(!f.contains(b00011000));
	BOOST_REQUIRE(!f.contains(b00110000));
	BOOST_REQUIRE(!f.contains(b00110010));
	BOOST_REQUIRE(!f.contains(b00111000));
	BOOST_REQUIRE(!f.contains(b00000110));
	BOOST_REQUIRE(!f.contains(b00110110));
	BOOST_REQUIRE(!f.contains(b00110111));
}

static const unsigned DistributionTestSize = 8;
static const unsigned TestArrSize = 8 * DistributionTestSize;

void updateDistribution(FixedHash<DistributionTestSize> const& _h, array<unsigned, TestArrSize>& _distribution)
{
	unsigned bits = 0;
	for (unsigned i = 0; i < DistributionTestSize; ++i)
		if (_h[i])
			for (unsigned j = 0; j < 8; ++j)
				if (_h[i] & c_powerOfTwoBitMmask[j])
				{
					_distribution[i * 8 + j]++;
					if (++bits >= TopicBloomFilterTest::BitsPerBloom)
						return;
				}
}

BOOST_AUTO_TEST_CASE(distributionRate)
{
	cnote << "Testing Bloom Filter Distribution Rate...";

	array<unsigned, TestArrSize> distribution;
	for (unsigned i = 0; i < TestArrSize; ++i)
		distribution[i] = 0;

	Topic x(0xC0FFEE); // deterministic pseudorandom value

	for (unsigned i = 0; i < 22000; ++i)
	{
		x = sha3(x);
		FixedHash<DistributionTestSize> h = x.template bloomPart<TopicBloomFilterTest::BitsPerBloom, DistributionTestSize>();
		updateDistribution(h, distribution);
	}

	unsigned average = 0;
	for (unsigned i = 0; i < TestArrSize; ++i)
		average += distribution[i];

	average /= TestArrSize;
	unsigned deviation = average / 10; // approx. 10%
	unsigned maxAllowed = average + deviation;
	unsigned minAllowed = average - deviation;

	for (unsigned i = 0; i < TestArrSize; ++i)
	{
		//cnote << i << ":" << distribution[i];
		BOOST_REQUIRE(distribution[i] > minAllowed);
		BOOST_REQUIRE(distribution[i] < maxAllowed);
	}
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include <gtest/gtest.h>

#include <string>

#include "magic_xattr.h"
#include "mountpoint.h"
#include "options.h"
#include "testutil.h"
#include "util/posix.h"
#include "uuid.h"

class T_MagicXattr : public ::testing::Test {
 protected:
  virtual void SetUp() {
    repo_path_ = "repo";
    uuid_dummy_ = cvmfs::Uuid::Create("");
    used_fds_ = GetNoUsedFds();
    fd_cwd_ = open(".", O_RDONLY);
    ASSERT_GE(fd_cwd_, 0);
    tmp_path_ = CreateTempDir("./cvmfs_ut_cache");
    options_mgr_.SetValue("CVMFS_CACHE_BASE", tmp_path_);
    options_mgr_.SetValue("CVMFS_SHARED_CACHE", "no");
    options_mgr_.SetValue("CVMFS_MAX_RETRIES", "0");
    fs_info_.name = "unit-test";
    fs_info_.options_mgr = &options_mgr_;
    // Silence syslog error
    options_mgr_.SetValue("CVMFS_MOUNT_DIR", "/no/such/dir");
    file_system_ = FileSystem::Create(fs_info_);
    mount_point_ = MountPoint::Create("keys.cern.ch", file_system_);
  }

  virtual void TearDown() {
    delete mount_point_;
    delete file_system_;
    delete uuid_dummy_;
    int retval = fchdir(fd_cwd_);
    ASSERT_EQ(0, retval);
    close(fd_cwd_);
    if (tmp_path_ != "")
      RemoveTree(tmp_path_);
    if (repo_path_ != "")
      RemoveTree(repo_path_);
  }

  MountPoint *mount_point_;
  FileSystem *file_system_;

  FileSystem::FileSystemInfo fs_info_;
  SimpleOptionsParser options_mgr_;
  std::string tmp_path_;
  std::string repo_path_;
  int fd_cwd_;
  unsigned used_fds_;
  /**
   * Initialize libuuid / open file descriptor on /dev/urandom
   */
  cvmfs::Uuid *uuid_dummy_;
};

TEST_F(T_MagicXattr, TestFqrn) {
  MagicXattrManager *mgr =
    new MagicXattrManager(mount_point_, MagicXattrManager::kVisibilityAlways);

  catalog::DirectoryEntry dirent =
    catalog::DirectoryEntryTestFactory::ExternalFile();
  PathString path("/asdf");
  MagicXattrRAIIWrapper attr(mgr->GetLocked("user.fqrn", path, &dirent));
  ASSERT_FALSE(attr.IsNull());
  ASSERT_TRUE(attr->PrepareValueFenced());
  EXPECT_STREQ("keys.cern.ch", attr->GetValue().c_str());
}

TEST_F(T_MagicXattr, HideAttributes) {
  shash::Any hash;
  catalog::DirectoryEntry dirent_name =
    catalog::DirectoryEntryTestFactory::RegularFile("name", 42, hash);
  catalog::DirectoryEntry dirent_root =
    catalog::DirectoryEntryTestFactory::Directory();

  MagicXattrManager *mgr =
    new MagicXattrManager(mount_point_, MagicXattrManager::kVisibilityNever);
  std::string list = mgr->GetListString(&dirent_name);
  EXPECT_EQ(0U, list.length());
  list = mgr->GetListString(&dirent_root);
  EXPECT_EQ(0U, list.length());

  MagicXattrManager *mgr2 =
    new MagicXattrManager(mount_point_, MagicXattrManager::kVisibilityRootOnly);
  list = mgr2->GetListString(&dirent_name);
  EXPECT_EQ(0U, list.length());
  list = mgr->GetListString(&dirent_root);
  EXPECT_GT(0U, list.length());
}
<commit_msg>Fix up xattr unit test<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include <gtest/gtest.h>

#include <string>

#include "magic_xattr.h"
#include "mountpoint.h"
#include "options.h"
#include "testutil.h"
#include "util/posix.h"
#include "uuid.h"

class T_MagicXattr : public ::testing::Test {
 protected:
  virtual void SetUp() {
    repo_path_ = "repo";
    uuid_dummy_ = cvmfs::Uuid::Create("");
    used_fds_ = GetNoUsedFds();
    fd_cwd_ = open(".", O_RDONLY);
    ASSERT_GE(fd_cwd_, 0);
    tmp_path_ = CreateTempDir("./cvmfs_ut_cache");
    options_mgr_.SetValue("CVMFS_CACHE_BASE", tmp_path_);
    options_mgr_.SetValue("CVMFS_SHARED_CACHE", "no");
    options_mgr_.SetValue("CVMFS_MAX_RETRIES", "0");
    fs_info_.name = "unit-test";
    fs_info_.options_mgr = &options_mgr_;
    // Silence syslog error
    options_mgr_.SetValue("CVMFS_MOUNT_DIR", "/no/such/dir");
    file_system_ = FileSystem::Create(fs_info_);
    mount_point_ = MountPoint::Create("keys.cern.ch", file_system_);
  }

  virtual void TearDown() {
    delete mount_point_;
    delete file_system_;
    delete uuid_dummy_;
    int retval = fchdir(fd_cwd_);
    ASSERT_EQ(0, retval);
    close(fd_cwd_);
    if (tmp_path_ != "")
      RemoveTree(tmp_path_);
    if (repo_path_ != "")
      RemoveTree(repo_path_);
  }

  MountPoint *mount_point_;
  FileSystem *file_system_;

  FileSystem::FileSystemInfo fs_info_;
  SimpleOptionsParser options_mgr_;
  std::string tmp_path_;
  std::string repo_path_;
  int fd_cwd_;
  unsigned used_fds_;
  /**
   * Initialize libuuid / open file descriptor on /dev/urandom
   */
  cvmfs::Uuid *uuid_dummy_;
};

TEST_F(T_MagicXattr, TestFqrn) {
  MagicXattrManager *mgr =
    new MagicXattrManager(mount_point_, MagicXattrManager::kVisibilityAlways);

  catalog::DirectoryEntry dirent =
    catalog::DirectoryEntryTestFactory::ExternalFile();
  PathString path("/asdf");
  MagicXattrRAIIWrapper attr(mgr->GetLocked("user.fqrn", path, &dirent));
  ASSERT_FALSE(attr.IsNull());
  ASSERT_TRUE(attr->PrepareValueFenced());
  EXPECT_STREQ("keys.cern.ch", attr->GetValue().c_str());
}

TEST_F(T_MagicXattr, HideAttributes) {
  catalog::DirectoryEntry dirent_name =
    catalog::DirectoryEntryTestFactory::RegularFile("name", 42, shash::Any());
  catalog::DirectoryEntry dirent_root =
    catalog::DirectoryEntryTestFactory::Directory();

  MagicXattrManager *mgr_never =
    new MagicXattrManager(mount_point_, MagicXattrManager::kVisibilityNever);
  std::string list = mgr_never->GetListString(&dirent_name);
  EXPECT_EQ(0U, list.length());
  list = mgr_never->GetListString(&dirent_root);
  EXPECT_EQ(0U, list.length());

  MagicXattrManager *mgr_rootonly =
    new MagicXattrManager(mount_point_, MagicXattrManager::kVisibilityRootOnly);
  list = mgr_rootonly->GetListString(&dirent_name);
  EXPECT_EQ(0U, list.length());
  list = mgr_rootonly->GetListString(&dirent_root);
  EXPECT_LT(0U, list.length());
}
<|endoftext|>


<commit_before>
#include "messagepub.hpp"
#include "../../include/componentpack.hpp"

using namespace std;

COMPONENT_INSTANCE(messagepub)
COMPONENT_CREATE(messagepub)
COMPONENT_DESTROY

messagepub::messagepub()
:icomponent(COMPONENT(messagepub)){
	// TODO Auto-generated constructor stub

}

messagepub::~messagepub() {
	destroy_task(_pub_task);
}

bool messagepub::setup()
{
	cossb_log->log(cossb::log::loglevel::INFO, "called messagepub setup");
	cossb_broker->regist(this, "service/helloworld");
	return true;
}
bool messagepub::run()
{
	if(!_pub_task)
		_pub_task = create_task(messagepub::pub);
	return true;
}
bool messagepub::stop()
{
	cossb_log->log(cossb::log::loglevel::INFO, "stop messagepub task");
	destroy_task(_pub_task);
	return true;
}
void messagepub::request(cossb::message::message* msg)
{
	cossb_log->log(cossb::log::loglevel::INFO, "received message");
}

void messagepub::pub()
{
	while(1)
	{
		try {
		boost::this_thread::sleep(boost::posix_time::milliseconds(1000));

		vector<unsigned char> data;
		data.push_back('a');
		cossb_broker->publish(this, "service/helloworld", "raw", data);
		cossb_log->log(cossb::log::loglevel::INFO, "message publish");
		}
		catch(thread_interrupted&)
		{
			break;
		}
	}
}
<commit_msg>change to korean for documentation<commit_after>
#include "messagepub.hpp"
#include "../../include/componentpack.hpp"

using namespace std;

COMPONENT_INSTANCE(messagepub)
COMPONENT_CREATE(messagepub)
COMPONENT_DESTROY

messagepub::messagepub()
:icomponent(COMPONENT(messagepub)){
	// TODO Auto-generated constructor stub

}

messagepub::~messagepub() {
	destroy_task(_pub_task);
}

bool messagepub::setup()
{
	cossb_broker->regist(this, "service/messagepub");
	return true;
}
bool messagepub::run()
{
	if(!_pub_task)
		_pub_task = create_task(messagepub::pub);
	return true;
}
bool messagepub::stop()
{
	destroy_task(_pub_task);
	return true;
}
void messagepub::request(cossb::message::message* msg)
{
	cossb_log->log(cossb::log::loglevel::INFO, "received message");
}

void messagepub::pub()
{
	while(1)
	{
		try {
		boost::this_thread::sleep(boost::posix_time::milliseconds(1000));

		vector<unsigned char> data;
		data.push_back('a');
		cossb_broker->publish(this, "service/messagepub", "raw", data);
		}
		catch(thread_interrupted&)
		{
			break;
		}
	}
}
<|endoftext|>


<commit_before>#include <iostream>

#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/Geometry>
#include <osg/Geode>

#include <osgUtil/Optimizer>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>

#include <osgProducer/Viewer>

struct SolarSystemParameters
{
    SolarSystemParameters():
        radiusSun(20.0),
        RorbitEarth(100.0),
        radiusEarth(10.0),
        radiusMoon(2.0),
        RorbitMoon(20.0),
        tiltEarth(5.0),
        rotateSpeedEarth(5.0),
    {}
};
/*
osg::Node* createSolarSystem()
{
    osg::Vec3 center(0.0f,0.0f,0.0f);
    float radius = 100.0f;

    osg::Group* root = new osg::Group;

    root->addChild(createMovingModel(center,radius*0.8f));

    root->addChild(createBase(center-osg::Vec3(0.0f,0.0f,radius*0.5),radius));

    return root;
}
*/

int main( int argc, char **argv )
{
    / use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of osg::AnimationPath and UpdateCallbacks for adding animation to your scenes.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // initialize the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    SolarSystemParameters myValues;

    while (arguments.read("--radiusMoon",myValues.radiusMoon)) {}

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // load the nodes from the commandline arguments.
    // osg::Node* model = createModel();
    if (!model)
    {
        return 1;
    }

    std::cout << "radiusSun = " << myValues.radiusSun << std::endl;
    std::cout << "RorbitEarth = " << myValues.RorbitEarth << std::endl;
    std::cout << "radiusEarth = " << myValues.radiusEarth << std::endl;
    std::cout << "radiusMoon = " << myValues.radiusMoon << std::endl;
    std::cout << "RorbitMoon = " << myValues.RorbitMoon << std::endl;
    std::cout << "tiltEarth = " << myValues.tiltEarth << std::endl;
    std::cout << "rotateSpeedEarth = " << myValues.rotateSpeedEarth << std::endl;
    std::cout << "rotateSpeedMoon = " << myValues.rotateSpeedMoon << std::endl;

    /*
    // tilt the scene so the default eye position is looking down on the model.
    osg::MatrixTransform* rootnode = new osg::MatrixTransform;
    rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f));
    rootnode->addChild(model);

    // run optimization over the scene graph
    osgUtil::Optimizer optimzer;
    optimzer.optimize(rootnode);

    // set the scene to render
    viewer.setSceneData(rootnode);

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();
*/
    return 0;
}

/*////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
{
    // set up the animation path
    osg::AnimationPath* animationPath = new osg::AnimationPath;
    animationPath->setLoopMode(osg::AnimationPath::LOOP);

    int numSamples = 40;
    float yaw = 0.0f;
    float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
    float roll = osg::inDegrees(30.0f);

    double time=0.0f;
    double time_delta = looptime/(double)numSamples;
    for(int i=0;i<numSamples;++i)
    {
        osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
        osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));

        animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));

        yaw += yaw_delta;
        time += time_delta;

    }
    return animationPath;
}

osg::Node* createBase(const osg::Vec3& center,float radius)
{

    int numTilesX = 10;
    int numTilesY = 10;

    float width = 2*radius;
    float height = 2*radius;

    osg::Vec3 v000(center - osg::Vec3(width*0.5f,height*0.5f,0.0f));
    osg::Vec3 dx(osg::Vec3(width/((float)numTilesX),0.0,0.0f));
    osg::Vec3 dy(osg::Vec3(0.0f,height/((float)numTilesY),0.0f));

    // fill in vertices for grid, note numTilesX+1 * numTilesY+1...
    osg::Vec3Array* coords = new osg::Vec3Array;
    int iy;
    for(iy=0;iy<=numTilesY;++iy)
    {
        for(int ix=0;ix<=numTilesX;++ix)
        {
            coords->push_back(v000+dx*(float)ix+dy*(float)iy);
        }
    }

    //Just two colours - black and white.
    osg::Vec4Array* colors = new osg::Vec4Array;
    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); // white
    colors->push_back(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); // black
    int numColors=colors->size();

    int numIndicesPerRow=numTilesX+1;
    osg::UByteArray* coordIndices = new osg::UByteArray; // assumes we are using less than 256 points...
    osg::UByteArray* colorIndices = new osg::UByteArray;
    for(iy=0;iy<numTilesY;++iy)
    {
        for(int ix=0;ix<numTilesX;++ix)
        {
            // four vertices per quad.
            coordIndices->push_back(ix    +(iy+1)*numIndicesPerRow);
            coordIndices->push_back(ix    +iy*numIndicesPerRow);
            coordIndices->push_back((ix+1)+iy*numIndicesPerRow);
            coordIndices->push_back((ix+1)+(iy+1)*numIndicesPerRow);

            // one color per quad
            colorIndices->push_back((ix+iy)%numColors);
        }
    }

    // set up a single normal
    osg::Vec3Array* normals = new osg::Vec3Array;
    normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));

    osg::Geometry* geom = new osg::Geometry;
    geom->setVertexArray(coords);
    geom->setVertexIndices(coordIndices);

    geom->setColorArray(colors);
    geom->setColorIndices(colorIndices);
    geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);

    geom->setNormalArray(normals);
    geom->setNormalBinding(osg::Geometry::BIND_OVERALL);

    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,coordIndices->size()));

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(geom);

    return geode;
}

osg::Node* createMovingModel(const osg::Vec3& center, float radius)
{
    float animationLength = 10.0f;

    osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);

    osg::Group* model = new osg::Group;

    osg::Node* glider = osgDB::readNodeFile("glider.osg");
    if (glider)
    {
        const osg::BoundingSphere& bs = glider->getBound();

        float size = radius/bs.radius()*0.3f;
        osg::MatrixTransform* positioned = new osg::MatrixTransform;
        positioned->setDataVariance(osg::Object::STATIC);
        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
                                     osg::Matrix::scale(size,size,size)*
                                     osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));

        positioned->addChild(glider);

        osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform;
        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));
        xform->addChild(positioned);

        model->addChild(xform);
    }

    osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
    if (cessna)
    {
        const osg::BoundingSphere& bs = cessna->getBound();

        float size = radius/bs.radius()*0.3f;
        osg::MatrixTransform* positioned = new osg::MatrixTransform;
        positioned->setDataVariance(osg::Object::STATIC);
        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
                                     osg::Matrix::scale(size,size,size)*
                                     osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));

        positioned->addChild(cessna);

        osg::MatrixTransform* xform = new osg::MatrixTransform;
        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
        xform->addChild(positioned);

        model->addChild(xform);
    }

    return model;
}

osg::Node* createModel()
{
    osg::Vec3 center(0.0f,0.0f,0.0f);
    float radius = 100.0f;

    osg::Group* root = new osg::Group;

    root->addChild(createMovingModel(center,radius*0.8f));

    root->addChild(createBase(center-osg::Vec3(0.0f,0.0f,radius*0.5),radius));

    return root;
} */
<commit_msg>Compile fixes<commit_after>#include <iostream>

#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/Geometry>
#include <osg/Geode>

#include <osgUtil/Optimizer>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>

#include <osgProducer/Viewer>

struct SolarSystemParameters
{
    SolarSystemParameters():
        radiusSun(20.0),
        RorbitEarth(100.0),
        radiusEarth(10.0),
        radiusMoon(2.0),
        RorbitMoon(20.0),
        tiltEarth(5.0),
        rotateSpeedEarth(5.0)
    {}

    double radiusSun;
    double RorbitEarth;
    double radiusEarth;
    double radiusMoon;
    double RorbitMoon;
    double tiltEarth;
    double rotateSpeedEarth;
};

osg::Node* createSolarSystem(SolarSystemParameters& parameters)
{
    return 0;
}

int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of osg::AnimationPath and UpdateCallbacks for adding animation to your scenes.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // initialize the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    SolarSystemParameters parameters;

    while (arguments.read("--radiusMoon",parameters.radiusMoon)) {}

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // load the nodes from the commandline arguments.
    osg::Node* model = createSolarSystem(parameters);
    if (!model)
    {
        return 1;
    }

    std::cout << "radiusSun = " << parameters.radiusSun << std::endl;
    std::cout << "RorbitEarth = " << parameters.RorbitEarth << std::endl;
    std::cout << "radiusEarth = " << parameters.radiusEarth << std::endl;
    std::cout << "radiusMoon = " << parameters.radiusMoon << std::endl;
    std::cout << "RorbitMoon = " << parameters.RorbitMoon << std::endl;
    std::cout << "tiltEarth = " << parameters.tiltEarth << std::endl;
    std::cout << "rotateSpeedEarth = " << parameters.rotateSpeedEarth << std::endl;

    /*
    // tilt the scene so the default eye position is looking down on the model.
    osg::MatrixTransform* rootnode = new osg::MatrixTransform;
    rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f));
    rootnode->addChild(model);

    // run optimization over the scene graph
    osgUtil::Optimizer optimzer;
    optimzer.optimize(rootnode);

    // set the scene to render
    viewer.setSceneData(rootnode);

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();
*/
    return 0;
}

/*////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
{
    // set up the animation path
    osg::AnimationPath* animationPath = new osg::AnimationPath;
    animationPath->setLoopMode(osg::AnimationPath::LOOP);

    int numSamples = 40;
    float yaw = 0.0f;
    float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
    float roll = osg::inDegrees(30.0f);

    double time=0.0f;
    double time_delta = looptime/(double)numSamples;
    for(int i=0;i<numSamples;++i)
    {
        osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
        osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));

        animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));

        yaw += yaw_delta;
        time += time_delta;

    }
    return animationPath;
}

osg::Node* createBase(const osg::Vec3& center,float radius)
{

    int numTilesX = 10;
    int numTilesY = 10;

    float width = 2*radius;
    float height = 2*radius;

    osg::Vec3 v000(center - osg::Vec3(width*0.5f,height*0.5f,0.0f));
    osg::Vec3 dx(osg::Vec3(width/((float)numTilesX),0.0,0.0f));
    osg::Vec3 dy(osg::Vec3(0.0f,height/((float)numTilesY),0.0f));

    // fill in vertices for grid, note numTilesX+1 * numTilesY+1...
    osg::Vec3Array* coords = new osg::Vec3Array;
    int iy;
    for(iy=0;iy<=numTilesY;++iy)
    {
        for(int ix=0;ix<=numTilesX;++ix)
        {
            coords->push_back(v000+dx*(float)ix+dy*(float)iy);
        }
    }

    //Just two colours - black and white.
    osg::Vec4Array* colors = new osg::Vec4Array;
    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); // white
    colors->push_back(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); // black
    int numColors=colors->size();

    int numIndicesPerRow=numTilesX+1;
    osg::UByteArray* coordIndices = new osg::UByteArray; // assumes we are using less than 256 points...
    osg::UByteArray* colorIndices = new osg::UByteArray;
    for(iy=0;iy<numTilesY;++iy)
    {
        for(int ix=0;ix<numTilesX;++ix)
        {
            // four vertices per quad.
            coordIndices->push_back(ix    +(iy+1)*numIndicesPerRow);
            coordIndices->push_back(ix    +iy*numIndicesPerRow);
            coordIndices->push_back((ix+1)+iy*numIndicesPerRow);
            coordIndices->push_back((ix+1)+(iy+1)*numIndicesPerRow);

            // one color per quad
            colorIndices->push_back((ix+iy)%numColors);
        }
    }

    // set up a single normal
    osg::Vec3Array* normals = new osg::Vec3Array;
    normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));

    osg::Geometry* geom = new osg::Geometry;
    geom->setVertexArray(coords);
    geom->setVertexIndices(coordIndices);

    geom->setColorArray(colors);
    geom->setColorIndices(colorIndices);
    geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);

    geom->setNormalArray(normals);
    geom->setNormalBinding(osg::Geometry::BIND_OVERALL);

    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,coordIndices->size()));

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(geom);

    return geode;
}

osg::Node* createMovingModel(const osg::Vec3& center, float radius)
{
    float animationLength = 10.0f;

    osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);

    osg::Group* model = new osg::Group;

    osg::Node* glider = osgDB::readNodeFile("glider.osg");
    if (glider)
    {
        const osg::BoundingSphere& bs = glider->getBound();

        float size = radius/bs.radius()*0.3f;
        osg::MatrixTransform* positioned = new osg::MatrixTransform;
        positioned->setDataVariance(osg::Object::STATIC);
        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
                                     osg::Matrix::scale(size,size,size)*
                                     osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));

        positioned->addChild(glider);

        osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform;
        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));
        xform->addChild(positioned);

        model->addChild(xform);
    }

    osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
    if (cessna)
    {
        const osg::BoundingSphere& bs = cessna->getBound();

        float size = radius/bs.radius()*0.3f;
        osg::MatrixTransform* positioned = new osg::MatrixTransform;
        positioned->setDataVariance(osg::Object::STATIC);
        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
                                     osg::Matrix::scale(size,size,size)*
                                     osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));

        positioned->addChild(cessna);

        osg::MatrixTransform* xform = new osg::MatrixTransform;
        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
        xform->addChild(positioned);

        model->addChild(xform);
    }

    return model;
}

osg::Node* createModel()
{
    osg::Vec3 center(0.0f,0.0f,0.0f);
    float radius = 100.0f;

    osg::Group* root = new osg::Group;

    root->addChild(createMovingModel(center,radius*0.8f));

    root->addChild(createBase(center-osg::Vec3(0.0f,0.0f,radius*0.5),radius));

    return root;
} */
<|endoftext|>


<commit_before>/*  -*-c++-*-
 *  Copyright (C) 2017 Julien Valentin <mp3butcher@hotmail.com>
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/

#include <osg/Program>
#include <osg/Sampler>
#include <osg/Texture2D>
#include <osg/ShapeDrawable>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>

#include <osgDB/ReadFile>
#include <osgDB/WriteFile>

/// add two composite texture color
static const char* fragSource =
{
    "uniform sampler2D tex1;\n"
    "uniform sampler2D tex2;\n"
    "void main(){\n"
    "    vec4 color1 = texture2D(tex1,gl_TexCoord[0].st);\n"
    "    vec4 color2 = texture2D(tex2,gl_TexCoord[0].st);\n"
    "    gl_FragColor = vec4(color1.xyz+color2.xyz,1.0);\n"
    "}\n"
};

class KeyboardEventHandler : public osgGA::GUIEventHandler
{
public:
    KeyboardEventHandler(osg::Sampler* tessInnerU, osg::Sampler* tessOuterU,osg::StateSet* ss):
        _sampler1(tessInnerU),
        _sampler2(tessOuterU),_ss(ss){}

    virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& gaa)
    {
        osg::Texture:: FilterMode newone=osg::Texture::NEAREST;
        if(ea.getEventType()==osgGA::GUIEventAdapter::KEYDOWN)
        {
            switch (ea.getKey())
            {
            case osgGA::GUIEventAdapter::KEY_A:
                if(_sampler1->getFilter(osg::Texture::MAG_FILTER)==osg::Texture::NEAREST)
                    newone=osg::Texture::LINEAR;
                _sampler1->setFilter(osg::Texture::MAG_FILTER,newone);
                _sampler1->setFilter(osg::Texture::MIN_FILTER,newone);
                return true;
            case osgGA::GUIEventAdapter::KEY_B:
                if(_sampler2->getFilter(osg::Texture::MAG_FILTER)==osg::Texture::NEAREST)
                    newone=osg::Texture::LINEAR;
                _sampler2->setFilter(osg::Texture::MAG_FILTER,newone);
                _sampler2->setFilter(osg::Texture::MIN_FILTER,newone);
                return true;

            }
        }
        return osgGA::GUIEventHandler::handle(ea, gaa);
    }

private:
    osg::Sampler* _sampler1;
    osg::Sampler* _sampler2;
    osg::StateSet* _ss;

};

int main(int argc, char* argv[])
{
    osg::ArgumentParser arguments(&argc,argv);
    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example for GL3 sampler.");
    osg::ApplicationUsage::UsageMap kmap;
    kmap["a"]="swap Linear/Nearest filtering on first texture";
    kmap["b"]="swap Linear/Nearest filtering on second texture";
    arguments.getApplicationUsage()->setKeyboardMouseBindings(kmap);

    osgViewer::Viewer viewer(arguments);
    osg::ref_ptr<osg::Program> program = new osg::Program();
    program->addShader(new osg::Shader(osg::Shader::FRAGMENT,fragSource));

    osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments);
    osg::ref_ptr<osg::Node> geode ;
    if (!loadedModel)
    {
        geode = new osg::Geode;
        ((osg::Geode*)geode.get())->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0,0,0),osg::Vec3(1,0,0),osg::Vec3(0,0,1) ));
    }
    else
    {
        geode=loadedModel;
    }

    osg::ref_ptr< osg::Texture2D> tex1, tex2;
    osg::ref_ptr<osg::Sampler > sampler1, sampler2;

    tex1=new osg::Texture2D();
    tex2=new osg::Texture2D();

    sampler1=new osg::Sampler();
    sampler2=new osg::Sampler();

    osg::Vec2ui resolution(4,4);
    {
        ///first texture//NO RED
        unsigned char *data = new  unsigned char[(resolution.x()* resolution.y()) * 4];
        unsigned char * ptr=data;
        unsigned int   sw=0,cptx=0;
        while (ptr != data + sizeof(unsigned char)*(resolution.x()* resolution.y()) * 4)
        {
            if(sw==1)
            {
                *ptr++=0;
                *ptr++=0xff;
                *ptr++=0xff;
                *ptr++=0xff;
            }
            else
            {
                *ptr++=0;
                *ptr++=0;
                *ptr++=0;
                *ptr++=0xff;
            }
            if(++cptx<resolution.x())sw=sw?0:1;
            else cptx=0;
        }
        osg::ref_ptr<osg::Image >im = new osg::Image();
        im->setImage(resolution.x(), resolution.y(), 1,GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE);
        im->dirty();
        tex1->setImage(im);
    }
    {
        ///second texture// RED ONLY
        unsigned char *data = new unsigned char[(resolution.x()* resolution.y()) * 4];
        unsigned char * ptr=data;
        unsigned int   sw=0,cptx=0;
        while (ptr != data + sizeof(unsigned char)*(resolution.x()* resolution.y()) * 4)
        {
            if(sw==1)
            {
                *ptr++=255;
                *ptr++=0;
                *ptr++=0;
                *ptr++=255;
            }
            else
            {
                *ptr++=0;
                *ptr++=0;
                *ptr++=0;
                *ptr++=255;
            }
            if(++cptx<resolution.x())sw=sw?0:1;
            else cptx=0;
        }
        osg::ref_ptr<osg::Image >im = new osg::Image();
        im->setImage(resolution.x(), resolution.y(), 1,GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE);
        im->dirty();
        tex2->setImage(im);
    }
    ///Overrided Filtering setup
    tex1->setFilter(osg::Texture::MAG_FILTER,osg::Texture::NEAREST);
    tex1->setFilter(osg::Texture::MIN_FILTER,osg::Texture::NEAREST);

    tex2->setFilter(osg::Texture::MAG_FILTER,osg::Texture::NEAREST);
    tex2->setFilter(osg::Texture::MIN_FILTER,osg::Texture::NEAREST);

    ///Filter Override samplers setup
    sampler1->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
    sampler1->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);

    sampler2->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
    sampler2->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);

    osg::StateSet *ss;
    ss = geode->getOrCreateStateSet();

    ss->setTextureAttribute(0,tex1,osg::StateAttribute::ON);
    ss->setTextureAttribute(1,tex2,osg::StateAttribute::ON);
    ss->setTextureAttribute(0,sampler1,osg::StateAttribute::ON);
    ss->setTextureAttribute(1,sampler2,osg::StateAttribute::ON);

    ss->addUniform(new osg::Uniform("tex1",(int)0));
    ss->addUniform(new osg::Uniform("tex2",(int)1));
    ss->setAttribute(program.get());

    viewer.addEventHandler(new KeyboardEventHandler(sampler1, sampler2,ss));
    viewer.addEventHandler(new osgViewer::StatsHandler);

    viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));

    viewer.setSceneData(geode.get());
    return viewer.run();
}
<commit_msg>improve example to get command arguments<commit_after>/*  -*-c++-*-
 *  Copyright (C) 2018 Julien Valentin <mp3butcher@hotmail.com>
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/

#include <osg/Program>
#include <osg/Sampler>
#include <osg/Texture2D>
#include <osg/ShapeDrawable>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>

#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgUtil/Optimizer>

/// add two composite texture color
static const char* fragSource =
{
    "uniform sampler2D tex1;\n"
    "uniform sampler2D tex2;\n"
    "void main(){\n"
    "    vec4 color1 = texture2D(tex1,gl_TexCoord[0].st);\n"
    "    vec4 color2 = texture2D(tex2,gl_TexCoord[0].st);\n"
    "    gl_FragColor = vec4(color1.xyz+color2.xyz,1.0);\n"
    "}\n"
};

class SamplersKeyboardEventHandler : public osgGA::GUIEventHandler
{
public:
    SamplersKeyboardEventHandler(osg::Sampler* tessInnerU, osg::Sampler* tessOuterU):
        _sampler1(tessInnerU),
        _sampler2(tessOuterU){}

    virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& gaa)
    {
        osg::Texture:: FilterMode newone=osg::Texture::NEAREST;
        if(ea.getEventType()==osgGA::GUIEventAdapter::KEYDOWN)
        {
            switch (ea.getKey())
            {
            case osgGA::GUIEventAdapter::KEY_A:
                if(_sampler1->getFilter(osg::Texture::MAG_FILTER)==osg::Texture::NEAREST)
                    newone=osg::Texture::LINEAR;
                _sampler1->setFilter(osg::Texture::MAG_FILTER,newone);
                _sampler1->setFilter(osg::Texture::MIN_FILTER,newone);
                return true;
            case osgGA::GUIEventAdapter::KEY_B:
                if(_sampler2->getFilter(osg::Texture::MAG_FILTER)==osg::Texture::NEAREST)
                    newone=osg::Texture::LINEAR;
                _sampler2->setFilter(osg::Texture::MAG_FILTER,newone);
                _sampler2->setFilter(osg::Texture::MIN_FILTER,newone);
                return true;
            }
        }
        return osgGA::GUIEventHandler::handle(ea, gaa);
    }

private:
    osg::Sampler* _sampler1;
    osg::Sampler* _sampler2;

};

class StateCollec: public osg::NodeVisitor{
public:
    StateCollec():osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN){}
    virtual void apply(osg::Node& node){
        osg::StateSet *ss=node.getStateSet();
        if(ss) _statesets.insert(ss);
        traverse(node);
    }
    std::set<osg::StateSet*> _statesets;
    std::set<osg::StateSet*> & getStateSets(){return _statesets;}
};

int main(int argc, char* argv[])
{
    osg::ArgumentParser arguments(&argc,argv);
    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example for GL3 sampler.");
    osg::ApplicationUsage::UsageMap kmap;
    kmap["a"]="swap Linear/Nearest filtering on first texture";
    kmap["b"]="swap Linear/Nearest filtering on second texture";
    arguments.getApplicationUsage()->setKeyboardMouseBindings(kmap);

    osgViewer::Viewer viewer(arguments);
    osg::ref_ptr<osg::Program> program = new osg::Program();
    program->addShader(new osg::Shader(osg::Shader::FRAGMENT,fragSource));

    osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments);
    osg::ref_ptr<osg::Node> geode ;

        osg::ref_ptr<osg::Sampler > sampler1, sampler2;
    if (loadedModel)
    {
        ///ensure loaded have Sampler
        geode=loadedModel;
        StateCollec sc;
        geode->accept(sc);
        for(std::set<osg::StateSet*>::iterator it=sc.getStateSets().begin();it != sc.getStateSets().end(); ++it)
        {
            osg::Sampler::generateSamplerObjects(*(*it));
            if(!sampler1.valid())
                sampler1 = sampler2 = (osg::Sampler*)(*it)->getTextureAttribute(0, osg::StateAttribute::SAMPLER);
            else
                sampler2=(osg::Sampler*)(*it)->getTextureAttribute(0, osg::StateAttribute::SAMPLER);
        }
        if(sampler1.valid()&&sampler2.valid()){
            OSG_WARN<<"2samplers manipulator setted"<<std::endl;
            viewer.addEventHandler(new SamplersKeyboardEventHandler(sampler1, sampler2));
        }
    }
    else
    {
        ///createQuadWith2TexturesMix
        geode = new osg::Geode;
        ((osg::Geode*)geode.get())->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0,0,0),osg::Vec3(1,0,0),osg::Vec3(0,0,1) ));

        osg::ref_ptr< osg::Texture2D> tex1, tex2;

        tex1=new osg::Texture2D();
        tex2=new osg::Texture2D();

        sampler1=new osg::Sampler();
        sampler2=new osg::Sampler();

        osg::Vec2ui resolution(4,4);
        {
            ///first texture//NO RED
            unsigned char *data = new  unsigned char[(resolution.x()* resolution.y()) * 4];
            unsigned char * ptr=data;
            unsigned int   sw=0, cptx=0;
            while (ptr != data + sizeof(unsigned char)*(resolution.x()* resolution.y()) * 4)
            {
                if(sw==1)
                {
                    *ptr++=0;                    *ptr++=0xff;                *ptr++=0xff;                  *ptr++=0xff;
                }
                else
                {
                    *ptr++=0;                    *ptr++=0;                    *ptr++=0;                    *ptr++=0xff;
                }
                if(++cptx<resolution.x())sw=sw?0:1;
                else cptx=0;
            }
            osg::ref_ptr<osg::Image >im = new osg::Image();
            im->setImage(resolution.x(), resolution.y(), 1,GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE);
            im->dirty();
            tex1->setImage(im);
        }
        {
            ///second texture// RED ONLY
            unsigned char *data = new unsigned char[(resolution.x()* resolution.y()) * 4];
            unsigned char * ptr=data;
            unsigned int   sw=0,cptx=0;
            while (ptr != data + sizeof(unsigned char)*(resolution.x()* resolution.y()) * 4)
            {
                if(sw==1)
                {
                    *ptr++=255;                  *ptr++=0;                    *ptr++=0;                    *ptr++=255;
                }
                else
                {
                    *ptr++=0;                    *ptr++=0;                    *ptr++=0;                    *ptr++=255;
                }
                if(++cptx<resolution.x())sw=sw?0:1;
                else cptx=0;
            }
            osg::ref_ptr<osg::Image >im = new osg::Image();
            im->setImage(resolution.x(), resolution.y(), 1,GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE);
            im->dirty();
            tex2->setImage(im);
        }
        ///Overrided Filtering setup
        tex1->setFilter(osg::Texture::MAG_FILTER,osg::Texture::NEAREST);
        tex1->setFilter(osg::Texture::MIN_FILTER,osg::Texture::NEAREST);

        tex2->setFilter(osg::Texture::MAG_FILTER,osg::Texture::NEAREST);
        tex2->setFilter(osg::Texture::MIN_FILTER,osg::Texture::NEAREST);

        ///Filter Override samplers setup
        sampler1->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
        sampler1->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);

        sampler2->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
        sampler2->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);

        osg::StateSet *ss;
        ss = geode->getOrCreateStateSet();

        ss->setTextureAttribute(0, tex1,osg::StateAttribute::ON);
        ss->setTextureAttribute(1, tex2,osg::StateAttribute::ON);
    //#define TEST_SAMPLER_OBJECT_AUTO_PORT 1
    #ifdef TEST_SAMPLER_OBJECT_AUTO_PORT

        osg::Sampler::generateSamplerObjects(*ss)
        if(
        (sampler1= static_cast<osg::Sampler*>(ss->getTextureAttribute(0,osg::StateAttribute::SAMPLER)))&&
        (sampler2= static_cast<osg::Sampler*>(ss->getTextureAttribute(1,osg::StateAttribute::SAMPLER)))
        )
        OSG_WARN<<"both samplers are generated"<<std::endl;
    #else
        ss->setTextureAttribute(0,sampler1,osg::StateAttribute::ON);
        ss->setTextureAttribute(1,sampler2,osg::StateAttribute::ON);
    #endif
        ss->addUniform(new osg::Uniform("tex1",(int)0));
        ss->addUniform(new osg::Uniform("tex2",(int)1));
        ss->setAttribute(program.get());

        viewer.addEventHandler(new SamplersKeyboardEventHandler(sampler1, sampler2));
    }

    viewer.addEventHandler(new osgViewer::StatsHandler);
    viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());

    viewer.setSceneData(geode.get());
    return viewer.run();
}
<|endoftext|>


<commit_before>#include <gtksourceview/gtksource.h>
#include "jazz.hpp"
#include "jazz_tablabel.hpp"
#include "jazz_sourceview.hpp"
#include "jazz_filetree.hpp"
#include "jazz_util.hpp"
#include <iostream>

using coral::zircon::json_loadfile;
namespace Jazz
{
JazzIDE::JazzIDE(): box(Gtk::ORIENTATION_VERTICAL, 1),
	h_box(Gtk::ORIENTATION_HORIZONTAL, 1), file_tree(g_get_current_dir()),
	project_doc(json_loadfile("test.jazzproj")),
	project_tree(),
	terminal(100, 50),
	language_manager(gtk_source_language_manager_get_default())
{
	builder = Gtk::Builder::create_from_file("jazz_menubar.ui");
	builder->add_from_file("jazz_project_dialog.ui");
	builder->add_from_file("jazz_toolbar.ui");
	builder->get_widget("jazz_menubar", menubar);
	menubar->show();

	set_default_size(800, 600);

	add(box);
	box.pack_end(terminal, true, true);
	box.pack_end(h_box, true, true);

	right_pane.set_tab_pos(Gtk::PositionType::POS_BOTTOM);
	right_pane.append_page(project_tree, *Gtk::manage(new Gtk::Label("Project")));
	right_pane.append_page(file_tree, *Gtk::manage(new Gtk::Label("File")));

	h_box.pack_end(right_pane, false, false);
	h_box.pack_end(notebook, true, true);

	Gtk::ToolButton* titem = nullptr;

	builder->get_widget("tb_newfile", titem);
	titem->signal_clicked().connect(sigc::mem_fun(*this, &JazzIDE::NewFile));

	builder->get_widget("tb_openfile", titem);
	titem->signal_clicked().connect(sigc::mem_fun(*this, &JazzIDE::OpenFile));
	titem->set_tooltip_text("Open File");

	builder->get_widget("tb_savefile", titem);
	titem->signal_clicked().connect(sigc::mem_fun(*this, &JazzIDE::SaveFile));
	titem->set_tooltip_text("Save As");

	builder->get_widget("tb_execute", titem);
	titem->signal_clicked().connect(sigc::mem_fun(*this, &JazzIDE::ExecuteProject));

	builder->get_widget("tb_resumedbg", titem);
	titem->signal_clicked().connect(sigc::mem_fun(*this, &JazzIDE::DebugContinueCmd));
	titem->set_tooltip_text("Continue");

	// Need to figure out how to step out first
	//builder->get_widget("tb_stepout", titem);
	//titem->signal_clicked().connect([this](){ gdb->Command() })
	builder->get_widget("tb_stepnext", titem);
	titem->signal_clicked().connect([this](){ gdb->Command("n"); });

	builder->get_widget("tb_stepinto", titem);
	titem->signal_clicked().connect([this](){ gdb->Command("s"); });

	builder->get_widget("jazz_toolbar", toolbar);
	box.pack_start(*menubar,false,false);
	box.pack_start(*toolbar, false, false);

	// Connect the new menu button to our member function for it
	Gtk::MenuItem* menu_item = nullptr;

	builder->get_widget("filemenunewfile", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::NewFile));

	builder->get_widget("filemenunewproject", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::NewProject));

	builder->get_widget("filemenuopen", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::OpenFile));

	builder->get_widget("filemenuopenfolder", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::OpenFolder));

	builder->get_widget("filemenusave", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::SaveFile));

	builder->get_widget("filemenusaveas", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::SaveFile));

	builder->get_widget("filemenuexit", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::Quit));

	builder->get_widget("editmenufont", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::ChooseFont));

	file_tree.TreeView().signal_row_activated().connect(sigc::mem_fun(*this, &JazzIDE::OpenFileFromTree));

	project_tree.SetProject(project_doc);

	show_all_children();
}
JazzIDE::~JazzIDE()
{
	//delete gdb;
}
namespace
{
	struct BreakpointCallbackData
	{
		int line;
		gulong signal_id;
		SourceView* source_view;
	};
    Glib::ustring BuildPathToFile(Gtk::TreeModel::Row row, Gtk::TreeModel::Row root_node, Jazz::FileTreeModelColumns& columns)
    {
        if(row == root_node)
            return "";

		return BuildPathToFile(*row.parent(), root_node, columns) + dir_seperator + row[columns.filename];
    }
}
void JazzIDE::OpenFileFromTree(const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn*)
{
	Gtk::TreeModel::iterator iter = file_tree.TreeStore()->get_iter(path);
	if(iter)
	{
		AddFileToNotebook(file_tree.CurrentPath() + BuildPathToFile(*iter, file_tree.Root(), file_tree.Columns()),
			[this](FileOpened file_status)
		{
			notebook.set_current_page(-1);
		});
	}
}
static void OnSizeAllocate(GtkTextView* view, GdkRectangle*, gpointer user_data)
{
	BreakpointCallbackData* callback = static_cast<BreakpointCallbackData*>(user_data);
	callback->source_view->ScrollToLine(callback->line);

	// We need to come up with a way to delete the user data after the signal is disconnected at some point
	//g_signal_handler_disconnect(view, callback->signal_id);
	//delete callback;
}
bool JazzIDE::HandleGDBOutput(Glib::IOCondition, const Glib::ustring& thing)
{
	if(thing[0] == '*')
	{
		if(thing.find("breakpoint-hit") !=  Glib::ustring::npos)
		{
			// Find the fullname property and open that file
			auto new_pos = thing.rfind("fullname=")+10U;
			auto str = thing.substr(new_pos);
			str = str.substr(0, str.find('"'));

			new_pos = thing.rfind("line=")+6U;
			int line_num = std::stoi(thing.substr(new_pos, thing.find('"', new_pos)));

			AddFileToNotebook(str, [this, str, line_num](FileOpened success){
				switch(success)
				{
					case FileOpened::Success:
					{
						SourceView* page = static_cast<SourceView*>(notebook.get_nth_page(notebook.get_current_page()));
						BreakpointCallbackData* data = new BreakpointCallbackData{line_num, 0U, page};
						data->signal_id = g_signal_connect(GTK_WIDGET(page->GetSourceView()), "size-allocate",
							G_CALLBACK(OnSizeAllocate), (gpointer)data);
						page->ScrollToLine(line_num);
					}break;
					case FileOpened::Failure:
					{
						// In the future we should use lib notify to inform the user that this operation didn't work
						ShowMessage("Breakpoint hit but could not open"
										" the file" + str + " successfully", this);
					}break;
					case FileOpened::WasOpen:
					{
						SourceView* page = static_cast<SourceView*>(notebook.get_nth_page(notebook.get_current_page()));
						page->ScrollToLine(line_num);
					}break;
				}
			});
		}
	}
	return true;
}
}
<commit_msg>Step out added<commit_after>#include <gtksourceview/gtksource.h>
#include "jazz.hpp"
#include "jazz_tablabel.hpp"
#include "jazz_sourceview.hpp"
#include "jazz_filetree.hpp"
#include "jazz_util.hpp"
#include <iostream>

using coral::zircon::json_loadfile;
namespace Jazz
{
JazzIDE::JazzIDE(): box(Gtk::ORIENTATION_VERTICAL, 1),
	h_box(Gtk::ORIENTATION_HORIZONTAL, 1), file_tree(g_get_current_dir()),
	project_doc(json_loadfile("test.jazzproj")),
	project_tree(),
	terminal(100, 50),
	language_manager(gtk_source_language_manager_get_default())
{
	builder = Gtk::Builder::create_from_file("jazz_menubar.ui");
	builder->add_from_file("jazz_project_dialog.ui");
	builder->add_from_file("jazz_toolbar.ui");
	builder->get_widget("jazz_menubar", menubar);
	menubar->show();

	set_default_size(800, 600);

	add(box);
	box.pack_end(terminal, true, true);
	box.pack_end(h_box, true, true);

	right_pane.set_tab_pos(Gtk::PositionType::POS_BOTTOM);
	right_pane.append_page(project_tree, *Gtk::manage(new Gtk::Label("Project")));
	right_pane.append_page(file_tree, *Gtk::manage(new Gtk::Label("File")));

	h_box.pack_end(right_pane, false, false);
	h_box.pack_end(notebook, true, true);

	Gtk::ToolButton* titem = nullptr;

	builder->get_widget("tb_newfile", titem);
	titem->signal_clicked().connect(sigc::mem_fun(*this, &JazzIDE::NewFile));

	builder->get_widget("tb_openfile", titem);
	titem->signal_clicked().connect(sigc::mem_fun(*this, &JazzIDE::OpenFile));
	titem->set_tooltip_text("Open File");

	builder->get_widget("tb_savefile", titem);
	titem->signal_clicked().connect(sigc::mem_fun(*this, &JazzIDE::SaveFile));
	titem->set_tooltip_text("Save As");

	builder->get_widget("tb_execute", titem);
	titem->signal_clicked().connect(sigc::mem_fun(*this, &JazzIDE::ExecuteProject));

	builder->get_widget("tb_resumedbg", titem);
	titem->signal_clicked().connect(sigc::mem_fun(*this, &JazzIDE::DebugContinueCmd));
	titem->set_tooltip_text("Continue");

	builder->get_widget("tb_stepout", titem);
	titem->signal_clicked().connect([this](){ gdb->Command("finish"); });

	builder->get_widget("tb_stepnext", titem);
	titem->signal_clicked().connect([this](){ gdb->Command("n"); });

	builder->get_widget("tb_stepinto", titem);
	titem->signal_clicked().connect([this](){ gdb->Command("s"); });

	builder->get_widget("jazz_toolbar", toolbar);
	box.pack_start(*menubar,false,false);
	box.pack_start(*toolbar, false, false);

	// Connect the new menu button to our member function for it
	Gtk::MenuItem* menu_item = nullptr;

	builder->get_widget("filemenunewfile", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::NewFile));

	builder->get_widget("filemenunewproject", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::NewProject));

	builder->get_widget("filemenuopen", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::OpenFile));

	builder->get_widget("filemenuopenfolder", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::OpenFolder));

	builder->get_widget("filemenusave", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::SaveFile));

	builder->get_widget("filemenusaveas", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::SaveFile));

	builder->get_widget("filemenuexit", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::Quit));

	builder->get_widget("editmenufont", menu_item);
	menu_item->signal_activate().connect(sigc::mem_fun(*this,&JazzIDE::ChooseFont));

	file_tree.TreeView().signal_row_activated().connect(sigc::mem_fun(*this, &JazzIDE::OpenFileFromTree));

	project_tree.SetProject(project_doc);

	show_all_children();
}
JazzIDE::~JazzIDE()
{
	//delete gdb;
}
namespace
{
	struct BreakpointCallbackData
	{
		int line;
		gulong signal_id;
		SourceView* source_view;
	};
    Glib::ustring BuildPathToFile(Gtk::TreeModel::Row row, Gtk::TreeModel::Row root_node, Jazz::FileTreeModelColumns& columns)
    {
        if(row == root_node)
            return "";

		return BuildPathToFile(*row.parent(), root_node, columns) + dir_seperator + row[columns.filename];
    }
}
void JazzIDE::OpenFileFromTree(const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn*)
{
	Gtk::TreeModel::iterator iter = file_tree.TreeStore()->get_iter(path);
	if(iter)
	{
		AddFileToNotebook(file_tree.CurrentPath() + BuildPathToFile(*iter, file_tree.Root(), file_tree.Columns()),
			[this](FileOpened file_status)
		{
			notebook.set_current_page(-1);
		});
	}
}
static void OnSizeAllocate(GtkTextView* view, GdkRectangle*, gpointer user_data)
{
	BreakpointCallbackData* callback = static_cast<BreakpointCallbackData*>(user_data);
	callback->source_view->ScrollToLine(callback->line);

	// We need to come up with a way to delete the user data after the signal is disconnected at some point
	//g_signal_handler_disconnect(view, callback->signal_id);
	//delete callback;
}
bool JazzIDE::HandleGDBOutput(Glib::IOCondition, const Glib::ustring& thing)
{
	if(thing[0] == '*')
	{
		if(thing.find("breakpoint-hit") !=  Glib::ustring::npos)
		{
			// Find the fullname property and open that file
			auto new_pos = thing.rfind("fullname=")+10U;
			auto str = thing.substr(new_pos);
			str = str.substr(0, str.find('"'));

			new_pos = thing.rfind("line=")+6U;
			int line_num = std::stoi(thing.substr(new_pos, thing.find('"', new_pos)));

			AddFileToNotebook(str, [this, str, line_num](FileOpened success){
				switch(success)
				{
					case FileOpened::Success:
					{
						SourceView* page = static_cast<SourceView*>(notebook.get_nth_page(notebook.get_current_page()));
						BreakpointCallbackData* data = new BreakpointCallbackData{line_num, 0U, page};
						data->signal_id = g_signal_connect(GTK_WIDGET(page->GetSourceView()), "size-allocate",
							G_CALLBACK(OnSizeAllocate), (gpointer)data);
						page->ScrollToLine(line_num);
					}break;
					case FileOpened::Failure:
					{
						// In the future we should use lib notify to inform the user that this operation didn't work
						ShowMessage("Breakpoint hit but could not open"
										" the file" + str + " successfully", this);
					}break;
					case FileOpened::WasOpen:
					{
						SourceView* page = static_cast<SourceView*>(notebook.get_nth_page(notebook.get_current_page()));
						page->ScrollToLine(line_num);
					}break;
				}
			});
		}
	}
	return true;
}
}
<|endoftext|>


<commit_before>#include "ece556.h"

void handler(int sig) {
    void *array[10];
    size_t size;

    size = backtrace(array, 10);

    fprintf(stderr, "ERROR: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}

int readBenchmark(const char *fileName, routingInst *rst){
    ifstream fin;
    fin.open(fileName);
    if(!fin.good()) return 0;
    int v = 0;
    //read each line of the file
    const char* token[20] = {}; // initialize to 0
    while(!fin.eof()){
        v++;
        // read an entire line into memory
        char buf[512];
        fin.getline(buf, 512);

        // parse the line into blank-delimited tokens
        int n = 0; // a for-loop index

        // array to store memory addresses of the tokens in buff

        //parse the line
        token[0] = strtok(buf, " "); // subsequent tokens
        if(token[0]){ // zerof if line is blank
            for (n = 1; n < 20; n++){
                token[n] = strtok(0, " "); //subsequent tokens
                if (!token[n]) break; // no more tokens
            }
        }else break;

        if(strncmp(token[0], "grid", 64) == 0){
            int x = atoi(token[1]);
            int y = atoi(token[2]);

            rst->gx = x;
            rst->gy = y;
            rst->numEdges = y*(x-1) + x*(y-1);
            rst->edgeCaps = (int *)malloc(rst->numEdges * sizeof(int));
        }
        else if(strncmp(token[0], "capacity",64) == 0){
            rst->cap = atoi(token[1]);
            for (int i = 0; i < rst->numEdges; i++)
                rst->edgeCaps[i] = rst->cap;
        }
        else if(strncmp(token[0], "num", 64) == 0){
            rst->numNets = atoi(token[2]);
            rst->nets = (net *)malloc(rst->numNets*sizeof(net));
        }
        else if(strcmp(token[0], "n0") == 0){
            for(int i = 0; i < rst->numNets; i++){
                int num = atoi(token[1]);
                net *tempNet = new net;
                tempNet->id = i;
                tempNet->numPins = num;
                tempNet->pins = (point *)malloc(num*sizeof(point));
                for(int j = 0; j < num; j++){
                    fin.getline(buf, 512);

                    // parse the line into blank-delimited tokens
                    int m = 0; // a for-loop index

                    //parse the line
                    token[0] = strtok(buf, " "); // subsequent tokens
                    if(token[0]){ // zerof if line is blank
                        for (m = 1; m < 20; m++){
                            token[m] = strtok(0, " "); //subsequent tokens
                            if (!token[m]) break; // no more tokens
                        }
                    }
                    point *tempPoint = new point;
                    tempPoint->x = atoi(token[0]);
                    tempPoint->y = atoi(token[1]);
                    tempNet->pins[j] = *tempPoint;
                    delete tempPoint;
                }
                rst->nets[i] = *tempNet;
                delete tempNet;
                if(i < rst->numNets -1) {// get the new net
                    fin.getline(buf, 512);

                    // parse the line into blank-delimited tokens
                    int m = 0; // a for-loop index

                    //parse the line
                    token[0] = strtok(buf, " "); // subsequent tokens
                    if(token[0]){ // zerof if line is blank
                        for (m = 1; m < 20; m++){
                            token[m] = strtok(0, " "); //subsequent tokens
                            if (!token[m]) break; // no more tokens
                        }
                    }
                }
            }
        }
        else{
            int num = atoi(token[0]);
            for(int i = 0; i < num; i++){
                fin.getline(buf, 512);
                // parse the line into blank-delimited tokens
                int m = 0; // a for-loop index

                //parse the line
                token[0] = strtok(buf, " "); // subsequent tokens
                if(token[0]){ // zerof if line is blank
                    for (m = 1; m < 20; m++){
                        token[m] = strtok(0, " "); //subsequent tokens
                        if (!token[m]) break; // no more tokens
                    }
                }
                int x1 = atoi(token[0]);
                int y1 = atoi(token[1]);
                int x2 = atoi(token[2]);
                int y2 = atoi(token[3]);
                int updatedCap = atoi(token[4]);

                // check if horizontal line
                if (y1 == y2) {
                    // calculate index in rst->edgeCaps
                    int xCap = 0;
                    if (x1 < x2)
                        xCap = x1;
                    else
                        xCap = x2;

                    int index = 2*y1 + xCap;
                    rst->edgeCaps[index] = updatedCap;
                }
                // else vertical line
                else {
                    // calculate index in rst->edgeCaps
                    int yCap = 0;
                    if (y1 < y2)
                        yCap = y1;
                    else
                        yCap = y2;

                    // number of horizontal indexes
                    rst->horizontalIndexes = (rst->gy)*(rst->gx - 1);

                    int index = rst->horizontalIndexes + 3*yCap + x1;
                    rst->edgeCaps[index] = updatedCap;
                }
            }
        }
    }
    return 1;
}

int solveRouting(routingInst *rst){
    //get every net in rst
    for (int i = 0; i < rst->numNets; i++) {
        net *tempNet = &(rst->nets[i]);
        tempNet->nroute.numSegs = 0;

        tempNet->nroute.segments = (segment *)malloc((tempNet->numPins-1)*2*sizeof(segment));

        for (int j = 0; j < tempNet->numPins-1; j++) {

            point p1 = tempNet->pins[j];
            point p2 = tempNet->pins[j+1];
            if (p1.x == p2.x || p1.y == p2.y) {
                segment *tempSeg = &(tempNet->nroute.segments[tempNet->nroute.numSegs]);
                tempNet->nroute.numSegs++;
                tempSeg->p1 = p1;
                tempSeg->p2 = p2;
                if (p1.x == p2.x) {
                    tempSeg->numEdges = abs(p1.y - p2.y);
                }
                else {
                    tempSeg->numEdges = abs(p1.x - p2.x);
                }

                // Needs to be changed after getIndex is complete
                tempSeg->edges = (int *)malloc(4*sizeof(int));
                tempSeg->edges[0] = p1.x;
                tempSeg->edges[1] = p1.y;
                tempSeg->edges[2] = p2.x;
                tempSeg->edges[3] = p2.y;
                // End of Changes to be made

            }
            else {
                point topP;
                point bottomP;
                if (p1.y < p2.y) {
                    topP = p2;
                    bottomP = p1;
                }
                else {
                    topP = p1;
                    bottomP = p2;
                 }
                // add topP to midPoint
                segment *tempSeg = &(tempNet->nroute.segments[tempNet->nroute.numSegs]);
                tempNet->nroute.numSegs++;
                tempSeg->p1 = topP;
                point *midPoint = new point;
                midPoint->x = topP.x;
                midPoint->y = bottomP.y;
                tempSeg->p2 = *midPoint;
                tempSeg->numEdges = abs(topP.y - midPoint->y);

                // Needs to be changed after getIndex is complete
                tempSeg->edges = (int *)malloc(4*sizeof(int));
                tempSeg->edges[0] = topP.x;
                tempSeg->edges[1] = topP.y;
                tempSeg->edges[2] = midPoint->x;
                tempSeg->edges[3] = midPoint->y;
                // End Changes

                //add midPoint to bottomP
                tempSeg = &(tempNet->nroute.segments[tempNet->nroute.numSegs]);
                tempNet->nroute.numSegs++;
                tempSeg->p1 = *midPoint;
                tempSeg->p2 = bottomP;
                tempSeg->numEdges = abs(midPoint->x - bottomP.x);

                // Needs to be changed after getIndex is complete
                tempSeg->edges = (int *)malloc(4*sizeof(int));
                tempSeg->edges[0] = midPoint->x;
                tempSeg->edges[1] = midPoint->y;
                tempSeg->edges[2] = bottomP.x;
                tempSeg->edges[3] = bottomP.y;
                // End Changes

            }
        }
    }
  return 1;
}

int writeOutput(const char *outRouteFile, routingInst *rst){
	try {
                ofstream output;
                output.open(outRouteFile);

                for (int i = 0; i < rst->numNets; i++) {

                        net tmpNet = rst->nets[i];
                        route tmpRoute = tmpNet.nroute;
                        output << "n" << tmpNet.id << "\n";

                        for (int j = 0; j < tmpRoute.numSegs; j++) {
                                segment tmpSeg = tmpRoute.segments[j];
                                output << "(" << tmpSeg.p1.x << "," << tmpSeg.p1.y << ")-(" <<
                                        tmpSeg.p2.x << "," << tmpSeg.p2.y << ")\n";
                        }
                        output << "!\n";
                }
                output.close();
        } catch(int e) {
                return 0;
        }
    return 1;
}

int release(routingInst *rst){
	try {
                for (int i = 0; i < rst->numNets; i++) {
                        net deleteNet = rst->nets[i];
                        delete deleteNet.nroute.segments;
                        delete deleteNet.pins;
                }

                delete rst->edgeCaps;
                //delete rst->edgeUtils;

                delete rst;

        } catch(int e) {
                return 0;
        }
    return 1;
}

int* getIndex(point p1, point p2, routingInst rst){
    int *index;
    int distance;
    index = (int *)malloc(sizeof(int));
    index[0] = -1;

    // check if horizontal line
    if (p1.y == p1.y) {
        // calculate index in rst->edgeCaps
        if ((p1.x-p2.x) == -1) {
            delete index;
            index = (int *)malloc(sizeof(int));
            index[0] = (rst.gx-1)*p1.y + p1.x;
        }
        else if((p1.x-p2.x) < -1) {
            distance = abs(p1.x-p2.x);
            delete index;
            index = (int *)malloc(distance*sizeof(int));
            for (int i=0; i < distance; i++) {
                index[0] = (rst.gx-1)*p1.y + p1.x + i;
            }
        }
        else if((p1.x-p2.x) == 1) {
            delete index;
            index = (int *)malloc(sizeof(int));
            index[0] = (rst.gx-1)*p1.y + p2.x;
        }
        else {
            distance = abs(p1.x-p2.x);
            delete index;
            index = (int *)malloc(distance*sizeof(int));
            for (int i=0; i < distance; i++) {
                index[0] = (rst.gx-1)*p1.y + p2.x + i;
            }
        } // case where p1.x-p2.x > 1
    }
    // else vertical line
    else if(p1.x == p2.x){
        // calculate index in rst->edgeCaps
        if ((p1.y-p2.y) == -1) {
            delete index;
            index = (int *)malloc(sizeof(int));
            index[0] = (rst.gy)*(rst.gx-1) + rst.gy*p1.y + p1.x;
        }
        else if ((p1.y-p2.y) < -1) {
            distance = abs(p1.x-p2.x);
            delete index;
            index = (int *)malloc(distance*sizeof(int));
            for (int i=0; i < distance; i++) {
                index[i] = (rst.gy)*(rst.gx-1) + rst.gy*(p1.y + i) + p1.x;
            }
        }
        else if ((p1.y-p2.y) == 1) {
            delete index;
            index = (int *)malloc(sizeof(int));
            index[0] = (rst.gy)*(rst.gx-1) + rst.gy*p2.y + p1.x;
        }
        else {
            distance = abs(p1.x-p2.x);
            delete index;
            index = (int *)malloc(distance*sizeof(int));
            for (int i=0; i < distance; i++) {
                index[i] = (rst.gy)*(rst.gx-1) + rst.gy*(p2.y + i) + p1.x;
            }
        } // case where p1.y-p2.y > 1
    }

    return index;
}
<commit_msg>debugged and fixed getIndex<commit_after>#include "ece556.h"

int* getIndex(point p1, point p2, routingInst *rst){
    int *index;
    int distance;
    index = (int *)malloc(sizeof(int));
    index[0] = -1;

    // check if horizontal line
    if (p1.y == p2.y) {
        // calculate index in rst->edgeCaps
        if ((p1.x-p2.x) == -1) {
            delete index;
            index = (int *)malloc(sizeof(int));
            index[0] = (rst->gx-1)*p1.y + p1.x;
        }
        else if((p1.x-p2.x) < -1) {
            distance = abs(p1.x-p2.x);
            delete index;
            index = (int *)malloc(distance*sizeof(int));
            for (int i=0; i < distance; i++) {
                index[i] = (rst->gx-1)*p1.y + p1.x + i;
            }
        }
        else if((p1.x-p2.x) == 1) {
            delete index;
            index = (int *)malloc(sizeof(int));
            index[0] = (rst->gx-1)*p1.y + p2.x;
        }
        else {
            distance = abs(p1.x-p2.x);
            delete index;
            index = (int *)malloc(distance*sizeof(int));
            for (int i=0; i < distance; i++) {
                index[i] = (rst->gx-1)*p1.y + p2.x + i;
            }
        } // case where p1.x-p2.x > 1
    }
    // else vertical line
    else if(p1.x == p2.x){
        // calculate index in rst->edgeCaps
        if ((p1.y-p2.y) == -1) {
            delete index;
            index = (int *)malloc(sizeof(int));
            index[0] = (rst->gy)*(rst->gx-1) + rst->gy*p1.y + p1.x;
        }
        else if ((p1.y-p2.y) < -1) {
            distance = abs(p1.y-p2.y);
            delete index;
            index = (int *)malloc(distance*sizeof(int));
            for (int i=0; i < distance; i++) {
                index[i] = (rst->gy)*(rst->gx-1) + rst->gy*(p1.y + i) + p1.x;
            }
        }
        else if ((p1.y-p2.y) == 1) {
            delete index;
            index = (int *)malloc(sizeof(int));
            index[0] = (rst->gy)*(rst->gx-1) + rst->gy*p2.y + p1.x;
        }
        else {
            distance = abs(p1.y-p2.y);
            delete index;
            index = (int *)malloc(distance*sizeof(int));
            for (int i=0; i < distance; i++) {
                index[i] = (rst->gy)*(rst->gx-1) + rst->gy*(p2.y + i) + p1.x;
            }
        } // case where p1.y-p2.y > 1
    }
    return index;
}

void handler(int sig) {
    void *array[10];
    size_t size;

    size = backtrace(array, 10);

    fprintf(stderr, "ERROR: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}

int readBenchmark(const char *fileName, routingInst *rst){
    ifstream fin;
    fin.open(fileName);
    if(!fin.good()) return 0;
    int v = 0;
    //read each line of the file
    const char* token[20] = {}; // initialize to 0
    while(!fin.eof()){
        v++;
        // read an entire line into memory
        char buf[512];
        fin.getline(buf, 512);

        // parse the line into blank-delimited tokens
        int n = 0; // a for-loop index

        // array to store memory addresses of the tokens in buff

        //parse the line
        token[0] = strtok(buf, " "); // subsequent tokens
        if(token[0]){ // zerof if line is blank
            for (n = 1; n < 20; n++){
                token[n] = strtok(0, " "); //subsequent tokens
                if (!token[n]) break; // no more tokens
            }
        }else break;

        if(strncmp(token[0], "grid", 64) == 0){
            int x = atoi(token[1]);
            int y = atoi(token[2]);

            rst->gx = x;
            rst->gy = y;
            rst->numEdges = y*(x-1) + x*(y-1);
            rst->edgeCaps = (int *)malloc(rst->numEdges * sizeof(int));
        }
        else if(strncmp(token[0], "capacity",64) == 0){
            rst->cap = atoi(token[1]);
            for (int i = 0; i < rst->numEdges; i++)
                rst->edgeCaps[i] = rst->cap;
        }
        else if(strncmp(token[0], "num", 64) == 0){
            rst->numNets = atoi(token[2]);
            rst->nets = (net *)malloc(rst->numNets*sizeof(net));
        }
        else if(strcmp(token[0], "n0") == 0){
            for(int i = 0; i < rst->numNets; i++){
                int num = atoi(token[1]);
                net *tempNet = new net;
                tempNet->id = i;
                tempNet->numPins = num;
                tempNet->pins = (point *)malloc(num*sizeof(point));
                for(int j = 0; j < num; j++){
                    fin.getline(buf, 512);

                    // parse the line into blank-delimited tokens
                    int m = 0; // a for-loop index

                    //parse the line
                    token[0] = strtok(buf, " "); // subsequent tokens
                    if(token[0]){ // zerof if line is blank
                        for (m = 1; m < 20; m++){
                            token[m] = strtok(0, " "); //subsequent tokens
                            if (!token[m]) break; // no more tokens
                        }
                    }
                    point *tempPoint = new point;
                    tempPoint->x = atoi(token[0]);
                    tempPoint->y = atoi(token[1]);
                    tempNet->pins[j] = *tempPoint;
                    delete tempPoint;
                }
                rst->nets[i] = *tempNet;
                delete tempNet;
                if(i < rst->numNets -1) {// get the new net
                    fin.getline(buf, 512);

                    // parse the line into blank-delimited tokens
                    int m = 0; // a for-loop index

                    //parse the line
                    token[0] = strtok(buf, " "); // subsequent tokens
                    if(token[0]){ // zerof if line is blank
                        for (m = 1; m < 20; m++){
                            token[m] = strtok(0, " "); //subsequent tokens
                            if (!token[m]) break; // no more tokens
                        }
                    }
                }
            }
        }
        else{
            int num = atoi(token[0]);
            for(int i = 0; i < num; i++){
                fin.getline(buf, 512);
                // parse the line into blank-delimited tokens
                int m = 0; // a for-loop index

                //parse the line
                token[0] = strtok(buf, " "); // subsequent tokens
                if(token[0]){ // zerof if line is blank
                    for (m = 1; m < 20; m++){
                        token[m] = strtok(0, " "); //subsequent tokens
                        if (!token[m]) break; // no more tokens
                    }
                }
                int x1 = atoi(token[0]);
                int y1 = atoi(token[1]);
                int x2 = atoi(token[2]);
                int y2 = atoi(token[3]);
                int updatedCap = atoi(token[4]);

                // check if horizontal line
                if (y1 == y2) {
                    // calculate index in rst->edgeCaps
                    int xCap = 0;
                    if (x1 < x2)
                        xCap = x1;
                    else
                        xCap = x2;

                    int index = 2*y1 + xCap;
                    rst->edgeCaps[index] = updatedCap;
                }
                // else vertical line
                else {
                    // calculate index in rst->edgeCaps
                    int yCap = 0;
                    if (y1 < y2)
                        yCap = y1;
                    else
                        yCap = y2;

                    // number of horizontal indexes
                    rst->horizontalIndexes = (rst->gy)*(rst->gx - 1);

                    int index = rst->horizontalIndexes + 3*yCap + x1;
                    rst->edgeCaps[index] = updatedCap;
                }
            }
        }
    }
    return 1;
}

int solveRouting(routingInst *rst){
    //get every net in rst
    for (int i = 0; i < rst->numNets; i++) {
        net *tempNet = &(rst->nets[i]);
        tempNet->nroute.numSegs = 0;

        tempNet->nroute.segments = (segment *)malloc((tempNet->numPins-1)*2*sizeof(segment));

        for (int j = 0; j < tempNet->numPins-1; j++) {

            point p1 = tempNet->pins[j];
            point p2 = tempNet->pins[j+1];
            if (p1.x == p2.x || p1.y == p2.y) {
                segment *tempSeg = &(tempNet->nroute.segments[tempNet->nroute.numSegs]);
                tempNet->nroute.numSegs++;
                tempSeg->p1 = p1;
                tempSeg->p2 = p2;
                if (p1.x == p2.x) {
                    tempSeg->numEdges = abs(p1.y - p2.y);
                }
                else {
                    tempSeg->numEdges = abs(p1.x - p2.x);
                }

                // Needs to be changed after getIndex is complete
                tempSeg->edges = (int *)malloc(4*sizeof(int));
                tempSeg->edges[0] = p1.x;
                tempSeg->edges[1] = p1.y;
                tempSeg->edges[2] = p2.x;
                tempSeg->edges[3] = p2.y;
                // End of Changes to be made

            }
            else {
                point topP;
                point bottomP;
                if (p1.y < p2.y) {
                    topP = p2;
                    bottomP = p1;
                }
                else {
                    topP = p1;
                    bottomP = p2;
                 }

                // add topP to midPoint
                segment *tempSeg = &(tempNet->nroute.segments[tempNet->nroute.numSegs]);
                tempNet->nroute.numSegs++;
                tempSeg->p1 = topP;
                point midPoint;
                midPoint.x = topP.x;
                midPoint.y = bottomP.y;
                tempSeg->p2 = midPoint;
                tempSeg->numEdges = abs(topP.y - midPoint.y);

                // save edges to the segment
                int* tempEdges = getIndex(topP,midPoint,rst);
                tempSeg->edges = (int *)malloc(tempSeg->numEdges*sizeof(int));
                tempSeg->edges = tempEdges;

                // uncomment for test purposes
                /*cout << "Start Segment:\n";
                for (int i = 0; i < tempSeg->numEdges; i++) {
                    cout << "edge: " << tempSeg->edges[i] << "\n";
                }
                cout << "\n";*/

                // add midPoint to bottomP
                tempSeg = &(tempNet->nroute.segments[tempNet->nroute.numSegs]);
                tempNet->nroute.numSegs++;
                tempSeg->p1 = midPoint;
                tempSeg->p2 = bottomP;
                tempSeg->numEdges = abs(midPoint.x - bottomP.x);

                // save edges to the segment
                tempEdges = getIndex(midPoint,bottomP,rst);
                tempSeg->edges = (int *)malloc(tempSeg->numEdges*sizeof(int));
                tempSeg->edges = tempEdges;

                // uncomment for test purposes
                /*cout << "Start Segment:\n";
                for (int i = 0; i < tempSeg->numEdges; i++) {
                    cout << "edge: " << tempSeg->edges[i] << "\n";
                }
                cout << "\n";*/
            }
        }
    }
  return 1;
}

int writeOutput(const char *outRouteFile, routingInst *rst){
	try {
                ofstream output;
                output.open(outRouteFile);

                for (int i = 0; i < rst->numNets; i++) {

                        net tmpNet = rst->nets[i];
                        route tmpRoute = tmpNet.nroute;
                        output << "n" << tmpNet.id << "\n";

                        for (int j = 0; j < tmpRoute.numSegs; j++) {
                                segment tmpSeg = tmpRoute.segments[j];
                                output << "(" << tmpSeg.p1.x << "," << tmpSeg.p1.y << ")-(" <<
                                        tmpSeg.p2.x << "," << tmpSeg.p2.y << ")\n";
                        }
                        output << "!\n";
                }
                output.close();
        } catch(int e) {
                return 0;
        }
    return 1;
}

int release(routingInst *rst){
	try {
                for (int i = 0; i < rst->numNets; i++) {
                        net deleteNet = rst->nets[i];
                        delete deleteNet.nroute.segments;
                        delete deleteNet.pins;
                }

                delete rst->edgeCaps;
                //delete rst->edgeUtils;

                delete rst;

        } catch(int e) {
                return 0;
        }
    return 1;
}
<|endoftext|>