<commit_before>#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <cassert>
#include <cstring>
#include <memory>

#include "server.hh"
#include "accept.hh"
#include "../thread.hh"

namespace mimosa
{
  namespace net
  {
    Server::Server()
      : fd_(-1)
    {
    }

    Server::~Server()
    {
      if (fd_ >= 0)
        ::close(fd_);
    }

#define LISTEN_COMMON_1(Domain)                         \
    do {                                                \
      if (fd_ >= 0)                                     \
        ::close(fd_);                                   \
                                                        \
      fd_ = ::socket(Domain, SOCK_STREAM, 0);           \
      if (fd_ < 0)                                      \
        return false;                                   \
                                                        \
      static const int enable = 1;                      \
      ::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR,       \
                   &enable, sizeof(enable));            \
    } while (0)

#define LISTEN_COMMON_2()                                       \
    do {                                                        \
      if (::bind(fd_, (struct sockaddr *)&addr, sizeof (addr))) \
        goto failure;                                           \
      if (::listen(fd_, 10))                                    \
        goto failure;                                           \
      return true;                                              \
                                                                \
      failure:                                                  \
      ::close(fd_);                                             \
      fd_ = -1;                                                 \
      return false;                                             \
    } while (0)

    bool
    Server::listenInet4(uint16_t port, const struct ::in_addr * interface)
    {
      LISTEN_COMMON_1(AF_INET);

      struct sockaddr_in addr;
      ::memset(&addr, 0, sizeof (addr));
      addr.sin_addr.s_addr = interface ? interface->s_addr : INADDR_ANY;
      addr.sin_family      = AF_INET;
      addr.sin_port        = htons(port);

      LISTEN_COMMON_2();
    }

    bool
    Server::listenInet6(uint16_t port, const::in6_addr *interface)
    {
      LISTEN_COMMON_1(AF_INET6);

      // accepts ipv4 connections
      static const int disable = 0;
      ::setsockopt(fd_, IPPROTO_IPV6, IPV6_V6ONLY, &disable, sizeof (disable));

      struct sockaddr_in6 addr;
      ::memset(&addr, 0, sizeof (addr));
      addr.sin6_addr   = interface ? *interface : ::in6addr_any;
      addr.sin6_family = AF_INET6;
      addr.sin6_port   = htons(port);

      LISTEN_COMMON_2();
    }

    bool
    Server::listenUnix(const std::string & path)
    {
      LISTEN_COMMON_1(AF_UNIX);

      std::unique_ptr<char> data(
        new char[((size_t) (((::sockaddr_un *) 0)->sun_path)) + path.size() + 1]);
      ::sockaddr_un & addr = *(::sockaddr_un*)data.get();
      addr.sun_family = AF_UNIX;
      ::memcpy(addr.sun_path, path.c_str(), path.size() + 1);
      ::unlink(path.c_str());

      LISTEN_COMMON_2();
    }

    int
    Server::accept(::sockaddr *  address,
                   ::socklen_t * address_len,
                   Time timeout) const
    {
      return net::accept(fd_, address, address_len, timeout);
    }

    void
    Server::serveOne(Time accept_timeout, bool new_thread) const
    {
      union {
        ::sockaddr addr;
        ::sockaddr_in in_addr;
        ::sockaddr_in6 in6_addr;
        ::sockaddr_un un_addr;
      } addr;
      ::socklen_t addr_len = sizeof (addr);

      int fd = accept(&addr.addr, &addr_len, accept_timeout);
      if (fd >= 0)
      {
        Server::ConstPtr server(this);
        if (new_thread)
          Thread([server, fd, addr, addr_len] {
              try {
                server->serve(fd, &addr.addr, addr_len);
              } catch (...) {
              }
            }).start();
        else
          serve(fd, &addr.addr, addr_len);
      }
    }

    void
    Server::close()
    {
      if (fd_ == -1)
        return;

      int fd = fd_;
      fd_ = -1;
      ::close(fd);
    }

    void
    Server::serve(int                fd,
                  const ::sockaddr * address,
                  socklen_t          address_len) const
    {
      ::close(fd);
    }
  }
}
<commit_msg>net::Server: fix  mismatch new/delete for listenUnix()<commit_after>#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <cassert>
#include <cstring>
#include <memory>

#include "server.hh"
#include "accept.hh"
#include "../thread.hh"

namespace mimosa
{
  namespace net
  {
    Server::Server()
      : fd_(-1)
    {
    }

    Server::~Server()
    {
      if (fd_ >= 0)
        ::close(fd_);
    }

#define LISTEN_COMMON_1(Domain)                         \
    do {                                                \
      if (fd_ >= 0)                                     \
        ::close(fd_);                                   \
                                                        \
      fd_ = ::socket(Domain, SOCK_STREAM, 0);           \
      if (fd_ < 0)                                      \
        return false;                                   \
                                                        \
      static const int enable = 1;                      \
      ::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR,       \
                   &enable, sizeof(enable));            \
    } while (0)

#define LISTEN_COMMON_2()                                       \
    do {                                                        \
      if (::bind(fd_, (struct sockaddr *)&addr, sizeof (addr))) \
        goto failure;                                           \
      if (::listen(fd_, 10))                                    \
        goto failure;                                           \
      return true;                                              \
                                                                \
      failure:                                                  \
      ::close(fd_);                                             \
      fd_ = -1;                                                 \
      return false;                                             \
    } while (0)

    bool
    Server::listenInet4(uint16_t port, const struct ::in_addr * interface)
    {
      LISTEN_COMMON_1(AF_INET);

      struct sockaddr_in addr;
      ::memset(&addr, 0, sizeof (addr));
      addr.sin_addr.s_addr = interface ? interface->s_addr : INADDR_ANY;
      addr.sin_family      = AF_INET;
      addr.sin_port        = htons(port);

      LISTEN_COMMON_2();
    }

    bool
    Server::listenInet6(uint16_t port, const::in6_addr *interface)
    {
      LISTEN_COMMON_1(AF_INET6);

      // accepts ipv4 connections
      static const int disable = 0;
      ::setsockopt(fd_, IPPROTO_IPV6, IPV6_V6ONLY, &disable, sizeof (disable));

      struct sockaddr_in6 addr;
      ::memset(&addr, 0, sizeof (addr));
      addr.sin6_addr   = interface ? *interface : ::in6addr_any;
      addr.sin6_family = AF_INET6;
      addr.sin6_port   = htons(port);

      LISTEN_COMMON_2();
    }

    bool
    Server::listenUnix(const std::string & path)
    {
      LISTEN_COMMON_1(AF_UNIX);

      char data[((size_t) (((::sockaddr_un *) 0)->sun_path)) + path.size() + 1];
      ::sockaddr_un & addr = *(::sockaddr_un*)data;
      addr.sun_family = AF_UNIX;
      ::memcpy(addr.sun_path, path.c_str(), path.size() + 1);
      ::unlink(path.c_str());

      LISTEN_COMMON_2();
    }

    int
    Server::accept(::sockaddr *  address,
                   ::socklen_t * address_len,
                   Time timeout) const
    {
      return net::accept(fd_, address, address_len, timeout);
    }

    void
    Server::serveOne(Time accept_timeout, bool new_thread) const
    {
      union {
        ::sockaddr addr;
        ::sockaddr_in in_addr;
        ::sockaddr_in6 in6_addr;
        ::sockaddr_un un_addr;
      } addr;
      ::socklen_t addr_len = sizeof (addr);

      int fd = accept(&addr.addr, &addr_len, accept_timeout);
      if (fd >= 0)
      {
        Server::ConstPtr server(this);
        if (new_thread)
          Thread([server, fd, addr, addr_len] {
              try {
                server->serve(fd, &addr.addr, addr_len);
              } catch (...) {
              }
            }).start();
        else
          serve(fd, &addr.addr, addr_len);
      }
    }

    void
    Server::close()
    {
      if (fd_ == -1)
        return;

      int fd = fd_;
      fd_ = -1;
      ::close(fd);
    }

    void
    Server::serve(int                fd,
                  const ::sockaddr * address,
                  socklen_t          address_len) const
    {
      ::close(fd);
    }
  }
}
<|endoftext|>


<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 jsonrpc.cpp
 * @author Marek Kotewicz <marek@ethdev.com>
 * @date 2014
 */

#if ETH_JSONRPC && 1

#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <libdevcore/Log.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonJS.h>
#include <libwebthree/WebThree.h>
#include <libethrpc/WebThreeStubServer.h>
#include <libethrpc/CorsHttpServer.h>
#include <jsonrpc/connectors/httpserver.h>
#include <jsonrpc/connectors/httpclient.h>
#include <set>
#include "JsonSpiritHeaders.h"
#include "TestHelper.h"
#include "webthreestubclient.h"

using namespace std;
using namespace dev;
using namespace dev::eth;
namespace js = json_spirit;

namespace jsonrpc_tests
{

string name = "Ethereum(++) tests";
string dbPath;
auto s = set<string>{"eth", "shh"};
dev::p2p::NetworkPreferences np(30303, std::string(), false);
dev::WebThreeDirect web3(name, dbPath, true, s, np);

auto_ptr<WebThreeStubServer> jsonrpcServer;
auto_ptr<WebThreeStubClient> jsonrpcClient;

struct JsonrpcFixture  {
	JsonrpcFixture()
	{
		cnote << "setup jsonrpc";

		web3.setIdealPeerCount(5);
		web3.ethereum()->setForceMining(true);
		jsonrpcServer = auto_ptr<WebThreeStubServer>(new WebThreeStubServer(new jsonrpc::CorsHttpServer(8080), web3, {}));
		jsonrpcServer->StartListening();

		jsonrpcClient = auto_ptr<WebThreeStubClient>(new WebThreeStubClient(new jsonrpc::HttpClient("http://localhost:8080")));
	}
	~JsonrpcFixture()
	{
		cnote << "teardown jsonrpc";
	}
};

BOOST_GLOBAL_FIXTURE(JsonrpcFixture)

BOOST_AUTO_TEST_CASE(jsonrpc_balanceAt)
{
	cnote << "Testing jsonrpc balanceAt...";
	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	string balance = jsonrpcClient->balanceAt(toJS(address), 0);
	BOOST_CHECK_EQUAL(toJS(web3.ethereum()->balanceAt(address)), balance);
}

BOOST_AUTO_TEST_CASE(jsonrpc_call)
{
}

BOOST_AUTO_TEST_CASE(jsonrpc_coinbase)
{
	cnote << "Testing jsonrpc coinbase...";
	string coinbase = jsonrpcClient->coinbase();
	BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3.ethereum()->address());
}

BOOST_AUTO_TEST_CASE(jsonrpc_countAt)
{
	cnote << "Testing jsonrpc countAt...";
	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	double countAt = jsonrpcClient->countAt(toJS(address), 0);
	BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3.ethereum()->countAt(address, 0));
}

BOOST_AUTO_TEST_CASE(jsonrpc_defaultBlock)
{
	cnote << "Testing jsonrpc defaultBlock...";
	int defaultBlock = jsonrpcClient->defaultBlock();
	BOOST_CHECK_EQUAL(defaultBlock, web3.ethereum()->getDefault());
}

BOOST_AUTO_TEST_CASE(jsonrpc_fromAscii)
{
	cnote << "Testing jsonrpc fromAscii...";
	string testString = "1234567890987654";
	string fromAscii = jsonrpcClient->fromAscii(32, testString);
	BOOST_CHECK_EQUAL(fromAscii, jsFromBinary(testString, 32));

}

BOOST_AUTO_TEST_CASE(jsonrpc_fromFixed)
{
	cnote << "Testing jsonrpc fromFixed...";
	string testString = "0x1234567890987654";
	double fromFixed = jsonrpcClient->fromFixed(testString);
	double ff = jsFromFixed(testString);
	string str1 = boost::lexical_cast<string> (fromFixed);
	string str2 = boost::lexical_cast<string> (ff);
	BOOST_CHECK_EQUAL(str1.substr(0, 3), str2.substr(0, 3));
}

BOOST_AUTO_TEST_CASE(jsonrpc_gasPrice)
{
	cnote << "Testing jsonrpc gasPrice...";
	string gasPrice = jsonrpcClient->gasPrice();
	BOOST_CHECK_EQUAL(gasPrice, toJS(10 * dev::eth::szabo));
}

BOOST_AUTO_TEST_CASE(jsonrpc_isListening)
{
	cnote << "Testing jsonrpc isListening...";

	web3.startNetwork();
	bool listeningOn = jsonrpcClient->listening();
	BOOST_CHECK_EQUAL(listeningOn, web3.isNetworkStarted());

	web3.stopNetwork();
	bool listeningOff = jsonrpcClient->listening();
	BOOST_CHECK_EQUAL(listeningOff, web3.isNetworkStarted());
}

BOOST_AUTO_TEST_CASE(jsonrpc_isMining)
{
	cnote << "Testing jsonrpc isMining...";

	web3.ethereum()->startMining();
	bool miningOn = jsonrpcClient->mining();
	BOOST_CHECK_EQUAL(miningOn, web3.ethereum()->isMining());

	web3.ethereum()->stopMining();
	bool miningOff = jsonrpcClient->mining();
	BOOST_CHECK_EQUAL(miningOff, web3.ethereum()->isMining());
}

BOOST_AUTO_TEST_CASE(jsonrpc_key)
{
	cnote << "Testing jsonrpc key...";
	dev::KeyPair key = KeyPair::create();
	jsonrpcServer->setKeys({key});
	string clientSecret = jsonrpcClient->key();
	jsonrpcServer->setKeys({});
	BOOST_CHECK_EQUAL(jsToSecret(clientSecret), key.secret());
}

BOOST_AUTO_TEST_CASE(jsonrpc_keys)
{
	cnote << "Testing jsonrpc keys...";
	std::vector <dev::KeyPair> keys = {KeyPair::create(), KeyPair::create()};
	jsonrpcServer->setKeys(keys);
	Json::Value k = jsonrpcClient->keys();
	jsonrpcServer->setKeys({});
	BOOST_CHECK_EQUAL(k.isArray(), true);
	BOOST_CHECK_EQUAL(k.size(),  keys.size());
	for (unsigned i = 0; i < k.size(); i++)
		BOOST_CHECK_EQUAL(jsToSecret(k[i].asString()) , keys[i].secret());
}

BOOST_AUTO_TEST_CASE(jsonrpc_messages)
{
	cnote << "Testing jsonrpc messages...";
	Json::Value msgs = jsonrpcClient->messages(Json::Value());
	auto messages = web3.ethereum()->messages(dev::eth::MessageFilter());
	BOOST_CHECK_EQUAL(msgs.isArray(), true);
	BOOST_CHECK_EQUAL(msgs.size(), messages.size());
}

BOOST_AUTO_TEST_CASE(jsonrpc_number)
{
	cnote << "Testing jsonrpc number...";
	int number = jsonrpcClient->number();
	BOOST_CHECK_EQUAL(number, web3.ethereum()->number() + 1);
}

BOOST_AUTO_TEST_CASE(jsonrpc_number2)
{
	cnote << "Testing jsonrpc number2...";
	int number = jsonrpcClient->number();
	BOOST_CHECK_EQUAL(number, web3.ethereum()->number() + 1);
	dev::eth::mine(*(web3.ethereum()), 1);
	int numberAfter = jsonrpcClient->number();
	BOOST_CHECK_EQUAL(number + 1, numberAfter);
	BOOST_CHECK_EQUAL(numberAfter, web3.ethereum()->number() + 1);
}

BOOST_AUTO_TEST_CASE(jsonrpc_peerCount)
{
	cnote << "Testing jsonrpc peerCount...";
	int peerCount = jsonrpcClient->peerCount();
	BOOST_CHECK_EQUAL(web3.peerCount(), peerCount);
}

BOOST_AUTO_TEST_CASE(jsonrpc_secretToAddress)
{
	cnote << "Testing jsonrpc secretToAddress...";
	dev::KeyPair pair = dev::KeyPair::create();
	string address = jsonrpcClient->secretToAddress(toJS(pair.secret()));
	BOOST_CHECK_EQUAL(jsToAddress(address), pair.address());
}

BOOST_AUTO_TEST_CASE(jsonrpc_setListening)
{
	cnote << "Testing jsonrpc setListening...";

	jsonrpcClient->setListening(true);
	BOOST_CHECK_EQUAL(web3.isNetworkStarted(), true);

	jsonrpcClient->setListening(false);
	BOOST_CHECK_EQUAL(web3.isNetworkStarted(), false);
}

BOOST_AUTO_TEST_CASE(jsonrpc_setMining)
{
	cnote << "Testing jsonrpc setMining...";

	jsonrpcClient->setMining(true);
	BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), true);

	jsonrpcClient->setMining(false);
	BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), false);
}

BOOST_AUTO_TEST_CASE(jsonrpc_sha3)
{
	cnote << "Testing jsonrpc sha3...";
	string testString = "1234567890987654";
	string sha3 = jsonrpcClient->sha3(testString);
	BOOST_CHECK_EQUAL(jsToFixed<32>(sha3), dev::sha3(jsToBytes(testString)));
}

BOOST_AUTO_TEST_CASE(jsonrpc_stateAt)
{
	cnote << "Testing jsonrpc stateAt...";
	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	string stateAt = jsonrpcClient->stateAt(toJS(address), 0, "0");
	BOOST_CHECK_EQUAL(toJS(web3.ethereum()->stateAt(address, jsToU256("0"), 0)), stateAt);
}

BOOST_AUTO_TEST_CASE(jsonrpc_toAscii)
{
	cnote << "Testing jsonrpc toAscii...";
	string testString = "1234567890987654";
	string ascii = jsonrpcClient->toAscii(testString);
	BOOST_CHECK_EQUAL(jsToBinary(testString), ascii);
}

BOOST_AUTO_TEST_CASE(jsonrpc_toDecimal)
{
	cnote << "Testing jsonrpc toDecimal...";
	string testString = "1234567890987654";
	string decimal = jsonrpcClient->toDecimal(testString);
	BOOST_CHECK_EQUAL(jsToDecimal(testString), decimal);
}

BOOST_AUTO_TEST_CASE(jsonrpc_toFixed)
{
	cnote << "Testing jsonrpc toFixed...";
	double testValue = 123567;
	string fixed = jsonrpcClient->toFixed(testValue);
	BOOST_CHECK_EQUAL(jsToFixed(testValue), fixed);
	BOOST_CHECK_EQUAL(testValue, jsFromFixed(fixed));
}

BOOST_AUTO_TEST_CASE(jsonrpc_transact)
{
	cnote << "Testing jsonrpc transact...";
	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	auto receiver = KeyPair::create();

	web3.ethereum()->setAddress(address);
	dev::eth::mine(*(web3.ethereum()), 1);
	auto balance = web3.ethereum()->balanceAt(address, 0);
	BOOST_REQUIRE(balance > 0);
	auto txAmount = balance / 2u;
	auto gasPrice = 10 * dev::eth::szabo;
	auto gas = dev::eth::c_txGas;

	Json::Value t;
	t["from"] = toJS(key.secret());
	t["value"] = jsToDecimal(toJS(txAmount));
	t["to"] = toJS(receiver.address());
	t["data"] = toJS(bytes());
	t["gas"] = toJS(gas);
	t["gasPrice"] = toJS(gasPrice);

	jsonrpcClient->transact(t);

	dev::eth::mine(*(web3.ethereum()), 1);
	auto balance2 = web3.ethereum()->balanceAt(receiver.address());
	auto messages = jsonrpcClient->messages(Json::Value());
	BOOST_REQUIRE(balance2 > 0);
	BOOST_CHECK_EQUAL(txAmount, balance2);
	BOOST_CHECK_EQUAL(txAmount, jsToU256(messages[0u]["value"].asString()));
}

}

#endif
<commit_msg>common changes in tests<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 jsonrpc.cpp
 * @author Marek Kotewicz <marek@ethdev.com>
 * @date 2014
 */

#if ETH_JSONRPC && 1

#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <libdevcore/Log.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonJS.h>
#include <libwebthree/WebThree.h>
#include <libethrpc/WebThreeStubServer.h>
#include <libethrpc/CorsHttpServer.h>
#include <jsonrpc/connectors/httpserver.h>
#include <jsonrpc/connectors/httpclient.h>
#include <set>
#include "JsonSpiritHeaders.h"
#include "TestHelper.h"
#include "webthreestubclient.h"

using namespace std;
using namespace dev;
using namespace dev::eth;
namespace js = json_spirit;

namespace jsonrpc_tests
{

string name = "Ethereum(++) tests";
string dbPath;
auto s = set<string>{"eth", "shh"};
dev::p2p::NetworkPreferences np(30303, std::string(), false);
dev::WebThreeDirect web3(name, dbPath, true, s, np);

auto_ptr<WebThreeStubServer> jsonrpcServer;
auto_ptr<WebThreeStubClient> jsonrpcClient;

struct JsonrpcFixture  {
	JsonrpcFixture()
	{
		cnote << "setup jsonrpc";

		web3.setIdealPeerCount(5);
		web3.ethereum()->setForceMining(true);
		jsonrpcServer = auto_ptr<WebThreeStubServer>(new WebThreeStubServer(new jsonrpc::CorsHttpServer(8080), web3, {}));
		jsonrpcServer->StartListening();

		jsonrpcClient = auto_ptr<WebThreeStubClient>(new WebThreeStubClient(new jsonrpc::HttpClient("http://localhost:8080")));
	}
	~JsonrpcFixture()
	{
		cnote << "teardown jsonrpc";
	}
};

BOOST_GLOBAL_FIXTURE(JsonrpcFixture)

BOOST_AUTO_TEST_CASE(jsonrpc_balanceAt)
{
	cnote << "Testing jsonrpc balanceAt...";
	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	string balance = jsonrpcClient->balanceAt(toJS(address), 0);
	BOOST_CHECK_EQUAL(toJS(web3.ethereum()->balanceAt(address)), balance);
}

BOOST_AUTO_TEST_CASE(jsonrpc_call)
{
}

BOOST_AUTO_TEST_CASE(jsonrpc_coinbase)
{
	cnote << "Testing jsonrpc coinbase...";
	string coinbase = jsonrpcClient->coinbase();
	BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3.ethereum()->address());
}

BOOST_AUTO_TEST_CASE(jsonrpc_countAt)
{
	cnote << "Testing jsonrpc countAt...";
	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	double countAt = jsonrpcClient->countAt(toJS(address), 0);
	BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3.ethereum()->countAt(address, 0));
}

BOOST_AUTO_TEST_CASE(jsonrpc_defaultBlock)
{
	cnote << "Testing jsonrpc defaultBlock...";
	int defaultBlock = jsonrpcClient->defaultBlock();
	BOOST_CHECK_EQUAL(defaultBlock, web3.ethereum()->getDefault());
}

BOOST_AUTO_TEST_CASE(jsonrpc_fromAscii)
{
	cnote << "Testing jsonrpc fromAscii...";
	string testString = "1234567890987654";
	string fromAscii = jsonrpcClient->fromAscii(32, testString);
	BOOST_CHECK_EQUAL(fromAscii, jsFromBinary(testString, 32));

}

BOOST_AUTO_TEST_CASE(jsonrpc_fromFixed)
{
	cnote << "Testing jsonrpc fromFixed...";
	string testString = "0x1234567890987654";
	double fromFixed = jsonrpcClient->fromFixed(testString);
	double ff = jsFromFixed(testString);
	string str1 = boost::lexical_cast<string> (fromFixed);
	string str2 = boost::lexical_cast<string> (ff);
	BOOST_CHECK_EQUAL(str1.substr(0, 3), str2.substr(0, 3));
}

BOOST_AUTO_TEST_CASE(jsonrpc_gasPrice)
{
	cnote << "Testing jsonrpc gasPrice...";
	string gasPrice = jsonrpcClient->gasPrice();
	BOOST_CHECK_EQUAL(gasPrice, toJS(10 * dev::eth::szabo));
}

BOOST_AUTO_TEST_CASE(jsonrpc_isListening)
{
	cnote << "Testing jsonrpc isListening...";

	web3.startNetwork();
	bool listeningOn = jsonrpcClient->listening();
	BOOST_CHECK_EQUAL(listeningOn, web3.isNetworkStarted());

	web3.stopNetwork();
	bool listeningOff = jsonrpcClient->listening();
	BOOST_CHECK_EQUAL(listeningOff, web3.isNetworkStarted());
}

BOOST_AUTO_TEST_CASE(jsonrpc_isMining)
{
	cnote << "Testing jsonrpc isMining...";

	web3.ethereum()->startMining();
	bool miningOn = jsonrpcClient->mining();
	BOOST_CHECK_EQUAL(miningOn, web3.ethereum()->isMining());

	web3.ethereum()->stopMining();
	bool miningOff = jsonrpcClient->mining();
	BOOST_CHECK_EQUAL(miningOff, web3.ethereum()->isMining());
}

BOOST_AUTO_TEST_CASE(jsonrpc_accounts)
{
	cnote << "Testing jsonrpc accounts...";
	std::vector <dev::KeyPair> keys = {KeyPair::create(), KeyPair::create()};
	jsonrpcServer->setAccounts(keys);
	Json::Value k = jsonrpcClient->accounts();
	jsonrpcServer->setAccounts({});
	BOOST_CHECK_EQUAL(k.isArray(), true);
	BOOST_CHECK_EQUAL(k.size(),  keys.size());
	for (auto &i:k)
	{
		auto it = std::find_if(keys.begin(), keys.end(), [i](dev::KeyPair const& keyPair){
			return jsToAddress(i.asString()) == keyPair.address();
		});
		BOOST_CHECK_EQUAL(it != keys.end(), true);
	}
}

BOOST_AUTO_TEST_CASE(jsonrpc_messages)
{
	cnote << "Testing jsonrpc messages...";
	Json::Value msgs = jsonrpcClient->messages(Json::Value());
	auto messages = web3.ethereum()->messages(dev::eth::MessageFilter());
	BOOST_CHECK_EQUAL(msgs.isArray(), true);
	BOOST_CHECK_EQUAL(msgs.size(), messages.size());
}

BOOST_AUTO_TEST_CASE(jsonrpc_number)
{
	cnote << "Testing jsonrpc number...";
	int number = jsonrpcClient->number();
	BOOST_CHECK_EQUAL(number, web3.ethereum()->number() + 1);
}

BOOST_AUTO_TEST_CASE(jsonrpc_number2)
{
	cnote << "Testing jsonrpc number2...";
	int number = jsonrpcClient->number();
	BOOST_CHECK_EQUAL(number, web3.ethereum()->number() + 1);
	dev::eth::mine(*(web3.ethereum()), 1);
	int numberAfter = jsonrpcClient->number();
	BOOST_CHECK_EQUAL(number + 1, numberAfter);
	BOOST_CHECK_EQUAL(numberAfter, web3.ethereum()->number() + 1);
}

BOOST_AUTO_TEST_CASE(jsonrpc_peerCount)
{
	cnote << "Testing jsonrpc peerCount...";
	int peerCount = jsonrpcClient->peerCount();
	BOOST_CHECK_EQUAL(web3.peerCount(), peerCount);
}

BOOST_AUTO_TEST_CASE(jsonrpc_secretToAddress)
{
	cnote << "Testing jsonrpc secretToAddress...";
	dev::KeyPair pair = dev::KeyPair::create();
	string address = jsonrpcClient->secretToAddress(toJS(pair.secret()));
	BOOST_CHECK_EQUAL(jsToAddress(address), pair.address());
}

BOOST_AUTO_TEST_CASE(jsonrpc_setListening)
{
	cnote << "Testing jsonrpc setListening...";

	jsonrpcClient->setListening(true);
	BOOST_CHECK_EQUAL(web3.isNetworkStarted(), true);

	jsonrpcClient->setListening(false);
	BOOST_CHECK_EQUAL(web3.isNetworkStarted(), false);
}

BOOST_AUTO_TEST_CASE(jsonrpc_setMining)
{
	cnote << "Testing jsonrpc setMining...";

	jsonrpcClient->setMining(true);
	BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), true);

	jsonrpcClient->setMining(false);
	BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), false);
}

BOOST_AUTO_TEST_CASE(jsonrpc_sha3)
{
	cnote << "Testing jsonrpc sha3...";
	string testString = "1234567890987654";
	string sha3 = jsonrpcClient->sha3(testString);
	BOOST_CHECK_EQUAL(jsToFixed<32>(sha3), dev::sha3(jsToBytes(testString)));
}

BOOST_AUTO_TEST_CASE(jsonrpc_stateAt)
{
	cnote << "Testing jsonrpc stateAt...";
	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	string stateAt = jsonrpcClient->stateAt(toJS(address), 0, "0");
	BOOST_CHECK_EQUAL(toJS(web3.ethereum()->stateAt(address, jsToU256("0"), 0)), stateAt);
}

BOOST_AUTO_TEST_CASE(jsonrpc_toAscii)
{
	cnote << "Testing jsonrpc toAscii...";
	string testString = "1234567890987654";
	string ascii = jsonrpcClient->toAscii(testString);
	BOOST_CHECK_EQUAL(jsToBinary(testString), ascii);
}

BOOST_AUTO_TEST_CASE(jsonrpc_toDecimal)
{
	cnote << "Testing jsonrpc toDecimal...";
	string testString = "1234567890987654";
	string decimal = jsonrpcClient->toDecimal(testString);
	BOOST_CHECK_EQUAL(jsToDecimal(testString), decimal);
}

BOOST_AUTO_TEST_CASE(jsonrpc_toFixed)
{
	cnote << "Testing jsonrpc toFixed...";
	double testValue = 123567;
	string fixed = jsonrpcClient->toFixed(testValue);
	BOOST_CHECK_EQUAL(jsToFixed(testValue), fixed);
	BOOST_CHECK_EQUAL(testValue, jsFromFixed(fixed));
}

BOOST_AUTO_TEST_CASE(jsonrpc_transact)
{
	cnote << "Testing jsonrpc transact...";
	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	auto receiver = KeyPair::create();

	web3.ethereum()->setAddress(address);
	jsonrpcServer->setAccounts({key});
	dev::eth::mine(*(web3.ethereum()), 1);
	auto balance = web3.ethereum()->balanceAt(address, 0);
	BOOST_REQUIRE(balance > 0);
	auto txAmount = balance / 2u;
	auto gasPrice = 10 * dev::eth::szabo;
	auto gas = dev::eth::c_txGas;

	Json::Value t;
	t["from"] = toJS(address);
	t["value"] = jsToDecimal(toJS(txAmount));
	t["to"] = toJS(receiver.address());
	t["data"] = toJS(bytes());
	t["gas"] = toJS(gas);
	t["gasPrice"] = toJS(gasPrice);

	jsonrpcClient->transact(t);
	jsonrpcServer->setAccounts({});
	dev::eth::mine(*(web3.ethereum()), 1);
	auto balance2 = web3.ethereum()->balanceAt(receiver.address());
	auto messages = jsonrpcClient->messages(Json::Value());

	BOOST_REQUIRE(balance2 > 0);
	BOOST_CHECK_EQUAL(txAmount, balance2);
	BOOST_CHECK_EQUAL(txAmount, jsToU256(messages[0u]["value"].asString()));
}

}

#endif
<|endoftext|>


<commit_before>#include "NoiseModuleManager.h"
#include "ModuleFactories.h"
#include <random>
#include <time.h>

NoiseModuleManager::NoiseModuleManager(const Options & options) :
    mRNG(time(nullptr))
{
    for (const auto& terrain : options.terrains)
    {
        mStochasticMasks.insert({terrain.first, makePlaceholder()});
    }
    for (const auto& clique : options.cliques)
    {
        // At least n*(n-1)/2 duplicates will be checked in each clique.
        for (const auto& t1 : clique)
            for (const auto& t2 : clique)
            {
                TerrainIDPair tp{t1, t2};
                if (mBordersHorizontal.find(tp) == mBordersHorizontal.end())
                    mBordersHorizontal.insert({tp, makePlaceholder(mRNG())});
                if (mBordersVertical.find(tp) == mBordersVertical.end())
                    mBordersVertical.insert({tp, makePlaceholder(mRNG())});
            }
    }
}

NoiseModuleManager::~NoiseModuleManager()
{
}

Reseedable& NoiseModuleManager::getBorderVertical(TerrainID top, TerrainID bottom, bool x_positive)
{
    Reseedable& r = mBordersVertical.at({top, bottom});
    if (x_positive)
        return r;
    return r.translatePoint(-1., 0., 0.);
}

Reseedable& NoiseModuleManager::getBorderHorizontal(TerrainID left, TerrainID right, bool y_positive)
{
    Reseedable& r = mBordersHorizontal.at({left, right});
    if (y_positive)
        return r;
    return r.translatePoint(0., -1., 0.);
}

Reseedable& NoiseModuleManager::getStochastic(TerrainID terrain)
{
    Reseedable& r = mStochasticMasks.at(terrain);
    r.setSeed(mRNG());
    return r;
}
<commit_msg>Fix type conversion warning<commit_after>#include "NoiseModuleManager.h"
#include "ModuleFactories.h"
#include <random>
#include <time.h>

NoiseModuleManager::NoiseModuleManager(const Options & options) :
    mRNG((unsigned int)time(nullptr))
{
    for (const auto& terrain : options.terrains)
    {
        mStochasticMasks.insert({terrain.first, makePlaceholder()});
    }
    for (const auto& clique : options.cliques)
    {
        // At least n*(n-1)/2 duplicates will be checked in each clique.
        for (const auto& t1 : clique)
            for (const auto& t2 : clique)
            {
                TerrainIDPair tp{t1, t2};
                if (mBordersHorizontal.find(tp) == mBordersHorizontal.end())
                    mBordersHorizontal.insert({tp, makePlaceholder(mRNG())});
                if (mBordersVertical.find(tp) == mBordersVertical.end())
                    mBordersVertical.insert({tp, makePlaceholder(mRNG())});
            }
    }
}

NoiseModuleManager::~NoiseModuleManager()
{
}

Reseedable& NoiseModuleManager::getBorderVertical(TerrainID top, TerrainID bottom, bool x_positive)
{
    Reseedable& r = mBordersVertical.at({top, bottom});
    if (x_positive)
        return r;
    return r.translatePoint(-1., 0., 0.);
}

Reseedable& NoiseModuleManager::getBorderHorizontal(TerrainID left, TerrainID right, bool y_positive)
{
    Reseedable& r = mBordersHorizontal.at({left, right});
    if (y_positive)
        return r;
    return r.translatePoint(0., -1., 0.);
}

Reseedable& NoiseModuleManager::getStochastic(TerrainID terrain)
{
    Reseedable& r = mStochasticMasks.at(terrain);
    r.setSeed(mRNG());
    return r;
}
<|endoftext|>


<commit_before>//========================================================================
// Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved.
//
// Author: The ALICE Off-line Project.
// Contributors are mentioned in the code where appropriate.
//
// Permission to use, copy, modify and distribute this software and its
// documentation strictly for non-commercial purposes is hereby granted
// without fee, provided that the above copyright notice appears in all
// copies and that both the copyright notice and this permission notice
// appear in the supporting documentation. The authors make no claims
// about the suitability of this software for any purpose. It is
// provided "as is" without express or implied warranty.
//========================================================================
//
//                       Class AliEMCALTrack
//                      ---------------------
//    A class implementing a track which is propagated to EMCAL and
//    matches and EMCAL cluster.
//    This track object will not update Kalman parameters, but it
//    allows for track propagation and suitable energy loss correction,
//    even in an environment with a variable magnetic field, which is not
//    well managed in the AliExternalTrackParam class.
// ------------------------------------------------------------------------
// author: A. Pulvirenti (alberto.pulvirenti@ct.infn.it)
//=========================================================================

#include "Riostream.h"

#include "TVector3.h"

#include "AliLog.h"
#include "AliTracker.h"
#include "AliESDtrack.h"

#include "AliEMCALTrack.h"

Bool_t AliEMCALTrack::fgUseOuterParams = kTRUE;
Bool_t AliEMCALTrack::fgCorrectForEL   = kFALSE;
Bool_t AliEMCALTrack::fgSortByPt       = kTRUE;

ClassImp(AliEMCALTrack)
//
//------------------------------------------------------------------------------
//
AliEMCALTrack::AliEMCALTrack()
  : AliExternalTrackParam(),
    fClusterIndex(-1),
    fClusterDist(1000.0),          // default: extremely large distance
    fMass(0.13957018),             // default: pion mass
    fSeedIndex(-1),
    fSeedLabel(-1)
{
	//
	// Default constructor.
	// Sets to meaningless values the indexes corresponding to
	// ESD seed track and matched cluster.
	//
}
//
//------------------------------------------------------------------------------
//
AliEMCALTrack::AliEMCALTrack(const AliESDtrack& t)
  : AliExternalTrackParam(),
    fClusterIndex(-1),
    fClusterDist(1000.0),
    fMass(t.GetMass()),
    fSeedIndex(-1),
    fSeedLabel(t.GetLabel())
{
	//
	// Constructor from AliESDtrack
	//

	// parameters are chosen according to static variable fUseOuterParams
	Double_t alpha, x, params[5], cov[15];
	if (fgUseOuterParams) {
		t.GetOuterExternalParameters(alpha, x, params);
		t.GetOuterExternalCovariance(cov);
	}
	else {
		alpha = t.GetAlpha();
		t.GetExternalParameters(x, params);
		t.GetExternalCovariance(cov);
	}

	if (alpha < -TMath::Pi()) alpha += TMath::TwoPi();
	else if (alpha >= TMath::Pi()) alpha -= TMath::TwoPi();

	// set this accordingly
	Set(x, alpha, params, cov);
}
//
//------------------------------------------------------------------------------
//
AliEMCALTrack::AliEMCALTrack(const AliEMCALTrack& t)
  : AliExternalTrackParam(t),
    fClusterIndex(t.fClusterIndex),
    fClusterDist(t.fClusterDist),
    fMass(t.fMass),
    fSeedIndex(t.fSeedIndex),
    fSeedLabel(t.fSeedLabel)
{
	//
	// Copy constructor.
	//
}
//
//------------------------------------------------------------------------------
//
AliEMCALTrack& AliEMCALTrack::operator=(const AliEMCALTrack &t)
{
	//
	// Assignment operator
	// Works like copy constructor
	//

	fClusterIndex = t.fClusterIndex;
	fClusterDist = t.fClusterDist;

	fMass = t.fMass;

	fSeedIndex = t.fSeedIndex;
	fSeedLabel = t.fSeedLabel;

	return *this;
}
//
//------------------------------------------------------------------------------
//
Int_t AliEMCALTrack::Compare(const TObject *obj) const
{
	//
	// Compare tracks.
	// How tracks are compared depends on the static flag
	// "fSortByPt" (boolean):
	// true  => tracks are compared w.r. to their transverse momentum
	// false => tracks are compared w.r. to their distance from cluster
	//

	AliEMCALTrack *that = (AliEMCALTrack*)obj;

	Double_t thisP[3], thisVal, thatP[3], thatVal;

	if (fgSortByPt) {
		this->GetPxPyPz(thisP);
		that->GetPxPyPz(thatP);
		thisVal = TMath::Sqrt(thisP[0]*thisP[0] + thisP[1]*thisP[1]);
		thatVal = TMath::Sqrt(thatP[0]*thatP[0] + thatP[1]*thatP[1]);
	}
	else {
		thisVal = this->GetClusterDist();
		thatVal = that->GetClusterDist();
	}

	if (thisVal > thatVal) return 1;
	else if (thisVal < thatVal) return -1;
	else return 0;
}
//
//------------------------------------------------------------------------------
//
Double_t AliEMCALTrack::GetBz() const
{
	//
	// Returns Z-component of the magnetic field in kG.
	// In case it B is not constant, its value is returned
	// at the current position of the track (local X,Y,Z)
	//

	// if magnetic field is constant...
	if (AliTracker::UniformField()) return AliTracker::GetBz();

	// ...else:
	Double_t r[3];
	GetXYZ(r);
	return AliTracker::GetBz(r);
}
//
//------------------------------------------------------------------------------
//
Bool_t AliEMCALTrack::PropagateTo(Double_t xk, Double_t d, Double_t x0)
{
	//
	// Propagates a track to the plane defined by x='xk'.
	// Second parameter is the width (in units of rad. length) crossed by the track.
	// Third parameter is the reference radiation length used.
	// Track propagation includes computing energy loss (modifies curvature)
	// and multiple scattering perturbation (alters covariance matrix), if requested.
	// Method returns kFALSE when something goes wrong with computations.
	//
	// An additional operation (thanks to Yuri Belikov) is done to check
	// when the track crosses a sector boundary. If this happens,
	// the local track reference frame is adjusted accordingly.
	//

	Double_t y;
	Double_t field = GetBz();
	Double_t width = TMath::Pi() / 9.0; // width of TPC/TRD/EMCAL sector (= 20 deg)
	Double_t ymax  = TMath::Abs(xk * TMath::Tan(0.5 * width)); // max allowed Y in local coords at distance xk

	// first check: try to compute the local 'y' at the distance 'xk':
	// if this attempt fails, the propagation cannot be done
	if (!GetYAt(xk, field, y)) return kFALSE;

	// if is -ymax < y < ymax ==> 'direct' propagation is done;
	if (TMath::Abs(y) <= ymax) return SimplePropagation(xk, d, x0);

	// otherwise, try change a sector to find one where the propagation is ok
	Int_t    i, incr, istart, nloops;
	Double_t alpha = GetAlpha();
	incr = (y > ymax) ? 1 : -1;
	if (alpha < 0.0) alpha += TMath::TwoPi();
	istart = (Int_t)(alpha / width);
	for (i = istart, nloops = 0; nloops < 18; i += incr, nloops++) {
		if (i == 18) i = 0;
		if (i == -1) i = 17;
		alpha = ((Double_t)i + 0.5) * width;
		if (Rotate(alpha)) {
			if (GetYAt(xk, field, y)) {
				if (TMath::Abs(y) <= ymax) {
					AliInfo(Form("Required change from sector %d to sector %d to succeed in propagation", istart, i));
					return SimplePropagation(xk, d, x0);
				}
			}
		}
	}

	// if the routine exits from the loop and reaches this point,
	// it means that none of the rotations succeeded
	AliWarning("Track propagation fails in every sector. Impossible to propagate.");
	return kFALSE;
}
//
//------------------------------------------------------------------------------
//
Double_t AliEMCALTrack::StraightPropagateTo(Double_t xk, Double_t &x, Double_t &y, Double_t &z)
{
	//
	// Does propagation with a straight line approximation.
	// This operation does not update track parameters, but it returns a point
	// in space, according to this propagation, which is stored in
	// the arguments #2, #3 and #4
	//

	Double_t oldX = GetX(), oldY = GetY(), oldZ = GetZ();
	Double_t newPos[3];

	newPos[0] = xk;
	newPos[1] = oldY * xk / oldX;
	newPos[2] = oldZ * xk / oldX;

	Double_t cs = TMath::Cos(GetAlpha()), sn = TMath::Sin(GetAlpha());
	x = newPos[0]*cs - newPos[1]*sn;
	y = newPos[0]*sn + newPos[1]*cs;
	z = newPos[2];

	return newPos[1];
}
//
//------------------------------------------------------------------------------
//
Bool_t AliEMCALTrack::PropagateToGlobal(Double_t x, Double_t y, Double_t z, Double_t d, Double_t x0)
{
	//
	// Propagate to a point specified with its global XYZ coordinates.
	// Here, the correct value of the 'X' parameter to be sent to "PropagateTo" is computed.
	//

	TVector3 vc(x, y, z);
	Double_t width = 20.0; // width of TPC/TRD/EMCAL sector
	Double_t phi   = vc.Phi() * TMath::RadToDeg();
	if (phi < 0.0) phi += 360.0;

	Int_t    isector = (Int_t)(phi / width);
	Double_t rotation = ((Double_t)isector + 0.5) * width;
	vc.RotateZ(rotation * TMath::DegToRad());

	return PropagateTo(vc.X(), d, x0);
}
//
//------------------------------------------------------------------------------
//
Bool_t AliEMCALTrack::SimplePropagation(Double_t xk, Double_t d, Double_t x0)
{
	//
	// Recall base class method for track propagation.
	//

	Double_t field = GetBz();

	// propagation...
	if (!AliExternalTrackParam::PropagateTo(xk, field)) return kFALSE;

	// EL correction is computed only if requested...
	if (!fgCorrectForEL) return kTRUE;
	return AliExternalTrackParam::CorrectForMaterial(d, x0, GetMass());
}
<commit_msg>Correct missing - sign in z rotation<commit_after>//========================================================================
// Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved.
//
// Author: The ALICE Off-line Project.
// Contributors are mentioned in the code where appropriate.
//
// Permission to use, copy, modify and distribute this software and its
// documentation strictly for non-commercial purposes is hereby granted
// without fee, provided that the above copyright notice appears in all
// copies and that both the copyright notice and this permission notice
// appear in the supporting documentation. The authors make no claims
// about the suitability of this software for any purpose. It is
// provided "as is" without express or implied warranty.
//========================================================================
//
//                       Class AliEMCALTrack
//                      ---------------------
//    A class implementing a track which is propagated to EMCAL and
//    matches and EMCAL cluster.
//    This track object will not update Kalman parameters, but it
//    allows for track propagation and suitable energy loss correction,
//    even in an environment with a variable magnetic field, which is not
//    well managed in the AliExternalTrackParam class.
// ------------------------------------------------------------------------
// author: A. Pulvirenti (alberto.pulvirenti@ct.infn.it)
//=========================================================================

#include "Riostream.h"

#include "TVector3.h"

#include "AliLog.h"
#include "AliTracker.h"
#include "AliESDtrack.h"

#include "AliEMCALTrack.h"

Bool_t AliEMCALTrack::fgUseOuterParams = kTRUE;
Bool_t AliEMCALTrack::fgCorrectForEL   = kFALSE;
Bool_t AliEMCALTrack::fgSortByPt       = kTRUE;

ClassImp(AliEMCALTrack)
//
//------------------------------------------------------------------------------
//
AliEMCALTrack::AliEMCALTrack()
  : AliExternalTrackParam(),
    fClusterIndex(-1),
    fClusterDist(1000.0),          // default: extremely large distance
    fMass(0.13957018),             // default: pion mass
    fSeedIndex(-1),
    fSeedLabel(-1)
{
	//
	// Default constructor.
	// Sets to meaningless values the indexes corresponding to
	// ESD seed track and matched cluster.
	//
}
//
//------------------------------------------------------------------------------
//
AliEMCALTrack::AliEMCALTrack(const AliESDtrack& t)
  : AliExternalTrackParam(),
    fClusterIndex(-1),
    fClusterDist(1000.0),
    fMass(t.GetMass()),
    fSeedIndex(-1),
    fSeedLabel(t.GetLabel())
{
	//
	// Constructor from AliESDtrack
	//

	// parameters are chosen according to static variable fUseOuterParams
	Double_t alpha, x, params[5], cov[15];
	if (fgUseOuterParams) {
		t.GetOuterExternalParameters(alpha, x, params);
		t.GetOuterExternalCovariance(cov);
	}
	else {
		alpha = t.GetAlpha();
		t.GetExternalParameters(x, params);
		t.GetExternalCovariance(cov);
	}

	if (alpha < -TMath::Pi()) alpha += TMath::TwoPi();
	else if (alpha >= TMath::Pi()) alpha -= TMath::TwoPi();

	// set this accordingly
	Set(x, alpha, params, cov);
}
//
//------------------------------------------------------------------------------
//
AliEMCALTrack::AliEMCALTrack(const AliEMCALTrack& t)
  : AliExternalTrackParam(t),
    fClusterIndex(t.fClusterIndex),
    fClusterDist(t.fClusterDist),
    fMass(t.fMass),
    fSeedIndex(t.fSeedIndex),
    fSeedLabel(t.fSeedLabel)
{
	//
	// Copy constructor.
	//
}
//
//------------------------------------------------------------------------------
//
AliEMCALTrack& AliEMCALTrack::operator=(const AliEMCALTrack &t)
{
	//
	// Assignment operator
	// Works like copy constructor
	//

	fClusterIndex = t.fClusterIndex;
	fClusterDist = t.fClusterDist;

	fMass = t.fMass;

	fSeedIndex = t.fSeedIndex;
	fSeedLabel = t.fSeedLabel;

	return *this;
}
//
//------------------------------------------------------------------------------
//
Int_t AliEMCALTrack::Compare(const TObject *obj) const
{
	//
	// Compare tracks.
	// How tracks are compared depends on the static flag
	// "fSortByPt" (boolean):
	// true  => tracks are compared w.r. to their transverse momentum
	// false => tracks are compared w.r. to their distance from cluster
	//

	AliEMCALTrack *that = (AliEMCALTrack*)obj;

	Double_t thisP[3], thisVal, thatP[3], thatVal;

	if (fgSortByPt) {
		this->GetPxPyPz(thisP);
		that->GetPxPyPz(thatP);
		thisVal = TMath::Sqrt(thisP[0]*thisP[0] + thisP[1]*thisP[1]);
		thatVal = TMath::Sqrt(thatP[0]*thatP[0] + thatP[1]*thatP[1]);
	}
	else {
		thisVal = this->GetClusterDist();
		thatVal = that->GetClusterDist();
	}

	if (thisVal > thatVal) return 1;
	else if (thisVal < thatVal) return -1;
	else return 0;
}
//
//------------------------------------------------------------------------------
//
Double_t AliEMCALTrack::GetBz() const
{
	//
	// Returns Z-component of the magnetic field in kG.
	// In case it B is not constant, its value is returned
	// at the current position of the track (local X,Y,Z)
	//

	// if magnetic field is constant...
	if (AliTracker::UniformField()) return AliTracker::GetBz();

	// ...else:
	Double_t r[3];
	GetXYZ(r);
	return AliTracker::GetBz(r);
}
//
//------------------------------------------------------------------------------
//
Bool_t AliEMCALTrack::PropagateTo(Double_t xk, Double_t d, Double_t x0)
{
	//
	// Propagates a track to the plane defined by x='xk'.
	// Second parameter is the width (in units of rad. length) crossed by the track.
	// Third parameter is the reference radiation length used.
	// Track propagation includes computing energy loss (modifies curvature)
	// and multiple scattering perturbation (alters covariance matrix), if requested.
	// Method returns kFALSE when something goes wrong with computations.
	//
	// An additional operation (thanks to Yuri Belikov) is done to check
	// when the track crosses a sector boundary. If this happens,
	// the local track reference frame is adjusted accordingly.
	//

	Double_t y;
	Double_t field = GetBz();
	Double_t width = TMath::Pi() / 9.0; // width of TPC/TRD/EMCAL sector (= 20 deg)
	Double_t ymax  = TMath::Abs(xk * TMath::Tan(0.5 * width)); // max allowed Y in local coords at distance xk

	// first check: try to compute the local 'y' at the distance 'xk':
	// if this attempt fails, the propagation cannot be done
	if (!GetYAt(xk, field, y)) return kFALSE;

	// if is -ymax < y < ymax ==> 'direct' propagation is done;
	if (TMath::Abs(y) <= ymax) return SimplePropagation(xk, d, x0);

	// otherwise, try change a sector to find one where the propagation is ok
	Int_t    i, incr, istart, nloops;
	Double_t alpha = GetAlpha();
	incr = (y > ymax) ? 1 : -1;
	if (alpha < 0.0) alpha += TMath::TwoPi();
	istart = (Int_t)(alpha / width);
	for (i = istart, nloops = 0; nloops < 18; i += incr, nloops++) {
		if (i == 18) i = 0;
		if (i == -1) i = 17;
		alpha = ((Double_t)i + 0.5) * width;
		if (Rotate(alpha)) {
			if (GetYAt(xk, field, y)) {
				if (TMath::Abs(y) <= ymax) {
					AliInfo(Form("Required change from sector %d to sector %d to succeed in propagation", istart, i));
					return SimplePropagation(xk, d, x0);
				}
			}
		}
	}

	// if the routine exits from the loop and reaches this point,
	// it means that none of the rotations succeeded
	AliWarning("Track propagation fails in every sector. Impossible to propagate.");
	return kFALSE;
}
//
//------------------------------------------------------------------------------
//
Double_t AliEMCALTrack::StraightPropagateTo(Double_t xk, Double_t &x, Double_t &y, Double_t &z)
{
	//
	// Does propagation with a straight line approximation.
	// This operation does not update track parameters, but it returns a point
	// in space, according to this propagation, which is stored in
	// the arguments #2, #3 and #4
	//

	Double_t oldX = GetX(), oldY = GetY(), oldZ = GetZ();
	Double_t newPos[3];

	newPos[0] = xk;
	newPos[1] = oldY * xk / oldX;
	newPos[2] = oldZ * xk / oldX;

	Double_t cs = TMath::Cos(GetAlpha()), sn = TMath::Sin(GetAlpha());
	x = newPos[0]*cs - newPos[1]*sn;
	y = newPos[0]*sn + newPos[1]*cs;
	z = newPos[2];

	return newPos[1];
}
//
//------------------------------------------------------------------------------
//
Bool_t AliEMCALTrack::PropagateToGlobal(Double_t x, Double_t y, Double_t z, Double_t d, Double_t x0)
{
	//
	// Propagate to a point specified with its global XYZ coordinates.
	// Here, the correct value of the 'X' parameter to be sent to "PropagateTo" is computed.
	//

	TVector3 vc(x, y, z);
	Double_t width = 20.0; // width of TPC/TRD/EMCAL sector
	Double_t phi   = vc.Phi() * TMath::RadToDeg();
	if (phi < 0.0) phi += 360.0;

	Int_t    isector = (Int_t)(phi / width);
	Double_t rotation = ((Double_t)isector + 0.5) * width;
	vc.RotateZ(-rotation * TMath::DegToRad());

	return PropagateTo(vc.X(), d, x0);
}
//
//------------------------------------------------------------------------------
//
Bool_t AliEMCALTrack::SimplePropagation(Double_t xk, Double_t d, Double_t x0)
{
	//
	// Recall base class method for track propagation.
	//

	Double_t field = GetBz();

	// propagation...
	if (!AliExternalTrackParam::PropagateTo(xk, field)) return kFALSE;

	// EL correction is computed only if requested...
	if (!fgCorrectForEL) return kTRUE;
	return AliExternalTrackParam::CorrectForMaterial(d, x0, GetMass());
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: cuigrfflt.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-03 18:22:11 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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 GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CUI_GRFFLT_HXX
#define _CUI_GRFFLT_HXX

#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _SV_SALBTYPE_HXX
#include <vcl/salbtype.hxx>
#endif
#ifndef _GRFMGR_HXX
#include <goodies/grfmgr.hxx>
#endif

#ifndef _GRAPHCTL_HXX
#include "graphctl.hxx"
#endif
#ifndef _SVX_DLG_CTRL_HXX
#include "dlgctrl.hxx"
#endif
#ifndef _SVX_RECTENUM_HXX
#include "rectenum.hxx"
#endif
/*
// ---------------
// - Error codes -
// ---------------

#define SVX_GRAPHICFILTER_ERRCODE_NONE              0x00000000
#define SVX_GRAPHICFILTER_UNSUPPORTED_GRAPHICTYPE   0x00000001
#define SVX_GRAPHICFILTER_UNSUPPORTED_SLOT          0x00000002

// --------------------
// - SvxGraphicFilter -
// --------------------

class SfxRequest;
class SfxItemSet;

class SvxGraphicFilter
{
public:

    static ULONG    ExecuteGrfFilterSlot( SfxRequest& rReq, GraphicObject& rFilterObject );
    static void     DisableGraphicFilterSlots( SfxItemSet& rSet );
};
*/
// -----------------------
// - GraphicFilterDialog -
// -----------------------

class GraphicFilterDialog : public ModalDialog
{
private:

    class PreviewWindow : public Control
    {
    private:

        GraphicObject   maGraphic;

        virtual void    Paint( const Rectangle& rRect );

    public:

                        PreviewWindow( Window* pParent, const ResId& rResId );
                        ~PreviewWindow();

        void            SetGraphic( const Graphic& rGraphic );
    };

private:

    Timer           maTimer;
    Link            maModifyHdl;
    Graphic         maGraphic;
    double          mfScaleX;
    double          mfScaleY;
    Size            maSizePixel;
    PreviewWindow   maPreview;
    FixedLine       maFlParameter;
    OKButton        maBtnOK;
    CancelButton    maBtnCancel;
    HelpButton      maBtnHelp;

                    DECL_LINK( ImplPreviewTimeoutHdl, Timer* pTimer );
                    DECL_LINK( ImplModifyHdl, void* p );

protected:

    const Link&     GetModifyHdl() const { return maModifyHdl; }
    const Size&     GetGraphicSizePixel() const { return maSizePixel; }

public:

                    GraphicFilterDialog( Window* pParent, const ResId& rResId, const Graphic& rGraphic );
                    ~GraphicFilterDialog();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY ) = 0;
};

// -----------------------
// - GraphicFilterMosaic -
// -----------------------

class GraphicFilterMosaic : public GraphicFilterDialog
{
private:

    FixedText       maFtWidth;
    MetricField     maMtrWidth;
    FixedText       maFtHeight;
    MetricField     maMtrHeight;
    CheckBox        maCbxEdges;

public:

                    GraphicFilterMosaic( Window* pParent, const Graphic& rGraphic,
                                         USHORT nTileWidth, USHORT nTileHeight, BOOL bEnhanceEdges );
                    ~GraphicFilterMosaic();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY );
    USHORT          GetTileWidth() const { return maMtrWidth.GetValue(); }
    USHORT          GetTileHeight() const { return maMtrHeight.GetValue(); }
    BOOL            IsEnhanceEdges() const { return maCbxEdges.IsChecked(); }
};

// -------------------------
// - GraphicFilterSolarize -
// -------------------------

class GraphicFilterSolarize : public GraphicFilterDialog
{
private:

    FixedText       maFtThreshold;
    MetricField     maMtrThreshold;
    CheckBox        maCbxInvert;

public:

                    GraphicFilterSolarize( Window* pParent, const Graphic& rGraphic,
                                           BYTE nGreyThreshold, BOOL bInvert );
                    ~GraphicFilterSolarize();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY );
    BYTE            GetGreyThreshold() const { return( (BYTE) FRound( maMtrThreshold.GetValue() * 2.55 ) ); }
    BOOL            IsInvert() const { return maCbxInvert.IsChecked(); }
};

// ----------------------
// - GraphicFilterSepia -
// ----------------------

class GraphicFilterSepia : public GraphicFilterDialog
{
private:

    FixedText       maFtSepia;
    MetricField     maMtrSepia;

public:

                    GraphicFilterSepia( Window* pParent, const Graphic& rGraphic,
                                        USHORT nSepiaPercent );
                    ~GraphicFilterSepia();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY );
    USHORT          GetSepiaPercent() const { return maMtrSepia.GetValue(); }
};

// -----------------------
// - GraphicFilterPoster -
// -----------------------

class GraphicFilterPoster : public GraphicFilterDialog
{
private:

    FixedText       maFtPoster;
    NumericField    maNumPoster;

public:

                    GraphicFilterPoster( Window* pParent, const Graphic& rGraphic,
                                         USHORT nPosterColorCount );
                    ~GraphicFilterPoster();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY );
    USHORT          GetPosterColorCount() const { return( (USHORT) maNumPoster.GetValue() ); }
};

// -----------------------
// - GraphicFilterEmboss -
// -----------------------

class GraphicFilterEmboss : public GraphicFilterDialog
{
private:

    class EmbossControl : public SvxRectCtl
    {
    private:

        Link            maModifyHdl;

        virtual void    MouseButtonDown( const MouseEvent& rEvt );

    public:

                        EmbossControl( Window* pParent, const ResId& rResId, RECT_POINT eRectPoint ) :
                            SvxRectCtl( pParent, rResId ) { SetActualRP( eRectPoint ); }

        void            SetModifyHdl( const Link& rHdl ) { maModifyHdl = rHdl; }
    };

private:

    FixedText       maFtLight;
    EmbossControl   maCtlLight;

public:

                    GraphicFilterEmboss( Window* pParent, const Graphic& rGraphic,
                                         RECT_POINT eLightSource );
                    ~GraphicFilterEmboss();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY );
    RECT_POINT      GetLightSource() const { return maCtlLight.GetActualRP(); }
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1044); FILE MERGED 2005/09/05 14:19:17 rt 1.2.1044.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cuigrfflt.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:51:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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 GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CUI_GRFFLT_HXX
#define _CUI_GRFFLT_HXX

#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _SV_SALBTYPE_HXX
#include <vcl/salbtype.hxx>
#endif
#ifndef _GRFMGR_HXX
#include <goodies/grfmgr.hxx>
#endif

#ifndef _GRAPHCTL_HXX
#include "graphctl.hxx"
#endif
#ifndef _SVX_DLG_CTRL_HXX
#include "dlgctrl.hxx"
#endif
#ifndef _SVX_RECTENUM_HXX
#include "rectenum.hxx"
#endif
/*
// ---------------
// - Error codes -
// ---------------

#define SVX_GRAPHICFILTER_ERRCODE_NONE              0x00000000
#define SVX_GRAPHICFILTER_UNSUPPORTED_GRAPHICTYPE   0x00000001
#define SVX_GRAPHICFILTER_UNSUPPORTED_SLOT          0x00000002

// --------------------
// - SvxGraphicFilter -
// --------------------

class SfxRequest;
class SfxItemSet;

class SvxGraphicFilter
{
public:

    static ULONG    ExecuteGrfFilterSlot( SfxRequest& rReq, GraphicObject& rFilterObject );
    static void     DisableGraphicFilterSlots( SfxItemSet& rSet );
};
*/
// -----------------------
// - GraphicFilterDialog -
// -----------------------

class GraphicFilterDialog : public ModalDialog
{
private:

    class PreviewWindow : public Control
    {
    private:

        GraphicObject   maGraphic;

        virtual void    Paint( const Rectangle& rRect );

    public:

                        PreviewWindow( Window* pParent, const ResId& rResId );
                        ~PreviewWindow();

        void            SetGraphic( const Graphic& rGraphic );
    };

private:

    Timer           maTimer;
    Link            maModifyHdl;
    Graphic         maGraphic;
    double          mfScaleX;
    double          mfScaleY;
    Size            maSizePixel;
    PreviewWindow   maPreview;
    FixedLine       maFlParameter;
    OKButton        maBtnOK;
    CancelButton    maBtnCancel;
    HelpButton      maBtnHelp;

                    DECL_LINK( ImplPreviewTimeoutHdl, Timer* pTimer );
                    DECL_LINK( ImplModifyHdl, void* p );

protected:

    const Link&     GetModifyHdl() const { return maModifyHdl; }
    const Size&     GetGraphicSizePixel() const { return maSizePixel; }

public:

                    GraphicFilterDialog( Window* pParent, const ResId& rResId, const Graphic& rGraphic );
                    ~GraphicFilterDialog();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY ) = 0;
};

// -----------------------
// - GraphicFilterMosaic -
// -----------------------

class GraphicFilterMosaic : public GraphicFilterDialog
{
private:

    FixedText       maFtWidth;
    MetricField     maMtrWidth;
    FixedText       maFtHeight;
    MetricField     maMtrHeight;
    CheckBox        maCbxEdges;

public:

                    GraphicFilterMosaic( Window* pParent, const Graphic& rGraphic,
                                         USHORT nTileWidth, USHORT nTileHeight, BOOL bEnhanceEdges );
                    ~GraphicFilterMosaic();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY );
    USHORT          GetTileWidth() const { return maMtrWidth.GetValue(); }
    USHORT          GetTileHeight() const { return maMtrHeight.GetValue(); }
    BOOL            IsEnhanceEdges() const { return maCbxEdges.IsChecked(); }
};

// -------------------------
// - GraphicFilterSolarize -
// -------------------------

class GraphicFilterSolarize : public GraphicFilterDialog
{
private:

    FixedText       maFtThreshold;
    MetricField     maMtrThreshold;
    CheckBox        maCbxInvert;

public:

                    GraphicFilterSolarize( Window* pParent, const Graphic& rGraphic,
                                           BYTE nGreyThreshold, BOOL bInvert );
                    ~GraphicFilterSolarize();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY );
    BYTE            GetGreyThreshold() const { return( (BYTE) FRound( maMtrThreshold.GetValue() * 2.55 ) ); }
    BOOL            IsInvert() const { return maCbxInvert.IsChecked(); }
};

// ----------------------
// - GraphicFilterSepia -
// ----------------------

class GraphicFilterSepia : public GraphicFilterDialog
{
private:

    FixedText       maFtSepia;
    MetricField     maMtrSepia;

public:

                    GraphicFilterSepia( Window* pParent, const Graphic& rGraphic,
                                        USHORT nSepiaPercent );
                    ~GraphicFilterSepia();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY );
    USHORT          GetSepiaPercent() const { return maMtrSepia.GetValue(); }
};

// -----------------------
// - GraphicFilterPoster -
// -----------------------

class GraphicFilterPoster : public GraphicFilterDialog
{
private:

    FixedText       maFtPoster;
    NumericField    maNumPoster;

public:

                    GraphicFilterPoster( Window* pParent, const Graphic& rGraphic,
                                         USHORT nPosterColorCount );
                    ~GraphicFilterPoster();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY );
    USHORT          GetPosterColorCount() const { return( (USHORT) maNumPoster.GetValue() ); }
};

// -----------------------
// - GraphicFilterEmboss -
// -----------------------

class GraphicFilterEmboss : public GraphicFilterDialog
{
private:

    class EmbossControl : public SvxRectCtl
    {
    private:

        Link            maModifyHdl;

        virtual void    MouseButtonDown( const MouseEvent& rEvt );

    public:

                        EmbossControl( Window* pParent, const ResId& rResId, RECT_POINT eRectPoint ) :
                            SvxRectCtl( pParent, rResId ) { SetActualRP( eRectPoint ); }

        void            SetModifyHdl( const Link& rHdl ) { maModifyHdl = rHdl; }
    };

private:

    FixedText       maFtLight;
    EmbossControl   maCtlLight;

public:

                    GraphicFilterEmboss( Window* pParent, const Graphic& rGraphic,
                                         RECT_POINT eLightSource );
                    ~GraphicFilterEmboss();

    virtual Graphic GetFilteredGraphic( const Graphic& rGraphic, double fScaleX, double fScaleY );
    RECT_POINT      GetLightSource() const { return maCtlLight.GetActualRP(); }
};

#endif
<|endoftext|>


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

#include <modules/basecl/processors/volumemaxclprocessor.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <modules/opencl/syncclgl.h>
#include <modules/opencl/buffer/buffercl.h>
#include <modules/opencl/buffer/bufferclgl.h>
#include <modules/opencl/volume/volumecl.h>
#include <modules/opencl/volume/volumeclgl.h>

namespace inviwo {

ProcessorClassIdentifier(VolumeMaxCLProcessor, "org.inviwo.VolumeMaxCL");
ProcessorDisplayName(VolumeMaxCLProcessor,  "Volume Max");
ProcessorTags(VolumeMaxCLProcessor, Tags::CL);
ProcessorCategory(VolumeMaxCLProcessor, "Volume Operation");
ProcessorCodeState(VolumeMaxCLProcessor, CODE_STATE_EXPERIMENTAL);

VolumeMaxCLProcessor::VolumeMaxCLProcessor()
    : Processor(), ProcessorKernelOwner(this)
    , inport_("volume")
    , outport_("volume")
    , volumeRegionSize_("region", "Region size", 8, 1, 100)
    , workGroupSize_("wgsize", "Work group size", ivec3(8), ivec3(0), ivec3(256))
    , useGLSharing_("glsharing", "Use OpenGL sharing", true)
    , supportsVolumeWrite_(false)
    , tmpVolume_(NULL)
    , kernel_(NULL)
{
    addPort(inport_);
    addPort(outport_);

    addProperty(volumeRegionSize_);
    addProperty(workGroupSize_);
    addProperty(useGLSharing_);
}

VolumeMaxCLProcessor::~VolumeMaxCLProcessor() {}

void VolumeMaxCLProcessor::initialize() {
    Processor::initialize();
    buildKernel();
}

void VolumeMaxCLProcessor::deinitialize() {
    Processor::deinitialize();
}

void VolumeMaxCLProcessor::process() {
    if (kernel_ == NULL) {
        return;
    }
    const Volume* volume = inport_.getData();

    uvec3 dim = volume->getDimensions();
    uvec3 outDim = uvec3(glm::ceil(vec3(dim)/static_cast<float>(volumeRegionSize_.get())));
    //const DataFormatBase* volFormat = inport_.getData()->getDataFormat(); // Not used

    if (!outport_.hasData() || outport_.getData()->getDimensions() != outDim) {
        Volume* volumeOut = new Volume(outDim, DataUINT8::get());
        //volumeOut = new Volume(outDim, DataUINT32::get());
        //volumeOut = new Volume(outDim, DataFLOAT32::get());
        // Use same transformation to make sure that they are render at the same location
        volumeOut->setModelMatrix(volume->getModelMatrix());
        volumeOut->setWorldMatrix(volume->getWorldMatrix());
        outport_.setData(volumeOut);
    }
    Volume* volumeOut = outport_.getData();

    svec3 localWorkGroupSize(workGroupSize_.get());
    svec3 globalWorkGroupSize(getGlobalWorkGroupSize(outDim.x, localWorkGroupSize.x),
                              getGlobalWorkGroupSize(outDim.y, localWorkGroupSize.y),
                              getGlobalWorkGroupSize(outDim.z, localWorkGroupSize.z));

    if (useGLSharing_.get()) {
        SyncCLGL glSync;
        const VolumeCLGL* volumeCL = volume->getRepresentation<VolumeCLGL>();
        VolumeCLGL* volumeOutCL = volumeOut->getEditableRepresentation<VolumeCLGL>();

        glSync.addToAquireGLObjectList(volumeCL);
        glSync.addToAquireGLObjectList(volumeOutCL);
        glSync.aquireAllObjects();

        executeVolumeOperation(volume, volumeCL, volumeOutCL, outDim, globalWorkGroupSize, localWorkGroupSize);
    } else {
        const VolumeCL* volumeCL = volume->getRepresentation<VolumeCL>();
        VolumeCL* volumeOutCL = volumeOut->getEditableRepresentation<VolumeCL>();
        executeVolumeOperation(volume, volumeCL, volumeOutCL, outDim, globalWorkGroupSize, localWorkGroupSize);
    }

}

void VolumeMaxCLProcessor::executeVolumeOperation(const Volume* volume, const VolumeCLBase* volumeCL, VolumeCLBase* volumeOutCL, const uvec3& outDim,
                                         const svec3& globalWorkGroupSize, const svec3& localWorkgroupSize) {
    cl::Event events[2];
    try {
        BufferCL* tmpVolumeCL;
        int argIndex = 0;
        kernel_->setArg(argIndex++, *volumeCL);
        kernel_->setArg(argIndex++, *(volumeCL->getVolumeStruct(volume).getRepresentation<BufferCL>())); // Scaling for 12-bit data
        if (supportsVolumeWrite_) {
            kernel_->setArg(argIndex++, *volumeOutCL);
        } else {
            size_t outDimFlattened = outDim.x*outDim.y*outDim.z;
            if (tmpVolume_ == NULL || tmpVolume_->getSize() != outDimFlattened) {
                delete tmpVolume_; tmpVolume_ = new Buffer_UINT8(outDimFlattened);
                //delete tmpVolume_; tmpVolume_ = new Buffer_UINT32(outDimFlattened);
                //delete tmpVolume_; tmpVolume_ = new Buffer_FLOAT32(outDimFlattened);
            }
            tmpVolumeCL = tmpVolume_->getEditableRepresentation<BufferCL>();
            kernel_->setArg(argIndex++, *tmpVolumeCL);
        }
        kernel_->setArg(argIndex++, ivec4(outDim, 0));
        kernel_->setArg(argIndex++, ivec4(volumeRegionSize_.get()));

        OpenCL::getPtr()->getQueue().enqueueNDRangeKernel(*kernel_, cl::NullRange, globalWorkGroupSize , localWorkgroupSize, NULL, &events[0]);

        if (!supportsVolumeWrite_) {
            std::vector<cl::Event> waitFor(1, events[0]);
            OpenCL::getPtr()->getQueue().enqueueCopyBufferToImage(tmpVolumeCL->get(), volumeOutCL->getEditable(), 0, svec3(0), svec3(outDim), &waitFor, &events[1]);
        }
    } catch (cl::Error& err) {
        LogError(getCLErrorString(err));
    }

#if IVW_PROFILING
    try {
        if (supportsVolumeWrite_) {
            events[0].wait();
            LogInfo("Exec time: " << events[0].getElapsedTime() << " ms");
        } else {
            // Measure both computation and copy (only need to wait for copy)
            events[1].wait();
            LogInfo("Exec time (computation, copy): " << events[0].getElapsedTime() << " + " << events[1].getElapsedTime() << " = " << events[0].getElapsedTime()+events[1].getElapsedTime() << " ms");
        }
    } catch (cl::Error& err) {
        LogError(getCLErrorString(err));
    }
#endif
}

void VolumeMaxCLProcessor::buildKernel() {
    std::stringstream defines;
    std::string extensions = OpenCL::getPtr()->getDevice().getInfo<CL_DEVICE_EXTENSIONS>();
    if (extensions.find("cl_khr_3d_image_writes") != std::string::npos) {
        supportsVolumeWrite_ = true;
        defines << " -D SUPPORTS_VOLUME_WRITE ";
    } else {
        supportsVolumeWrite_ = false;
    }
    kernel_ = addKernel("volumemax.cl", "volumeMaxKernel", defines.str());

}

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

#include <modules/basecl/processors/volumemaxclprocessor.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <modules/opencl/syncclgl.h>
#include <modules/opencl/buffer/buffercl.h>
#include <modules/opencl/buffer/bufferclgl.h>
#include <modules/opencl/volume/volumecl.h>
#include <modules/opencl/volume/volumeclgl.h>

namespace inviwo {

ProcessorClassIdentifier(VolumeMaxCLProcessor, "org.inviwo.VolumeMaxCL");
ProcessorDisplayName(VolumeMaxCLProcessor,  "Volume Max");
ProcessorTags(VolumeMaxCLProcessor, Tags::CL);
ProcessorCategory(VolumeMaxCLProcessor, "Volume Operation");
ProcessorCodeState(VolumeMaxCLProcessor, CODE_STATE_EXPERIMENTAL);

VolumeMaxCLProcessor::VolumeMaxCLProcessor()
    : Processor(), ProcessorKernelOwner(this)
    , inport_("volume")
    , outport_("volume")
    , volumeRegionSize_("region", "Region size", 8, 1, 100)
    , workGroupSize_("wgsize", "Work group size", ivec3(8), ivec3(0), ivec3(256))
    , useGLSharing_("glsharing", "Use OpenGL sharing", true)
    , supportsVolumeWrite_(false)
    , tmpVolume_(NULL)
    , kernel_(NULL)
{
    addPort(inport_);
    addPort(outport_);

    addProperty(volumeRegionSize_);
    addProperty(workGroupSize_);
    addProperty(useGLSharing_);
}

VolumeMaxCLProcessor::~VolumeMaxCLProcessor() {}

void VolumeMaxCLProcessor::initialize() {
    Processor::initialize();
    buildKernel();
}

void VolumeMaxCLProcessor::deinitialize() {
    Processor::deinitialize();
    delete tmpVolume_;
    tmpVolume_ = NULL;
}

void VolumeMaxCLProcessor::process() {
    if (kernel_ == NULL) {
        return;
    }
    const Volume* volume = inport_.getData();

    uvec3 dim = volume->getDimensions();
    uvec3 outDim = uvec3(glm::ceil(vec3(dim)/static_cast<float>(volumeRegionSize_.get())));
    //const DataFormatBase* volFormat = inport_.getData()->getDataFormat(); // Not used

    if (!outport_.hasData() || outport_.getData()->getDimensions() != outDim) {
        Volume* volumeOut = new Volume(outDim, DataUINT8::get());
        //volumeOut = new Volume(outDim, DataUINT32::get());
        //volumeOut = new Volume(outDim, DataFLOAT32::get());
        // Use same transformation to make sure that they are render at the same location
        volumeOut->setModelMatrix(volume->getModelMatrix());
        volumeOut->setWorldMatrix(volume->getWorldMatrix());
        outport_.setData(volumeOut);
    }
    Volume* volumeOut = outport_.getData();

    svec3 localWorkGroupSize(workGroupSize_.get());
    svec3 globalWorkGroupSize(getGlobalWorkGroupSize(outDim.x, localWorkGroupSize.x),
                              getGlobalWorkGroupSize(outDim.y, localWorkGroupSize.y),
                              getGlobalWorkGroupSize(outDim.z, localWorkGroupSize.z));

    if (useGLSharing_.get()) {
        SyncCLGL glSync;
        const VolumeCLGL* volumeCL = volume->getRepresentation<VolumeCLGL>();
        VolumeCLGL* volumeOutCL = volumeOut->getEditableRepresentation<VolumeCLGL>();

        glSync.addToAquireGLObjectList(volumeCL);
        glSync.addToAquireGLObjectList(volumeOutCL);
        glSync.aquireAllObjects();

        executeVolumeOperation(volume, volumeCL, volumeOutCL, outDim, globalWorkGroupSize, localWorkGroupSize);
    } else {
        const VolumeCL* volumeCL = volume->getRepresentation<VolumeCL>();
        VolumeCL* volumeOutCL = volumeOut->getEditableRepresentation<VolumeCL>();
        executeVolumeOperation(volume, volumeCL, volumeOutCL, outDim, globalWorkGroupSize, localWorkGroupSize);
    }

}

void VolumeMaxCLProcessor::executeVolumeOperation(const Volume* volume, const VolumeCLBase* volumeCL, VolumeCLBase* volumeOutCL, const uvec3& outDim,
                                         const svec3& globalWorkGroupSize, const svec3& localWorkgroupSize) {
    cl::Event events[2];
    try {
        BufferCL* tmpVolumeCL;
        int argIndex = 0;
        kernel_->setArg(argIndex++, *volumeCL);
        kernel_->setArg(argIndex++, *(volumeCL->getVolumeStruct(volume).getRepresentation<BufferCL>())); // Scaling for 12-bit data
        if (supportsVolumeWrite_) {
            kernel_->setArg(argIndex++, *volumeOutCL);
        } else {
            size_t outDimFlattened = outDim.x*outDim.y*outDim.z;
            if (tmpVolume_ == NULL || tmpVolume_->getSize() != outDimFlattened) {
                delete tmpVolume_; tmpVolume_ = new Buffer_UINT8(outDimFlattened);
                //delete tmpVolume_; tmpVolume_ = new Buffer_UINT32(outDimFlattened);
                //delete tmpVolume_; tmpVolume_ = new Buffer_FLOAT32(outDimFlattened);
            }
            tmpVolumeCL = tmpVolume_->getEditableRepresentation<BufferCL>();
            kernel_->setArg(argIndex++, *tmpVolumeCL);
        }
        kernel_->setArg(argIndex++, ivec4(outDim, 0));
        kernel_->setArg(argIndex++, ivec4(volumeRegionSize_.get()));

        OpenCL::getPtr()->getQueue().enqueueNDRangeKernel(*kernel_, cl::NullRange, globalWorkGroupSize , localWorkgroupSize, NULL, &events[0]);

        if (!supportsVolumeWrite_) {
            std::vector<cl::Event> waitFor(1, events[0]);
            OpenCL::getPtr()->getQueue().enqueueCopyBufferToImage(tmpVolumeCL->get(), volumeOutCL->getEditable(), 0, svec3(0), svec3(outDim), &waitFor, &events[1]);
        }
    } catch (cl::Error& err) {
        LogError(getCLErrorString(err));
    }

#if IVW_PROFILING
    try {
        if (supportsVolumeWrite_) {
            events[0].wait();
            LogInfo("Exec time: " << events[0].getElapsedTime() << " ms");
        } else {
            // Measure both computation and copy (only need to wait for copy)
            events[1].wait();
            LogInfo("Exec time (computation, copy): " << events[0].getElapsedTime() << " + " << events[1].getElapsedTime() << " = " << events[0].getElapsedTime()+events[1].getElapsedTime() << " ms");
        }
    } catch (cl::Error& err) {
        LogError(getCLErrorString(err));
    }
#endif
}

void VolumeMaxCLProcessor::buildKernel() {
    std::stringstream defines;
    std::string extensions = OpenCL::getPtr()->getDevice().getInfo<CL_DEVICE_EXTENSIONS>();
    if (extensions.find("cl_khr_3d_image_writes") != std::string::npos) {
        supportsVolumeWrite_ = true;
        defines << " -D SUPPORTS_VOLUME_WRITE ";
    } else {
        supportsVolumeWrite_ = false;
    }
    kernel_ = addKernel("volumemax.cl", "volumeMaxKernel", defines.str());

}

} // inviwo namespace
<|endoftext|>


<commit_before><commit_msg>introduce allocator<commit_after><|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/layerfactory.h"

#include "elm/core/exception.h"
#include "elm/core/inputname.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"
#include "elm/layers/saliencyitti.h" ///< to have layer dervied classes to test with
#include "elm/layers/weightedsum.h"  ///< to have layer dervied classes to test with
#include "elm/ts/ts.h"

using std::shared_ptr;
using namespace elm;

namespace {

/**
 * @brief class or testing LayerFactory's static methods
 */
class LayerFactoryStaticTest : public ::testing::Test
{
};

TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared)
{
    {
        shared_ptr<base_Layer> ptr = LayerFactory::CreateShared("LayerY");
        EXPECT_TRUE(bool(ptr));
    }
    {
        shared_ptr<base_Layer> ptr = LayerFactory::CreateShared("WeightedSum");
        EXPECT_TRUE(bool(ptr));
    }
}

TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_WrongType)
{
    EXPECT_THROW(LayerFactory::CreateShared("Blahbla"), elm::ExceptionTypeError);
}

TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_UniqueInstancesSameType)
{
    const std::string TYPE="WeightedSum";

    shared_ptr<base_Layer> ptr1 = LayerFactory::CreateShared(TYPE);
    shared_ptr<base_Layer> ptr2 = LayerFactory::CreateShared(TYPE);

    EXPECT_NE(ptr1, ptr2);
}

TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_WithConfig)
{
    PTree params;
    params.put(WeightedSum::PARAM_A, 0.2f);
    params.put(WeightedSum::PARAM_B, 0.3f);
    LayerConfig config;
    config.Params(params);

    const std::string NAME_STIMULUS = "in";
    const std::string NAME_RESPONSE = "out";

    config.Input(WeightedSum::KEY_INPUT_STIMULUS, NAME_STIMULUS);
    config.Output(WeightedSum::KEY_OUTPUT_RESPONSE, NAME_RESPONSE);

    shared_ptr<base_Layer> ptr = LayerFactory::CreateShared("WeightedSum", config, config);
    EXPECT_TRUE(bool(ptr));

    // populate signal with input feature
    Signal signal;
    signal.Append("in", cv::Mat1f::ones(1, 2));
    EXPECT_TRUE(signal.Exists(NAME_STIMULUS));
    EXPECT_FALSE(signal.Exists(NAME_RESPONSE));

    // apply signal to layer
    ptr->Activate(signal);
    ptr->Response(signal);

    // check response
    EXPECT_TRUE(signal.Exists(NAME_RESPONSE));
    EXPECT_MAT_DIMS_EQ(signal.MostRecentMat1f(NAME_RESPONSE), cv::Size2i(1, 1));
    EXPECT_FLOAT_EQ(signal.MostRecentMat1f(NAME_RESPONSE).at<float>(0), 0.5f);
}

} // annonymous namespace
<commit_msg>test LayerFactory constructor<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/layerfactory.h"

#include "elm/core/exception.h"
#include "elm/core/inputname.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"
#include "elm/layers/saliencyitti.h" ///< to have layer dervied classes to test with
#include "elm/layers/weightedsum.h"  ///< to have layer dervied classes to test with
#include "elm/ts/ts.h"

using std::shared_ptr;
using namespace elm;

namespace {

/**
 * @brief class or testing LayerFactory's static methods
 */
class LayerFactoryStaticTest : public ::testing::Test
{
};

TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared)
{
    {
        shared_ptr<base_Layer> ptr = LayerFactory::CreateShared("LayerY");
        EXPECT_TRUE(bool(ptr));
    }
    {
        shared_ptr<base_Layer> ptr = LayerFactory::CreateShared("WeightedSum");
        EXPECT_TRUE(bool(ptr));
    }
}

TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_WrongType)
{
    EXPECT_THROW(LayerFactory::CreateShared("Blahbla"), elm::ExceptionTypeError);
}

TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_UniqueInstancesSameType)
{
    const std::string TYPE="WeightedSum";

    shared_ptr<base_Layer> ptr1 = LayerFactory::CreateShared(TYPE);
    shared_ptr<base_Layer> ptr2 = LayerFactory::CreateShared(TYPE);

    EXPECT_NE(ptr1, ptr2);
}

TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_WithConfig)
{
    PTree params;
    params.put(WeightedSum::PARAM_A, 0.2f);
    params.put(WeightedSum::PARAM_B, 0.3f);
    LayerConfig config;
    config.Params(params);

    const std::string NAME_STIMULUS = "in";
    const std::string NAME_RESPONSE = "out";

    config.Input(WeightedSum::KEY_INPUT_STIMULUS, NAME_STIMULUS);
    config.Output(WeightedSum::KEY_OUTPUT_RESPONSE, NAME_RESPONSE);

    shared_ptr<base_Layer> ptr = LayerFactory::CreateShared("WeightedSum", config, config);
    EXPECT_TRUE(bool(ptr));

    // populate signal with input feature
    Signal signal;
    signal.Append("in", cv::Mat1f::ones(1, 2));
    EXPECT_TRUE(signal.Exists(NAME_STIMULUS));
    EXPECT_FALSE(signal.Exists(NAME_RESPONSE));

    // apply signal to layer
    ptr->Activate(signal);
    ptr->Response(signal);

    // check response
    EXPECT_TRUE(signal.Exists(NAME_RESPONSE));
    EXPECT_MAT_DIMS_EQ(signal.MostRecentMat1f(NAME_RESPONSE), cv::Size2i(1, 1));
    EXPECT_FLOAT_EQ(signal.MostRecentMat1f(NAME_RESPONSE).at<float>(0), 0.5f);
}

class LayerFactoryTest : public ::testing::Test
{
};

TEST_F(LayerFactoryStaticTest, Constructor)
{
    EXPECT_NO_THROW(LayerFactory to);
}

} // annonymous namespace
<|endoftext|>