text
stringlengths 54
60.6k
|
---|
<commit_before>// SimplePackPE.cpp : Defines the entry point for the console application.
//
#include "includes.h"
#include "loader.h"
int StubEP()
{
stub::PSTUB_DATA pStubData;
// get address of STUB_DATA
__asm{
jmp __data_raw_end
__data_raw:
nop // <-- packer will write RVA of stub data here
nop
nop
nop
__data_raw_end:
call __getmyaddr
__getmyaddr:
pop eax // <-- current eip in edx
sub eax, 4 + 5 // <-- get VA of __data_raw: [4 - count of nops(sizeof stubDataOffset)] + [5-sizeof call __getmyaddr]
mov ecx, eax // save stubDataOffset
add eax, [ecx]
mov pStubData, eax
}
PPEB Peb;
__asm {
mov eax, FS:[0x30];
mov Peb, eax
nop
}
pStubData->dwOriginalEP += Peb->ImageBaseAddress;
pStubData->dwImageBase = Peb->ImageBaseAddress;
UnpackSections(pStubData);
StartOriginalPE(pStubData);
return 0;
}
void StartOriginalPE(stub::PSTUB_DATA pStubData)
{
auto pOriginalEP = reinterpret_cast<LPVOID>(pStubData->dwOriginalEP);
__asm
{
jmp pOriginalEP
}
}
void UnpackSections(stub::PSTUB_DATA pStubData)
{
PIMAGE_DOS_HEADER pDOSHead = reinterpret_cast<PIMAGE_DOS_HEADER>(pStubData->dwImageBase);
PIMAGE_NT_HEADERS32 pNtHead = reinterpret_cast<PIMAGE_NT_HEADERS32>(reinterpret_cast<char*>(pDOSHead) + pDOSHead->e_lfanew);
DWORD dwSizeOfOptHead = pNtHead->FileHeader.SizeOfOptionalHeader;
PIMAGE_SECTION_HEADER pSectionHead = reinterpret_cast<PIMAGE_SECTION_HEADER>(reinterpret_cast<char*>(&pNtHead->OptionalHeader) + dwSizeOfOptHead);
DWORD dwFileAlignment = pNtHead->OptionalHeader.FileAlignment;
DWORD dwNumberOfSections = pNtHead->FileHeader.NumberOfSections;
DWORD dwUnpackedSize = 0;
for (DWORD i = 0; i < dwNumberOfSections; ++i, ++pSectionHead)
{
if (pSectionHead->SizeOfRawData == 0)
{
continue;
}
DWORD dwRsrc = 0x72737263; // "rsrc"
if (memcmp(reinterpret_cast<char*>(&pSectionHead->Name[1]), reinterpret_cast<char*>(&dwRsrc), 4) == 0)
{
continue;
}
((fpRtlDecompressBuffer)pStubData->pRtlDecompressBuffer)(
COMPRESSION_FORMAT_LZNT1,
reinterpret_cast<PUCHAR>(pStubData->dwImageBase + pSectionHead->VirtualAddress),
pSectionHead->SizeOfRawData,
reinterpret_cast<PUCHAR>(pStubData->dwImageBase + pSectionHead->VirtualAddress),
pSectionHead->Misc.VirtualSize,
reinterpret_cast<PULONG>(dwUnpackedSize));
}
}
<commit_msg>fixed calculating of StubData in loader<commit_after>// SimplePackPE.cpp : Defines the entry point for the console application.
//
#include "includes.h"
#include "loader.h"
int StubEP()
{
stub::PSTUB_DATA pStubData;
// get address of STUB_DATA
__asm{
jmp __data_raw_end
__data_raw:
nop // <-- packer will write RVA of stub data here
nop
nop
nop
__data_raw_end:
call __getmyaddr
__getmyaddr:
pop eax // <-- current eip in edx
sub eax, 4 + 5 // <-- get VA of __data_raw: [4 - count of nops(sizeof stubDataOffset)] + [5-sizeof call __getmyaddr]
mov ecx, eax // save stubDataOffset
sub eax, [ecx]
mov pStubData, eax
}
PPEB Peb;
__asm {
mov eax, FS:[0x30];
mov Peb, eax
nop
}
pStubData->dwOriginalEP += Peb->ImageBaseAddress;
pStubData->dwImageBase = Peb->ImageBaseAddress;
UnpackSections(pStubData);
StartOriginalPE(pStubData);
return 0;
}
void StartOriginalPE(stub::PSTUB_DATA pStubData)
{
auto pOriginalEP = reinterpret_cast<LPVOID>(pStubData->dwOriginalEP);
__asm
{
jmp pOriginalEP
}
}
void UnpackSections(stub::PSTUB_DATA pStubData)
{
PIMAGE_DOS_HEADER pDOSHead = reinterpret_cast<PIMAGE_DOS_HEADER>(pStubData->dwImageBase);
PIMAGE_NT_HEADERS32 pNtHead = reinterpret_cast<PIMAGE_NT_HEADERS32>(reinterpret_cast<char*>(pDOSHead) + pDOSHead->e_lfanew);
DWORD dwSizeOfOptHead = pNtHead->FileHeader.SizeOfOptionalHeader;
PIMAGE_SECTION_HEADER pSectionHead = reinterpret_cast<PIMAGE_SECTION_HEADER>(reinterpret_cast<char*>(&pNtHead->OptionalHeader) + dwSizeOfOptHead);
DWORD dwFileAlignment = pNtHead->OptionalHeader.FileAlignment;
DWORD dwNumberOfSections = pNtHead->FileHeader.NumberOfSections;
DWORD dwUnpackedSize = 0;
for (DWORD i = 0; i < dwNumberOfSections; ++i, ++pSectionHead)
{
if (pSectionHead->SizeOfRawData == 0)
{
continue;
}
DWORD dwRsrc = 0x72737263; // "rsrc"
if (memcmp(reinterpret_cast<char*>(&pSectionHead->Name[1]), reinterpret_cast<char*>(&dwRsrc), 4) == 0)
{
continue;
}
((fpRtlDecompressBuffer)pStubData->pRtlDecompressBuffer)(
COMPRESSION_FORMAT_LZNT1,
reinterpret_cast<PUCHAR>(pStubData->dwImageBase + pSectionHead->VirtualAddress),
pSectionHead->SizeOfRawData,
reinterpret_cast<PUCHAR>(pStubData->dwImageBase + pSectionHead->VirtualAddress),
pSectionHead->Misc.VirtualSize,
reinterpret_cast<PULONG>(dwUnpackedSize));
}
}
<|endoftext|> |
<commit_before>#include <benchmark/benchmark.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wdouble-promotion"
#include <flat_hash_map.hpp>
#include <sparsehash/dense_hash_map>
#pragma GCC diagnostic pop
#include <random>
#include <unordered_map>
#include <utils/macros.h>
#include <vector>
namespace
{
template <typename HashTableT, typename PostInitF>
HashTableT CreateHashTable(std::size_t iNumberElements, PostInitF&& iPostInitFunctor)
{
using T = typename HashTableT::key_type;
std::uniform_int_distribution<T> randomDistribution(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
std::mt19937_64 generator;
HashTableT hashTable;
iPostInitFunctor(hashTable);
while (hashTable.size() != iNumberElements)
{
hashTable.emplace(randomDistribution(generator), hashTable.size());
}
return hashTable;
}
template <typename HashTableT, typename PostInitF>
void HashTableLookup_RunBenchmark(benchmark::State& iState, PostInitF&& iPostInitFunctor)
{
HashTableT hashTable = CreateHashTable<HashTableT>(iState.range(0), std::forward<PostInitF>(iPostInitFunctor));
std::vector<typename HashTableT::key_type> dataToLookup;
dataToLookup.reserve(hashTable.size());
for (const auto& element : hashTable)
{
dataToLookup.emplace_back(element.first);
}
std::mt19937_64 randomGenerator(235432876);
std::shuffle(std::begin(dataToLookup), std::end(dataToLookup), randomGenerator);
std::size_t i = 0;
for ([[maybe_unused]] auto handler : iState)
{
benchmark::DoNotOptimize(hashTable.find(dataToLookup[i]));
if (unlikely(dataToLookup.size() == ++i))
{
i = 0;
}
}
}
template <typename HashTableT>
void HashTableLookup_RunBenchmark(benchmark::State& iState)
{
return HashTableLookup_RunBenchmark<HashTableT>(iState, [](HashTableT& iHashTable) {});
}
void HashTableLookup_DenseHashMapBenchmark(benchmark::State& iState)
{
HashTableLookup_RunBenchmark<google::dense_hash_map<std::int64_t, std::int64_t>>(iState, [](auto& iHashTable) { iHashTable.set_empty_key(-1); });
}
void HashTableLookup_FlatHashMapBenchmark(benchmark::State& iState)
{
HashTableLookup_RunBenchmark<ska::flat_hash_map<std::int64_t, std::int64_t>>(iState);
}
void HashTableLookup_UnorderedMapBenchmark(benchmark::State& iState)
{
HashTableLookup_RunBenchmark<std::unordered_map<std::int64_t, std::int64_t>>(iState);
}
void HashTableLookup_Arguments(benchmark::internal::Benchmark* iBenchmark)
{
for (double i = 10; i <= 120'000; i *= 12) // NOLINT
{
iBenchmark->Arg(i);
}
}
}
// All of the graphs are spiky. This is because all hashtables have different performance depending on the current load factor.
// Meaning depending on how full they are. When a table is 25% full lookups will be faster than when it’s 50% full.
// The reason for this is that there are more hash collisions when the table is more full.
// So you can see the cost go up until at some point the table decides that it’s too full and that it should reallocate, which makes lookups fast again.
// Another thing that we notice is that all the graphs are essentially flat on the left half of the screen.
// This is because the table fits entirely into the cache. Only when we get to the point where the data doesn’t fit into the L3 cache do we see the different graphs really diverge.
// You will only get the numbers on the left if the element you’re looking for is already in the cache.
BENCHMARK(HashTableLookup_DenseHashMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT
BENCHMARK(HashTableLookup_FlatHashMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT
BENCHMARK(HashTableLookup_UnorderedMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT
<commit_msg>Update benchmark_lookup.cpp<commit_after>#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wdouble-promotion"
#include <flat_hash_map.hpp>
#include <sparsehash/dense_hash_map>
#pragma GCC diagnostic pop
#include <algorithm>
#include <benchmark/benchmark.h>
#include <random>
#include <unordered_map>
#include <utils/macros.h>
#include <vector>
namespace
{
template <typename HashTableT, typename PostInitF>
HashTableT CreateHashTable(std::size_t iNumberElements, PostInitF&& iPostInitFunctor)
{
using T = typename HashTableT::key_type;
std::uniform_int_distribution<T> randomDistribution(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
std::mt19937_64 generator;
HashTableT hashTable;
iPostInitFunctor(hashTable);
while (hashTable.size() != iNumberElements)
{
hashTable.emplace(randomDistribution(generator), hashTable.size());
}
return hashTable;
}
template <typename HashTableT, typename PostInitF>
void HashTableLookup_RunBenchmark(benchmark::State& iState, PostInitF&& iPostInitFunctor)
{
HashTableT hashTable = CreateHashTable<HashTableT>(iState.range(0), std::forward<PostInitF>(iPostInitFunctor));
std::vector<typename HashTableT::key_type> dataToLookup;
dataToLookup.reserve(hashTable.size());
for (const auto& element : hashTable)
{
dataToLookup.emplace_back(element.first);
}
std::mt19937_64 randomGenerator(235432876);
std::shuffle(std::begin(dataToLookup), std::end(dataToLookup), randomGenerator);
std::size_t i = 0;
for ([[maybe_unused]] auto handler : iState)
{
benchmark::DoNotOptimize(hashTable.find(dataToLookup[i]));
if (unlikely(dataToLookup.size() == ++i))
{
i = 0;
}
}
}
template <typename HashTableT>
void HashTableLookup_RunBenchmark(benchmark::State& iState)
{
return HashTableLookup_RunBenchmark<HashTableT>(iState, [](HashTableT& iHashTable) {});
}
void HashTableLookup_DenseHashMapBenchmark(benchmark::State& iState)
{
HashTableLookup_RunBenchmark<google::dense_hash_map<std::int64_t, std::int64_t>>(iState, [](auto& iHashTable) { iHashTable.set_empty_key(-1); });
}
void HashTableLookup_FlatHashMapBenchmark(benchmark::State& iState)
{
HashTableLookup_RunBenchmark<ska::flat_hash_map<std::int64_t, std::int64_t>>(iState);
}
void HashTableLookup_UnorderedMapBenchmark(benchmark::State& iState)
{
HashTableLookup_RunBenchmark<std::unordered_map<std::int64_t, std::int64_t>>(iState);
}
void HashTableLookup_Arguments(benchmark::internal::Benchmark* iBenchmark)
{
for (double i = 10; i <= 120'000; i *= 12) // NOLINT
{
iBenchmark->Arg(i);
}
}
}
// All of the graphs are spiky. This is because all hashtables have different performance depending on the current load factor.
// Meaning depending on how full they are. When a table is 25% full lookups will be faster than when it’s 50% full.
// The reason for this is that there are more hash collisions when the table is more full.
// So you can see the cost go up until at some point the table decides that it’s too full and that it should reallocate, which makes lookups fast again.
// Another thing that we notice is that all the graphs are essentially flat on the left half of the screen.
// This is because the table fits entirely into the cache. Only when we get to the point where the data doesn’t fit into the L3 cache do we see the different graphs really diverge.
// You will only get the numbers on the left if the element you’re looking for is already in the cache.
BENCHMARK(HashTableLookup_DenseHashMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT
BENCHMARK(HashTableLookup_FlatHashMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT
BENCHMARK(HashTableLookup_UnorderedMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sslt.h>
#include <vector>
#include <string>
#include "base/eintr_wrapper.h"
#include "base/base64.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/values.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/net_log_unittest.h"
#include "net/base/ssl_config_service.h"
#include "net/base/test_completion_callback.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/ssl_client_socket.h"
#include "net/socket/ssl_client_socket_nss.h"
#include "net/socket/ssl_host_info.h"
#include "net/socket/tcp_client_socket.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
namespace net {
// TestSSLHostInfo is an SSLHostInfo which stores a single state in memory and
// pretends that certificate verification always succeeds.
class TestSSLHostInfo : public SSLHostInfo {
public:
TestSSLHostInfo()
: SSLHostInfo("example.com", kDefaultSSLConfig) {
if (!saved_.empty())
Parse(saved_);
cert_verification_complete_ = true;
cert_verification_error_ = OK;
}
virtual void Start() {
}
virtual int WaitForDataReady(CompletionCallback*) { return OK; }
virtual void Persist() {
saved_ = Serialize();
}
static void Reset() {
saved_.clear();
}
private:
static SSLConfig kDefaultSSLConfig;
static std::string saved_;
};
std::string TestSSLHostInfo::saved_;
SSLConfig TestSSLHostInfo::kDefaultSSLConfig;
class SSLClientSocketSnapStartTest : public PlatformTest {
public:
SSLClientSocketSnapStartTest()
: child_(base::kNullProcessHandle),
socket_factory_(ClientSocketFactory::GetDefaultFactory()),
log_(CapturingNetLog::kUnbounded) {
TestSSLHostInfo::Reset();
ssl_config_.snap_start_enabled = true;
}
virtual void TearDown() {
if (child_ != base::kNullProcessHandle) {
int exit_code;
EXPECT_TRUE(base::WaitForExitCode(child_, &exit_code));
EXPECT_EQ(0, exit_code);
}
}
protected:
void StartSnapStartServer(const char* arg, ...) {
FilePath dir_exe;
PathService::Get(base::DIR_EXE, &dir_exe);
FilePath helper_binary = dir_exe.Append("openssl_helper");
std::vector<std::string> args;
args.push_back(helper_binary.value());
va_list ap;
va_start(ap, arg);
while (arg) {
args.push_back(arg);
arg = va_arg(ap, const char*);
}
va_end(ap);
const int listener = socket(AF_INET, SOCK_STREAM, 0);
ASSERT_GE(listener, 0);
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = PF_INET;
ASSERT_EQ(0, bind(listener, (struct sockaddr*) &sin, sizeof(sin)));
socklen_t socklen = sizeof(remote_);
ASSERT_EQ(0, getsockname(listener, (struct sockaddr*) &remote_, &socklen));
ASSERT_EQ(sizeof(remote_), socklen);
ASSERT_EQ(0, listen(listener, 1));
base::file_handle_mapping_vector mapping;
// The listening socket is installed as the child's fd 3.
mapping.push_back(std::make_pair(listener, 3));
base::LaunchApp(args, mapping, false /* don't wait */, &child_);
HANDLE_EINTR(close(listener));
}
// LoadDefaultCert returns the DER encoded default certificate.
std::string LoadDefaultCert() {
FilePath path;
PathService::Get(base::DIR_SOURCE_ROOT, &path);
path = path.Append("net");
path = path.Append("data");
path = path.Append("ssl");
path = path.Append("certificates");
path = path.Append("ok_cert.pem");
std::string pem;
bool r = file_util::ReadFileToString(path, &pem);
CHECK(r) << "failed to read " << path.value();
static const char kStartMarker[] = "-----BEGIN CERTIFICATE-----\n";
static const char kEndMarker[] = "-----END CERTIFICATE-----\n";
std::string::size_type i = pem.find(kStartMarker);
std::string::size_type j = pem.find(kEndMarker);
CHECK(i != std::string::npos);
CHECK(j != std::string::npos);
CHECK_GT(j, i);
i += sizeof(kStartMarker) - 1;
std::string b64data = pem.substr(i, j - i);
ReplaceSubstringsAfterOffset(&b64data, 0 /* start offset */, "\n", "");
std::string der;
base::Base64Decode(b64data, &der);
return der;
}
void SetupSSLConfig() {
if (ssl_config_.allowed_bad_certs.size())
return;
const std::string der = LoadDefaultCert();
SSLConfig::CertAndStatus cert_and_status;
cert_and_status.cert =
X509Certificate::CreateFromBytes(der.data(), der.size());
cert_and_status.cert_status = ERR_CERT_AUTHORITY_INVALID;
ssl_config_.allowed_bad_certs.push_back(cert_and_status);
}
// PerformConnection makes an SSL connection to the openssl_helper binary and
// does a ping-pong test to check the the SSL socket is working correctly.
void PerformConnection() {
client_ = socket(AF_INET, SOCK_STREAM, 0);
ASSERT_LE(0, client_);
ASSERT_EQ(
0, connect(client_, (struct sockaddr*) &remote_, sizeof(remote_)));
int on = 1;
setsockopt(client_, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
SetupSSLConfig();
log_.Clear();
std::vector<uint8> localhost;
localhost.push_back(127);
localhost.push_back(0);
localhost.push_back(0);
localhost.push_back(1);
AddressList addr_list(localhost, 443, false);
TCPClientSocket* transport = new TCPClientSocket(
addr_list, &log_, NetLog::Source());
transport->AdoptSocket(client_);
scoped_ptr<SSLClientSocket> sock(
socket_factory_->CreateSSLClientSocket(
transport, HostPortPair("example.com", 443), ssl_config_,
new TestSSLHostInfo()));
TestCompletionCallback callback;
int rv = sock->Connect(&callback);
if (rv != OK) {
ASSERT_EQ(ERR_IO_PENDING, rv);
EXPECT_FALSE(sock->IsConnected());
rv = callback.WaitForResult();
EXPECT_EQ(OK, rv);
}
EXPECT_TRUE(sock->IsConnected());
static const char request_text[] = "hello!";
scoped_refptr<IOBuffer> request_buffer =
new IOBuffer(arraysize(request_text) - 1);
memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
rv = sock->Write(request_buffer, arraysize(request_text), &callback);
if (rv < 0) {
ASSERT_EQ(ERR_IO_PENDING, rv);
rv = callback.WaitForResult();
}
EXPECT_EQ(7, rv);
scoped_refptr<IOBuffer> reply_buffer = new IOBuffer(8);
rv = sock->Read(reply_buffer, 8, &callback);
if (rv < 0) {
ASSERT_EQ(ERR_IO_PENDING, rv);
rv = callback.WaitForResult();
}
EXPECT_EQ(8, rv);
EXPECT_TRUE(memcmp(reply_buffer->data(), "goodbye!", 8) == 0);
next_proto_status_ = sock->GetNextProto(&next_proto_);
sock->Disconnect();
}
// SnapStartEventType extracts the type of Snap Start from the NetLog. See
// the SSL_SNAP_START_* defines in sslt.h
int SnapStartEventType() {
CapturingNetLog::EntryList entries;
log_.GetEntries(&entries);
for (CapturingNetLog::EntryList::const_iterator
i = entries.begin(); i != entries.end(); i++) {
if (i->type == NetLog::TYPE_SSL_SNAP_START) {
scoped_ptr<Value> value(i->extra_parameters->ToValue());
CHECK(value->GetType() == Value::TYPE_DICTIONARY);
DictionaryValue* dict = reinterpret_cast<DictionaryValue*>(value.get());
int ret;
CHECK(dict->GetInteger("type", &ret));
return ret;
}
}
return -1;
}
// DidMerge returns true if the NetLog suggests the the SSL connection merged
// it's certificate validation with the optimistic validation from the
// SSLHostInfo.
bool DidMerge() {
CapturingNetLog::EntryList entries;
log_.GetEntries(&entries);
for (CapturingNetLog::EntryList::const_iterator
i = entries.begin(); i != entries.end(); i++) {
if (i->type == NetLog::TYPE_SSL_VERIFICATION_MERGED)
return true;
}
return false;
}
base::ProcessHandle child_;
ClientSocketFactory* const socket_factory_;
struct sockaddr_in remote_;
int client_;
SSLConfig ssl_config_;
CapturingNetLog log_;
SSLClientSocket::NextProtoStatus next_proto_status_;
std::string next_proto_;
};
TEST_F(SSLClientSocketSnapStartTest, Basic) {
// Not a Snap Start connection.
StartSnapStartServer(NULL);
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStart) {
StartSnapStartServer("snap-start", NULL);
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
SSLClientSocketNSS::ClearSessionCache();
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_FULL, SnapStartEventType());
EXPECT_TRUE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStartResume) {
StartSnapStartServer("snap-start", NULL);
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_RESUME, SnapStartEventType());
EXPECT_TRUE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStartRecovery) {
StartSnapStartServer("snap-start-recovery", NULL);
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
SSLClientSocketNSS::ClearSessionCache();
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_RECOVERY, SnapStartEventType());
EXPECT_TRUE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStartResumeRecovery) {
StartSnapStartServer("snap-start-recovery", NULL);
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_RESUME_RECOVERY, SnapStartEventType());
EXPECT_TRUE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStartWithNPN) {
ssl_config_.next_protos.assign("\003foo\003bar");
StartSnapStartServer("snap-start", "npn", NULL);
PerformConnection();
EXPECT_EQ(SSLClientSocket::kNextProtoNegotiated, next_proto_status_);
EXPECT_EQ("foo", next_proto_);
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
SSLClientSocketNSS::ClearSessionCache();
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_FULL, SnapStartEventType());
EXPECT_EQ(SSLClientSocket::kNextProtoNegotiated, next_proto_status_);
EXPECT_EQ("foo", next_proto_);
EXPECT_TRUE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStartWithNPNMispredict) {
// This tests that we recover in the event of a misprediction.
ssl_config_.next_protos.assign("\003foo\003baz");
StartSnapStartServer("snap-start", "npn-mispredict", NULL);
PerformConnection();
EXPECT_EQ(SSLClientSocket::kNextProtoNegotiated, next_proto_status_);
EXPECT_EQ("foo", next_proto_);
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
SSLClientSocketNSS::ClearSessionCache();
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_RECOVERY, SnapStartEventType());
EXPECT_EQ(SSLClientSocket::kNextProtoNegotiated, next_proto_status_);
EXPECT_EQ("baz", next_proto_);
EXPECT_TRUE(DidMerge());
SSLClientSocketNSS::ClearSessionCache();
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_FULL, SnapStartEventType());
EXPECT_EQ(SSLClientSocket::kNextProtoNegotiated, next_proto_status_);
EXPECT_EQ("baz", next_proto_);
EXPECT_TRUE(DidMerge());
}
} // namespace net
<commit_msg>Don't ignore return value from HANDLE_EINTR(close(...))<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sslt.h>
#include <vector>
#include <string>
#include "base/eintr_wrapper.h"
#include "base/base64.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/values.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/net_log_unittest.h"
#include "net/base/ssl_config_service.h"
#include "net/base/test_completion_callback.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/ssl_client_socket.h"
#include "net/socket/ssl_client_socket_nss.h"
#include "net/socket/ssl_host_info.h"
#include "net/socket/tcp_client_socket.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
namespace net {
// TestSSLHostInfo is an SSLHostInfo which stores a single state in memory and
// pretends that certificate verification always succeeds.
class TestSSLHostInfo : public SSLHostInfo {
public:
TestSSLHostInfo()
: SSLHostInfo("example.com", kDefaultSSLConfig) {
if (!saved_.empty())
Parse(saved_);
cert_verification_complete_ = true;
cert_verification_error_ = OK;
}
virtual void Start() {
}
virtual int WaitForDataReady(CompletionCallback*) { return OK; }
virtual void Persist() {
saved_ = Serialize();
}
static void Reset() {
saved_.clear();
}
private:
static SSLConfig kDefaultSSLConfig;
static std::string saved_;
};
std::string TestSSLHostInfo::saved_;
SSLConfig TestSSLHostInfo::kDefaultSSLConfig;
class SSLClientSocketSnapStartTest : public PlatformTest {
public:
SSLClientSocketSnapStartTest()
: child_(base::kNullProcessHandle),
socket_factory_(ClientSocketFactory::GetDefaultFactory()),
log_(CapturingNetLog::kUnbounded) {
TestSSLHostInfo::Reset();
ssl_config_.snap_start_enabled = true;
}
virtual void TearDown() {
if (child_ != base::kNullProcessHandle) {
int exit_code;
EXPECT_TRUE(base::WaitForExitCode(child_, &exit_code));
EXPECT_EQ(0, exit_code);
}
}
protected:
void StartSnapStartServer(const char* arg, ...) {
FilePath dir_exe;
PathService::Get(base::DIR_EXE, &dir_exe);
FilePath helper_binary = dir_exe.Append("openssl_helper");
std::vector<std::string> args;
args.push_back(helper_binary.value());
va_list ap;
va_start(ap, arg);
while (arg) {
args.push_back(arg);
arg = va_arg(ap, const char*);
}
va_end(ap);
const int listener = socket(AF_INET, SOCK_STREAM, 0);
ASSERT_GE(listener, 0);
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = PF_INET;
ASSERT_EQ(0, bind(listener, (struct sockaddr*) &sin, sizeof(sin)));
socklen_t socklen = sizeof(remote_);
ASSERT_EQ(0, getsockname(listener, (struct sockaddr*) &remote_, &socklen));
ASSERT_EQ(sizeof(remote_), socklen);
ASSERT_EQ(0, listen(listener, 1));
base::file_handle_mapping_vector mapping;
// The listening socket is installed as the child's fd 3.
mapping.push_back(std::make_pair(listener, 3));
base::LaunchApp(args, mapping, false /* don't wait */, &child_);
ASSERT_EQ(0, HANDLE_EINTR(close(listener)));
}
// LoadDefaultCert returns the DER encoded default certificate.
std::string LoadDefaultCert() {
FilePath path;
PathService::Get(base::DIR_SOURCE_ROOT, &path);
path = path.Append("net");
path = path.Append("data");
path = path.Append("ssl");
path = path.Append("certificates");
path = path.Append("ok_cert.pem");
std::string pem;
bool r = file_util::ReadFileToString(path, &pem);
CHECK(r) << "failed to read " << path.value();
static const char kStartMarker[] = "-----BEGIN CERTIFICATE-----\n";
static const char kEndMarker[] = "-----END CERTIFICATE-----\n";
std::string::size_type i = pem.find(kStartMarker);
std::string::size_type j = pem.find(kEndMarker);
CHECK(i != std::string::npos);
CHECK(j != std::string::npos);
CHECK_GT(j, i);
i += sizeof(kStartMarker) - 1;
std::string b64data = pem.substr(i, j - i);
ReplaceSubstringsAfterOffset(&b64data, 0 /* start offset */, "\n", "");
std::string der;
base::Base64Decode(b64data, &der);
return der;
}
void SetupSSLConfig() {
if (ssl_config_.allowed_bad_certs.size())
return;
const std::string der = LoadDefaultCert();
SSLConfig::CertAndStatus cert_and_status;
cert_and_status.cert =
X509Certificate::CreateFromBytes(der.data(), der.size());
cert_and_status.cert_status = ERR_CERT_AUTHORITY_INVALID;
ssl_config_.allowed_bad_certs.push_back(cert_and_status);
}
// PerformConnection makes an SSL connection to the openssl_helper binary and
// does a ping-pong test to check the the SSL socket is working correctly.
void PerformConnection() {
client_ = socket(AF_INET, SOCK_STREAM, 0);
ASSERT_LE(0, client_);
ASSERT_EQ(
0, connect(client_, (struct sockaddr*) &remote_, sizeof(remote_)));
int on = 1;
setsockopt(client_, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
SetupSSLConfig();
log_.Clear();
std::vector<uint8> localhost;
localhost.push_back(127);
localhost.push_back(0);
localhost.push_back(0);
localhost.push_back(1);
AddressList addr_list(localhost, 443, false);
TCPClientSocket* transport = new TCPClientSocket(
addr_list, &log_, NetLog::Source());
transport->AdoptSocket(client_);
scoped_ptr<SSLClientSocket> sock(
socket_factory_->CreateSSLClientSocket(
transport, HostPortPair("example.com", 443), ssl_config_,
new TestSSLHostInfo()));
TestCompletionCallback callback;
int rv = sock->Connect(&callback);
if (rv != OK) {
ASSERT_EQ(ERR_IO_PENDING, rv);
EXPECT_FALSE(sock->IsConnected());
rv = callback.WaitForResult();
EXPECT_EQ(OK, rv);
}
EXPECT_TRUE(sock->IsConnected());
static const char request_text[] = "hello!";
scoped_refptr<IOBuffer> request_buffer =
new IOBuffer(arraysize(request_text) - 1);
memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
rv = sock->Write(request_buffer, arraysize(request_text), &callback);
if (rv < 0) {
ASSERT_EQ(ERR_IO_PENDING, rv);
rv = callback.WaitForResult();
}
EXPECT_EQ(7, rv);
scoped_refptr<IOBuffer> reply_buffer = new IOBuffer(8);
rv = sock->Read(reply_buffer, 8, &callback);
if (rv < 0) {
ASSERT_EQ(ERR_IO_PENDING, rv);
rv = callback.WaitForResult();
}
EXPECT_EQ(8, rv);
EXPECT_TRUE(memcmp(reply_buffer->data(), "goodbye!", 8) == 0);
next_proto_status_ = sock->GetNextProto(&next_proto_);
sock->Disconnect();
}
// SnapStartEventType extracts the type of Snap Start from the NetLog. See
// the SSL_SNAP_START_* defines in sslt.h
int SnapStartEventType() {
CapturingNetLog::EntryList entries;
log_.GetEntries(&entries);
for (CapturingNetLog::EntryList::const_iterator
i = entries.begin(); i != entries.end(); i++) {
if (i->type == NetLog::TYPE_SSL_SNAP_START) {
scoped_ptr<Value> value(i->extra_parameters->ToValue());
CHECK(value->GetType() == Value::TYPE_DICTIONARY);
DictionaryValue* dict = reinterpret_cast<DictionaryValue*>(value.get());
int ret;
CHECK(dict->GetInteger("type", &ret));
return ret;
}
}
return -1;
}
// DidMerge returns true if the NetLog suggests the the SSL connection merged
// it's certificate validation with the optimistic validation from the
// SSLHostInfo.
bool DidMerge() {
CapturingNetLog::EntryList entries;
log_.GetEntries(&entries);
for (CapturingNetLog::EntryList::const_iterator
i = entries.begin(); i != entries.end(); i++) {
if (i->type == NetLog::TYPE_SSL_VERIFICATION_MERGED)
return true;
}
return false;
}
base::ProcessHandle child_;
ClientSocketFactory* const socket_factory_;
struct sockaddr_in remote_;
int client_;
SSLConfig ssl_config_;
CapturingNetLog log_;
SSLClientSocket::NextProtoStatus next_proto_status_;
std::string next_proto_;
};
TEST_F(SSLClientSocketSnapStartTest, Basic) {
// Not a Snap Start connection.
StartSnapStartServer(NULL);
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStart) {
StartSnapStartServer("snap-start", NULL);
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
SSLClientSocketNSS::ClearSessionCache();
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_FULL, SnapStartEventType());
EXPECT_TRUE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStartResume) {
StartSnapStartServer("snap-start", NULL);
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_RESUME, SnapStartEventType());
EXPECT_TRUE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStartRecovery) {
StartSnapStartServer("snap-start-recovery", NULL);
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
SSLClientSocketNSS::ClearSessionCache();
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_RECOVERY, SnapStartEventType());
EXPECT_TRUE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStartResumeRecovery) {
StartSnapStartServer("snap-start-recovery", NULL);
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_RESUME_RECOVERY, SnapStartEventType());
EXPECT_TRUE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStartWithNPN) {
ssl_config_.next_protos.assign("\003foo\003bar");
StartSnapStartServer("snap-start", "npn", NULL);
PerformConnection();
EXPECT_EQ(SSLClientSocket::kNextProtoNegotiated, next_proto_status_);
EXPECT_EQ("foo", next_proto_);
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
SSLClientSocketNSS::ClearSessionCache();
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_FULL, SnapStartEventType());
EXPECT_EQ(SSLClientSocket::kNextProtoNegotiated, next_proto_status_);
EXPECT_EQ("foo", next_proto_);
EXPECT_TRUE(DidMerge());
}
TEST_F(SSLClientSocketSnapStartTest, SnapStartWithNPNMispredict) {
// This tests that we recover in the event of a misprediction.
ssl_config_.next_protos.assign("\003foo\003baz");
StartSnapStartServer("snap-start", "npn-mispredict", NULL);
PerformConnection();
EXPECT_EQ(SSLClientSocket::kNextProtoNegotiated, next_proto_status_);
EXPECT_EQ("foo", next_proto_);
EXPECT_EQ(SSL_SNAP_START_NONE, SnapStartEventType());
EXPECT_FALSE(DidMerge());
SSLClientSocketNSS::ClearSessionCache();
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_RECOVERY, SnapStartEventType());
EXPECT_EQ(SSLClientSocket::kNextProtoNegotiated, next_proto_status_);
EXPECT_EQ("baz", next_proto_);
EXPECT_TRUE(DidMerge());
SSLClientSocketNSS::ClearSessionCache();
PerformConnection();
EXPECT_EQ(SSL_SNAP_START_FULL, SnapStartEventType());
EXPECT_EQ(SSLClientSocket::kNextProtoNegotiated, next_proto_status_);
EXPECT_EQ("baz", next_proto_);
EXPECT_TRUE(DidMerge());
}
} // namespace net
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
// Basics of pointers in C++
void ChangeValue(int);
void ChangePointer(int *);
void ChangeTwoPointers(int *, int *);
int main(int argc, char* argv[]) {
int x = 5, y = 100; // normal int variables
// A "pointer" is a special variable that "points" to another variable.
// Pointers are initialized by assigning the *address* of another variable of
// the same type.
int *p;
// p is a variable of type "pointer to int."
// The * indicates a pointer variable. Whitespace doesn't matter.
// int * p, int* p, int *p -- all the same.
// Like all variables, p has a garbage value until it is assigned something.
// We assign the addresses of variables to pointers.
p = &x; // & means "address of"; &x means "address of x". assigning &x to p
// makes p point to x.
/*
To change the VALUE of the thing p points to, we use the * operator on p to
"de-reference" the pointer. This gives us access to the actual memory that
it points to. We can then read or write to that memory as usual.
*/
cout << *p << endl; // Read the value of the thing that p points to.
*p = 10; // Assign a value to the thing that p points to.
// We can declare and initialize a pointer in one line:
int *p2 = &x;
// Pointers are type-safe, somewhat: can't assign int* to double*
// double *cant = &x; // error: cannot convert from 'int *' to 'double *'
// But you can assign one pointer to another
int *otherPointer = p;
// This line DECLARES a pointer and INITIALIZES IT to point to the thing
// p points to.
*otherPointer = 100; // what does this change?
/*
THIS IS IMPORTANT!
When you copy or assign pointer A to pointer B, you are making B point to the
same thing that A points to.
*/
/*
MINI QUIZ:
Which of these statements will not compile?
int *a = &x;
int *b = &a;
int *c = 10;
short *d = &x;
int *e = *a;
*/
// Pointers can be made to "point" to something else by assigning them a
// new address.
p = &y; // this does not change x's value; it makes p "point to" y
*p = 40; // what actual variable changed?
// What does this output now?
cout << "*p is: " << *p << " -- y is: " << y << endl;
/*
Pointers can be passed to functions. This allows the function to change a
parameter so that the caller sees the change.
Before passing pointers as arguments, review passing "normal" variables.
*/
ChangeValue(x); // x has value 100 before this call; what about after?
// That's because variables are passed to functions...
// BY ____________ (fill in the blank).
/*
Because the "value" of a pointer is a memory address, when a pointer is
passed by value, the address of the thing it points to is copied to the
parameter, creating a pointer that points to the same thing as what the
argument points to.
*/
ChangePointer(p);
// The address p points to is copied to the function's parameter...
// then what?
cout << "After function, *p == " << *p << endl;
// It is more common to pass &y directly to the function.
ChangePointer(&y);
cout << "After function, y and *p == " << *p << " (" << y << ")"
<< endl;
return 0;
}
void ChangeValue(int v) {
v = 500;
}
void ChangePointer(int *p) {
*p = 1000;
}
void ChangeTwoPointers(int *p1, int *p2) {
*p1 = -1;
*p2 = -2;
}<commit_msg>Expanded example.<commit_after>#include <iostream>
using namespace std;
// Basics of pointers in C++
void ChangeValue(int);
void ChangePointer(int *);
void ChangeTwoPointers(int *, int *);
int main(int argc, char* argv[]) {
int x = 5, y = 100; // normal int variables
// A "pointer" is a special variable that "points" to another variable.
// Pointers are initialized by assigning the *address* of another variable of
// the same type.
int *p;
// p is a variable of type "pointer to int."
// The * indicates a pointer variable. Whitespace doesn't matter.
// int * p, int* p, int *p -- all the same.
// Like all variables, p has a garbage value until it is assigned something.
// We assign the addresses of variables to pointers.
p = &x; // & means "address of"; &x means "address of x". assigning &x to p
// makes p point to x.
/*
To change the VALUE of the thing p points to, we use the * operator on p to
"de-reference" the pointer. This gives us access to the actual memory that
it points to. We can then read or write to that memory as usual.
*/
cout << *p << endl; // Read the value of the thing that p points to.
*p = 10; // Assign a value to the thing that p points to.
// We can declare and initialize a pointer in one line:
int *p2 = &x;
// Pointers are type-safe, somewhat: can't assign int* to double*
// double *cant = &x; // error: cannot convert from 'int *' to 'double *'
// But you can assign one pointer to another
int *otherPointer = p;
// This line DECLARES a pointer and INITIALIZES IT to point to the thing
// p points to.
*otherPointer = 100; // what does this change?
/*
THIS IS IMPORTANT!
When you copy or assign pointer A to pointer B, you are making B point to the
same thing that A points to.
` */
/*
MINI QUIZ:
Which of these statements will not compile?
int *a = &x;
int *b = &a;
int *c = 10;
short *d = &x;
int *e = *a;
*/
// Pointers can be made to "point" to something else by assigning them a
// new address.
p = &y; // this does not change x's value; it makes p "point to" y
*p = 40; // what actual variable changed?
// What does this output now?
cout << "*p is: " << *p << " -- y is: " << y << endl;
/*
Pointers can be passed to functions. This allows the function to change a
parameter so that the caller sees the change.
Before passing pointers as arguments, review passing "normal" variables.
*/
ChangeValue(x); // x has value 100 before this call; what about after?
// That's because variables are passed to functions...
// BY ____________ (fill in the blank).
/*
Because the "value" of a pointer is a memory address, when a pointer is
passed by value, the address of the thing it points to is copied to the
parameter, creating a pointer that points to the same thing as what the
argument points to.
*/
ChangePointer(p);
// The address p points to is copied to the function's parameter...
// then what?
cout << "After function, *p == " << *p << endl;
// It is more common to pass &y directly to the function.
ChangePointer(&y);
cout << "After function, y and *p == " << *p << " (" << y << ")"
<< endl;
ChangeTwoPointers(&x, &y);
return 0;
}
void ChangeValue(int v) {
v = 500;
}
void ChangePointer(int *p) {
*p = 1000;
}
void ChangeTwoPointers(int *p1, int *p2) {
*p1 = -1;
*p2 = -2;
}<|endoftext|> |
<commit_before>#include "Kernel.h"
#include "Graphics.h"
#include "OS.h"
#include "Log.h"
#include "transitions/fade.h"
#include "browsers/mysqlbrowser.h"
#include "IPC/dbus.h"
#include <portable/Time.h>
#include <portable/Process.h>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <syscall.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#ifdef LINUX
#include <sys/time.h>
#endif
#ifdef WIN32
#include <windows.h>
#endif
#ifndef NULL
#define NULL 0
#endif
bool* daemon_running = NULL;
const char* application_name = "slideshow";
void quit_signal(int){
Log::message(Log::Verbose, "Caught SIGQUIT\n");
signal(SIGQUIT, quit_signal);
*daemon_running = false;
}
Kernel::Kernel(int argc, char* argv[]):
_width(800),
_height(600),
_frames(0),
_fullscreen(false),
_daemon(false),
_transition_time(5.0f),
_switch_time(3.0f),
_graphics(NULL),
_browser(NULL),
_ipc(NULL),
_db_username(NULL),
_db_password(NULL),
_db_name(NULL),
_logfile("slideshow.log"){
parse_argv(argc, argv);
initTime();
Log::initialize(_logfile, "slideshow.debug.log");
if ( _daemon ){
Log::message(Log::Verbose, "Kernel: Starting slideshow daemon\n");
Portable::daemonize(application_name);
if ( signal(SIGQUIT, quit_signal) == SIG_ERR ){
Log::message(Log::Fatal, "Kernel: Could not initialize signal handler!\n");
exit(3);
}
///@ hack
daemon_running = &_running;
} else {
Log::message(Log::Verbose, "Kernel: Starting slideshow\n");
}
_graphics = new Graphics(_width, _height, _fullscreen);
_graphics->set_transition(new FadeTransition);
_ipc = new DBus(this, 50);
_browser = new MySQLBrowser(_db_username, _db_password, _db_name);
_browser->reload();
_state = SWITCH;
}
Kernel::~Kernel(){
if ( _daemon ){
Portable::daemon_stop(application_name);
}
delete _browser;
delete _graphics;
delete _ipc;
free( _db_username );
free( _db_password );
free( _db_name );
_browser = NULL;
_graphics = NULL;
_ipc = NULL;
Log::deinitialize();
}
void Kernel::run(){
_running = true;
_last_switch = getTime();
_transition_start = 0.0f;
while ( _running ){
OS::poll_events(_running);
double t = getTime();
// Simple statemachine
switch ( _state ){
case VIEW:
view_state(t);
break;
case TRANSITION:
transition_state(t);
break;
case SWITCH:
switch_state(t);
break;
}
}
}
void Kernel::parse_argv(int argc, char* argv[]){
for ( int i = 0; i < argc; i++ ){
if ( strcmp(argv[i], "--fullscreen") == 0 ){
_fullscreen = true;
continue;
}
if ( strcmp(argv[i], "--daemon") == 0 ){
_daemon = true;
continue;
}
if ( strcmp(argv[i], "--db_user") == 0 ){
i++;
const char* user = argv[i];
_db_username = (char*)malloc(strlen(user)+1);
strcpy(_db_username, user);
continue;
}
if ( strcmp(argv[i], "--db_pass") == 0 ){
i++;
const char* pass = argv[i];
_db_password = (char*)malloc(strlen(pass)+1);
strcpy(_db_password, pass);
continue;
}
if ( strcmp(argv[i], "--db_name") == 0 ){
i++;
const char* name = argv[i];
_db_name = (char*)malloc(strlen(name)+1);
strcpy(_db_name, name);
continue;
}
if ( strcmp(argv[i], "--resolution") == 0 ){
i++;
sscanf(argv[i], "%dx%d", &_width, &_height);
continue;
}
}
}
void Kernel::view_state(double t){
if ( t - _last_switch > _switch_time ){
_state = SWITCH;
return;
}
if ( _ipc ){
_ipc->poll();
}
// Sleep for a while
wait( 0.1f );
}
// The transition state calculates how long of the
// transition has come and calls the renderer
void Kernel::transition_state(double t){
double s = (t - _transition_start) / _transition_time;
_frames++;
_graphics->render( s );
// If the transition is complete the state changes to VIEW
if ( s > 1.0f ){
printf("Frames: %d\nFPS: %f\n\n", _frames, (float)_frames/_transition_time);
_state = VIEW;
_last_switch = t;
}
}
void Kernel::switch_state(double t){
const char* filename = _browser->get_next_file();
if ( !filename ){
Log::message(Log::Warning, "Kernel: Queue is empty\n", filename);
//wait( _switch_time * 0.9f );
return;
}
///@fulhack, register handlers instead...
char* ext = get_file_ext(filename);
if ( is_movie_ext(ext) ){
play_video(filename);
free(ext);
return;
}
free(ext);
Log::message(Log::Debug, "Kernel: Switching to image \"%s\"\n", filename);
try {
_graphics->load_image( filename );
} catch ( ... ) {
Log::message(Log::Warning, "Kernel: Failed to load image '%s'\n", filename);
return;
}
_state = TRANSITION;
_frames = 0;
_transition_start = getTime();
}
void Kernel::play_video(const char* fullpath){
Log::message(Log::Verbose, "Kernel: Playing video \"%s\"\n", fullpath);
int status;
if ( fork() == 0 ){
execlp("mplayer", "", "-fs", fullpath, NULL);
exit(0);
}
::wait(&status);
}
char* Kernel::get_file_ext(const char* filename){
const char* start = filename;
const char* ptr = filename + strlen(filename);
///@note Hmm, copy&paste is not always good... Rewrite using strrchr... 2008-02-27 --ext
while( ptr > start){
if( *ptr == '.'){
unsigned int len = strlen(ptr) - 1;
char* ext = (char*)malloc( len + 1 );
unsigned int i;
for ( i = 0; i < len; i++ ){
ext[i] = tolower( *(ptr+i+1) );
}
ext[i] = '\0';
return ext;
}
ptr--;
}
return NULL;
}
bool Kernel::is_movie_ext(const char* ext){
if ( !ext ){
return false;
}
if ( strcmp(ext, "avi") == 0 ){
return true;
}
if ( strcmp(ext, "mpg") == 0 ){
return true;
}
if ( strcmp(ext, "mpeg") == 0 ){
return true;
}
if ( strcmp(ext, "mkv") == 0 ){
return true;
}
if ( strcmp(ext, "ogv") == 0 ){
return true;
}
if ( strcmp(ext, "mov") == 0 ){
return true;
}
if ( strcmp(ext, "wmv") == 0 ){
return true;
}
return false;
}
void Kernel::quit(){
_running = false;
}
void Kernel::reload_browser(){
_browser->reload();
}
void Kernel::ipc_quit(){
delete _ipc;
_ipc = NULL;
}
void Kernel::debug_dumpqueue(){
_browser->dump_queue();
}
<commit_msg>mplayer arguments, no fps printing and 15 sec switch time<commit_after>#include "Kernel.h"
#include "Graphics.h"
#include "OS.h"
#include "Log.h"
#include "transitions/fade.h"
#include "browsers/mysqlbrowser.h"
#include "IPC/dbus.h"
#include <portable/Time.h>
#include <portable/Process.h>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <syscall.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#ifdef LINUX
#include <sys/time.h>
#endif
#ifdef WIN32
#include <windows.h>
#endif
#ifndef NULL
#define NULL 0
#endif
bool* daemon_running = NULL;
const char* application_name = "slideshow";
void quit_signal(int){
Log::message(Log::Verbose, "Caught SIGQUIT\n");
signal(SIGQUIT, quit_signal);
*daemon_running = false;
}
Kernel::Kernel(int argc, char* argv[]):
_width(800),
_height(600),
_frames(0),
_fullscreen(false),
_daemon(false),
_transition_time(5.0f),
_switch_time(15.0f),
_graphics(NULL),
_browser(NULL),
_ipc(NULL),
_db_username(NULL),
_db_password(NULL),
_db_name(NULL),
_logfile("slideshow.log"){
parse_argv(argc, argv);
initTime();
Log::initialize(_logfile, "slideshow.debug.log");
if ( _daemon ){
Log::message(Log::Verbose, "Kernel: Starting slideshow daemon\n");
Portable::daemonize(application_name);
if ( signal(SIGQUIT, quit_signal) == SIG_ERR ){
Log::message(Log::Fatal, "Kernel: Could not initialize signal handler!\n");
exit(3);
}
///@ hack
daemon_running = &_running;
} else {
Log::message(Log::Verbose, "Kernel: Starting slideshow\n");
}
_graphics = new Graphics(_width, _height, _fullscreen);
_graphics->set_transition(new FadeTransition);
_ipc = new DBus(this, 50);
_browser = new MySQLBrowser(_db_username, _db_password, _db_name);
_browser->reload();
_state = SWITCH;
}
Kernel::~Kernel(){
if ( _daemon ){
Portable::daemon_stop(application_name);
}
delete _browser;
delete _graphics;
delete _ipc;
free( _db_username );
free( _db_password );
free( _db_name );
_browser = NULL;
_graphics = NULL;
_ipc = NULL;
Log::deinitialize();
}
void Kernel::run(){
_running = true;
_last_switch = getTime();
_transition_start = 0.0f;
while ( _running ){
OS::poll_events(_running);
double t = getTime();
// Simple statemachine
switch ( _state ){
case VIEW:
view_state(t);
break;
case TRANSITION:
transition_state(t);
break;
case SWITCH:
switch_state(t);
break;
}
}
}
void Kernel::parse_argv(int argc, char* argv[]){
for ( int i = 0; i < argc; i++ ){
if ( strcmp(argv[i], "--fullscreen") == 0 ){
_fullscreen = true;
continue;
}
if ( strcmp(argv[i], "--daemon") == 0 ){
_daemon = true;
continue;
}
if ( strcmp(argv[i], "--db_user") == 0 ){
i++;
const char* user = argv[i];
_db_username = (char*)malloc(strlen(user)+1);
strcpy(_db_username, user);
continue;
}
if ( strcmp(argv[i], "--db_pass") == 0 ){
i++;
const char* pass = argv[i];
_db_password = (char*)malloc(strlen(pass)+1);
strcpy(_db_password, pass);
continue;
}
if ( strcmp(argv[i], "--db_name") == 0 ){
i++;
const char* name = argv[i];
_db_name = (char*)malloc(strlen(name)+1);
strcpy(_db_name, name);
continue;
}
if ( strcmp(argv[i], "--resolution") == 0 ){
i++;
sscanf(argv[i], "%dx%d", &_width, &_height);
continue;
}
}
}
void Kernel::view_state(double t){
if ( t - _last_switch > _switch_time ){
_state = SWITCH;
return;
}
if ( _ipc ){
_ipc->poll();
}
// Sleep for a while
wait( 0.1f );
}
// The transition state calculates how long of the
// transition has come and calls the renderer
void Kernel::transition_state(double t){
double s = (t - _transition_start) / _transition_time;
_frames++;
_graphics->render( s );
// If the transition is complete the state changes to VIEW
if ( s > 1.0f ){
//printf("Frames: %d\nFPS: %f\n\n", _frames, (float)_frames/_transition_time);
_state = VIEW;
_last_switch = t;
}
}
void Kernel::switch_state(double t){
const char* filename = _browser->get_next_file();
if ( !filename ){
Log::message(Log::Warning, "Kernel: Queue is empty\n", filename);
//wait( _switch_time * 0.9f );
return;
}
///@fulhack, register handlers instead...
char* ext = get_file_ext(filename);
if ( is_movie_ext(ext) ){
play_video(filename);
free(ext);
return;
}
free(ext);
Log::message(Log::Debug, "Kernel: Switching to image \"%s\"\n", filename);
try {
_graphics->load_image( filename );
} catch ( ... ) {
Log::message(Log::Warning, "Kernel: Failed to load image '%s'\n", filename);
return;
}
_state = TRANSITION;
_frames = 0;
_transition_start = getTime();
}
void Kernel::play_video(const char* fullpath){
Log::message(Log::Verbose, "Kernel: Playing video \"%s\"\n", fullpath);
int status;
if ( fork() == 0 ){
execlp("mplayer", "", "-fs", "-really-quiet", fullpath, NULL);
exit(0);
}
::wait(&status);
}
char* Kernel::get_file_ext(const char* filename){
const char* start = filename;
const char* ptr = filename + strlen(filename);
///@note Hmm, copy&paste is not always good... Rewrite using strrchr... 2008-02-27 --ext
while( ptr > start){
if( *ptr == '.'){
unsigned int len = strlen(ptr) - 1;
char* ext = (char*)malloc( len + 1 );
unsigned int i;
for ( i = 0; i < len; i++ ){
ext[i] = tolower( *(ptr+i+1) );
}
ext[i] = '\0';
return ext;
}
ptr--;
}
return NULL;
}
bool Kernel::is_movie_ext(const char* ext){
if ( !ext ){
return false;
}
if ( strcmp(ext, "avi") == 0 ){
return true;
}
if ( strcmp(ext, "mpg") == 0 ){
return true;
}
if ( strcmp(ext, "mpeg") == 0 ){
return true;
}
if ( strcmp(ext, "mkv") == 0 ){
return true;
}
if ( strcmp(ext, "ogv") == 0 ){
return true;
}
if ( strcmp(ext, "mov") == 0 ){
return true;
}
if ( strcmp(ext, "wmv") == 0 ){
return true;
}
return false;
}
void Kernel::quit(){
_running = false;
}
void Kernel::reload_browser(){
_browser->reload();
}
void Kernel::ipc_quit(){
delete _ipc;
_ipc = NULL;
}
void Kernel::debug_dumpqueue(){
_browser->dump_queue();
}
<|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. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
///
/// This is a class for reading raw data from a date monitoring libraries.
/// It supports two modes - event taken from shared memory via DATE monitoring
/// libs, or an emulation mode when the events are taken from a DATE file using
/// the same monitoring libs.
/// The constructor requires an argument:
///
/// : - events are taken from shared memory
/// or
/// <DATE_filename> - events are taken from date file
///
/// Cvetan Cheshkov 1/04/2008
///////////////////////////////////////////////////////////////////////////////
#include "AliRawReaderDateOnline.h"
#include "AliLog.h"
#ifdef ALI_DATE
#include "event.h"
#include "monitor.h"
#endif
ClassImp(AliRawReaderDateOnline)
AliRawReaderDateOnline::AliRawReaderDateOnline(
#ifdef ALI_DATE
const char* filename
#else
const char* /* filename */
#endif
) :
AliRawReaderDate((void*)NULL)
{
// Constructor
// Initialize the DATE monitoring libs
#ifdef ALI_DATE
// Removal of the selection of physics events
// Requested by Filimon and FMD experts
// fSelectEventType = PHYSICS_EVENT;
int status;
/* define data source : this is argument 1 */
status=monitorSetDataSource( (char* )filename );
if (status!=0) {
AliFatal(Form("monitorSetDataSource() failed : %s",monitorDecodeError(status)));
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
AliFatal(Form("monitorDeclareMp() failed : %s",monitorDecodeError(status)));
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
#else
Fatal("AliRawReaderDateOnline", "this class was compiled without DATE");
#endif
}
Bool_t AliRawReaderDateOnline::NextEvent()
{
// wait and get the next event
// from shared memory
#ifdef ALI_DATE
// Event already loaded no need take a new one
if (AliRawReaderDate::NextEvent()) return kTRUE;
if (fEvent) free(fEvent);
fEvent = NULL;
while (1) {
/* get next event (blocking call until timeout) */
int status=monitorGetEventDynamic((void**)&fEvent);
if (status==MON_ERR_EOF) {
AliInfo("End of File detected");
Reset();
fEvent = NULL;
return kFALSE; /* end of monitoring file has been reached */
}
if (status!=0) {
AliError(Form("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status)));
Reset();
fEvent = NULL;
return kFALSE;
}
/* retry if got no event */
if (fEvent==NULL) {
continue;
}
eventTypeType eventT=fEvent->eventType;
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
AliInfo("EOR event detected");
Reset();
fEvent = NULL;
return kFALSE;
}
if (!IsEventSelected()) {
continue;
}
AliInfo(Form("Run #%lu, event size: %lu, BC:0x%x, Orbit:0x%x, Period:0x%x",
(unsigned long)fEvent->eventRunNb,
(unsigned long)fEvent->eventSize,
EVENT_ID_GET_BUNCH_CROSSING(fEvent->eventId),
EVENT_ID_GET_ORBIT(fEvent->eventId),
EVENT_ID_GET_PERIOD(fEvent->eventId)
));
break;
}
fEventNumber++;
Reset();
return kTRUE;
}
#else
return kFALSE;
}
#endif
AliRawReaderDateOnline::~AliRawReaderDateOnline()
{
// Destructor
// Free the last event in shared memory
#ifdef ALI_DATE
if (fEvent) free(fEvent);
#endif
}
<commit_msg>Release event in case it is end_of_run or not selected by the raw reader.<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. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
///
/// This is a class for reading raw data from a date monitoring libraries.
/// It supports two modes - event taken from shared memory via DATE monitoring
/// libs, or an emulation mode when the events are taken from a DATE file using
/// the same monitoring libs.
/// The constructor requires an argument:
///
/// : - events are taken from shared memory
/// or
/// <DATE_filename> - events are taken from date file
///
/// Cvetan Cheshkov 1/04/2008
///////////////////////////////////////////////////////////////////////////////
#include "AliRawReaderDateOnline.h"
#include "AliLog.h"
#ifdef ALI_DATE
#include "event.h"
#include "monitor.h"
#endif
ClassImp(AliRawReaderDateOnline)
AliRawReaderDateOnline::AliRawReaderDateOnline(
#ifdef ALI_DATE
const char* filename
#else
const char* /* filename */
#endif
) :
AliRawReaderDate((void*)NULL)
{
// Constructor
// Initialize the DATE monitoring libs
#ifdef ALI_DATE
// Removal of the selection of physics events
// Requested by Filimon and FMD experts
// fSelectEventType = PHYSICS_EVENT;
int status;
/* define data source : this is argument 1 */
status=monitorSetDataSource( (char* )filename );
if (status!=0) {
AliFatal(Form("monitorSetDataSource() failed : %s",monitorDecodeError(status)));
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
AliFatal(Form("monitorDeclareMp() failed : %s",monitorDecodeError(status)));
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
#else
Fatal("AliRawReaderDateOnline", "this class was compiled without DATE");
#endif
}
Bool_t AliRawReaderDateOnline::NextEvent()
{
// wait and get the next event
// from shared memory
#ifdef ALI_DATE
// Event already loaded no need take a new one
if (AliRawReaderDate::NextEvent()) return kTRUE;
if (fEvent) free(fEvent);
fEvent = NULL;
while (1) {
/* get next event (blocking call until timeout) */
int status=monitorGetEventDynamic((void**)&fEvent);
if (status==MON_ERR_EOF) {
AliInfo("End of File detected");
Reset();
fEvent = NULL;
return kFALSE; /* end of monitoring file has been reached */
}
if (status!=0) {
AliError(Form("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status)));
Reset();
fEvent = NULL;
return kFALSE;
}
/* retry if got no event */
if (fEvent==NULL) {
continue;
}
eventTypeType eventT=fEvent->eventType;
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
AliInfo("EOR event detected");
Reset();
free(fEvent);
fEvent = NULL;
return kFALSE;
}
if (!IsEventSelected()) {
free(fEvent);
continue;
}
AliInfo(Form("Run #%lu, event size: %lu, BC:0x%x, Orbit:0x%x, Period:0x%x",
(unsigned long)fEvent->eventRunNb,
(unsigned long)fEvent->eventSize,
EVENT_ID_GET_BUNCH_CROSSING(fEvent->eventId),
EVENT_ID_GET_ORBIT(fEvent->eventId),
EVENT_ID_GET_PERIOD(fEvent->eventId)
));
break;
}
fEventNumber++;
Reset();
return kTRUE;
}
#else
return kFALSE;
}
#endif
AliRawReaderDateOnline::~AliRawReaderDateOnline()
{
// Destructor
// Free the last event in shared memory
#ifdef ALI_DATE
if (fEvent) free(fEvent);
#endif
}
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* 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 <osgProducer/GraphicsContextImplementation>
#include <osg/TextureRectangle>
#include <osg/TextureCubeMap>
#include <osg/Notify>
using namespace osgProducer;
namespace osgProducer
{
struct MyWindowingSystemInterface : public osg::GraphicsContext::WindowingSystemInterface
{
virtual unsigned int getNumScreens(const osg::GraphicsContext::ScreenIdentifier& /*screenIdentifier*/)
{
return Producer::RenderSurface::getNumberOfScreens();
}
virtual void getScreenResolution(const osg::GraphicsContext::ScreenIdentifier& screenIdentifier, unsigned int& width, unsigned int& height)
{
osg::ref_ptr<Producer::RenderSurface> rs = new Producer::RenderSurface;
rs->setHostName(screenIdentifier.hostName);
rs->setDisplayNum(screenIdentifier.displayNum);
rs->setScreenNum(screenIdentifier.screenNum);
rs->getScreenSize(width, height);
}
virtual osg::GraphicsContext* createGraphicsContext(osg::GraphicsContext::Traits* traits)
{
return new GraphicsContextImplementation(traits);
}
};
struct RegisterWindowingSystemInterfaceProxy
{
RegisterWindowingSystemInterfaceProxy()
{
osg::GraphicsContext::setWindowingSystemInterface(new MyWindowingSystemInterface);
}
~RegisterWindowingSystemInterfaceProxy()
{
osg::GraphicsContext::setWindowingSystemInterface(0);
}
};
RegisterWindowingSystemInterfaceProxy createWindowingSystemInterfaceProxy;
};
GraphicsContextImplementation::GraphicsContextImplementation(Traits* traits)
{
_traits = traits;
_rs = new Producer::RenderSurface;
_rs->setWindowName(traits->windowName);
_rs->setWindowRectangle(traits->x, traits->y, traits->width, traits->height);
_rs->useBorder(traits->windowDecoration);
_rs->setDisplayNum(traits->displayNum);
_rs->setScreenNum(traits->screenNum);
// set the visual chooser
Producer::VisualChooser* rs_vc = _rs->getVisualChooser();
if (!rs_vc)
{
rs_vc = new Producer::VisualChooser;
_rs->setVisualChooser(rs_vc);
}
rs_vc->setRedSize(_traits->red);
rs_vc->setGreenSize(_traits->green);
rs_vc->setBlueSize(_traits->blue);
rs_vc->setAlphaSize(_traits->alpha);
rs_vc->setDepthSize(_traits->depth);
rs_vc->setStencilSize(_traits->stencil);
if (_traits->doubleBuffer) rs_vc->useDoubleBuffer();
rs_vc->addAttribute( Producer::VisualChooser::RGBA );
// Always use UseGL
rs_vc->addAttribute( Producer::VisualChooser::UseGL );
if (traits->pbuffer)
{
_rs->setDrawableType(Producer::RenderSurface::DrawableType_PBuffer);
if (traits->target)
{
_rs->setRenderToTextureOptions(traits->mipMapGeneration ? Producer::RenderSurface::RequestSpaceForMipMaps :
Producer::RenderSurface::RenderToTextureOptions_Default);
_rs->setRenderToTextureMipMapLevel(traits->level);
_rs->setRenderToTextureMode(traits->alpha>0 ? Producer::RenderSurface::RenderToRGBATexture :
Producer::RenderSurface::RenderToRGBTexture);
switch(traits->target)
{
case(GL_TEXTURE_1D) :
_rs->setRenderToTextureTarget(Producer::RenderSurface::Texture1D);
break;
case(GL_TEXTURE_2D) :
_rs->setRenderToTextureTarget(Producer::RenderSurface::Texture2D);
break;
case(GL_TEXTURE_3D) :
osg::notify(osg::NOTICE)<<"PBuffer render to Texture3D not supported."<<std::endl;
// not supported.
// _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture3D);
break;
case(GL_TEXTURE_RECTANGLE) :
osg::notify(osg::NOTICE)<<"PBuffer render to TextureRectangle not supported."<<std::endl;
// not supported.
// _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureRectangle);
break;
case(GL_TEXTURE_CUBE_MAP_POSITIVE_X) :
case(GL_TEXTURE_CUBE_MAP_NEGATIVE_X) :
case(GL_TEXTURE_CUBE_MAP_POSITIVE_Y) :
case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) :
case(GL_TEXTURE_CUBE_MAP_POSITIVE_Z) :
case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) :
_rs->setRenderToTextureTarget(Producer::RenderSurface::TextureCUBE);
_rs->setRenderToTextureFace( Producer::RenderSurface::CubeMapFace(traits->target - GL_TEXTURE_CUBE_MAP_POSITIVE_X));
break;
}
}
}
GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(traits->sharedContext);
if (sharedContext)
{
// different graphics context so we have our own state.
setState(new osg::State);
if (sharedContext->getState())
{
getState()->setContextID( sharedContext->getState()->getContextID() );
incrementContextIDUsageCount( sharedContext->getState()->getContextID() );
}
else
{
getState()->setContextID( osg::GraphicsContext::createNewContextID() );
}
// but we share texture objects etc. so we also share the same contextID
//_rs->realize( 0, sharedContext->_rs->getGLContext() );
}
else
{
// need to do something here....
setState( new osg::State );
getState()->setContextID( osg::GraphicsContext::createNewContextID() );
//_rs->realize();
}
// _rs->useConfigEventThread(false);
_closeOnDestruction = true;
}
GraphicsContextImplementation::GraphicsContextImplementation(Producer::RenderSurface* rs)
{
_rs = rs;
_closeOnDestruction = false;
_traits = new osg::GraphicsContext::Traits;
_traits->windowName = _rs->getWindowName();
_traits->displayNum = _rs->getDisplayNum();
_traits->screenNum = _rs->getScreenNum();
}
GraphicsContextImplementation::~GraphicsContextImplementation()
{
if (_closeOnDestruction) close();
}
bool GraphicsContextImplementation::realizeImplementation()
{
if (_rs.valid())
{
GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(_traits->sharedContext);
if (sharedContext)
{
_rs->realize( 0, sharedContext->_rs->getGLContext() );
}
else
{
osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::realize"<<std::endl;
_rs->realize();
}
return _rs->isRealized();
}
else
{
return false;
}
}
bool GraphicsContextImplementation::makeCurrentImplementation()
{
if (!_rs)
{
osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() no RenderSurface."<<std::endl;
return false;
}
if (!isRealized())
{
osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() not Realized."<<std::endl;
return false;
}
// osg::notify(osg::INFO)<<"GraphicsContextImplementation::makeCurrentImplementation()"<<std::endl;
_rs->setReadDrawable( 0 );
// comment out right now, as Producer's setReadDrawable() is doing a call for us.
// _rs->makeCurrent();
return true;
}
bool GraphicsContextImplementation::makeContextCurrentImplementation(osg::GraphicsContext* readContext)
{
if (!_rs) return false;
GraphicsContextImplementation* readContextImplemention = dynamic_cast<GraphicsContextImplementation*>(readContext);
if (readContextImplemention)
{
_rs->setReadDrawable( readContextImplemention->getRenderSurface() );
}
else
{
_rs->setReadDrawable( 0 );
}
// comment out right now, as Producer's setReadDrawable() is doing a call for us.
// _rs->makeCurrent();
return true;
}
bool GraphicsContextImplementation::releaseContextImplementation()
{
osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::releaseContextImplementation(): not implemented - release not supported under Producer."<<std::endl;
return false;
}
void GraphicsContextImplementation::closeImplementation()
{
if (!_rs) return;
// close render surface by deleting it
_rs = 0;
}
void GraphicsContextImplementation::bindPBufferToTextureImplementation(GLenum buffer)
{
if (!_rs) return;
Producer::RenderSurface::BufferType bufferType = Producer::RenderSurface::FrontBuffer;
switch(buffer)
{
case(GL_BACK): bufferType = Producer::RenderSurface::BackBuffer; break;
case(GL_FRONT): bufferType = Producer::RenderSurface::FrontBuffer; break;
default: bufferType = Producer::RenderSurface::FrontBuffer; break;
}
_rs->bindPBufferToTexture(bufferType);
}
void GraphicsContextImplementation::swapBuffersImplementation()
{
_rs->swapBuffers();
}
<commit_msg>Removed the automatic registration of GraphicsContextImplementation.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* 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 <osgProducer/GraphicsContextImplementation>
#include <osg/TextureRectangle>
#include <osg/TextureCubeMap>
#include <osg/Notify>
using namespace osgProducer;
#if 0
namespace osgProducer
{
struct MyWindowingSystemInterface : public osg::GraphicsContext::WindowingSystemInterface
{
virtual unsigned int getNumScreens(const osg::GraphicsContext::ScreenIdentifier& /*screenIdentifier*/)
{
return Producer::RenderSurface::getNumberOfScreens();
}
virtual void getScreenResolution(const osg::GraphicsContext::ScreenIdentifier& screenIdentifier, unsigned int& width, unsigned int& height)
{
osg::ref_ptr<Producer::RenderSurface> rs = new Producer::RenderSurface;
rs->setHostName(screenIdentifier.hostName);
rs->setDisplayNum(screenIdentifier.displayNum);
rs->setScreenNum(screenIdentifier.screenNum);
rs->getScreenSize(width, height);
}
virtual osg::GraphicsContext* createGraphicsContext(osg::GraphicsContext::Traits* traits)
{
return new GraphicsContextImplementation(traits);
}
};
struct RegisterWindowingSystemInterfaceProxy
{
RegisterWindowingSystemInterfaceProxy()
{
osg::GraphicsContext::setWindowingSystemInterface(new MyWindowingSystemInterface);
}
~RegisterWindowingSystemInterfaceProxy()
{
osg::GraphicsContext::setWindowingSystemInterface(0);
}
};
RegisterWindowingSystemInterfaceProxy createWindowingSystemInterfaceProxy;
};
#endif
GraphicsContextImplementation::GraphicsContextImplementation(Traits* traits)
{
_traits = traits;
_rs = new Producer::RenderSurface;
_rs->setWindowName(traits->windowName);
_rs->setWindowRectangle(traits->x, traits->y, traits->width, traits->height);
_rs->useBorder(traits->windowDecoration);
_rs->setDisplayNum(traits->displayNum);
_rs->setScreenNum(traits->screenNum);
// set the visual chooser
Producer::VisualChooser* rs_vc = _rs->getVisualChooser();
if (!rs_vc)
{
rs_vc = new Producer::VisualChooser;
_rs->setVisualChooser(rs_vc);
}
rs_vc->setRedSize(_traits->red);
rs_vc->setGreenSize(_traits->green);
rs_vc->setBlueSize(_traits->blue);
rs_vc->setAlphaSize(_traits->alpha);
rs_vc->setDepthSize(_traits->depth);
rs_vc->setStencilSize(_traits->stencil);
if (_traits->doubleBuffer) rs_vc->useDoubleBuffer();
rs_vc->addAttribute( Producer::VisualChooser::RGBA );
// Always use UseGL
rs_vc->addAttribute( Producer::VisualChooser::UseGL );
if (traits->pbuffer)
{
_rs->setDrawableType(Producer::RenderSurface::DrawableType_PBuffer);
if (traits->target)
{
_rs->setRenderToTextureOptions(traits->mipMapGeneration ? Producer::RenderSurface::RequestSpaceForMipMaps :
Producer::RenderSurface::RenderToTextureOptions_Default);
_rs->setRenderToTextureMipMapLevel(traits->level);
_rs->setRenderToTextureMode(traits->alpha>0 ? Producer::RenderSurface::RenderToRGBATexture :
Producer::RenderSurface::RenderToRGBTexture);
switch(traits->target)
{
case(GL_TEXTURE_1D) :
_rs->setRenderToTextureTarget(Producer::RenderSurface::Texture1D);
break;
case(GL_TEXTURE_2D) :
_rs->setRenderToTextureTarget(Producer::RenderSurface::Texture2D);
break;
case(GL_TEXTURE_3D) :
osg::notify(osg::NOTICE)<<"PBuffer render to Texture3D not supported."<<std::endl;
// not supported.
// _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture3D);
break;
case(GL_TEXTURE_RECTANGLE) :
osg::notify(osg::NOTICE)<<"PBuffer render to TextureRectangle not supported."<<std::endl;
// not supported.
// _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureRectangle);
break;
case(GL_TEXTURE_CUBE_MAP_POSITIVE_X) :
case(GL_TEXTURE_CUBE_MAP_NEGATIVE_X) :
case(GL_TEXTURE_CUBE_MAP_POSITIVE_Y) :
case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) :
case(GL_TEXTURE_CUBE_MAP_POSITIVE_Z) :
case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) :
_rs->setRenderToTextureTarget(Producer::RenderSurface::TextureCUBE);
_rs->setRenderToTextureFace( Producer::RenderSurface::CubeMapFace(traits->target - GL_TEXTURE_CUBE_MAP_POSITIVE_X));
break;
}
}
}
GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(traits->sharedContext);
if (sharedContext)
{
// different graphics context so we have our own state.
setState(new osg::State);
if (sharedContext->getState())
{
getState()->setContextID( sharedContext->getState()->getContextID() );
incrementContextIDUsageCount( sharedContext->getState()->getContextID() );
}
else
{
getState()->setContextID( osg::GraphicsContext::createNewContextID() );
}
// but we share texture objects etc. so we also share the same contextID
//_rs->realize( 0, sharedContext->_rs->getGLContext() );
}
else
{
// need to do something here....
setState( new osg::State );
getState()->setContextID( osg::GraphicsContext::createNewContextID() );
//_rs->realize();
}
// _rs->useConfigEventThread(false);
_closeOnDestruction = true;
}
GraphicsContextImplementation::GraphicsContextImplementation(Producer::RenderSurface* rs)
{
_rs = rs;
_closeOnDestruction = false;
_traits = new osg::GraphicsContext::Traits;
_traits->windowName = _rs->getWindowName();
_traits->displayNum = _rs->getDisplayNum();
_traits->screenNum = _rs->getScreenNum();
}
GraphicsContextImplementation::~GraphicsContextImplementation()
{
if (_closeOnDestruction) close();
}
bool GraphicsContextImplementation::realizeImplementation()
{
if (_rs.valid())
{
GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(_traits->sharedContext);
if (sharedContext)
{
_rs->realize( 0, sharedContext->_rs->getGLContext() );
}
else
{
osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::realize"<<std::endl;
_rs->realize();
}
return _rs->isRealized();
}
else
{
return false;
}
}
bool GraphicsContextImplementation::makeCurrentImplementation()
{
if (!_rs)
{
osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() no RenderSurface."<<std::endl;
return false;
}
if (!isRealized())
{
osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() not Realized."<<std::endl;
return false;
}
// osg::notify(osg::INFO)<<"GraphicsContextImplementation::makeCurrentImplementation()"<<std::endl;
_rs->setReadDrawable( 0 );
// comment out right now, as Producer's setReadDrawable() is doing a call for us.
// _rs->makeCurrent();
return true;
}
bool GraphicsContextImplementation::makeContextCurrentImplementation(osg::GraphicsContext* readContext)
{
if (!_rs) return false;
GraphicsContextImplementation* readContextImplemention = dynamic_cast<GraphicsContextImplementation*>(readContext);
if (readContextImplemention)
{
_rs->setReadDrawable( readContextImplemention->getRenderSurface() );
}
else
{
_rs->setReadDrawable( 0 );
}
// comment out right now, as Producer's setReadDrawable() is doing a call for us.
// _rs->makeCurrent();
return true;
}
bool GraphicsContextImplementation::releaseContextImplementation()
{
osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::releaseContextImplementation(): not implemented - release not supported under Producer."<<std::endl;
return false;
}
void GraphicsContextImplementation::closeImplementation()
{
if (!_rs) return;
// close render surface by deleting it
_rs = 0;
}
void GraphicsContextImplementation::bindPBufferToTextureImplementation(GLenum buffer)
{
if (!_rs) return;
Producer::RenderSurface::BufferType bufferType = Producer::RenderSurface::FrontBuffer;
switch(buffer)
{
case(GL_BACK): bufferType = Producer::RenderSurface::BackBuffer; break;
case(GL_FRONT): bufferType = Producer::RenderSurface::FrontBuffer; break;
default: bufferType = Producer::RenderSurface::FrontBuffer; break;
}
_rs->bindPBufferToTexture(bufferType);
}
void GraphicsContextImplementation::swapBuffersImplementation()
{
_rs->swapBuffers();
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <string>
#include "common.h"
#include "global.h"
#include "StateDatabase.h"
#include "BZDBCache.h"
#include "TankGeometryMgr.h"
#include "OpenGLGState.h"
// the one and only
TankGeometryMgr TANKGEOMMGR;
// handy dandy casted value
static const GLuint InvalidList = (GLuint) -1;
// use the namespaces
using namespace TankGeometryEnums;
using namespace TankGeometryUtils;
GLfloat TankGeometryMgr::scaleFactors[LastTankSize][3] = {
{1.0f, 1.0f, 1.0f}, // Normal
{1.0f, 1.0f, 1.0f}, // Obese
{1.0f, 1.0f, 1.0f}, // Tiny
{1.0f, 0.001f, 1.0f}, // Narrow
{1.0f, 1.0f, 1.0f} // Thief
};
const float* TankGeometryMgr::scaleFactor = scaleFactors[Normal];
TankShadow TankGeometryMgr::shadowMode = ShadowOn;
GLuint TankGeometryMgr::displayLists
[LastTankShadow][LastTankLOD][LastTankSize][LastTankPart];
const TankGeometryMgr::PartFunction
TankGeometryMgr::partFunctions[LastTankLOD][BasicTankParts] = {
{ buildLowBody,
buildLowBarrel,
buildLowTurret,
buildLowLCasing,
buildLowRCasing
},
{ buildMedBody,
buildMedBarrel,
buildMedTurret,
buildMedLCasing,
buildMedRCasing
},
{ buildHighBody,
buildHighBarrel,
buildHighTurret,
buildHighLCasingOld,
buildHighRCasingOld
}
};
TankGeometryMgr::TankGeometryMgr()
{
// initialize the lists to invalid
for (int shadow = 0; shadow < LastTankShadow; shadow++) {
for (int lod = 0; lod < LastTankLOD; lod++) {
for (int size = 0; size < LastTankSize; size++) {
for (int part = 0; part < LastTankPart; part++) {
displayLists[shadow][lod][size][part] = InvalidList;
}
}
}
}
callbacksInstalled = false;
OpenGLGState::registerContextInitializer (initContext, NULL);
return;
}
TankGeometryMgr::~TankGeometryMgr()
{
// FIXME: do we still have GL?
deleteLists();
// FIXME: really worth doing?
if (callbacksInstalled) {
OpenGLGState::unregisterContextInitializer(initContext, (void*)this);
}
return;
}
void TankGeometryMgr::deleteLists()
{
// initialize the lists to invalid
for (int shadow = 0; shadow < LastTankShadow; shadow++) {
for (int lod = 0; lod < LastTankLOD; lod++) {
for (int size = 0; size < LastTankSize; size++) {
for (int part = 0; part < LastTankPart; part++) {
GLuint list = displayLists[shadow][lod][size][part];
if (list != InvalidList) {
glDeleteLists(list, 1);
}
}
}
}
}
return;
}
void TankGeometryMgr::setupScales(const std::string& /*name*/, void * /*data*/)
{
float scale;
scaleFactors[Normal][0] = BZDB.eval(StateDatabase::BZDB_TANKLENGTH);
scale = atof(BZDB.getDefault(StateDatabase::BZDB_TANKLENGTH).c_str());
scaleFactors[Normal][0] /= scale;
scaleFactors[Normal][1] = BZDB.eval(StateDatabase::BZDB_TANKWIDTH);
scale = atof(BZDB.getDefault(StateDatabase::BZDB_TANKWIDTH).c_str());
scaleFactors[Normal][1] /= scale;
scaleFactors[Normal][2] = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);
scale = atof(BZDB.getDefault(StateDatabase::BZDB_TANKHEIGHT).c_str());
scaleFactors[Normal][2] /= scale;
scale = BZDB.eval(StateDatabase::BZDB_OBESEFACTOR);
scaleFactors[Obese][0] = scale * scaleFactors[Normal][0];
scaleFactors[Obese][1] = scale * scaleFactors[Normal][1];
scaleFactors[Obese][2] = scaleFactors[Normal][2];
scale = BZDB.eval(StateDatabase::BZDB_TINYFACTOR);
scaleFactors[Tiny][0] = scale * scaleFactors[Normal][0];
scaleFactors[Tiny][1] = scale * scaleFactors[Normal][1];
scaleFactors[Tiny][2] = scaleFactors[Normal][2];
scale = BZDB.eval(StateDatabase::BZDB_THIEFTINYFACTOR);
scaleFactors[Thief][0] = scale * scaleFactors[Normal][0];
scaleFactors[Thief][1] = scale * scaleFactors[Normal][1];
scaleFactors[Thief][2] = scaleFactors[Normal][2];
scaleFactors[Narrow][0] = scaleFactors[Normal][0];
scaleFactors[Narrow][1] = 0.001f;
scaleFactors[Narrow][2] = scaleFactors[Normal][2];
return;
}
void TankGeometryMgr::initContext(void * /*data*/)
{
TANKGEOMMGR.rebuildLists();
return;
}
void TankGeometryMgr::rebuildLists()
{
// install the calllbacks
if (!callbacksInstalled) {
// the BZDB callbacks (at least), cannot be installed at
// global statup because BZDB is not initialized until
// main() is called
BZDB.addCallback (StateDatabase::BZDB_OBESEFACTOR, setupScales, NULL);
BZDB.addCallback (StateDatabase::BZDB_TINYFACTOR, setupScales, NULL);
BZDB.addCallback (StateDatabase::BZDB_THIEFTINYFACTOR, setupScales, NULL);
callbacksInstalled = true;
}
// setup the scale factors
std::string junk;
setupScales(junk, NULL);
scaleFactor = scaleFactors[Normal];
// delete any old lists
deleteLists();
for (int shadow = 0; shadow < LastTankShadow; shadow++) {
for (int lod = 0; lod < LastTankLOD; lod++) {
for (int size = 0; size < LastTankSize; size++) {
// only do the basics, unless we're making a HighTank
int lastPart = BasicTankParts;
if (lod == HighTankLOD) {
lastPart = HighTankParts;
}
// set the shadow mode for the doNormal3f() and doTexcoord2f()
shadowMode = (TankShadow) shadow;
for (int part = 0; part < lastPart; part++) {
// get a new OpenGL display list
GLuint& list = displayLists[shadow][lod][size][part];
list = glGenLists(1);
glNewList(list, GL_COMPILE);
// setup the scale factor
scaleFactor = scaleFactors[size];
if (part < MedTankParts) {
// the basic parts
if (!(lod == HighTankLOD)) {
partFunctions[lod][part]();
} else {
if (part == LeftCasing) {
buildHighLCasing(30);
}
else if (part == RightCasing) {
buildHighRCasing(30);
}
else {
partFunctions[lod][part]();
}
}
}
else {
// the animated parts
switch (part) {
case LeftTread: {
buildHighLTread(30);
break;
}
case RightTread: {
buildHighRTread(30);
break;
}
case LeftWheel0:
case LeftWheel1:
case LeftWheel2:
case LeftWheel3: {
int wheel = part - LeftWheel0;
buildHighLWheel(wheel, (float)wheel * M_PI/2.0f, 12);
break;
}
case RightWheel0:
case RightWheel1:
case RightWheel2:
case RightWheel3: {
int wheel = part - RightWheel0;
buildHighRWheel(wheel, (float)wheel * M_PI/2.0f, 12);
break;
}
} // end part switch
}
// end of the list
glEndList();
} // part
} // size
} // lod
} // shadow
return;
}
void TankGeometryUtils::doVertex3f(GLfloat x, GLfloat y, GLfloat z)
{
const float* scale = TankGeometryMgr::currentScaleFactor();
x = x * scale[0];
y = y * scale[1];
z = z * scale[2];
glVertex3f(x, y, z);
return;
}
void TankGeometryUtils::doNormal3f(GLfloat x, GLfloat y, GLfloat z)
{
if (TankGeometryMgr::getShadowMode() == ShadowOn) {
return;
}
const float* scale = TankGeometryMgr::currentScaleFactor();
GLfloat sx = x * scale[0];
GLfloat sy = y * scale[1];
GLfloat sz = z * scale[2];
const GLfloat d = sqrtf ((sx * sx) + (sy * sy) + (sz * sz));
if (d > 1.0e-5f) {
x *= scale[0] / d;
y *= scale[1] / d;
z *= scale[2] / d;
}
glNormal3f(x, y, z);
return;
}
void TankGeometryUtils::doTexCoord2f(GLfloat x, GLfloat y)
{
if (TankGeometryMgr::getShadowMode() == ShadowOn) {
return;
}
glTexCoord2f(x, y);
return;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>make the register and unregister calls line up<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <string>
#include "common.h"
#include "global.h"
#include "StateDatabase.h"
#include "BZDBCache.h"
#include "TankGeometryMgr.h"
#include "OpenGLGState.h"
// the one and only
TankGeometryMgr TANKGEOMMGR;
// handy dandy casted value
static const GLuint InvalidList = (GLuint) -1;
// use the namespaces
using namespace TankGeometryEnums;
using namespace TankGeometryUtils;
GLfloat TankGeometryMgr::scaleFactors[LastTankSize][3] = {
{1.0f, 1.0f, 1.0f}, // Normal
{1.0f, 1.0f, 1.0f}, // Obese
{1.0f, 1.0f, 1.0f}, // Tiny
{1.0f, 0.001f, 1.0f}, // Narrow
{1.0f, 1.0f, 1.0f} // Thief
};
const float* TankGeometryMgr::scaleFactor = scaleFactors[Normal];
TankShadow TankGeometryMgr::shadowMode = ShadowOn;
GLuint TankGeometryMgr::displayLists
[LastTankShadow][LastTankLOD][LastTankSize][LastTankPart];
const TankGeometryMgr::PartFunction
TankGeometryMgr::partFunctions[LastTankLOD][BasicTankParts] = {
{ buildLowBody,
buildLowBarrel,
buildLowTurret,
buildLowLCasing,
buildLowRCasing
},
{ buildMedBody,
buildMedBarrel,
buildMedTurret,
buildMedLCasing,
buildMedRCasing
},
{ buildHighBody,
buildHighBarrel,
buildHighTurret,
buildHighLCasingOld,
buildHighRCasingOld
}
};
TankGeometryMgr::TankGeometryMgr()
{
// initialize the lists to invalid
for (int shadow = 0; shadow < LastTankShadow; shadow++) {
for (int lod = 0; lod < LastTankLOD; lod++) {
for (int size = 0; size < LastTankSize; size++) {
for (int part = 0; part < LastTankPart; part++) {
displayLists[shadow][lod][size][part] = InvalidList;
}
}
}
}
callbacksInstalled = false;
OpenGLGState::registerContextInitializer (initContext, (void*)this);
return;
}
TankGeometryMgr::~TankGeometryMgr()
{
// FIXME: do we still have GL?
deleteLists();
// FIXME: really worth doing?
if (callbacksInstalled) {
OpenGLGState::unregisterContextInitializer(initContext, (void*)this);
}
return;
}
void TankGeometryMgr::deleteLists()
{
// initialize the lists to invalid
for (int shadow = 0; shadow < LastTankShadow; shadow++) {
for (int lod = 0; lod < LastTankLOD; lod++) {
for (int size = 0; size < LastTankSize; size++) {
for (int part = 0; part < LastTankPart; part++) {
GLuint list = displayLists[shadow][lod][size][part];
if (list != InvalidList) {
glDeleteLists(list, 1);
}
}
}
}
}
return;
}
void TankGeometryMgr::setupScales(const std::string& /*name*/, void * /*data*/)
{
float scale;
scaleFactors[Normal][0] = BZDB.eval(StateDatabase::BZDB_TANKLENGTH);
scale = atof(BZDB.getDefault(StateDatabase::BZDB_TANKLENGTH).c_str());
scaleFactors[Normal][0] /= scale;
scaleFactors[Normal][1] = BZDB.eval(StateDatabase::BZDB_TANKWIDTH);
scale = atof(BZDB.getDefault(StateDatabase::BZDB_TANKWIDTH).c_str());
scaleFactors[Normal][1] /= scale;
scaleFactors[Normal][2] = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);
scale = atof(BZDB.getDefault(StateDatabase::BZDB_TANKHEIGHT).c_str());
scaleFactors[Normal][2] /= scale;
scale = BZDB.eval(StateDatabase::BZDB_OBESEFACTOR);
scaleFactors[Obese][0] = scale * scaleFactors[Normal][0];
scaleFactors[Obese][1] = scale * scaleFactors[Normal][1];
scaleFactors[Obese][2] = scaleFactors[Normal][2];
scale = BZDB.eval(StateDatabase::BZDB_TINYFACTOR);
scaleFactors[Tiny][0] = scale * scaleFactors[Normal][0];
scaleFactors[Tiny][1] = scale * scaleFactors[Normal][1];
scaleFactors[Tiny][2] = scaleFactors[Normal][2];
scale = BZDB.eval(StateDatabase::BZDB_THIEFTINYFACTOR);
scaleFactors[Thief][0] = scale * scaleFactors[Normal][0];
scaleFactors[Thief][1] = scale * scaleFactors[Normal][1];
scaleFactors[Thief][2] = scaleFactors[Normal][2];
scaleFactors[Narrow][0] = scaleFactors[Normal][0];
scaleFactors[Narrow][1] = 0.001f;
scaleFactors[Narrow][2] = scaleFactors[Normal][2];
return;
}
void TankGeometryMgr::initContext(void * /*data*/)
{
TANKGEOMMGR.rebuildLists();
return;
}
void TankGeometryMgr::rebuildLists()
{
// install the calllbacks
if (!callbacksInstalled) {
// the BZDB callbacks (at least), cannot be installed at
// global statup because BZDB is not initialized until
// main() is called
BZDB.addCallback (StateDatabase::BZDB_OBESEFACTOR, setupScales, NULL);
BZDB.addCallback (StateDatabase::BZDB_TINYFACTOR, setupScales, NULL);
BZDB.addCallback (StateDatabase::BZDB_THIEFTINYFACTOR, setupScales, NULL);
callbacksInstalled = true;
}
// setup the scale factors
std::string junk;
setupScales(junk, NULL);
scaleFactor = scaleFactors[Normal];
// delete any old lists
deleteLists();
for (int shadow = 0; shadow < LastTankShadow; shadow++) {
for (int lod = 0; lod < LastTankLOD; lod++) {
for (int size = 0; size < LastTankSize; size++) {
// only do the basics, unless we're making a HighTank
int lastPart = BasicTankParts;
if (lod == HighTankLOD) {
lastPart = HighTankParts;
}
// set the shadow mode for the doNormal3f() and doTexcoord2f()
shadowMode = (TankShadow) shadow;
for (int part = 0; part < lastPart; part++) {
// get a new OpenGL display list
GLuint& list = displayLists[shadow][lod][size][part];
list = glGenLists(1);
glNewList(list, GL_COMPILE);
// setup the scale factor
scaleFactor = scaleFactors[size];
if (part < MedTankParts) {
// the basic parts
if (!(lod == HighTankLOD)) {
partFunctions[lod][part]();
} else {
if (part == LeftCasing) {
buildHighLCasing(30);
}
else if (part == RightCasing) {
buildHighRCasing(30);
}
else {
partFunctions[lod][part]();
}
}
}
else {
// the animated parts
switch (part) {
case LeftTread: {
buildHighLTread(30);
break;
}
case RightTread: {
buildHighRTread(30);
break;
}
case LeftWheel0:
case LeftWheel1:
case LeftWheel2:
case LeftWheel3: {
int wheel = part - LeftWheel0;
buildHighLWheel(wheel, (float)wheel * M_PI/2.0f, 12);
break;
}
case RightWheel0:
case RightWheel1:
case RightWheel2:
case RightWheel3: {
int wheel = part - RightWheel0;
buildHighRWheel(wheel, (float)wheel * M_PI/2.0f, 12);
break;
}
} // end part switch
}
// end of the list
glEndList();
} // part
} // size
} // lod
} // shadow
return;
}
void TankGeometryUtils::doVertex3f(GLfloat x, GLfloat y, GLfloat z)
{
const float* scale = TankGeometryMgr::currentScaleFactor();
x = x * scale[0];
y = y * scale[1];
z = z * scale[2];
glVertex3f(x, y, z);
return;
}
void TankGeometryUtils::doNormal3f(GLfloat x, GLfloat y, GLfloat z)
{
if (TankGeometryMgr::getShadowMode() == ShadowOn) {
return;
}
const float* scale = TankGeometryMgr::currentScaleFactor();
GLfloat sx = x * scale[0];
GLfloat sy = y * scale[1];
GLfloat sz = z * scale[2];
const GLfloat d = sqrtf ((sx * sx) + (sy * sy) + (sz * sz));
if (d > 1.0e-5f) {
x *= scale[0] / d;
y *= scale[1] / d;
z *= scale[2] / d;
}
glNormal3f(x, y, z);
return;
}
void TankGeometryUtils::doTexCoord2f(GLfloat x, GLfloat y)
{
if (TankGeometryMgr::getShadowMode() == ShadowOn) {
return;
}
glTexCoord2f(x, y);
return;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file ir_constant_folding.cpp
* Replace constant-valued expressions with references to constant values.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_optimization.h"
#include "glsl_types.h"
/**
* Visitor class for replacing expressions with ir_constant values.
*/
class ir_constant_folding_visitor : public ir_visitor {
public:
ir_constant_folding_visitor()
{
/* empty */
}
virtual ~ir_constant_folding_visitor()
{
/* empty */
}
/**
* \name Visit methods
*
* As typical for the visitor pattern, there must be one \c visit method for
* each concrete subclass of \c ir_instruction. Virtual base classes within
* the hierarchy should not have \c visit methods.
*/
/*@{*/
virtual void visit(ir_variable *);
virtual void visit(ir_function_signature *);
virtual void visit(ir_function *);
virtual void visit(ir_expression *);
virtual void visit(ir_texture *);
virtual void visit(ir_swizzle *);
virtual void visit(ir_dereference_variable *);
virtual void visit(ir_dereference_array *);
virtual void visit(ir_dereference_record *);
virtual void visit(ir_assignment *);
virtual void visit(ir_constant *);
virtual void visit(ir_call *);
virtual void visit(ir_return *);
virtual void visit(ir_discard *);
virtual void visit(ir_if *);
virtual void visit(ir_loop *);
virtual void visit(ir_loop_jump *);
/*@}*/
};
void
ir_constant_folding_visitor::visit(ir_variable *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_function_signature *ir)
{
visit_exec_list(&ir->body, this);
}
void
ir_constant_folding_visitor::visit(ir_function *ir)
{
foreach_iter(exec_list_iterator, iter, *ir) {
ir_function_signature *const sig = (ir_function_signature *) iter.get();
sig->accept(this);
}
}
void
ir_constant_folding_visitor::visit(ir_expression *ir)
{
ir_constant *op[2];
unsigned int operand;
for (operand = 0; operand < ir->get_num_operands(); operand++) {
op[operand] = ir->operands[operand]->constant_expression_value();
if (op[operand]) {
ir->operands[operand] = op[operand];
} else {
ir->operands[operand]->accept(this);
}
}
}
void
ir_constant_folding_visitor::visit(ir_texture *ir)
{
// FINISHME: Do stuff with texture lookups
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_swizzle *ir)
{
ir->val->accept(this);
}
void
ir_constant_folding_visitor::visit(ir_dereference_variable *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_dereference_array *ir)
{
ir_constant *const_val =
ir->array_index->constant_expression_value();
if (const_val)
ir->array_index = const_val;
else
ir->array_index->accept(this);
ir->array->accept(this);
}
void
ir_constant_folding_visitor::visit(ir_dereference_record *ir)
{
ir->record->accept(this);
}
void
ir_constant_folding_visitor::visit(ir_assignment *ir)
{
ir_constant *const_val = ir->rhs->constant_expression_value();
if (const_val)
ir->rhs = const_val;
else
ir->rhs->accept(this);
}
void
ir_constant_folding_visitor::visit(ir_constant *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_call *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_return *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_discard *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_if *ir)
{
ir_constant *const_val = ir->condition->constant_expression_value();
if (const_val)
ir->condition = const_val;
else
ir->condition->accept(this);
visit_exec_list(&ir->then_instructions, this);
visit_exec_list(&ir->else_instructions, this);
}
void
ir_constant_folding_visitor::visit(ir_loop *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_loop_jump *ir)
{
(void) ir;
}
bool
do_constant_folding(exec_list *instructions)
{
ir_constant_folding_visitor constant_folding;
visit_exec_list(instructions, &constant_folding);
/* FINISHME: Return real progress. */
return false;
}
<commit_msg>glsl2: Constant-fold assignment conditions.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file ir_constant_folding.cpp
* Replace constant-valued expressions with references to constant values.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_optimization.h"
#include "glsl_types.h"
/**
* Visitor class for replacing expressions with ir_constant values.
*/
class ir_constant_folding_visitor : public ir_visitor {
public:
ir_constant_folding_visitor()
{
/* empty */
}
virtual ~ir_constant_folding_visitor()
{
/* empty */
}
/**
* \name Visit methods
*
* As typical for the visitor pattern, there must be one \c visit method for
* each concrete subclass of \c ir_instruction. Virtual base classes within
* the hierarchy should not have \c visit methods.
*/
/*@{*/
virtual void visit(ir_variable *);
virtual void visit(ir_function_signature *);
virtual void visit(ir_function *);
virtual void visit(ir_expression *);
virtual void visit(ir_texture *);
virtual void visit(ir_swizzle *);
virtual void visit(ir_dereference_variable *);
virtual void visit(ir_dereference_array *);
virtual void visit(ir_dereference_record *);
virtual void visit(ir_assignment *);
virtual void visit(ir_constant *);
virtual void visit(ir_call *);
virtual void visit(ir_return *);
virtual void visit(ir_discard *);
virtual void visit(ir_if *);
virtual void visit(ir_loop *);
virtual void visit(ir_loop_jump *);
/*@}*/
};
void
ir_constant_folding_visitor::visit(ir_variable *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_function_signature *ir)
{
visit_exec_list(&ir->body, this);
}
void
ir_constant_folding_visitor::visit(ir_function *ir)
{
foreach_iter(exec_list_iterator, iter, *ir) {
ir_function_signature *const sig = (ir_function_signature *) iter.get();
sig->accept(this);
}
}
void
ir_constant_folding_visitor::visit(ir_expression *ir)
{
ir_constant *op[2];
unsigned int operand;
for (operand = 0; operand < ir->get_num_operands(); operand++) {
op[operand] = ir->operands[operand]->constant_expression_value();
if (op[operand]) {
ir->operands[operand] = op[operand];
} else {
ir->operands[operand]->accept(this);
}
}
}
void
ir_constant_folding_visitor::visit(ir_texture *ir)
{
// FINISHME: Do stuff with texture lookups
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_swizzle *ir)
{
ir->val->accept(this);
}
void
ir_constant_folding_visitor::visit(ir_dereference_variable *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_dereference_array *ir)
{
ir_constant *const_val =
ir->array_index->constant_expression_value();
if (const_val)
ir->array_index = const_val;
else
ir->array_index->accept(this);
ir->array->accept(this);
}
void
ir_constant_folding_visitor::visit(ir_dereference_record *ir)
{
ir->record->accept(this);
}
void
ir_constant_folding_visitor::visit(ir_assignment *ir)
{
ir_constant *const_val = ir->rhs->constant_expression_value();
if (const_val)
ir->rhs = const_val;
else
ir->rhs->accept(this);
if (ir->condition) {
/* If the condition is constant, either remove the condition or
* remove the never-executed assignment.
*/
const_val = ir->condition->constant_expression_value();
if (const_val) {
if (const_val->value.b[0])
ir->condition = NULL;
else
ir->remove();
}
}
}
void
ir_constant_folding_visitor::visit(ir_constant *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_call *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_return *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_discard *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_if *ir)
{
ir_constant *const_val = ir->condition->constant_expression_value();
if (const_val)
ir->condition = const_val;
else
ir->condition->accept(this);
visit_exec_list(&ir->then_instructions, this);
visit_exec_list(&ir->else_instructions, this);
}
void
ir_constant_folding_visitor::visit(ir_loop *ir)
{
(void) ir;
}
void
ir_constant_folding_visitor::visit(ir_loop_jump *ir)
{
(void) ir;
}
bool
do_constant_folding(exec_list *instructions)
{
ir_constant_folding_visitor constant_folding;
visit_exec_list(instructions, &constant_folding);
/* FINISHME: Return real progress. */
return false;
}
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+');
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':') {
return true;
}
return false;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize the literal string [[ ... ]] nesting level, if we are inside such a string.
int literalStringLevel = 0;
if (initStyle == SCE_LUA_LITERALSTRING) {
literalStringLevel = styler.GetLineState(currentLine - 1);
}
// Initialize the block comment --[[ ... ]] nesting level, if we are inside such a comment
int blockCommentLevel = 0;
if (initStyle == SCE_LUA_COMMENT) {
blockCommentLevel = styler.GetLineState(currentLine - 1);
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
// Inside a literal string, we set the line state
styler.SetLineState(currentLine, literalStringLevel);
break;
case SCE_LUA_COMMENT: // Block comment
// Inside a block comment, we set the line state
styler.SetLineState(currentLine, blockCommentLevel);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING) {
if (sc.Match('[', '[')) {
literalStringLevel++;
sc.Forward();
sc.SetState(SCE_LUA_LITERALSTRING);
} else if (sc.Match(']', ']') && literalStringLevel > 0) {
literalStringLevel--;
sc.Forward();
if (literalStringLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
} else if (sc.state == SCE_LUA_COMMENT) { // Lua 5.0's block comment
if (sc.Match('[', '[')) {
blockCommentLevel++;
sc.Forward();
} else if (sc.Match(']', ']') && blockCommentLevel > 0) {
blockCommentLevel--;
sc.Forward();
if (blockCommentLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.Match('\"')) {
sc.SetState(SCE_LUA_STRING);
} else if (sc.Match('\'')) {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.Match('[', '[')) {
literalStringLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward();
} else if (sc.Match("--[[")) { // Lua 5.0's block comment
blockCommentLevel = 1;
sc.SetState(SCE_LUA_COMMENT);
sc.Forward(3);
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
sc.Forward();
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<commit_msg>Patch from Kein-Hong Man support new Lua 5.1 long string and block comment syntax [=[...]=] and --[=[...]=].<commit_after>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+');
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':') {
return true;
}
return false;
}
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<|endoftext|> |
<commit_before>#include <QtPlugin>
\
#include "animatedtilesplugin.h"
#include "animatedtilesitem.h"
AnimatedTilesPlugin::AnimatedTilesPlugin()
{
setName("AnimatedTiles");
//This should not be an advertized plugin until it is implemented
//setRole("animatedTiles");
}
Q_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin)
void AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context)
{
qmlRegisterType<AnimatedTilesItem>("AnimatedTiles", 1, 0, "AnimatedTiles");
}
<commit_msg>Remove stray \<commit_after>#include <QtPlugin>
#include "animatedtilesplugin.h"
#include "animatedtilesitem.h"
AnimatedTilesPlugin::AnimatedTilesPlugin()
{
setName("AnimatedTiles");
//This should not be an advertized plugin until it is implemented
//setRole("animatedTiles");
}
Q_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin)
void AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context)
{
qmlRegisterType<AnimatedTilesItem>("AnimatedTiles", 1, 0, "AnimatedTiles");
}
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Anton Chernov <chernov.anton.mail@gmail.com>
// Copyright 2012 "LOTES TM" LLC <lotes.sis@gmail.com>
// Copyright 2012 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "DeclarativeDataPlugin.h"
#include "DeclarativeDataPluginModel.h"
#include "DeclarativeDataPluginItem.h"
#include "MarbleDeclarativeWidget.h"
#include "MarbleDebug.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include <QtCore/QMetaObject>
#include <QtCore/QMetaProperty>
#include <QtScript/QScriptValue>
using namespace Marble;
class DeclarativeDataPluginPrivate {
public:
DeclarativeDataPlugin* q;
QString m_planet;
QString m_name;
QString m_nameId;
QString m_version;
QString m_guiString;
QString m_copyrightYears;
QString m_description;
QList<Marble::PluginAuthor> m_authors;
QString m_aboutText;
bool m_isInitialized;
QList<AbstractDataPluginItem *> m_items;
QList<DeclarativeDataPluginModel*> m_modelInstances;
QDeclarativeComponent* m_delegate;
QVariant m_model;
static int m_counter;
DeclarativeDataPluginPrivate( DeclarativeDataPlugin* q );
void parseChunk( DeclarativeDataPluginItem * item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value );
void addItem( DeclarativeDataPluginItem* item, const GeoDataCoordinates &coordinates );
void parseListModel( QAbstractListModel* listModel );
void parseObject( QObject* object );
};
int DeclarativeDataPluginPrivate::m_counter = 0;
DeclarativeDataPluginPrivate::DeclarativeDataPluginPrivate( DeclarativeDataPlugin* parent ) :
q( parent ), m_planet( "earth"), m_isInitialized( false ), m_delegate( 0 )
{
++m_counter;
}
void DeclarativeDataPluginPrivate::parseChunk( DeclarativeDataPluginItem *item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value )
{
if( key == "lat" || key == "latitude" ) {
coordinates.setLatitude( value.toDouble(), GeoDataCoordinates::Degree );
} else if( key == "lon" || key == "longitude" ) {
coordinates.setLongitude( value.toDouble(), GeoDataCoordinates::Degree );
} else if( key == "alt" || key == "altitude" ) {
coordinates.setAltitude( value.toDouble() );
} else {
item->setProperty( key.toAscii(), value );
}
}
void DeclarativeDataPluginPrivate::addItem( DeclarativeDataPluginItem *item, const GeoDataCoordinates &coordinates )
{
if ( coordinates.isValid() ) {
item->setCoordinate( coordinates );
item->setTarget( m_planet );
QVariant const idValue = item->property( "identifier" );
if ( idValue.isValid() && !idValue.toString().isEmpty() ) {
item->setId( idValue.toString() );
} else {
item->setId( coordinates.toString() ) ;
}
m_items.append( item );
} else {
delete item;
}
}
void DeclarativeDataPluginPrivate::parseListModel( QAbstractListModel *listModel )
{
QHash< int, QByteArray > roles = listModel->roleNames();
for( int i = 0; i < listModel->rowCount(); ++i ) {
GeoDataCoordinates coordinates;
QMap< int, QVariant > const itemData = listModel->itemData( listModel->index( i ) );
QHash< int, QByteArray >::const_iterator it = roles.constBegin();
DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q );
for ( ; it != roles.constEnd(); ++it ) {
parseChunk( item, coordinates, it.value(), itemData.value( it.key() ) );
}
addItem( item, coordinates );
}
}
void DeclarativeDataPluginPrivate::parseObject( QObject *object )
{
int count = 0;
QMetaObject const * meta = object->metaObject();
for( int i = 0; i < meta->propertyCount(); ++i ) {
if( qstrcmp( meta->property(i).name(), "count" ) == 0 ) {
count = meta->property(i).read( object ).toInt();
}
}
for( int i = 0; i < meta->methodCount(); ++i ) {
if( qstrcmp( meta->method(i).signature(), "get(int)" ) == 0 ) {
for( int j=0; j < count; ++j ) {
QScriptValue value;
meta->method(i).invoke( object, Qt::AutoConnection, Q_RETURN_ARG( QScriptValue , value), Q_ARG( int, j ) );
QObject * propertyObject = value.toQObject();
GeoDataCoordinates coordinates;
DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q );
if ( propertyObject ) {
for( int k = 0; k < propertyObject->metaObject()->propertyCount(); ++k ) {
QString const propertyName = propertyObject->metaObject()->property( k ).name();
QVariant const value = propertyObject->metaObject()->property( k ).read( propertyObject );
parseChunk( item, coordinates, propertyName, value );
}
} else {
QScriptValueIterator it( value );
while ( it.hasNext() ) {
it.next();
parseChunk( item, coordinates, it.name(), it.value().toVariant() );
}
}
addItem( item, coordinates );
}
}
}
}
Marble::RenderPlugin *DeclarativeDataPlugin::newInstance(const Marble::MarbleModel *marbleModel) const
{
DeclarativeDataPlugin* instance = new DeclarativeDataPlugin( marbleModel );
instance->d->m_planet = d->m_planet;
instance->d->m_name = d->m_name;
instance->d->m_nameId = d->m_nameId;
instance->d->m_version = d->m_version;
instance->d->m_guiString = d->m_guiString;
instance->d->m_copyrightYears = d->m_copyrightYears;
instance->d->m_description = d->m_description;
instance->d->m_authors = d->m_authors;
instance->d->m_aboutText = d->m_aboutText;
instance->d->m_isInitialized = d->m_isInitialized;
instance->d->m_items = d->m_items;
instance->d->m_delegate = d->m_delegate;
instance->d->m_model = d->m_model;
instance->d->m_counter = d->m_counter;
DeclarativeDataPluginModel* dataModel = new DeclarativeDataPluginModel( marbleModel );
dataModel->addItemsToList( d->m_items );
instance->setModel( dataModel );
connect( dataModel, SIGNAL(dataRequest(qreal,qreal,qreal,qreal)), this, SIGNAL(dataRequest(qreal,qreal,qreal,qreal)) );
d->m_modelInstances << dataModel;
return instance;
}
DeclarativeDataPlugin::DeclarativeDataPlugin( const Marble::MarbleModel *marbleModel )
: AbstractDataPlugin( marbleModel ), d( new DeclarativeDataPluginPrivate( this ) )
{
setEnabled( true );
setVisible( true );
}
DeclarativeDataPlugin::~DeclarativeDataPlugin()
{
delete d;
}
QString DeclarativeDataPlugin::planet() const
{
return d->m_planet;
}
void DeclarativeDataPlugin::setPlanet( const QString &planet )
{
if ( d->m_planet != planet ) {
d->m_planet = planet;
emit planetChanged();
}
}
QString DeclarativeDataPlugin::name() const
{
return d->m_name.isEmpty() ? "Anonymous DeclarativeDataPlugin" : d->m_name;
}
QString DeclarativeDataPlugin::guiString() const
{
return d->m_guiString.isEmpty() ? name() : d->m_guiString;
}
QString DeclarativeDataPlugin::nameId() const
{
return d->m_nameId.isEmpty() ? QString( "DeclarativeDataPlugin_%1" ).arg( d->m_counter ) : d->m_nameId;
}
QString DeclarativeDataPlugin::version() const
{
return d->m_version.isEmpty() ? "1.0" : d->m_version;
}
QString DeclarativeDataPlugin::description() const
{
return d->m_description;
}
QString DeclarativeDataPlugin::copyrightYears() const
{
return d->m_copyrightYears;
}
QList<PluginAuthor> DeclarativeDataPlugin::pluginAuthors() const
{
return d->m_authors;
}
QStringList DeclarativeDataPlugin::authors() const
{
QStringList authors;
foreach( const PluginAuthor& author, d->m_authors ) {
authors<< author.name << author.email;
}
return authors;
}
QString DeclarativeDataPlugin::aboutDataText() const
{
return d->m_aboutText;
}
QIcon DeclarativeDataPlugin::icon() const
{
return QIcon();
}
void DeclarativeDataPlugin::setName( const QString & name )
{
if( d->m_name != name ) {
d->m_name = name;
emit nameChanged();
}
}
void DeclarativeDataPlugin::setGuiString( const QString & guiString )
{
if( d->m_guiString != guiString ) {
d->m_guiString = guiString;
emit guiStringChanged();
}
}
void DeclarativeDataPlugin::setNameId( const QString & nameId )
{
if( d->m_nameId != nameId ) {
d->m_nameId = nameId;
emit nameIdChanged();
}
}
void DeclarativeDataPlugin::setVersion( const QString & version )
{
if( d->m_version != version ) {
d->m_version = version;
emit versionChanged();
}
}
void DeclarativeDataPlugin::setCopyrightYears( const QString & copyrightYears )
{
if( d->m_copyrightYears != copyrightYears ) {
d->m_copyrightYears = copyrightYears;
emit copyrightYearsChanged();
}
}
void DeclarativeDataPlugin::setDescription( const QString description )
{
if( d->m_description != description ) {
d->m_description = description;
emit descriptionChanged();
}
}
void DeclarativeDataPlugin::setAuthors( const QStringList & pluginAuthors )
{
if( pluginAuthors.size() % 2 == 0 ) {
QStringList::const_iterator it = pluginAuthors.constBegin();
while ( it != pluginAuthors.constEnd() ) {
QString name = *(++it);
QString email = *(++it);;
d->m_authors.append( PluginAuthor( name, email) );
}
emit authorsChanged();
}
}
void DeclarativeDataPlugin::setAboutDataText( const QString & aboutDataText )
{
if( d->m_aboutText != aboutDataText ) {
d->m_aboutText = aboutDataText;
emit aboutDataTextChanged();
}
}
QDeclarativeComponent *DeclarativeDataPlugin::delegate()
{
return d->m_delegate;
}
void DeclarativeDataPlugin::setDelegate( QDeclarativeComponent *delegate )
{
if ( delegate != d->m_delegate ) {
d->m_delegate = delegate;
emit delegateChanged();
}
}
void DeclarativeDataPlugin::initialize()
{
if( !model() ) {
setModel( new DeclarativeDataPluginModel( marbleModel(), this ) );
}
d->m_isInitialized = true;
}
bool DeclarativeDataPlugin::isInitialized() const
{
return d->m_isInitialized;
}
void DeclarativeDataPlugin::setDeclarativeModel( const QVariant &model )
{
d->m_model = model;
d->m_items.clear();
QObject* object = qVariantValue<QObject*>( model );
if( qobject_cast< QAbstractListModel* >( object ) ) {
d->parseListModel( qobject_cast< QAbstractListModel *>( object ) );
} else {
d->parseObject( object );
}
/** @todo: Listen for and reflect changes to the items in the model */
foreach( DeclarativeDataPluginModel* model, d->m_modelInstances ) {
model->addItemsToList( d->m_items );
}
emit declarativeModelChanged();
}
QVariant DeclarativeDataPlugin::declarativeModel()
{
return d->m_model;
}
#include "DeclarativeDataPlugin.moc"
<commit_msg>Use shared counter only for initialization.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Anton Chernov <chernov.anton.mail@gmail.com>
// Copyright 2012 "LOTES TM" LLC <lotes.sis@gmail.com>
// Copyright 2012 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "DeclarativeDataPlugin.h"
#include "DeclarativeDataPluginModel.h"
#include "DeclarativeDataPluginItem.h"
#include "MarbleDeclarativeWidget.h"
#include "MarbleDebug.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include <QtCore/QMetaObject>
#include <QtCore/QMetaProperty>
#include <QtScript/QScriptValue>
using namespace Marble;
class DeclarativeDataPluginPrivate {
public:
DeclarativeDataPlugin* q;
QString m_planet;
QString m_name;
QString m_nameId;
QString m_version;
QString m_guiString;
QString m_copyrightYears;
QString m_description;
QList<Marble::PluginAuthor> m_authors;
QString m_aboutText;
bool m_isInitialized;
QList<AbstractDataPluginItem *> m_items;
QList<DeclarativeDataPluginModel*> m_modelInstances;
QDeclarativeComponent* m_delegate;
QVariant m_model;
static int m_global_counter;
int m_counter;
DeclarativeDataPluginPrivate( DeclarativeDataPlugin* q );
void parseChunk( DeclarativeDataPluginItem * item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value );
void addItem( DeclarativeDataPluginItem* item, const GeoDataCoordinates &coordinates );
void parseListModel( QAbstractListModel* listModel );
void parseObject( QObject* object );
};
int DeclarativeDataPluginPrivate::m_global_counter = 0;
DeclarativeDataPluginPrivate::DeclarativeDataPluginPrivate( DeclarativeDataPlugin* parent ) :
q( parent ), m_planet( "earth"), m_isInitialized( false ), m_delegate( 0 ), m_counter( m_global_counter )
{
++m_global_counter;
}
void DeclarativeDataPluginPrivate::parseChunk( DeclarativeDataPluginItem *item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value )
{
if( key == "lat" || key == "latitude" ) {
coordinates.setLatitude( value.toDouble(), GeoDataCoordinates::Degree );
} else if( key == "lon" || key == "longitude" ) {
coordinates.setLongitude( value.toDouble(), GeoDataCoordinates::Degree );
} else if( key == "alt" || key == "altitude" ) {
coordinates.setAltitude( value.toDouble() );
} else {
item->setProperty( key.toAscii(), value );
}
}
void DeclarativeDataPluginPrivate::addItem( DeclarativeDataPluginItem *item, const GeoDataCoordinates &coordinates )
{
if ( coordinates.isValid() ) {
item->setCoordinate( coordinates );
item->setTarget( m_planet );
QVariant const idValue = item->property( "identifier" );
if ( idValue.isValid() && !idValue.toString().isEmpty() ) {
item->setId( idValue.toString() );
} else {
item->setId( coordinates.toString() ) ;
}
m_items.append( item );
} else {
delete item;
}
}
void DeclarativeDataPluginPrivate::parseListModel( QAbstractListModel *listModel )
{
QHash< int, QByteArray > roles = listModel->roleNames();
for( int i = 0; i < listModel->rowCount(); ++i ) {
GeoDataCoordinates coordinates;
QMap< int, QVariant > const itemData = listModel->itemData( listModel->index( i ) );
QHash< int, QByteArray >::const_iterator it = roles.constBegin();
DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q );
for ( ; it != roles.constEnd(); ++it ) {
parseChunk( item, coordinates, it.value(), itemData.value( it.key() ) );
}
addItem( item, coordinates );
}
}
void DeclarativeDataPluginPrivate::parseObject( QObject *object )
{
int count = 0;
QMetaObject const * meta = object->metaObject();
for( int i = 0; i < meta->propertyCount(); ++i ) {
if( qstrcmp( meta->property(i).name(), "count" ) == 0 ) {
count = meta->property(i).read( object ).toInt();
}
}
for( int i = 0; i < meta->methodCount(); ++i ) {
if( qstrcmp( meta->method(i).signature(), "get(int)" ) == 0 ) {
for( int j=0; j < count; ++j ) {
QScriptValue value;
meta->method(i).invoke( object, Qt::AutoConnection, Q_RETURN_ARG( QScriptValue , value), Q_ARG( int, j ) );
QObject * propertyObject = value.toQObject();
GeoDataCoordinates coordinates;
DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q );
if ( propertyObject ) {
for( int k = 0; k < propertyObject->metaObject()->propertyCount(); ++k ) {
QString const propertyName = propertyObject->metaObject()->property( k ).name();
QVariant const value = propertyObject->metaObject()->property( k ).read( propertyObject );
parseChunk( item, coordinates, propertyName, value );
}
} else {
QScriptValueIterator it( value );
while ( it.hasNext() ) {
it.next();
parseChunk( item, coordinates, it.name(), it.value().toVariant() );
}
}
addItem( item, coordinates );
}
}
}
}
Marble::RenderPlugin *DeclarativeDataPlugin::newInstance(const Marble::MarbleModel *marbleModel) const
{
DeclarativeDataPlugin* instance = new DeclarativeDataPlugin( marbleModel );
instance->d->m_planet = d->m_planet;
instance->d->m_name = d->m_name;
instance->d->m_nameId = d->m_nameId;
instance->d->m_version = d->m_version;
instance->d->m_guiString = d->m_guiString;
instance->d->m_copyrightYears = d->m_copyrightYears;
instance->d->m_description = d->m_description;
instance->d->m_authors = d->m_authors;
instance->d->m_aboutText = d->m_aboutText;
instance->d->m_isInitialized = d->m_isInitialized;
instance->d->m_items = d->m_items;
instance->d->m_delegate = d->m_delegate;
instance->d->m_model = d->m_model;
instance->d->m_counter = d->m_counter;
DeclarativeDataPluginModel* dataModel = new DeclarativeDataPluginModel( marbleModel );
dataModel->addItemsToList( d->m_items );
instance->setModel( dataModel );
connect( dataModel, SIGNAL(dataRequest(qreal,qreal,qreal,qreal)), this, SIGNAL(dataRequest(qreal,qreal,qreal,qreal)) );
d->m_modelInstances << dataModel;
return instance;
}
DeclarativeDataPlugin::DeclarativeDataPlugin( const Marble::MarbleModel *marbleModel )
: AbstractDataPlugin( marbleModel ), d( new DeclarativeDataPluginPrivate( this ) )
{
setEnabled( true );
setVisible( true );
}
DeclarativeDataPlugin::~DeclarativeDataPlugin()
{
delete d;
}
QString DeclarativeDataPlugin::planet() const
{
return d->m_planet;
}
void DeclarativeDataPlugin::setPlanet( const QString &planet )
{
if ( d->m_planet != planet ) {
d->m_planet = planet;
emit planetChanged();
}
}
QString DeclarativeDataPlugin::name() const
{
return d->m_name.isEmpty() ? "Anonymous DeclarativeDataPlugin" : d->m_name;
}
QString DeclarativeDataPlugin::guiString() const
{
return d->m_guiString.isEmpty() ? name() : d->m_guiString;
}
QString DeclarativeDataPlugin::nameId() const
{
return d->m_nameId.isEmpty() ? QString( "DeclarativeDataPlugin_%1" ).arg( d->m_counter ) : d->m_nameId;
}
QString DeclarativeDataPlugin::version() const
{
return d->m_version.isEmpty() ? "1.0" : d->m_version;
}
QString DeclarativeDataPlugin::description() const
{
return d->m_description;
}
QString DeclarativeDataPlugin::copyrightYears() const
{
return d->m_copyrightYears;
}
QList<PluginAuthor> DeclarativeDataPlugin::pluginAuthors() const
{
return d->m_authors;
}
QStringList DeclarativeDataPlugin::authors() const
{
QStringList authors;
foreach( const PluginAuthor& author, d->m_authors ) {
authors<< author.name << author.email;
}
return authors;
}
QString DeclarativeDataPlugin::aboutDataText() const
{
return d->m_aboutText;
}
QIcon DeclarativeDataPlugin::icon() const
{
return QIcon();
}
void DeclarativeDataPlugin::setName( const QString & name )
{
if( d->m_name != name ) {
d->m_name = name;
emit nameChanged();
}
}
void DeclarativeDataPlugin::setGuiString( const QString & guiString )
{
if( d->m_guiString != guiString ) {
d->m_guiString = guiString;
emit guiStringChanged();
}
}
void DeclarativeDataPlugin::setNameId( const QString & nameId )
{
if( d->m_nameId != nameId ) {
d->m_nameId = nameId;
emit nameIdChanged();
}
}
void DeclarativeDataPlugin::setVersion( const QString & version )
{
if( d->m_version != version ) {
d->m_version = version;
emit versionChanged();
}
}
void DeclarativeDataPlugin::setCopyrightYears( const QString & copyrightYears )
{
if( d->m_copyrightYears != copyrightYears ) {
d->m_copyrightYears = copyrightYears;
emit copyrightYearsChanged();
}
}
void DeclarativeDataPlugin::setDescription( const QString description )
{
if( d->m_description != description ) {
d->m_description = description;
emit descriptionChanged();
}
}
void DeclarativeDataPlugin::setAuthors( const QStringList & pluginAuthors )
{
if( pluginAuthors.size() % 2 == 0 ) {
QStringList::const_iterator it = pluginAuthors.constBegin();
while ( it != pluginAuthors.constEnd() ) {
QString name = *(++it);
QString email = *(++it);;
d->m_authors.append( PluginAuthor( name, email) );
}
emit authorsChanged();
}
}
void DeclarativeDataPlugin::setAboutDataText( const QString & aboutDataText )
{
if( d->m_aboutText != aboutDataText ) {
d->m_aboutText = aboutDataText;
emit aboutDataTextChanged();
}
}
QDeclarativeComponent *DeclarativeDataPlugin::delegate()
{
return d->m_delegate;
}
void DeclarativeDataPlugin::setDelegate( QDeclarativeComponent *delegate )
{
if ( delegate != d->m_delegate ) {
d->m_delegate = delegate;
emit delegateChanged();
}
}
void DeclarativeDataPlugin::initialize()
{
if( !model() ) {
setModel( new DeclarativeDataPluginModel( marbleModel(), this ) );
}
d->m_isInitialized = true;
}
bool DeclarativeDataPlugin::isInitialized() const
{
return d->m_isInitialized;
}
void DeclarativeDataPlugin::setDeclarativeModel( const QVariant &model )
{
d->m_model = model;
d->m_items.clear();
QObject* object = qVariantValue<QObject*>( model );
if( qobject_cast< QAbstractListModel* >( object ) ) {
d->parseListModel( qobject_cast< QAbstractListModel *>( object ) );
} else {
d->parseObject( object );
}
/** @todo: Listen for and reflect changes to the items in the model */
foreach( DeclarativeDataPluginModel* model, d->m_modelInstances ) {
model->addItemsToList( d->m_items );
}
emit declarativeModelChanged();
}
QVariant DeclarativeDataPlugin::declarativeModel()
{
return d->m_model;
}
#include "DeclarativeDataPlugin.moc"
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "remotelinuxruncontrol.h"
#include "maemoglobal.h"
#include "remotelinuxapplicationrunner.h"
#include "remotelinuxrunconfiguration.h"
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/qtcassert.h>
#include <QtGui/QMessageBox>
using namespace ProjectExplorer;
namespace RemoteLinux {
using ProjectExplorer::RunConfiguration;
AbstractRemoteLinuxRunControl::AbstractRemoteLinuxRunControl(RunConfiguration *rc)
: RunControl(rc, ProjectExplorer::Constants::RUNMODE)
, m_running(false)
{
}
AbstractRemoteLinuxRunControl::~AbstractRemoteLinuxRunControl()
{
}
void AbstractRemoteLinuxRunControl::start()
{
m_running = true;
emit started();
disconnect(runner(), 0, this, 0);
connect(runner(), SIGNAL(error(QString)), SLOT(handleSshError(QString)));
connect(runner(), SIGNAL(readyForExecution()), SLOT(startExecution()));
connect(runner(), SIGNAL(remoteErrorOutput(QByteArray)),
SLOT(handleRemoteErrorOutput(QByteArray)));
connect(runner(), SIGNAL(remoteOutput(QByteArray)),
SLOT(handleRemoteOutput(QByteArray)));
connect(runner(), SIGNAL(remoteProcessStarted()),
SLOT(handleRemoteProcessStarted()));
connect(runner(), SIGNAL(remoteProcessFinished(qint64)),
SLOT(handleRemoteProcessFinished(qint64)));
connect(runner(), SIGNAL(reportProgress(QString)),
SLOT(handleProgressReport(QString)));
runner()->start();
}
RunControl::StopResult AbstractRemoteLinuxRunControl::stop()
{
runner()->stop();
return StoppedSynchronously;
}
void AbstractRemoteLinuxRunControl::handleSshError(const QString &error)
{
handleError(error);
setFinished();
}
void AbstractRemoteLinuxRunControl::startExecution()
{
appendMessage(tr("Starting remote process ...\n"), Utils::NormalMessageFormat);
runner()->startExecution(QString::fromLocal8Bit("%1 %2 %3")
.arg(runner()->commandPrefix())
.arg(runner()->remoteExecutable())
.arg(runner()->arguments()).toUtf8());
}
void AbstractRemoteLinuxRunControl::handleRemoteProcessFinished(qint64 exitCode)
{
if (exitCode != RemoteLinuxApplicationRunner::InvalidExitCode) {
appendMessage(tr("Finished running remote process. Exit code was %1.\n")
.arg(exitCode), Utils::NormalMessageFormat);
}
setFinished();
}
void AbstractRemoteLinuxRunControl::handleRemoteOutput(const QByteArray &output)
{
appendMessage(QString::fromUtf8(output), Utils::StdOutFormatSameLine);
}
void AbstractRemoteLinuxRunControl::handleRemoteErrorOutput(const QByteArray &output)
{
appendMessage(QString::fromUtf8(output), Utils::StdErrFormatSameLine);
}
void AbstractRemoteLinuxRunControl::handleProgressReport(const QString &progressString)
{
appendMessage(progressString + QLatin1Char('\n'), Utils::NormalMessageFormat);
}
bool AbstractRemoteLinuxRunControl::isRunning() const
{
return m_running;
}
QIcon AbstractRemoteLinuxRunControl::icon() const
{
return QIcon(ProjectExplorer::Constants::ICON_RUN_SMALL);
}
void AbstractRemoteLinuxRunControl::handleError(const QString &errString)
{
stop();
appendMessage(errString, Utils::ErrorMessageFormat);
QMessageBox::critical(0, tr("Remote Execution Failure"), errString);
}
void AbstractRemoteLinuxRunControl::setFinished()
{
disconnect(runner(), 0, this, 0);
m_running = false;
emit finished();
}
RemoteLinuxRunControl::RemoteLinuxRunControl(ProjectExplorer::RunConfiguration *runConfig)
: AbstractRemoteLinuxRunControl(runConfig),
m_runner(new RemoteLinuxApplicationRunner(this, qobject_cast<RemoteLinuxRunConfiguration *>(runConfig)))
{
}
RemoteLinuxRunControl::~RemoteLinuxRunControl()
{
}
RemoteLinuxApplicationRunner *RemoteLinuxRunControl::runner() const
{
return m_runner;
}
} // namespace RemoteLinux
<commit_msg>RemoteLinux: Report correct run control stop type.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "remotelinuxruncontrol.h"
#include "maemoglobal.h"
#include "remotelinuxapplicationrunner.h"
#include "remotelinuxrunconfiguration.h"
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/qtcassert.h>
#include <QtGui/QMessageBox>
using namespace ProjectExplorer;
namespace RemoteLinux {
using ProjectExplorer::RunConfiguration;
AbstractRemoteLinuxRunControl::AbstractRemoteLinuxRunControl(RunConfiguration *rc)
: RunControl(rc, ProjectExplorer::Constants::RUNMODE)
, m_running(false)
{
}
AbstractRemoteLinuxRunControl::~AbstractRemoteLinuxRunControl()
{
}
void AbstractRemoteLinuxRunControl::start()
{
m_running = true;
emit started();
disconnect(runner(), 0, this, 0);
connect(runner(), SIGNAL(error(QString)), SLOT(handleSshError(QString)));
connect(runner(), SIGNAL(readyForExecution()), SLOT(startExecution()));
connect(runner(), SIGNAL(remoteErrorOutput(QByteArray)),
SLOT(handleRemoteErrorOutput(QByteArray)));
connect(runner(), SIGNAL(remoteOutput(QByteArray)),
SLOT(handleRemoteOutput(QByteArray)));
connect(runner(), SIGNAL(remoteProcessStarted()),
SLOT(handleRemoteProcessStarted()));
connect(runner(), SIGNAL(remoteProcessFinished(qint64)),
SLOT(handleRemoteProcessFinished(qint64)));
connect(runner(), SIGNAL(reportProgress(QString)),
SLOT(handleProgressReport(QString)));
runner()->start();
}
RunControl::StopResult AbstractRemoteLinuxRunControl::stop()
{
runner()->stop();
return AsynchronousStop;
}
void AbstractRemoteLinuxRunControl::handleSshError(const QString &error)
{
handleError(error);
setFinished();
}
void AbstractRemoteLinuxRunControl::startExecution()
{
appendMessage(tr("Starting remote process ...\n"), Utils::NormalMessageFormat);
runner()->startExecution(QString::fromLocal8Bit("%1 %2 %3")
.arg(runner()->commandPrefix())
.arg(runner()->remoteExecutable())
.arg(runner()->arguments()).toUtf8());
}
void AbstractRemoteLinuxRunControl::handleRemoteProcessFinished(qint64 exitCode)
{
if (exitCode != RemoteLinuxApplicationRunner::InvalidExitCode) {
appendMessage(tr("Finished running remote process. Exit code was %1.\n")
.arg(exitCode), Utils::NormalMessageFormat);
}
setFinished();
}
void AbstractRemoteLinuxRunControl::handleRemoteOutput(const QByteArray &output)
{
appendMessage(QString::fromUtf8(output), Utils::StdOutFormatSameLine);
}
void AbstractRemoteLinuxRunControl::handleRemoteErrorOutput(const QByteArray &output)
{
appendMessage(QString::fromUtf8(output), Utils::StdErrFormatSameLine);
}
void AbstractRemoteLinuxRunControl::handleProgressReport(const QString &progressString)
{
appendMessage(progressString + QLatin1Char('\n'), Utils::NormalMessageFormat);
}
bool AbstractRemoteLinuxRunControl::isRunning() const
{
return m_running;
}
QIcon AbstractRemoteLinuxRunControl::icon() const
{
return QIcon(ProjectExplorer::Constants::ICON_RUN_SMALL);
}
void AbstractRemoteLinuxRunControl::handleError(const QString &errString)
{
stop();
appendMessage(errString, Utils::ErrorMessageFormat);
QMessageBox::critical(0, tr("Remote Execution Failure"), errString);
}
void AbstractRemoteLinuxRunControl::setFinished()
{
disconnect(runner(), 0, this, 0);
m_running = false;
emit finished();
}
RemoteLinuxRunControl::RemoteLinuxRunControl(ProjectExplorer::RunConfiguration *runConfig)
: AbstractRemoteLinuxRunControl(runConfig),
m_runner(new RemoteLinuxApplicationRunner(this, qobject_cast<RemoteLinuxRunConfiguration *>(runConfig)))
{
}
RemoteLinuxRunControl::~RemoteLinuxRunControl()
{
}
RemoteLinuxApplicationRunner *RemoteLinuxRunControl::runner() const
{
return m_runner;
}
} // namespace RemoteLinux
<|endoftext|> |
<commit_before>#ifndef __STRESS_CLIENT_PROTOCOLS_RETHINKDB_PROTOCOL_HPP__
#define __STRESS_CLIENT_PROTOCOLS_RETHINKDB_PROTOCOL_HPP__
#include <assert.h>
#include <errno.h>
#include <netdb.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sys/socket.h>
#include "query_language.pb.h"
#define MAX_PROTOBUF_SIZE (1024*1024)
#define RDB_TABLE_NAME "Welcome-rdb"
#define PRIMARY_KEY_NAME "id"
struct rethinkdb_protocol_t : protocol_t {
rethinkdb_protocol_t(const char *conn_str) : sockfd(-1), outstanding_reads(0) {
// initialize the socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket() failed");
exit(-1);
}
// parse the host string
char _host[MAX_HOST];
strncpy(_host, conn_str, MAX_HOST);
int port;
if (char *_port = strchr(_host, ':')) {
*_port = '\0';
_port++;
port = atoi(_port);
if (port == 0) {
fprintf(stderr, "Cannot parse port string: \"%s\".\n", _port);
exit(-1);
}
}
// set up socket
struct sockaddr_in sin;
struct hostent *host = gethostbyname(_host);
if (!host) {
herror("gethostbyname() failed");
exit(-1);
}
memcpy(&sin.sin_addr.s_addr, host->h_addr, host->h_length);
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
// connect to server
int res = ::connect(sockfd, (struct sockaddr *)&sin, sizeof(sin));
if (res < 0) {
perror("connect() failed");
exit(-1);
}
}
virtual ~rethinkdb_protocol_t() {
// close the socket
if (sockfd != -1) {
int res = close(sockfd);
if (res != 0) {
perror("close() failed");
exit(-1);
}
}
}
virtual void remove(const char *key, size_t key_size) {
assert(!exist_outstanding_pipeline_reads());
// generate query
Query *query = new Query;
query->set_type(Query::WRITE);
WriteQuery *write_query = query->mutable_write_query();
write_query->set_type(WriteQuery::POINTDELETE);
WriteQuery::PointDelete *point_delete = write_query->mutable_point_delete();
TableRef *table_ref = point_delete->mutable_table_ref();
table_ref->set_table_name(RDB_TABLE_NAME);
point_delete->set_attrname(PRIMARY_KEY_NAME);
Term *term_key = point_delete->mutable_key();
term_key->set_type(Term::STRING);
term_key->set_valuestring(std::string(key, key_size));
send_query(query);
// get response
Response *response = new Response;
get_response(response);
if (response->token() != query->token()) {
fprintf(stderr, "Delete response token %ld did not match query token %ld.\n", response->token(), query->token());
}
if (response->status_code() != Response::SUCCESS_JSON) {
fprintf(stderr, "Failed to remove key %s: %s\n", key, response->error_message().c_str());
}
// temporary debug output
printf("%s\n", query->DebugString().c_str());
printf("%s\n", response->DebugString().c_str());
}
virtual void update(const char *key, size_t key_size,
const char *value, size_t value_size) {
insert(key, key_size, value, value_size); // TODO: use PointUpdate or PointMutate instead?
}
virtual void insert(const char *key, size_t key_size,
const char *value, size_t value_size) {
assert(!exist_outstanding_pipeline_reads());
// generate query
Query *query = new Query;
query->set_type(Query::WRITE);
WriteQuery *write_query = query->mutable_write_query();
write_query->set_type(WriteQuery::INSERT);
WriteQuery::Insert *insert = write_query->mutable_insert();
TableRef *table_ref = insert->mutable_table_ref();
table_ref->set_table_name(RDB_TABLE_NAME);
Term *term = insert->add_terms();
term->set_type(Term::JSON);
std::string json_insert = std::string("{\"") + std::string(PRIMARY_KEY_NAME) + std::string("\" : \"") + std::string(key, key_size) + std::string("\", \"val\" : \"") + std::string(value, value_size) + std::string("\"}");
term->set_jsonstring(json_insert);
send_query(query);
// get response
Response *response = new Response;
get_response(response);
if (response->token() != query->token()) {
fprintf(stderr, "Insert response token %ld did not match query token %ld.\n", response->token(), query->token());
}
if (response->status_code() != Response::SUCCESS_JSON) {
fprintf(stderr, "Failed to insert key %s, value %s: %s\n", key, value, response->error_message().c_str());
}
// temporary debug output
printf("%s\n", query->DebugString().c_str());
printf("%s\n", response->DebugString().c_str());
}
// TODO: make this more efficient instead of just doing a bunch of reads in a row
virtual void read(payload_t *keys, int count, payload_t *values = NULL) {
assert(!exist_outstanding_pipeline_reads());
for (int i = 0; i < count; i++) {
// generate query
Query *query = new Query;
query->set_type(Query::READ);
ReadQuery *read_query = query->mutable_read_query();
Term *term = read_query->mutable_term();
term->set_type(Term::GETBYKEY);
Term::GetByKey *get_by_key = term->mutable_get_by_key();
TableRef *table_ref = get_by_key->mutable_table_ref();
table_ref->set_table_name(RDB_TABLE_NAME);
get_by_key->set_attrname(PRIMARY_KEY_NAME);
Term *term_key = get_by_key->mutable_key();
term_key->set_type(Term::STRING);
term_key->set_valuestring(std::string(keys[i].first, keys[i].second));
send_query(query);
// get response
Response *response = new Response;
get_response(response);
if (response->token() != query->token()) {
fprintf(stderr, "Read response token %ld did not match query token %ld.\n", response->token(), query->token());
}
if (response->status_code() != Response::SUCCESS_JSON) {
fprintf(stderr, "Failed to read key %s: %s\n", keys[i].first, response->error_message().c_str());
}
if (values) {
// TODO: use some JSON parser instead of this
int last_quote = (int) response->response(0).find_last_of('"');
int second_to_last_quote = (int) response->response(0).find_last_of(last_quote - 1);
assert(last_quote >= 0 && last_quote < response->response(0).length());
assert(second_to_last_quote >= 0 && second_to_last_quote < response->response(0).length());
std::string result = response->response(0).substr(second_to_last_quote + 1, last_quote - second_to_last_quote - 1);
if (std::string(values[i].first, values[i].second) != result) {
fprintf(stderr, "Read failed: wanted %s but got %s for key %s.\n", values[i].first, result.c_str(), keys[i].first);
}
}
// temporary debug output
printf("%s\n", query->DebugString().c_str());
printf("%s\n", response->DebugString().c_str());
}
}
virtual void enqueue_read(payload_t *keys, int count, payload_t *values = NULL) {
for (int i = 0; i < count; i++) {
// generate query
Query *query = new Query;
query->set_type(Query::READ);
ReadQuery *read_query = query->mutable_read_query();
Term *term = read_query->mutable_term();
term->set_type(Term::GETBYKEY);
Term::GetByKey *get_by_key = term->mutable_get_by_key();
TableRef *table_ref = get_by_key->mutable_table_ref();
table_ref->set_table_name(RDB_TABLE_NAME);
get_by_key->set_attrname(PRIMARY_KEY_NAME);
Term *term_key = get_by_key->mutable_key();
term_key->set_type(Term::STRING);
term_key->set_valuestring(std::string(keys[i].first, keys[i].second));
send_query(query);
// temporary debug output
printf("%s\n", query->DebugString().c_str());
outstanding_reads++;
}
}
// TODO: implement this method properly
virtual bool dequeue_read_maybe(payload_t *keys, int count, payload_t *values = NULL) {
dequeue_read(keys, count, values);
return true;
}
virtual void dequeue_read(payload_t *keys, int count, payload_t *values = NULL) {
for (int i = 0; i < count; i++) {
// get response
Response *response = new Response;
get_response(response);
if (response->status_code() != Response::SUCCESS_JSON) {
fprintf(stderr, "Failed to read key %s: %s\n", keys[i].first, response->error_message().c_str());
}
if (values) {
// TODO: use some JSON parser instead of this
int last_quote = (int) response->response(0).find_last_of('"');
int second_to_last_quote = (int) response->response(0).find_last_of(last_quote - 1);
assert(last_quote >= 0 && last_quote < response->response(0).length());
assert(second_to_last_quote >= 0 && second_to_last_quote < response->response(0).length());
std::string result = response->response(0).substr(second_to_last_quote + 1, last_quote - second_to_last_quote - 1);
if (std::string(values[i].first, values[i].second) != result) {
fprintf(stderr, "Read failed: wanted %s but got %s for key %s.\n", values[i].first, result.c_str(), keys[i].first);
}
}
// temporary debug output
printf("%s\n", response->DebugString().c_str());
outstanding_reads--;
}
}
virtual void range_read(char* lkey, size_t lkey_size, char* rkey, size_t rkey_size, int count_limit, payload_t *values = NULL) {
fprintf(stderr, "RANGE READ NOT YET IMPLEMENTED\n");
}
virtual void append(const char *key, size_t key_size,
const char *value, size_t value_size) {
fprintf(stderr, "APPEND NOT YET IMPLEMENTED\n");
}
virtual void prepend(const char *key, size_t key_size,
const char *value, size_t value_size) {
fprintf(stderr, "PREPEND NOT YET IMPLEMENTED\n");
}
private:
// TODO: add timeout to send_all and recv_all?
void send_all(const char *buf, int size) {
int total_sent = 0, sent;
while (total_sent < size) {
sent = send(sockfd, buf + total_sent, size - total_sent, 0);
if (sent < 0) {
perror("send() failed");
exit(-1);
}
total_sent += sent;
}
}
void recv_all(char *buf, int size) {
int total_received = 0, received;
while (total_received < size) {
received = recv(sockfd, buf + total_received, size - total_received, 0);
if (received < 0) {
perror("recv() failed");
exit(-1);
}
total_received += received;
}
}
void send_query(Query *query) {
// set token
query->set_token(token_index++);
// serialize query
std::string query_serialized;
if (!query->SerializeToString(&query_serialized)) {
fprintf(stderr, "faild to serialize query\n");
fprintf(stderr, "%s\n", query->DebugString().c_str());
exit(-1);
}
// send message
int size = int(query_serialized.length());
send_all((char *) &size, sizeof(size));
send_all(query_serialized.c_str(), size);
}
void get_response(Response *response) {
// get message
int size;
recv_all((char *) &size, sizeof(size));
recv_all(buffer, size);
// unserialize
if (!response->ParseFromString(std::string(buffer, size))) {
fprintf(stderr, "failed to unserialize response\n");
exit(-1);
}
}
bool exist_outstanding_pipeline_reads() {
return outstanding_reads != 0;
}
private:
static int token_index;
int sockfd;
int outstanding_reads;
char buffer[MAX_PROTOBUF_SIZE];
} ;
int rethinkdb_protocol_t::token_index = 0;
#endif // __STRESS_CLIENT_PROTOCOLS_RETHINKDB_PROTOCOL_HPP__
<commit_msg>Added a thread mutex to make sure that two commands do not interfere with each other.<commit_after>#ifndef __STRESS_CLIENT_PROTOCOLS_RETHINKDB_PROTOCOL_HPP__
#define __STRESS_CLIENT_PROTOCOLS_RETHINKDB_PROTOCOL_HPP__
#include <assert.h>
#include <errno.h>
#include <netdb.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sys/socket.h>
#include "query_language.pb.h"
#define MAX_PROTOBUF_SIZE (1024*1024)
#define RDB_TABLE_NAME "Welcome-rdb"
#define PRIMARY_KEY_NAME "id"
struct rethinkdb_protocol_t : protocol_t {
rethinkdb_protocol_t(const char *conn_str) : sockfd(-1), outstanding_reads(0) {
// initialize the socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket() failed");
exit(-1);
}
// parse the host string
char _host[MAX_HOST];
strncpy(_host, conn_str, MAX_HOST);
int port;
if (char *_port = strchr(_host, ':')) {
*_port = '\0';
_port++;
port = atoi(_port);
if (port == 0) {
fprintf(stderr, "Cannot parse port string: \"%s\".\n", _port);
exit(-1);
}
}
// set up socket
struct sockaddr_in sin;
struct hostent *host = gethostbyname(_host);
if (!host) {
herror("gethostbyname() failed");
exit(-1);
}
memcpy(&sin.sin_addr.s_addr, host->h_addr, host->h_length);
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
// connect to server
int res = ::connect(sockfd, (struct sockaddr *)&sin, sizeof(sin));
if (res < 0) {
perror("connect() failed");
exit(-1);
}
// initialize send mutex
pthread_mutex_init(&send_mutex, NULL);
}
virtual ~rethinkdb_protocol_t() {
// close the socket
if (sockfd != -1) {
int res = close(sockfd);
if (res != 0) {
perror("close() failed");
exit(-1);
}
}
// destroy send mutex
pthread_mutex_destroy(&send_mutex);
}
virtual void remove(const char *key, size_t key_size) {
assert(!exist_outstanding_pipeline_reads());
// generate query
Query *query = new Query;
query->set_type(Query::WRITE);
WriteQuery *write_query = query->mutable_write_query();
write_query->set_type(WriteQuery::POINTDELETE);
WriteQuery::PointDelete *point_delete = write_query->mutable_point_delete();
TableRef *table_ref = point_delete->mutable_table_ref();
table_ref->set_table_name(RDB_TABLE_NAME);
point_delete->set_attrname(PRIMARY_KEY_NAME);
Term *term_key = point_delete->mutable_key();
term_key->set_type(Term::STRING);
term_key->set_valuestring(std::string(key, key_size));
send_query(query);
// get response
Response *response = new Response;
get_response(response);
if (response->token() != query->token()) {
fprintf(stderr, "Delete response token %ld did not match query token %ld.\n", response->token(), query->token());
}
if (response->status_code() != Response::SUCCESS_JSON) {
fprintf(stderr, "Failed to remove key %s: %s\n", key, response->error_message().c_str());
}
// temporary debug output
printf("%s\n", query->DebugString().c_str());
printf("%s\n", response->DebugString().c_str());
}
virtual void update(const char *key, size_t key_size,
const char *value, size_t value_size) {
insert(key, key_size, value, value_size); // TODO: use PointUpdate or PointMutate instead?
}
virtual void insert(const char *key, size_t key_size,
const char *value, size_t value_size) {
assert(!exist_outstanding_pipeline_reads());
// generate query
Query *query = new Query;
query->set_type(Query::WRITE);
WriteQuery *write_query = query->mutable_write_query();
write_query->set_type(WriteQuery::INSERT);
WriteQuery::Insert *insert = write_query->mutable_insert();
TableRef *table_ref = insert->mutable_table_ref();
table_ref->set_table_name(RDB_TABLE_NAME);
Term *term = insert->add_terms();
term->set_type(Term::JSON);
std::string json_insert = std::string("{\"") + std::string(PRIMARY_KEY_NAME) + std::string("\" : \"") + std::string(key, key_size) + std::string("\", \"val\" : \"") + std::string(value, value_size) + std::string("\"}");
term->set_jsonstring(json_insert);
send_query(query);
// get response
Response *response = new Response;
get_response(response);
if (response->token() != query->token()) {
fprintf(stderr, "Insert response token %ld did not match query token %ld.\n", response->token(), query->token());
}
if (response->status_code() != Response::SUCCESS_JSON) {
fprintf(stderr, "Failed to insert key %s, value %s: %s\n", key, value, response->error_message().c_str());
}
// temporary debug output
printf("%s\n", query->DebugString().c_str());
printf("%s\n", response->DebugString().c_str());
}
// TODO: make this more efficient instead of just doing a bunch of reads in a row
virtual void read(payload_t *keys, int count, payload_t *values = NULL) {
assert(!exist_outstanding_pipeline_reads());
for (int i = 0; i < count; i++) {
// generate query
Query *query = new Query;
query->set_type(Query::READ);
ReadQuery *read_query = query->mutable_read_query();
Term *term = read_query->mutable_term();
term->set_type(Term::GETBYKEY);
Term::GetByKey *get_by_key = term->mutable_get_by_key();
TableRef *table_ref = get_by_key->mutable_table_ref();
table_ref->set_table_name(RDB_TABLE_NAME);
get_by_key->set_attrname(PRIMARY_KEY_NAME);
Term *term_key = get_by_key->mutable_key();
term_key->set_type(Term::STRING);
term_key->set_valuestring(std::string(keys[i].first, keys[i].second));
send_query(query);
// get response
Response *response = new Response;
get_response(response);
if (response->token() != query->token()) {
fprintf(stderr, "Read response token %ld did not match query token %ld.\n", response->token(), query->token());
}
if (response->status_code() != Response::SUCCESS_JSON) {
fprintf(stderr, "Failed to read key %s: %s\n", keys[i].first, response->error_message().c_str());
}
if (values) {
// TODO: use some JSON parser instead of this
int last_quote = (int) response->response(0).find_last_of('"');
int second_to_last_quote = (int) response->response(0).find_last_of(last_quote - 1);
assert(last_quote >= 0 && last_quote < response->response(0).length());
assert(second_to_last_quote >= 0 && second_to_last_quote < response->response(0).length());
std::string result = response->response(0).substr(second_to_last_quote + 1, last_quote - second_to_last_quote - 1);
if (std::string(values[i].first, values[i].second) != result) {
fprintf(stderr, "Read failed: wanted %s but got %s for key %s.\n", values[i].first, result.c_str(), keys[i].first);
}
}
// temporary debug output
printf("%s\n", query->DebugString().c_str());
printf("%s\n", response->DebugString().c_str());
}
}
virtual void enqueue_read(payload_t *keys, int count, payload_t *values = NULL) {
for (int i = 0; i < count; i++) {
// generate query
Query *query = new Query;
query->set_type(Query::READ);
ReadQuery *read_query = query->mutable_read_query();
Term *term = read_query->mutable_term();
term->set_type(Term::GETBYKEY);
Term::GetByKey *get_by_key = term->mutable_get_by_key();
TableRef *table_ref = get_by_key->mutable_table_ref();
table_ref->set_table_name(RDB_TABLE_NAME);
get_by_key->set_attrname(PRIMARY_KEY_NAME);
Term *term_key = get_by_key->mutable_key();
term_key->set_type(Term::STRING);
term_key->set_valuestring(std::string(keys[i].first, keys[i].second));
send_query(query);
// temporary debug output
printf("%s\n", query->DebugString().c_str());
outstanding_reads++;
}
}
// TODO: implement this method properly
virtual bool dequeue_read_maybe(payload_t *keys, int count, payload_t *values = NULL) {
dequeue_read(keys, count, values);
return true;
}
virtual void dequeue_read(payload_t *keys, int count, payload_t *values = NULL) {
for (int i = 0; i < count; i++) {
// get response
Response *response = new Response;
get_response(response);
if (response->status_code() != Response::SUCCESS_JSON) {
fprintf(stderr, "Failed to read key %s: %s\n", keys[i].first, response->error_message().c_str());
}
if (values) {
// TODO: use some JSON parser instead of this
int last_quote = (int) response->response(0).find_last_of('"');
int second_to_last_quote = (int) response->response(0).find_last_of(last_quote - 1);
assert(last_quote >= 0 && last_quote < response->response(0).length());
assert(second_to_last_quote >= 0 && second_to_last_quote < response->response(0).length());
std::string result = response->response(0).substr(second_to_last_quote + 1, last_quote - second_to_last_quote - 1);
if (std::string(values[i].first, values[i].second) != result) {
fprintf(stderr, "Read failed: wanted %s but got %s for key %s.\n", values[i].first, result.c_str(), keys[i].first);
}
}
// temporary debug output
printf("%s\n", response->DebugString().c_str());
outstanding_reads--;
}
}
virtual void range_read(char* lkey, size_t lkey_size, char* rkey, size_t rkey_size, int count_limit, payload_t *values = NULL) {
fprintf(stderr, "RANGE READ NOT YET IMPLEMENTED\n");
}
virtual void append(const char *key, size_t key_size,
const char *value, size_t value_size) {
fprintf(stderr, "APPEND NOT YET IMPLEMENTED\n");
}
virtual void prepend(const char *key, size_t key_size,
const char *value, size_t value_size) {
fprintf(stderr, "PREPEND NOT YET IMPLEMENTED\n");
}
private:
// TODO: add timeout to send_all and recv_all?
void send_all(const char *buf, int size) {
int total_sent = 0, sent;
while (total_sent < size) {
sent = send(sockfd, buf + total_sent, size - total_sent, 0);
if (sent < 0) {
perror("send() failed");
exit(-1);
}
total_sent += sent;
}
}
void recv_all(char *buf, int size) {
int total_received = 0, received;
while (total_received < size) {
received = recv(sockfd, buf + total_received, size - total_received, 0);
if (received < 0) {
perror("recv() failed");
exit(-1);
}
total_received += received;
}
}
void send_query(Query *query) {
pthread_mutex_lock(&send_mutex);
printf("got mutex for token %d\n", token_index);
// set token
query->set_token(token_index++);
// serialize query
std::string query_serialized;
if (!query->SerializeToString(&query_serialized)) {
fprintf(stderr, "faild to serialize query\n");
fprintf(stderr, "%s\n", query->DebugString().c_str());
exit(-1);
}
// send message
int size = int(query_serialized.length());
send_all((char *) &size, sizeof(size));
send_all(query_serialized.c_str(), size);
printf("about to release mutex for token %d\n", token_index - 1);
pthread_mutex_unlock(&send_mutex);
}
// TODO: RethinkDB apparently does not guarantee that responses come back in the same order
// that queries were sent. Thus, we should keep some storage of received Responses
// and when we want to check the response to a particular query, we wait for the storage to
// gain the response with the token we want.
void get_response(Response *response) {
// get message
int size;
recv_all((char *) &size, sizeof(size));
recv_all(buffer, size);
// unserialize
if (!response->ParseFromString(std::string(buffer, size))) {
fprintf(stderr, "failed to unserialize response\n");
exit(-1);
}
}
bool exist_outstanding_pipeline_reads() {
return outstanding_reads != 0;
}
private:
static int token_index;
static pthread_mutex_t send_mutex;
int sockfd;
int outstanding_reads;
char buffer[MAX_PROTOBUF_SIZE];
} ;
int rethinkdb_protocol_t::token_index = 0;
pthread_mutex_t rethinkdb_protocol_t::send_mutex;
#endif // __STRESS_CLIENT_PROTOCOLS_RETHINKDB_PROTOCOL_HPP__
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "query.h"
#include <vespa/searchlib/parsequery/stackdumpiterator.h>
#include <vespa/vespalib/objects/visit.hpp>
#include <cassert>
namespace search::streaming {
void
QueryConnector::visitMembers(vespalib::ObjectVisitor &visitor) const
{
visit(visitor, "Operator", _opName);
}
QueryConnector::QueryConnector(const char * opName)
: QueryNode(),
_opName(opName),
_index(),
_children()
{
}
void
QueryConnector::addChild(QueryNode::UP child) {
_children.push_back(std::move(child));
}
QueryConnector::~QueryConnector() = default;
const HitList &
QueryConnector::evaluateHits(HitList & hl) const
{
if (evaluate()) {
hl.push_back(Hit(1, 0, 0, 1));
}
return hl;
}
void
QueryConnector::reset()
{
for (const auto & node : _children) {
node->reset();
}
}
void
QueryConnector::getLeafs(QueryTermList & tl)
{
for (const auto & node : _children) {
node->getLeafs(tl);
}
}
void
QueryConnector::getLeafs(ConstQueryTermList & tl) const
{
for (const auto & node : _children) {
node->getLeafs(tl);
}
}
void
QueryConnector::getPhrases(QueryNodeRefList & tl)
{
for (const auto & node : _children) {
node->getPhrases(tl);
}
}
void
QueryConnector::getPhrases(ConstQueryNodeRefList & tl) const
{
for (const auto & node : _children) {
node->getPhrases(tl);
}
}
size_t
QueryConnector::depth() const
{
size_t d(0);
for (const auto & node : _children) {
size_t t = node->depth();
if (t > d) {
d = t;
}
}
return d+1;
}
size_t
QueryConnector::width() const
{
size_t w(0);
for (const auto & node : _children) {
w += node->width();
}
return w;
}
std::unique_ptr<QueryConnector>
QueryConnector::create(ParseItem::ItemType type)
{
switch (type) {
case search::ParseItem::ITEM_AND: return std::make_unique<AndQueryNode>();
case search::ParseItem::ITEM_OR: return std::make_unique<OrQueryNode>();
case search::ParseItem::ITEM_WEAK_AND: return std::make_unique<OrQueryNode>();
case search::ParseItem::ITEM_EQUIV: return std::make_unique<EquivQueryNode>();
case search::ParseItem::ITEM_WEIGHTED_SET: return std::make_unique<EquivQueryNode>();
case search::ParseItem::ITEM_DOT_PRODUCT: return std::make_unique<OrQueryNode>();
case search::ParseItem::ITEM_WAND: return std::make_unique<OrQueryNode>();
case search::ParseItem::ITEM_NOT: return std::make_unique<AndNotQueryNode>();
case search::ParseItem::ITEM_PHRASE: return std::make_unique<PhraseQueryNode>();
case search::ParseItem::ITEM_SAME_ELEMENT: return std::make_unique<SameElementQueryNode>();
case search::ParseItem::ITEM_NEAR: return std::make_unique<NearQueryNode>();
case search::ParseItem::ITEM_ONEAR: return std::make_unique<ONearQueryNode>();
default: return nullptr;
}
}
bool
TrueNode::evaluate() const
{
return true;
}
bool
AndQueryNode::evaluate() const
{
for (const auto & qn : getChildren()) {
if ( ! qn->evaluate() ) return false;
}
return true;
}
bool
AndNotQueryNode::evaluate() const {
auto it = getChildren().begin();
auto mt = getChildren().end();
if ((it != getChildren().end()) && (*it)->evaluate()) {
for (++it; it != mt; it++) {
if ((*it)->evaluate()) return false;
}
return true;
}
return false;
}
bool
OrQueryNode::evaluate() const {
for (const auto & qn : getChildren()) {
if (qn->evaluate()) return true;
}
return false;
}
bool
EquivQueryNode::evaluate() const
{
return OrQueryNode::evaluate();
}
bool
SameElementQueryNode::evaluate() const {
HitList hl;
return ! evaluateHits(hl).empty();
}
void
SameElementQueryNode::addChild(QueryNode::UP child) {
assert(dynamic_cast<const QueryTerm *>(child.get()) != nullptr);
AndQueryNode::addChild(std::move(child));
}
const HitList &
SameElementQueryNode::evaluateHits(HitList & hl) const
{
hl.clear();
if ( !AndQueryNode::evaluate()) return hl;
HitList tmpHL;
const QueryNodeList & children = getChildren();
unsigned int numFields = children.size();
unsigned int currMatchCount = 0;
std::vector<unsigned int> indexVector(numFields, 0);
auto curr = static_cast<const QueryTerm *> (children[currMatchCount].get());
bool exhausted( curr->evaluateHits(tmpHL).empty());
for (; !exhausted; ) {
auto next = static_cast<const QueryTerm *>(children[currMatchCount+1].get());
unsigned int & currIndex = indexVector[currMatchCount];
unsigned int & nextIndex = indexVector[currMatchCount+1];
const auto & currHit = curr->evaluateHits(tmpHL)[currIndex];
uint32_t currElemId = currHit.elemId();
const HitList & nextHL = next->evaluateHits(tmpHL);
size_t nextIndexMax = nextHL.size();
while ((nextIndex < nextIndexMax) && (nextHL[nextIndex].elemId() < currElemId)) {
nextIndex++;
}
if ((nextIndex < nextIndexMax) && (nextHL[nextIndex].elemId() == currElemId)) {
currMatchCount++;
if ((currMatchCount+1) == numFields) {
Hit h = nextHL[indexVector[currMatchCount]];
hl.emplace_back(0, h.context(), h.elemId(), h.weight());
currMatchCount = 0;
indexVector[0]++;
}
} else {
currMatchCount = 0;
indexVector[currMatchCount]++;
}
curr = static_cast<const QueryTerm *>(children[currMatchCount].get());
exhausted = (nextIndex >= nextIndexMax) || (indexVector[currMatchCount] >= curr->evaluateHits(tmpHL).size());
}
return hl;
}
bool
PhraseQueryNode::evaluate() const
{
HitList hl;
return ! evaluateHits(hl).empty();
}
void PhraseQueryNode::getPhrases(QueryNodeRefList & tl) { tl.push_back(this); }
void PhraseQueryNode::getPhrases(ConstQueryNodeRefList & tl) const { tl.push_back(this); }
void
PhraseQueryNode::addChild(QueryNode::UP child) {
assert(dynamic_cast<const QueryTerm *>(child.get()) != nullptr);
AndQueryNode::addChild(std::move(child));
}
const HitList &
PhraseQueryNode::evaluateHits(HitList & hl) const
{
hl.clear();
_fieldInfo.clear();
if ( ! AndQueryNode::evaluate()) return hl;
HitList tmpHL;
const QueryNodeList & children = getChildren();
unsigned int fullPhraseLen = children.size();
unsigned int currPhraseLen = 0;
std::vector<unsigned int> indexVector(fullPhraseLen, 0);
auto curr = static_cast<const QueryTerm *> (children[currPhraseLen].get());
bool exhausted( curr->evaluateHits(tmpHL).empty());
for (; !exhausted; ) {
auto next = static_cast<const QueryTerm *>(children[currPhraseLen+1].get());
unsigned int & currIndex = indexVector[currPhraseLen];
unsigned int & nextIndex = indexVector[currPhraseLen+1];
const auto & currHit = curr->evaluateHits(tmpHL)[currIndex];
size_t firstPosition = currHit.pos();
uint32_t currElemId = currHit.elemId();
uint32_t currContext = currHit.context();
const HitList & nextHL = next->evaluateHits(tmpHL);
int diff(0);
size_t nextIndexMax = nextHL.size();
while ((nextIndex < nextIndexMax) &&
((nextHL[nextIndex].context() < currContext) ||
((nextHL[nextIndex].context() == currContext) && (nextHL[nextIndex].elemId() <= currElemId))) &&
((diff = nextHL[nextIndex].pos()-firstPosition) < 1))
{
nextIndex++;
}
if ((diff == 1) && (nextHL[nextIndex].context() == currContext) && (nextHL[nextIndex].elemId() == currElemId)) {
currPhraseLen++;
if ((currPhraseLen+1) == fullPhraseLen) {
Hit h = nextHL[indexVector[currPhraseLen]];
hl.push_back(h);
const QueryTerm::FieldInfo & fi = next->getFieldInfo(h.context());
updateFieldInfo(h.context(), hl.size() - 1, fi.getFieldLength());
currPhraseLen = 0;
indexVector[0]++;
}
} else {
currPhraseLen = 0;
indexVector[currPhraseLen]++;
}
curr = static_cast<const QueryTerm *>(children[currPhraseLen].get());
exhausted = (nextIndex >= nextIndexMax) || (indexVector[currPhraseLen] >= curr->evaluateHits(tmpHL).size());
}
return hl;
}
void
PhraseQueryNode::updateFieldInfo(size_t fid, size_t offset, size_t fieldLength) const
{
if (fid >= _fieldInfo.size()) {
_fieldInfo.resize(fid + 1);
// only set hit offset and field length the first time
QueryTerm::FieldInfo & fi = _fieldInfo[fid];
fi.setHitOffset(offset);
fi.setFieldLength(fieldLength);
}
QueryTerm::FieldInfo & fi = _fieldInfo[fid];
fi.setHitCount(fi.getHitCount() + 1);
}
bool
NearQueryNode::evaluate() const
{
return AndQueryNode::evaluate();
}
void
NearQueryNode::visitMembers(vespalib::ObjectVisitor &visitor) const
{
AndQueryNode::visitMembers(visitor);
visit(visitor, "distance", static_cast<uint64_t>(_distance));
}
bool
ONearQueryNode::evaluate() const
{
bool ok(NearQueryNode::evaluate());
return ok;
}
Query::Query() = default;
Query::Query(const QueryNodeResultFactory & factory, const QueryPacketT & queryRep)
: _root()
{
build(factory, queryRep);
}
bool
Query::evaluate() const {
return valid() ? _root->evaluate() : false;
}
bool
Query::build(const QueryNodeResultFactory & factory, const QueryPacketT & queryRep)
{
search::SimpleQueryStackDumpIterator stack(queryRep);
if (stack.next()) {
_root = QueryNode::Build(nullptr, factory, stack, true);
}
return valid();
}
void
Query::getLeafs(QueryTermList & tl) {
if (valid()) {
_root->getLeafs(tl);
}
}
void
Query::getLeafs(ConstQueryTermList & tl) const {
if (valid()) {
_root->getLeafs(tl);
}
}
void
Query::getPhrases(QueryNodeRefList & tl) {
if (valid()) {
_root->getPhrases(tl);
}
}
void
Query::getPhrases(ConstQueryNodeRefList & tl) const {
if (valid()) {
_root->getPhrases(tl);
}
}
void
Query::reset() {
if (valid()) {
_root->reset();
}
}
size_t
Query::depth() const {
return valid() ? _root->depth() : 0;
}
size_t
Query::width() const {
return valid() ? _root->width() : 0;
}
}
<commit_msg>Return true from AndNot when no children at all.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "query.h"
#include <vespa/searchlib/parsequery/stackdumpiterator.h>
#include <vespa/vespalib/objects/visit.hpp>
#include <cassert>
namespace search::streaming {
void
QueryConnector::visitMembers(vespalib::ObjectVisitor &visitor) const
{
visit(visitor, "Operator", _opName);
}
QueryConnector::QueryConnector(const char * opName)
: QueryNode(),
_opName(opName),
_index(),
_children()
{
}
void
QueryConnector::addChild(QueryNode::UP child) {
_children.push_back(std::move(child));
}
QueryConnector::~QueryConnector() = default;
const HitList &
QueryConnector::evaluateHits(HitList & hl) const
{
if (evaluate()) {
hl.push_back(Hit(1, 0, 0, 1));
}
return hl;
}
void
QueryConnector::reset()
{
for (const auto & node : _children) {
node->reset();
}
}
void
QueryConnector::getLeafs(QueryTermList & tl)
{
for (const auto & node : _children) {
node->getLeafs(tl);
}
}
void
QueryConnector::getLeafs(ConstQueryTermList & tl) const
{
for (const auto & node : _children) {
node->getLeafs(tl);
}
}
void
QueryConnector::getPhrases(QueryNodeRefList & tl)
{
for (const auto & node : _children) {
node->getPhrases(tl);
}
}
void
QueryConnector::getPhrases(ConstQueryNodeRefList & tl) const
{
for (const auto & node : _children) {
node->getPhrases(tl);
}
}
size_t
QueryConnector::depth() const
{
size_t d(0);
for (const auto & node : _children) {
size_t t = node->depth();
if (t > d) {
d = t;
}
}
return d+1;
}
size_t
QueryConnector::width() const
{
size_t w(0);
for (const auto & node : _children) {
w += node->width();
}
return w;
}
std::unique_ptr<QueryConnector>
QueryConnector::create(ParseItem::ItemType type)
{
switch (type) {
case search::ParseItem::ITEM_AND: return std::make_unique<AndQueryNode>();
case search::ParseItem::ITEM_OR: return std::make_unique<OrQueryNode>();
case search::ParseItem::ITEM_WEAK_AND: return std::make_unique<OrQueryNode>();
case search::ParseItem::ITEM_EQUIV: return std::make_unique<EquivQueryNode>();
case search::ParseItem::ITEM_WEIGHTED_SET: return std::make_unique<EquivQueryNode>();
case search::ParseItem::ITEM_DOT_PRODUCT: return std::make_unique<OrQueryNode>();
case search::ParseItem::ITEM_WAND: return std::make_unique<OrQueryNode>();
case search::ParseItem::ITEM_NOT: return std::make_unique<AndNotQueryNode>();
case search::ParseItem::ITEM_PHRASE: return std::make_unique<PhraseQueryNode>();
case search::ParseItem::ITEM_SAME_ELEMENT: return std::make_unique<SameElementQueryNode>();
case search::ParseItem::ITEM_NEAR: return std::make_unique<NearQueryNode>();
case search::ParseItem::ITEM_ONEAR: return std::make_unique<ONearQueryNode>();
default: return nullptr;
}
}
bool
TrueNode::evaluate() const
{
return true;
}
bool
AndQueryNode::evaluate() const
{
for (const auto & qn : getChildren()) {
if ( ! qn->evaluate() ) return false;
}
return true;
}
bool
AndNotQueryNode::evaluate() const {
if (getChildren().empty()) return true;
auto it = getChildren().begin();
auto mt = getChildren().end();
if ((*it)->evaluate()) {
for (++it; it != mt; it++) {
if ((*it)->evaluate()) return false;
}
return true;
}
return false;
}
bool
OrQueryNode::evaluate() const {
for (const auto & qn : getChildren()) {
if (qn->evaluate()) return true;
}
return false;
}
bool
EquivQueryNode::evaluate() const
{
return OrQueryNode::evaluate();
}
bool
SameElementQueryNode::evaluate() const {
HitList hl;
return ! evaluateHits(hl).empty();
}
void
SameElementQueryNode::addChild(QueryNode::UP child) {
assert(dynamic_cast<const QueryTerm *>(child.get()) != nullptr);
AndQueryNode::addChild(std::move(child));
}
const HitList &
SameElementQueryNode::evaluateHits(HitList & hl) const
{
hl.clear();
if ( !AndQueryNode::evaluate()) return hl;
HitList tmpHL;
const auto & children = getChildren();
unsigned int numFields = children.size();
unsigned int currMatchCount = 0;
std::vector<unsigned int> indexVector(numFields, 0);
auto curr = static_cast<const QueryTerm *> (children[currMatchCount].get());
bool exhausted( curr->evaluateHits(tmpHL).empty());
for (; !exhausted; ) {
auto next = static_cast<const QueryTerm *>(children[currMatchCount+1].get());
unsigned int & currIndex = indexVector[currMatchCount];
unsigned int & nextIndex = indexVector[currMatchCount+1];
const auto & currHit = curr->evaluateHits(tmpHL)[currIndex];
uint32_t currElemId = currHit.elemId();
const HitList & nextHL = next->evaluateHits(tmpHL);
size_t nextIndexMax = nextHL.size();
while ((nextIndex < nextIndexMax) && (nextHL[nextIndex].elemId() < currElemId)) {
nextIndex++;
}
if ((nextIndex < nextIndexMax) && (nextHL[nextIndex].elemId() == currElemId)) {
currMatchCount++;
if ((currMatchCount+1) == numFields) {
Hit h = nextHL[indexVector[currMatchCount]];
hl.emplace_back(0, h.context(), h.elemId(), h.weight());
currMatchCount = 0;
indexVector[0]++;
}
} else {
currMatchCount = 0;
indexVector[currMatchCount]++;
}
curr = static_cast<const QueryTerm *>(children[currMatchCount].get());
exhausted = (nextIndex >= nextIndexMax) || (indexVector[currMatchCount] >= curr->evaluateHits(tmpHL).size());
}
return hl;
}
bool
PhraseQueryNode::evaluate() const
{
HitList hl;
return ! evaluateHits(hl).empty();
}
void PhraseQueryNode::getPhrases(QueryNodeRefList & tl) { tl.push_back(this); }
void PhraseQueryNode::getPhrases(ConstQueryNodeRefList & tl) const { tl.push_back(this); }
void
PhraseQueryNode::addChild(QueryNode::UP child) {
assert(dynamic_cast<const QueryTerm *>(child.get()) != nullptr);
AndQueryNode::addChild(std::move(child));
}
const HitList &
PhraseQueryNode::evaluateHits(HitList & hl) const
{
hl.clear();
_fieldInfo.clear();
if ( ! AndQueryNode::evaluate()) return hl;
HitList tmpHL;
const auto & children = getChildren();
unsigned int fullPhraseLen = children.size();
unsigned int currPhraseLen = 0;
std::vector<unsigned int> indexVector(fullPhraseLen, 0);
auto curr = static_cast<const QueryTerm *> (children[currPhraseLen].get());
bool exhausted( curr->evaluateHits(tmpHL).empty());
for (; !exhausted; ) {
auto next = static_cast<const QueryTerm *>(children[currPhraseLen+1].get());
unsigned int & currIndex = indexVector[currPhraseLen];
unsigned int & nextIndex = indexVector[currPhraseLen+1];
const auto & currHit = curr->evaluateHits(tmpHL)[currIndex];
size_t firstPosition = currHit.pos();
uint32_t currElemId = currHit.elemId();
uint32_t currContext = currHit.context();
const HitList & nextHL = next->evaluateHits(tmpHL);
int diff(0);
size_t nextIndexMax = nextHL.size();
while ((nextIndex < nextIndexMax) &&
((nextHL[nextIndex].context() < currContext) ||
((nextHL[nextIndex].context() == currContext) && (nextHL[nextIndex].elemId() <= currElemId))) &&
((diff = nextHL[nextIndex].pos()-firstPosition) < 1))
{
nextIndex++;
}
if ((diff == 1) && (nextHL[nextIndex].context() == currContext) && (nextHL[nextIndex].elemId() == currElemId)) {
currPhraseLen++;
if ((currPhraseLen+1) == fullPhraseLen) {
Hit h = nextHL[indexVector[currPhraseLen]];
hl.push_back(h);
const QueryTerm::FieldInfo & fi = next->getFieldInfo(h.context());
updateFieldInfo(h.context(), hl.size() - 1, fi.getFieldLength());
currPhraseLen = 0;
indexVector[0]++;
}
} else {
currPhraseLen = 0;
indexVector[currPhraseLen]++;
}
curr = static_cast<const QueryTerm *>(children[currPhraseLen].get());
exhausted = (nextIndex >= nextIndexMax) || (indexVector[currPhraseLen] >= curr->evaluateHits(tmpHL).size());
}
return hl;
}
void
PhraseQueryNode::updateFieldInfo(size_t fid, size_t offset, size_t fieldLength) const
{
if (fid >= _fieldInfo.size()) {
_fieldInfo.resize(fid + 1);
// only set hit offset and field length the first time
QueryTerm::FieldInfo & fi = _fieldInfo[fid];
fi.setHitOffset(offset);
fi.setFieldLength(fieldLength);
}
QueryTerm::FieldInfo & fi = _fieldInfo[fid];
fi.setHitCount(fi.getHitCount() + 1);
}
bool
NearQueryNode::evaluate() const
{
return AndQueryNode::evaluate();
}
void
NearQueryNode::visitMembers(vespalib::ObjectVisitor &visitor) const
{
AndQueryNode::visitMembers(visitor);
visit(visitor, "distance", static_cast<uint64_t>(_distance));
}
bool
ONearQueryNode::evaluate() const
{
bool ok(NearQueryNode::evaluate());
return ok;
}
Query::Query() = default;
Query::Query(const QueryNodeResultFactory & factory, const QueryPacketT & queryRep)
: _root()
{
build(factory, queryRep);
}
bool
Query::evaluate() const {
return valid() ? _root->evaluate() : false;
}
bool
Query::build(const QueryNodeResultFactory & factory, const QueryPacketT & queryRep)
{
search::SimpleQueryStackDumpIterator stack(queryRep);
if (stack.next()) {
_root = QueryNode::Build(nullptr, factory, stack, true);
}
return valid();
}
void
Query::getLeafs(QueryTermList & tl) {
if (valid()) {
_root->getLeafs(tl);
}
}
void
Query::getLeafs(ConstQueryTermList & tl) const {
if (valid()) {
_root->getLeafs(tl);
}
}
void
Query::getPhrases(QueryNodeRefList & tl) {
if (valid()) {
_root->getPhrases(tl);
}
}
void
Query::getPhrases(ConstQueryNodeRefList & tl) const {
if (valid()) {
_root->getPhrases(tl);
}
}
void
Query::reset() {
if (valid()) {
_root->reset();
}
}
size_t
Query::depth() const {
return valid() ? _root->depth() : 0;
}
size_t
Query::width() const {
return valid() ? _root->width() : 0;
}
}
<|endoftext|> |
<commit_before>
#include "Module.h"
namespace HttpServer
{
Module::Module(): lib_handle(nullptr)
{
}
Module::Module(const std::string &libPath): lib_handle(nullptr)
{
open(libPath);
}
Module::Module(const Module &module) : lib_handle(module.lib_handle)
{
}
Module::Module(Module &&module) : lib_handle(module.lib_handle)
{
module.lib_handle = nullptr;
}
bool Module::open(const std::string &libPath)
{
if (is_open() )
{
close();
}
#ifdef WIN32
const size_t pos_slash = libPath.rfind('\\');
const size_t pos_slash_back = libPath.rfind('/');
size_t pos = std::string::npos;
if (pos_slash != std::string::npos && pos_slash > pos_slash_back)
{
pos = pos_slash;
}
else if (pos_slash_back != std::string::npos)
{
pos = pos_slash_back;
}
DLL_DIRECTORY_COOKIE cookie = nullptr;
if (std::string::npos != pos)
{
std::wstring directory(libPath.cbegin(), libPath.cbegin() + pos + 1);
cookie = ::AddDllDirectory(directory.data() );
}
lib_handle = ::LoadLibraryEx(libPath.c_str(), 0, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
if (cookie)
{
::RemoveDllDirectory(cookie);
}
#elif POSIX
lib_handle = ::dlopen(libPath.c_str(), RTLD_NOW | RTLD_LOCAL);
#else
#error "Undefine platform"
#endif
if (nullptr == lib_handle)
{
#ifdef POSIX
std::cout << ::dlerror() << std::endl;
#endif
return false;
}
return true;
}
void Module::close()
{
if (lib_handle)
{
#ifdef WIN32
::FreeLibrary(lib_handle);
#elif POSIX
::dlclose(lib_handle);
#else
#error "Undefine platform"
#endif
lib_handle = nullptr;
}
}
bool Module::find(const std::string &symbolName, void *(**addr)(void *) ) const
{
if (lib_handle)
{
#ifdef WIN32
*addr = reinterpret_cast<void *(*)(void *)>(::GetProcAddress(lib_handle, symbolName.c_str() ) );
return nullptr != *addr;
#elif POSIX
char *error = ::dlerror();
*addr = reinterpret_cast<void *(*)(void *)>(::dlsym(lib_handle, symbolName.c_str() ) );
error = ::dlerror();
return nullptr == error;
#else
#error "Undefine platform"
#endif
}
return false;
}
bool Module::find(const char *symbolName, void *(**addr)(void *) ) const
{
if (lib_handle)
{
#ifdef WIN32
*addr = reinterpret_cast<void *(*)(void *)>(::GetProcAddress(lib_handle, symbolName) );
return nullptr != *addr;
#elif POSIX
char *error = ::dlerror();
*addr = reinterpret_cast<void *(*)(void *)>(::dlsym(lib_handle, symbolName) );
error = ::dlerror();
return nullptr == error;
#else
#error "Undefine platform"
#endif
}
return false;
}
Module &Module::operator =(const Module &module)
{
if (*this != module)
{
close();
lib_handle = module.lib_handle;
}
return *this;
}
Module &Module::operator =(Module &&module)
{
if (*this != module)
{
close();
lib_handle = module.lib_handle;
module.lib_handle = nullptr;
}
return *this;
}
};<commit_msg>Fix to POSIX system<commit_after>
#include "Module.h"
#include <iostream>
namespace HttpServer
{
Module::Module(): lib_handle(nullptr)
{
}
Module::Module(const std::string &libPath): lib_handle(nullptr)
{
open(libPath);
}
Module::Module(const Module &module) : lib_handle(module.lib_handle)
{
}
Module::Module(Module &&module) : lib_handle(module.lib_handle)
{
module.lib_handle = nullptr;
}
bool Module::open(const std::string &libPath)
{
if (is_open() )
{
close();
}
#ifdef WIN32
const size_t pos_slash = libPath.rfind('\\');
const size_t pos_slash_back = libPath.rfind('/');
size_t pos = std::string::npos;
if (pos_slash != std::string::npos && pos_slash > pos_slash_back)
{
pos = pos_slash;
}
else if (pos_slash_back != std::string::npos)
{
pos = pos_slash_back;
}
DLL_DIRECTORY_COOKIE cookie = nullptr;
if (std::string::npos != pos)
{
std::wstring directory(libPath.cbegin(), libPath.cbegin() + pos + 1);
cookie = ::AddDllDirectory(directory.data() );
}
lib_handle = ::LoadLibraryEx(libPath.c_str(), 0, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
if (cookie)
{
::RemoveDllDirectory(cookie);
}
#elif POSIX
lib_handle = ::dlopen(libPath.c_str(), RTLD_NOW | RTLD_LOCAL);
#else
#error "Undefine platform"
#endif
if (nullptr == lib_handle)
{
#ifdef POSIX
std::cout << ::dlerror() << std::endl;
#endif
return false;
}
return true;
}
void Module::close()
{
if (lib_handle)
{
#ifdef WIN32
::FreeLibrary(lib_handle);
#elif POSIX
::dlclose(lib_handle);
#else
#error "Undefine platform"
#endif
lib_handle = nullptr;
}
}
bool Module::find(const std::string &symbolName, void *(**addr)(void *) ) const
{
if (lib_handle)
{
#ifdef WIN32
*addr = reinterpret_cast<void *(*)(void *)>(::GetProcAddress(lib_handle, symbolName.c_str() ) );
return nullptr != *addr;
#elif POSIX
char *error = ::dlerror();
*addr = reinterpret_cast<void *(*)(void *)>(::dlsym(lib_handle, symbolName.c_str() ) );
error = ::dlerror();
return nullptr == error;
#else
#error "Undefine platform"
#endif
}
return false;
}
bool Module::find(const char *symbolName, void *(**addr)(void *) ) const
{
if (lib_handle)
{
#ifdef WIN32
*addr = reinterpret_cast<void *(*)(void *)>(::GetProcAddress(lib_handle, symbolName) );
return nullptr != *addr;
#elif POSIX
char *error = ::dlerror();
*addr = reinterpret_cast<void *(*)(void *)>(::dlsym(lib_handle, symbolName) );
error = ::dlerror();
return nullptr == error;
#else
#error "Undefine platform"
#endif
}
return false;
}
Module &Module::operator =(const Module &module)
{
if (*this != module)
{
close();
lib_handle = module.lib_handle;
}
return *this;
}
Module &Module::operator =(Module &&module)
{
if (*this != module)
{
close();
lib_handle = module.lib_handle;
module.lib_handle = nullptr;
}
return *this;
}
};<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Test mesh collision
//
// =============================================================================
#include "chrono/ChConfig.h"
#include "chrono/physics/ChSystemNSC.h"
#include "chrono/physics/ChSystemSMC.h"
#include "chrono_irrlicht/ChIrrApp.h"
using namespace chrono;
using namespace chrono::irrlicht;
// ====================================================================================
int main(int argc, char* argv[]) {
// ---------------------
// Simulation parameters
// ---------------------
double gravity = 9.81; // gravitational acceleration
double time_step = 1e-4; // integration step size
// ---------------------------
// Contact material properties
// ---------------------------
ChMaterialSurface::ContactMethod contact_method = ChMaterialSurface::SMC;
bool use_mat_properties = true;
float object_friction = 0.9f;
float object_restitution = 0.1f;
float object_young_modulus = 2e7f;
float object_poisson_ratio = 0.3f;
float object_adhesion = 0.0f;
float object_kn = 2e5;
float object_gn = 40;
float object_kt = 2e5;
float object_gt = 20;
float ground_friction = 0.9f;
float ground_restitution = 0.01f;
float ground_young_modulus = 2e7f;
float ground_poisson_ratio = 0.3f;
float ground_adhesion = 0.0f;
float ground_kn = 2e5;
float ground_gn = 40;
float ground_kt = 2e5;
float ground_gt = 20;
// ---------------------------------
// Parameters for the falling object
// ---------------------------------
int objectId = 100;
double mass = 1000;
ChVector<> pos(0, 0, 1);
ChQuaternion<> rot(1, 0, 0, 0);
ChVector<> init_vel(0, 0, 0);
ChVector<> init_omg(0, 0, 0);
// ---------------------------------
// Parameters for the containing bin
// ---------------------------------
int groundId = 200;
double width = 2;
double length = 1;
double thickness = 0.1;
// -----------------
// Create the system
// -----------------
ChSystem* system;
switch (contact_method) {
case ChMaterialSurface::NSC:
system = new ChSystemNSC();
break;
case ChMaterialSurface::SMC:
system = new ChSystemSMC(use_mat_properties);
break;
}
system->Set_G_acc(ChVector<>(0, 0, -gravity));
// Create the Irrlicht visualization
ChIrrApp application(system, L"mesh collision", irr::core::dimension2d<irr::u32>(800, 600), false, true);
// Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene
application.AddTypicalLogo();
application.AddTypicalSky();
application.AddTypicalLights();
application.AddTypicalCamera(irr::core::vector3df(0, 4, -0.2f), irr::core::vector3df(0, 0, 0));
// This means that contact forces will be shown in Irrlicht application
application.SetSymbolscale(1e-4);
application.SetContactsDrawMode(ChIrrTools::eCh_ContactsDrawMode::CONTACT_FORCES);
// Create the falling object
auto object = std::shared_ptr<ChBody>(system->NewBody());
system->AddBody(object);
object->SetIdentifier(objectId);
object->SetMass(mass);
object->SetInertiaXX(400.0 * ChVector<>(1, 1, 1));
object->SetPos(pos);
object->SetRot(rot);
object->SetPos_dt(init_vel);
object->SetWvel_par(init_omg);
object->SetCollide(true);
object->SetBodyFixed(false);
switch (object->GetContactMethod()) {
case ChMaterialSurface::NSC:
object->GetMaterialSurfaceNSC()->SetFriction(object_friction);
object->GetMaterialSurfaceNSC()->SetRestitution(object_restitution);
break;
case ChMaterialSurface::SMC:
object->GetMaterialSurfaceSMC()->SetFriction(object_friction);
object->GetMaterialSurfaceSMC()->SetRestitution(object_restitution);
object->GetMaterialSurfaceSMC()->SetYoungModulus(object_young_modulus);
object->GetMaterialSurfaceSMC()->SetPoissonRatio(object_poisson_ratio);
object->GetMaterialSurfaceSMC()->SetKn(object_kn);
object->GetMaterialSurfaceSMC()->SetGn(object_gn);
object->GetMaterialSurfaceSMC()->SetKt(object_kt);
object->GetMaterialSurfaceSMC()->SetGt(object_gt);
break;
}
auto trimesh = chrono_types::make_shared<geometry::ChTriangleMeshConnected>();
trimesh->LoadWavefrontMesh(GetChronoDataFile("vehicle/hmmwv/hmmwv_tire.obj"), true, false);
object->GetCollisionModel()->ClearModel();
object->GetCollisionModel()->AddTriangleMesh(trimesh, false, false, ChVector<>(0), ChMatrix33<>(1), 0.01);
object->GetCollisionModel()->BuildModel();
auto trimesh_shape = chrono_types::make_shared<ChTriangleMeshShape>();
trimesh_shape->SetMesh(trimesh);
object->AddAsset(trimesh_shape);
std::shared_ptr<ChColorAsset> mcol(new ChColorAsset);
mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f));
object->AddAsset(mcol);
// Create ground body
auto ground = std::shared_ptr<ChBody>(system->NewBody());
system->AddBody(ground);
ground->SetIdentifier(groundId);
ground->SetMass(1);
ground->SetPos(ChVector<>(0, 0, 0));
ground->SetRot(ChQuaternion<>(1, 0, 0, 0));
ground->SetCollide(true);
ground->SetBodyFixed(true);
switch (object->GetContactMethod()) {
case ChMaterialSurface::NSC:
ground->GetMaterialSurfaceNSC()->SetFriction(ground_friction);
ground->GetMaterialSurfaceNSC()->SetRestitution(ground_restitution);
break;
case ChMaterialSurface::SMC:
ground->GetMaterialSurfaceSMC()->SetFriction(ground_friction);
ground->GetMaterialSurfaceSMC()->SetRestitution(ground_restitution);
ground->GetMaterialSurfaceSMC()->SetYoungModulus(ground_young_modulus);
ground->GetMaterialSurfaceSMC()->SetPoissonRatio(ground_poisson_ratio);
ground->GetMaterialSurfaceSMC()->SetKn(ground_kn);
ground->GetMaterialSurfaceSMC()->SetGn(ground_gn);
ground->GetMaterialSurfaceSMC()->SetKt(ground_kt);
ground->GetMaterialSurfaceSMC()->SetGt(ground_gt);
break;
}
ground->GetCollisionModel()->ClearModel();
ground->GetCollisionModel()->AddBox(width, length, thickness, ChVector<>(0, 0, -thickness));
ground->GetCollisionModel()->BuildModel();
auto box = chrono_types::make_shared<ChBoxShape>();
box->GetBoxGeometry().Size = ChVector<>(width, length, thickness);
box->GetBoxGeometry().Pos = ChVector<>(0, 0, -thickness);
ground->AddAsset(box);
// Complete asset construction
application.AssetBindAll();
application.AssetUpdateAll();
// ---------------
// Simulation loop
// ---------------
while (application.GetDevice()->run()) {
application.BeginScene();
application.DrawAll();
system->DoStepDynamics(time_step);
application.EndScene();
}
return 0;
}
<commit_msg>Modify test_CTC_mesh to check both mesh-mesh and mesh-box collision<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Test mesh collision
//
// =============================================================================
#include "chrono/ChConfig.h"
#include "chrono/physics/ChSystemNSC.h"
#include "chrono/physics/ChSystemSMC.h"
#include "chrono_irrlicht/ChIrrApp.h"
using namespace chrono;
using namespace chrono::irrlicht;
// ====================================================================================
int main(int argc, char* argv[]) {
// ---------------------
// Simulation parameters
// ---------------------
double gravity = 9.81; // gravitational acceleration
double time_step = 1e-4; // integration step size
enum class ContactType {
MESH_BOX, // use box for ground collision model
MESH_MESH // use mesh for ground collision model
};
ContactType contact_type = ContactType::MESH_MESH;
double mesh_swept_sphere_radius = 0.005;
// ---------------------------
// Contact material properties
// ---------------------------
ChMaterialSurface::ContactMethod contact_method = ChMaterialSurface::SMC;
bool use_mat_properties = true;
float object_friction = 0.9f;
float object_restitution = 0.1f;
float object_young_modulus = 2e7f;
float object_poisson_ratio = 0.3f;
float object_adhesion = 0.0f;
float object_kn = 2e5;
float object_gn = 40;
float object_kt = 2e5;
float object_gt = 20;
float ground_friction = 0.9f;
float ground_restitution = 0.01f;
float ground_young_modulus = 1e6f;
float ground_poisson_ratio = 0.3f;
float ground_adhesion = 0.0f;
float ground_kn = 2e5;
float ground_gn = 40;
float ground_kt = 2e5;
float ground_gt = 20;
// ---------------------------------
// Parameters for the falling object
// ---------------------------------
ChVector<> pos(0, 0.75, 0);
ChVector<> init_vel(0, 0, 0);
ChVector<> init_omg(0, 0, 0);
// ---------------------------------
// Parameters for the containing bin
// ---------------------------------
double width = 2;
double length = 1;
double thickness = 0.1;
// -----------------
// Create the system
// -----------------
ChSystem* system;
switch (contact_method) {
case ChMaterialSurface::NSC:
system = new ChSystemNSC();
break;
case ChMaterialSurface::SMC:
system = new ChSystemSMC(use_mat_properties);
break;
}
system->Set_G_acc(ChVector<>(0, -gravity, 0));
// Create the Irrlicht visualization
ChIrrApp application(system, L"mesh collision", irr::core::dimension2d<irr::u32>(800, 600), false, true);
// Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene
application.AddTypicalLogo();
application.AddTypicalSky();
application.AddTypicalLights();
application.AddTypicalCamera(irr::core::vector3df(0.5, 1, -2), irr::core::vector3df(0, 0, 0));
// This means that contact forces will be shown in Irrlicht application
application.SetSymbolscale(5e-3);
application.SetContactsDrawMode(ChIrrTools::eCh_ContactsDrawMode::CONTACT_FORCES);
// Rotation Z->Y (becauset meshes used here assume Z up)
ChQuaternion<> z2y = Q_from_AngX(-CH_C_PI_2);
// Create the falling object
auto object = std::shared_ptr<ChBody>(system->NewBody());
system->AddBody(object);
object->SetMass(200);
object->SetInertiaXX(40.0 * ChVector<>(1, 1, 0.2));
object->SetPos(pos);
object->SetRot(z2y);
object->SetPos_dt(init_vel);
object->SetWvel_par(init_omg);
object->SetCollide(true);
object->SetBodyFixed(false);
switch (object->GetContactMethod()) {
case ChMaterialSurface::NSC:
object->GetMaterialSurfaceNSC()->SetFriction(object_friction);
object->GetMaterialSurfaceNSC()->SetRestitution(object_restitution);
break;
case ChMaterialSurface::SMC:
object->GetMaterialSurfaceSMC()->SetFriction(object_friction);
object->GetMaterialSurfaceSMC()->SetRestitution(object_restitution);
object->GetMaterialSurfaceSMC()->SetYoungModulus(object_young_modulus);
object->GetMaterialSurfaceSMC()->SetPoissonRatio(object_poisson_ratio);
object->GetMaterialSurfaceSMC()->SetKn(object_kn);
object->GetMaterialSurfaceSMC()->SetGn(object_gn);
object->GetMaterialSurfaceSMC()->SetKt(object_kt);
object->GetMaterialSurfaceSMC()->SetGt(object_gt);
break;
}
auto trimesh = chrono_types::make_shared<geometry::ChTriangleMeshConnected>();
trimesh->LoadWavefrontMesh(GetChronoDataFile("vehicle/hmmwv/hmmwv_tire.obj"), true, false);
object->GetCollisionModel()->ClearModel();
object->GetCollisionModel()->AddTriangleMesh(trimesh, false, false, ChVector<>(0), ChMatrix33<>(1),
mesh_swept_sphere_radius);
object->GetCollisionModel()->BuildModel();
auto trimesh_shape = chrono_types::make_shared<ChTriangleMeshShape>();
trimesh_shape->SetMesh(trimesh);
object->AddAsset(trimesh_shape);
std::shared_ptr<ChColorAsset> mcol(new ChColorAsset);
mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f));
object->AddAsset(mcol);
// Create ground body
auto ground = std::shared_ptr<ChBody>(system->NewBody());
system->AddBody(ground);
ground->SetMass(1);
ground->SetPos(ChVector<>(0, 0, 0));
ground->SetRot(z2y);
ground->SetCollide(true);
ground->SetBodyFixed(true);
switch (object->GetContactMethod()) {
case ChMaterialSurface::NSC:
ground->GetMaterialSurfaceNSC()->SetFriction(ground_friction);
ground->GetMaterialSurfaceNSC()->SetRestitution(ground_restitution);
break;
case ChMaterialSurface::SMC:
ground->GetMaterialSurfaceSMC()->SetFriction(ground_friction);
ground->GetMaterialSurfaceSMC()->SetRestitution(ground_restitution);
ground->GetMaterialSurfaceSMC()->SetYoungModulus(ground_young_modulus);
ground->GetMaterialSurfaceSMC()->SetPoissonRatio(ground_poisson_ratio);
ground->GetMaterialSurfaceSMC()->SetKn(ground_kn);
ground->GetMaterialSurfaceSMC()->SetGn(ground_gn);
ground->GetMaterialSurfaceSMC()->SetKt(ground_kt);
ground->GetMaterialSurfaceSMC()->SetGt(ground_gt);
break;
}
switch (contact_type) {
case ContactType::MESH_BOX: {
ground->GetCollisionModel()->ClearModel();
ground->GetCollisionModel()->AddBox(width, length, thickness, ChVector<>(0, 0, -thickness));
ground->GetCollisionModel()->BuildModel();
auto box = chrono_types::make_shared<ChBoxShape>();
box->GetBoxGeometry().Size = ChVector<>(width, length, thickness);
box->GetBoxGeometry().Pos = ChVector<>(0, 0, -thickness);
ground->AddAsset(box);
break;
}
case ContactType::MESH_MESH: {
auto trimesh_ground = chrono_types::make_shared<geometry::ChTriangleMeshConnected>();
trimesh_ground->LoadWavefrontMesh(GetChronoDataFile("vehicle/terrain/meshes/ramp_10x1.obj"), true, false);
ground->GetCollisionModel()->ClearModel();
ground->GetCollisionModel()->AddTriangleMesh(trimesh_ground, false, false, ChVector<>(0), ChMatrix33<>(1),
mesh_swept_sphere_radius);
ground->GetCollisionModel()->BuildModel();
auto trimesh_ground_shape = chrono_types::make_shared<ChTriangleMeshShape>();
trimesh_ground_shape->SetMesh(trimesh_ground);
ground->AddAsset(trimesh_ground_shape);
break;
}
}
// Complete asset construction
application.AssetBindAll();
application.AssetUpdateAll();
// ---------------
// Simulation loop
// ---------------
while (application.GetDevice()->run()) {
application.BeginScene();
application.DrawAll();
system->DoStepDynamics(time_step);
application.EndScene();
}
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2016-2019 INRA
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ORG_VLEPROJECT_BARYONYX_SOLVER_PRIVATE_HPP
#define ORG_VLEPROJECT_BARYONYX_SOLVER_PRIVATE_HPP
#include <baryonyx/core>
#include <unordered_map>
#include <utility>
#include <fmt/color.h>
#include <fmt/format.h>
#include <cstdio>
#define bx_stringify_detail(x) #x
#define bx_stringify(x) bx_stringify_detail(x)
#if defined(__clang__) || defined(__GNUC__)
#define bx_always_inline __attribute__((always_inline))
#define bx_likely(x) __builtin_expect(!!(x), 1)
#define bx_unlikely(x) __builtin_expect(!!(x), 0)
#else
#define bx_always_inline
#define bx_likely(x) (!!(x))
#define bx_unlikely(x) (!!(x))
#endif
namespace baryonyx {
struct context
{
enum class message_type
{
emerg = 0, ///< system is unusable
alert, ///< action must be taken immediately
crit, ///< critical conditions
err, ///< error conditions
warning, ///< warning conditions
notice, ///< normal, but significant, condition
info, ///< informational message
debug, ///< debug-level message
};
static const fmt::text_style message_style[];
static message_type convert_verbose_level(int level) noexcept
{
return static_cast<context::message_type>(std::clamp(level, 0, 7));
}
context(int verbose_level = 6)
: log_priority(convert_verbose_level(verbose_level))
{}
solver_parameters parameters;
std::string method;
solver_started_cb start;
solver_updated_cb update;
solver_finished_cb finish;
message_type log_priority = context::message_type::info;
};
namespace details {
#ifdef __unix__
#define error_symbol "\u26d4 "
#define warning_symbol "\u26a0 "
#else
#define error_symbol ""
#define warning_symbol ""
#endif
} // namespace details
template<typename... Args>
void to_log([[maybe_unused]] std::FILE* os,
[[maybe_unused]] const std::string_view fmt,
[[maybe_unused]] const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
#ifdef BARYONYX_ENABLE_DEBUG
fmt::print(os, fmt, args...);
#endif
#endif
}
template<typename... Args>
void to_log([[maybe_unused]] std::FILE* os,
[[maybe_unused]] unsigned indent,
[[maybe_unused]] const std::string_view fmt,
[[maybe_unused]] const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
#ifdef BARYONYX_ENABLE_DEBUG
fmt::print(os, "{:{}}", "", indent);
fmt::print(os, fmt, args...);
#endif
#endif
}
inline bool
is_loggable(context::message_type current_level,
int level) noexcept
{
return static_cast<int>(current_level) >= level;
}
template<typename... Args>
void
log(FILE* out, int style, const char* fmt, const Args&... args)
{
fmt::print(out, context::message_style[style], fmt, args...);
}
template<typename... Args>
void
log(FILE* out, int style, const char* msg)
{
fmt::print(out, context::message_style[style], msg);
}
template<typename T>
void
log(FILE* out, int style, const T& msg)
{
fmt::print(out, context::message_style[style], "{}", msg);
}
namespace detail {
struct sink
{
template<typename... Args>
sink(const Args&...)
{}
};
}
template<typename... Args>
void
emerg(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 0))
return;
log(stderr, 0, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
alert(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 1))
return;
log(stderr, 1, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
crit(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 2))
return;
log(stderr, 2, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
error(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 3))
return;
log(stderr, 3, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
warning(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 4))
return;
log(stderr, 4, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
notice(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 5))
return;
log(stdout, 5, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
info(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 6))
return;
log(stdout, 6, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
debug(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
#ifdef BARYONYX_ENABLE_DEBUG
if (!is_loggable(ctx->log_priority, 7))
return;
log(stdout, 7, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename Arg1, typename... Args>
void
emerg(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 0))
return;
log(stderr, 0, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
alert(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 1))
return;
log(stderr, 1, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
crit(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 2))
return;
log(stderr, 2, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
error(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 3))
return;
log(stderr, 3, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
warning(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 4))
return;
log(stderr, 4, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
notice(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 5))
return;
log(stdout, 5, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
info(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 6))
return;
log(stdout, 6, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
debug(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
#ifdef BARYONYX_ENABLE_DEBUG
if (!is_loggable(ctx->log_priority, 7))
return;
log(stdout, 7, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
////////////////////////////////////////////////
template<typename T>
void
emerg(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 0))
return;
log(stderr, 0, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
alert(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 1))
return;
log(stderr, 1, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
crit(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 2))
return;
log(stderr, 2, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
error(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 3))
return;
log(stderr, 3, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
warning(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 4))
return;
log(stderr, 4, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
notice(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 5))
return;
log(stdout, 5, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
info(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 6))
return;
log(stdout, 6, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
debug(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
#ifndef BARYONYX_ENABLE_DEBUG
if (!is_loggable(ctx->log_priority, 7))
return;
log(stdout, 7, msg);
#else
detail::sink(ctx, msg);
#endif
#else
detail::sink(ctx, msg);
#endif
}
} // namespace baryonyx
#endif
<commit_msg>private: remove dead code<commit_after>/* Copyright (C) 2016-2019 INRA
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ORG_VLEPROJECT_BARYONYX_SOLVER_PRIVATE_HPP
#define ORG_VLEPROJECT_BARYONYX_SOLVER_PRIVATE_HPP
#include <baryonyx/core>
#include <utility>
#include <fmt/color.h>
#include <fmt/format.h>
#include <cstdio>
#define bx_stringify_detail(x) #x
#define bx_stringify(x) bx_stringify_detail(x)
#if defined(__clang__) || defined(__GNUC__)
#define bx_always_inline __attribute__((always_inline))
#define bx_likely(x) __builtin_expect(!!(x), 1)
#define bx_unlikely(x) __builtin_expect(!!(x), 0)
#else
#define bx_always_inline
#define bx_likely(x) (!!(x))
#define bx_unlikely(x) (!!(x))
#endif
namespace baryonyx {
struct context
{
enum class message_type
{
emerg = 0, ///< system is unusable
alert, ///< action must be taken immediately
crit, ///< critical conditions
err, ///< error conditions
warning, ///< warning conditions
notice, ///< normal, but significant, condition
info, ///< informational message
debug, ///< debug-level message
};
static const fmt::text_style message_style[];
static message_type convert_verbose_level(int level) noexcept
{
return static_cast<context::message_type>(std::clamp(level, 0, 7));
}
context(int verbose_level = 6)
: log_priority(convert_verbose_level(verbose_level))
{}
solver_parameters parameters;
std::string method;
solver_started_cb start;
solver_updated_cb update;
solver_finished_cb finish;
message_type log_priority = context::message_type::info;
};
template<typename... Args>
void to_log([[maybe_unused]] std::FILE* os,
[[maybe_unused]] const std::string_view fmt,
[[maybe_unused]] const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
#ifdef BARYONYX_ENABLE_DEBUG
fmt::print(os, fmt, args...);
#endif
#endif
}
template<typename... Args>
void to_log([[maybe_unused]] std::FILE* os,
[[maybe_unused]] unsigned indent,
[[maybe_unused]] const std::string_view fmt,
[[maybe_unused]] const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
#ifdef BARYONYX_ENABLE_DEBUG
fmt::print(os, "{:{}}", "", indent);
fmt::print(os, fmt, args...);
#endif
#endif
}
inline bool
is_loggable(context::message_type current_level,
int level) noexcept
{
return static_cast<int>(current_level) >= level;
}
template<typename... Args>
void
log(FILE* out, int style, const char* fmt, const Args&... args)
{
fmt::print(out, context::message_style[style], fmt, args...);
}
template<typename... Args>
void
log(FILE* out, int style, const char* msg)
{
fmt::print(out, context::message_style[style], msg);
}
template<typename T>
void
log(FILE* out, int style, const T& msg)
{
fmt::print(out, context::message_style[style], "{}", msg);
}
namespace detail {
struct sink
{
template<typename... Args>
sink(const Args&...)
{}
};
}
template<typename... Args>
void
emerg(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 0))
return;
log(stderr, 0, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
alert(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 1))
return;
log(stderr, 1, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
crit(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 2))
return;
log(stderr, 2, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
error(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 3))
return;
log(stderr, 3, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
warning(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 4))
return;
log(stderr, 4, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
notice(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 5))
return;
log(stdout, 5, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
info(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 6))
return;
log(stdout, 6, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename... Args>
void
debug(const context_ptr& ctx, const char* fmt, const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
#ifdef BARYONYX_ENABLE_DEBUG
if (!is_loggable(ctx->log_priority, 7))
return;
log(stdout, 7, fmt, args...);
#else
detail::sink(ctx, fmt, args...);
#endif
#else
detail::sink(ctx, fmt, args...);
#endif
}
template<typename Arg1, typename... Args>
void
emerg(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 0))
return;
log(stderr, 0, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
alert(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 1))
return;
log(stderr, 1, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
crit(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 2))
return;
log(stderr, 2, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
error(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 3))
return;
log(stderr, 3, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
warning(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 4))
return;
log(stderr, 4, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
notice(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 5))
return;
log(stdout, 5, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
info(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 6))
return;
log(stdout, 6, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
template<typename Arg1, typename... Args>
void
debug(const context_ptr& ctx,
const char* fmt,
const Arg1& arg1,
const Args&... args)
{
#ifdef BARYONYX_ENABLE_LOG
#ifdef BARYONYX_ENABLE_DEBUG
if (!is_loggable(ctx->log_priority, 7))
return;
log(stdout, 7, fmt, arg1, args...);
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
#else
detail::sink(ctx, fmt, arg1, args...);
#endif
}
////////////////////////////////////////////////
template<typename T>
void
emerg(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 0))
return;
log(stderr, 0, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
alert(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 1))
return;
log(stderr, 1, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
crit(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 2))
return;
log(stderr, 2, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
error(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 3))
return;
log(stderr, 3, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
warning(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 4))
return;
log(stderr, 4, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
notice(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 5))
return;
log(stdout, 5, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
info(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
if (!is_loggable(ctx->log_priority, 6))
return;
log(stdout, 6, msg);
#else
detail::sink(ctx, msg);
#endif
}
template<typename T>
void
debug(const context_ptr& ctx, const T& msg)
{
#ifdef BARYONYX_ENABLE_LOG
#ifndef BARYONYX_ENABLE_DEBUG
if (!is_loggable(ctx->log_priority, 7))
return;
log(stdout, 7, msg);
#else
detail::sink(ctx, msg);
#endif
#else
detail::sink(ctx, msg);
#endif
}
} // namespace baryonyx
#endif
<|endoftext|> |
<commit_before>class JointUtils
{
public:
JointUtils (){
// Atlas:
// Note: ordering here MUST match that in AtlasControlTypes.h ***********************
atlas_joint_names = {"back_bkz", "back_bky", "back_bkx",
"neck_ay", "l_leg_hpz", "l_leg_hpx", "l_leg_hpy",
"l_leg_kny", "l_leg_aky", "l_leg_akx", "r_leg_hpz",
"r_leg_hpx", "r_leg_hpy", "r_leg_kny", "r_leg_aky",
"r_leg_akx", "l_arm_usy", "l_arm_shx", "l_arm_ely",
"l_arm_elx", "l_arm_uwy", "l_arm_mwx", "r_arm_usy",
"r_arm_shx", "r_arm_ely", "r_arm_elx", "r_arm_uwy", "r_arm_mwx"};
head_joint_names = {"hokuyo_joint","pre_spindle_cal_x_joint", "pre_spindle_cal_y_joint",
"pre_spindle_cal_z_joint", "pre_spindle_cal_roll_joint", "pre_spindle_cal_pitch_joint",
"pre_spindle_cal_yaw_joint", "post_spindle_cal_x_joint", "post_spindle_cal_y_joint",
"post_spindle_cal_z_joint", "post_spindle_cal_roll_joint", "post_spindle_cal_pitch_joint", "post_spindle_cal_yaw_joint" };
simple_head_joint_names = {"hokuyo_joint"}; // used in simulation
sandia_l_joint_names = {"left_f0_j0","left_f0_j1","left_f0_j2", "left_f1_j0","left_f1_j1","left_f1_j2",
"left_f2_j0","left_f2_j1","left_f2_j2", "left_f3_j0","left_f3_j1","left_f3_j2" };
sandia_r_joint_names = {"right_f0_j0","right_f0_j1","right_f0_j2", "right_f1_j0","right_f1_j1","right_f1_j2",
"right_f2_j0","right_f2_j1","right_f2_j2", "right_f3_j0","right_f3_j1","right_f3_j2" };
/// iRobot:
irobot_l_joint_names = {"left_finger[0]/joint_base_rotation", "left_finger[0]/joint_base",
"left_finger[0]/joint_flex", "left_finger[1]/joint_base_rotation",
"left_finger[1]/joint_base", "left_finger[1]/joint_flex",
"left_finger[2]/joint_base", "left_finger[2]/joint_flex" };
irobot_r_joint_names = {"right_finger[0]/joint_base_rotation", "right_finger[0]/joint_base",
"right_finger[0]/joint_flex", "right_finger[1]/joint_base_rotation",
"right_finger[1]/joint_base", "right_finger[1]/joint_flex",
"right_finger[2]/joint_base", "right_finger[2]/joint_flex" };
};
~JointUtils() {}
std::vector<std::string> atlas_joint_names, head_joint_names, simple_head_joint_names;
std::vector<std::string> irobot_l_joint_names, irobot_r_joint_names;
std::vector<std::string> sandia_l_joint_names, sandia_r_joint_names;
private:
};
<commit_msg>git-svn-id: https://svn.csail.mit.edu/drc/trunk@7980 c7283977-0100-402a-a91a-fa70b306dbfe<commit_after>class JointUtils
{
public:
JointUtils (){
// Atlas:
// Note: ordering here MUST match that in AtlasControlTypes.h ***********************
atlas_joint_names = {"back_bkz", "back_bky", "back_bkx",
"neck_ay", "l_leg_hpz", "l_leg_hpx", "l_leg_hpy",
"l_leg_kny", "l_leg_aky", "l_leg_akx", "r_leg_hpz",
"r_leg_hpx", "r_leg_hpy", "r_leg_kny", "r_leg_aky",
"r_leg_akx", "l_arm_usy", "l_arm_shx", "l_arm_ely",
"l_arm_elx", "l_arm_uwy", "l_arm_mwx", "r_arm_usy",
"r_arm_shx", "r_arm_ely", "r_arm_elx", "r_arm_uwy", "r_arm_mwx"};
head_joint_names = {"hokuyo_joint","pre_spindle_cal_x_joint", "pre_spindle_cal_y_joint",
"pre_spindle_cal_z_joint", "pre_spindle_cal_roll_joint", "pre_spindle_cal_pitch_joint",
"pre_spindle_cal_yaw_joint", "post_spindle_cal_x_joint", "post_spindle_cal_y_joint",
"post_spindle_cal_z_joint", "post_spindle_cal_roll_joint", "post_spindle_cal_pitch_joint", "post_spindle_cal_yaw_joint" };
simple_head_joint_names = {"hokuyo_joint"}; // used in simulation
sandia_l_joint_names = {"left_f0_j0","left_f0_j1","left_f0_j2", "left_f1_j0","left_f1_j1","left_f1_j2",
"left_f2_j0","left_f2_j1","left_f2_j2", "left_f3_j0","left_f3_j1","left_f3_j2" };
sandia_r_joint_names = {"right_f0_j0","right_f0_j1","right_f0_j2", "right_f1_j0","right_f1_j1","right_f1_j2",
"right_f2_j0","right_f2_j1","right_f2_j2", "right_f3_j0","right_f3_j1","right_f3_j2" };
/// iRobot:
irobot_l_joint_names = {"left_finger[0]/joint_base_rotation", "left_finger[0]/joint_base",
"left_finger[0]/joint_flex", "left_finger[1]/joint_base_rotation",
"left_finger[1]/joint_base", "left_finger[1]/joint_flex",
"left_finger[2]/joint_base", "left_finger[2]/joint_flex" };
irobot_r_joint_names = {"right_finger[0]/joint_base_rotation", "right_finger[0]/joint_base",
"right_finger[0]/joint_flex", "right_finger[1]/joint_base_rotation",
"right_finger[1]/joint_base", "right_finger[1]/joint_flex",
"right_finger[2]/joint_base", "right_finger[2]/joint_flex" };
/// Robotiq:
robotiq_l_joint_names = { "left_finger_1_joint_1", "left_finger_1_joint_2", "left_finger_1_joint_3",
"left_finger_2_joint_1", "left_finger_2_joint_2", "left_finger_2_joint_3",
"left_finger_middle_joint_1", "left_finger_middle_joint_2", "left_finger_middle_joint_3",
"left_palm_finger_1_joint", "left_palm_finger_2_joint"};
robotiq_r_joint_names = { "right_finger_1_joint_1", "right_finger_1_joint_2", "right_finger_1_joint_3",
"right_finger_2_joint_1", "right_finger_2_joint_2", "right_finger_2_joint_3",
"right_finger_middle_joint_1", "right_finger_middle_joint_2", "right_finger_middle_joint_3",
"right_palm_finger_1_joint", "right_palm_finger_2_joint"};
};
~JointUtils() {}
std::vector<std::string> atlas_joint_names, head_joint_names, simple_head_joint_names;
std::vector<std::string> irobot_l_joint_names, irobot_r_joint_names;
std::vector<std::string> sandia_l_joint_names, sandia_r_joint_names;
std::vector<std::string> robotiq_l_joint_names, robotiq_r_joint_names;
private:
};
<|endoftext|> |
<commit_before><commit_msg>vcl: Fix several coordinates calculations<commit_after><|endoftext|> |
<commit_before><commit_msg>Modify formatting for textureReferences<commit_after><|endoftext|> |
<commit_before>/*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2018, Marcus Rowe <undisbeliever@gmail.com>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#include "filesystemwatcher.h"
#include "abstractproject.h"
#include "abstractresourceitem.h"
#include "models/common/imagecache.h"
#include <QDebug>
#include <QDir>
#include <QFileInfo>
using namespace UnTech::GuiQt;
FilesystemWatcher::FilesystemWatcher(AbstractProject* project)
: QObject(project)
, _project(project)
, _watcher(new QFileSystemWatcher(this))
, _filenameToItems()
, _itemToFilenames()
{
Q_ASSERT(project);
connect(_watcher, &QFileSystemWatcher::fileChanged,
this, &FilesystemWatcher::onFileChanged);
connect(_project, &AbstractProject::resourceItemCreated,
this, &FilesystemWatcher::onResourceItemCreated);
connect(_project, &AbstractProject::selectedResourceChanged,
this, &FilesystemWatcher::onSelectedResourceChanged);
connect(_project, &AbstractProject::resourceItemAboutToBeRemoved,
this, &FilesystemWatcher::onResourceItemAboutToBeRemoved);
}
void FilesystemWatcher::onResourceItemCreated(AbstractResourceItem* item)
{
updateExternalFiles(item);
connect(item, &AbstractResourceItem::externalFilesChanged,
this, &FilesystemWatcher::onResourceItemExternalFilesChanged);
}
void FilesystemWatcher::onResourceItemAboutToBeRemoved(AbstractResourceItem* item)
{
removeResourceItem(item);
}
void FilesystemWatcher::onSelectedResourceChanged()
{
// Reload the watcher when the selected item is changed.
// Just in case a file that did not exist is now existing.
updateExternalFiles(_project->selectedResource());
}
void FilesystemWatcher::onResourceItemExternalFilesChanged()
{
auto* item = qobject_cast<AbstractResourceItem*>(sender());
updateExternalFiles(item);
}
void FilesystemWatcher::updateExternalFiles(AbstractResourceItem* item)
{
if (item) {
QStringList nativeFilenames = item->externalFiles();
nativeFilenames.removeAll(QString());
for (QString& fn : nativeFilenames) {
fn = QDir::toNativeSeparators(QFileInfo(fn).absoluteFilePath());
}
updateWatcherAndMaps(item, nativeFilenames);
}
}
void FilesystemWatcher::removeResourceItem(AbstractResourceItem* item)
{
if (item) {
updateWatcherAndMaps(item, QStringList());
}
}
void FilesystemWatcher::updateWatcherAndMaps(AbstractResourceItem* item, const QStringList& nativeFilenames)
{
Q_ASSERT(item);
const QStringList previousFilenames = _itemToFilenames.value(item);
{
// Always try to add the filenames to the watcher.
// It may not have existed in the past, but it could exist now.
QStringList toWatch;
toWatch.reserve(nativeFilenames.size());
for (const QString& fn : nativeFilenames) {
if (QFile::exists(fn)) {
toWatch << fn;
}
}
if (toWatch.isEmpty() == false) {
// This is more efficient then adding paths one at a time
_watcher->addPaths(toWatch);
}
}
QStringList toAdd = nativeFilenames;
for (const QString& prevFilename : previousFilenames) {
int i = toAdd.indexOf(prevFilename);
if (i >= 0) {
toAdd.removeAt(i);
}
else {
// prevFilename no longer used by item
auto it = _filenameToItems.find(prevFilename);
if (it != _filenameToItems.end()) {
it->removeAll(item);
if (it->isEmpty()) {
_watcher->removePath(prevFilename);
_filenameToItems.remove(prevFilename);
}
}
}
}
for (const QString& filename : toAdd) {
auto it = _filenameToItems.find(filename);
if (it == _filenameToItems.end()) {
it = _filenameToItems.insert(filename, {});
}
if (it->contains(item) == false) {
it->append(item);
}
}
if (nativeFilenames.isEmpty() == false) {
_itemToFilenames.insert(item, nativeFilenames);
}
else {
_itemToFilenames.remove(item);
}
if (nativeFilenames != previousFilenames) {
emit item->externalFilesModified();
}
}
void FilesystemWatcher::onFileChanged(const QString& path)
{
// If the path was replaced (ie, file copy or atomic write) then the
// watcher will automatically remove the path and we need to add it back
// again.
if (_watcher->files().contains(path) == false) {
if (QFile::exists(path)) {
_watcher->addPath(path);
}
}
QString nativePath = QDir::toNativeSeparators(path);
ImageCache::invalidateFilename(nativePath.toStdString());
auto it = _filenameToItems.find(nativePath);
if (it != _filenameToItems.end()) {
const auto& items = *it;
for (AbstractResourceItem* item : items) {
emit item->externalFilesModified();
item->markUnchecked();
}
}
else {
qWarning() << nativePath << "is not linked to a ResourceItem";
}
}
<commit_msg>Fix bug when a RI external file is deleted and then created<commit_after>/*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2018, Marcus Rowe <undisbeliever@gmail.com>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#include "filesystemwatcher.h"
#include "abstractproject.h"
#include "abstractresourceitem.h"
#include "models/common/imagecache.h"
#include <QDebug>
#include <QDir>
#include <QFileInfo>
using namespace UnTech::GuiQt;
FilesystemWatcher::FilesystemWatcher(AbstractProject* project)
: QObject(project)
, _project(project)
, _watcher(new QFileSystemWatcher(this))
, _filenameToItems()
, _itemToFilenames()
{
Q_ASSERT(project);
connect(_watcher, &QFileSystemWatcher::fileChanged,
this, &FilesystemWatcher::onFileChanged);
connect(_project, &AbstractProject::resourceItemCreated,
this, &FilesystemWatcher::onResourceItemCreated);
connect(_project, &AbstractProject::selectedResourceChanged,
this, &FilesystemWatcher::onSelectedResourceChanged);
connect(_project, &AbstractProject::resourceItemAboutToBeRemoved,
this, &FilesystemWatcher::onResourceItemAboutToBeRemoved);
}
void FilesystemWatcher::onResourceItemCreated(AbstractResourceItem* item)
{
updateExternalFiles(item);
connect(item, &AbstractResourceItem::externalFilesChanged,
this, &FilesystemWatcher::onResourceItemExternalFilesChanged);
}
void FilesystemWatcher::onResourceItemAboutToBeRemoved(AbstractResourceItem* item)
{
removeResourceItem(item);
}
void FilesystemWatcher::onSelectedResourceChanged()
{
// Reload the watcher when the selected item is changed.
// Just in case a file that did not exist is now existing.
updateExternalFiles(_project->selectedResource());
}
void FilesystemWatcher::onResourceItemExternalFilesChanged()
{
auto* item = qobject_cast<AbstractResourceItem*>(sender());
updateExternalFiles(item);
}
void FilesystemWatcher::updateExternalFiles(AbstractResourceItem* item)
{
if (item) {
QStringList nativeFilenames = item->externalFiles();
nativeFilenames.removeAll(QString());
for (QString& fn : nativeFilenames) {
fn = QDir::toNativeSeparators(QFileInfo(fn).absoluteFilePath());
}
updateWatcherAndMaps(item, nativeFilenames);
}
}
void FilesystemWatcher::removeResourceItem(AbstractResourceItem* item)
{
if (item) {
updateWatcherAndMaps(item, QStringList());
}
}
void FilesystemWatcher::updateWatcherAndMaps(AbstractResourceItem* item, const QStringList& nativeFilenames)
{
Q_ASSERT(item);
const QStringList watchedFiles = _watcher->files();
const QStringList previousFilenames = _itemToFilenames.value(item);
bool emitModified = previousFilenames != nativeFilenames;
{
// Check the watched/existing status of every filename.
// It may not have existed in the past, but it could exist now.
QStringList toWatch;
toWatch.reserve(nativeFilenames.size());
for (const QString& nativePath : nativeFilenames) {
QString path = QDir::fromNativeSeparators(nativePath);
bool fileUnwatched = watchedFiles.contains(path) == false;
bool fileExists = QFile::exists(nativePath);
if (fileUnwatched && fileExists) {
toWatch << path;
emitModified = true;
}
if (fileUnwatched || !fileExists) {
ImageCache::invalidateFilename(nativePath.toStdString());
}
}
if (toWatch.isEmpty() == false) {
// This is more efficient then adding paths one at a time
_watcher->addPaths(toWatch);
}
}
QStringList toAdd = nativeFilenames;
for (const QString& prevFilename : previousFilenames) {
int i = toAdd.indexOf(prevFilename);
if (i >= 0) {
toAdd.removeAt(i);
}
else {
// prevFilename no longer used by item
auto it = _filenameToItems.find(prevFilename);
if (it != _filenameToItems.end()) {
it->removeAll(item);
if (it->isEmpty()) {
_watcher->removePath(prevFilename);
_filenameToItems.remove(prevFilename);
}
}
}
}
for (const QString& filename : toAdd) {
auto it = _filenameToItems.find(filename);
if (it == _filenameToItems.end()) {
it = _filenameToItems.insert(filename, {});
}
if (it->contains(item) == false) {
it->append(item);
}
}
if (nativeFilenames.isEmpty() == false) {
_itemToFilenames.insert(item, nativeFilenames);
}
else {
_itemToFilenames.remove(item);
}
if (emitModified) {
emit item->externalFilesModified();
item->markUnchecked();
}
}
void FilesystemWatcher::onFileChanged(const QString& path)
{
// If the path was replaced (ie, file copy or atomic write) then the
// watcher will automatically remove the path and we need to add it back
// again.
if (_watcher->files().contains(path) == false) {
if (QFile::exists(path)) {
_watcher->addPath(path);
}
}
QString nativePath = QDir::toNativeSeparators(path);
ImageCache::invalidateFilename(nativePath.toStdString());
auto it = _filenameToItems.find(nativePath);
if (it != _filenameToItems.end()) {
const auto& items = *it;
for (AbstractResourceItem* item : items) {
emit item->externalFilesModified();
item->markUnchecked();
}
}
else {
qWarning() << nativePath << "is not linked to a ResourceItem";
}
}
<|endoftext|> |
<commit_before>#include "bindings-gfx.h"
#include "../luaapi/types.h"
#include "../luaapi/macros.h"
#include "../luaapi/classes.h"
#include "util/log.h"
#ifndef DEDICATED_ONLY
#include "CViewport.h"
#include "../gfx.h"
#endif
#include <cmath>
#include <iostream>
#include "gusanos/allegro.h"
using std::cerr;
using std::endl;
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
using boost::lexical_cast;
namespace LuaBindings
{
#ifndef DEDICATED_ONLY
LuaReference ALLEGRO_BITMAPMetaTable;
BlitterContext blitter;
#endif
/*! gfx_draw_box(bitmap, x1, y1, x2, y2, r, g, b)
//This function is deprecated in 0.9c and later. Use the draw_box method of Bitmap instead//.
*/
/*! Bitmap:draw_box(bitmap, x1, y1, x2, y2, color)
Draws a filled box with the corners (x1, y1) and (x2, y2)
with the color //color// using the currently selected blender.
*/
int l_gfx_draw_box(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
//ALLEGRO_BITMAP* b = *static_cast<ALLEGRO_BITMAP **>(lua_touserdata(L, 1));
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
int x1 = lua_tointeger(L, 2);
int y1 = lua_tointeger(L, 3);
int x2 = lua_tointeger(L, 4);
int y2 = lua_tointeger(L, 5);
int c = lua_tointeger(L, 6);
#ifndef NO_DEPRECATED
if(lua_gettop(L) >= 8) // Deprecated
{
LUA_WLOG_ONCE("The r, g, b version of draw_box is deprecated, replace the r, g, b parameters by color(r, g, b)");
int g = lua_tointeger(L, 7);
int b = lua_tointeger(L, 8);
c = makecol(c, g, b);
}
#endif
blitter.rectfill(b, x1, y1, x2, y2, c);
#endif
return 0;
}
#ifndef NO_DEPRECATED
int l_gfx_draw_box_depr(lua_State* L)
{
LuaContext context(L);
LUA_WLOG_ONCE("gfx_draw_box is deprecated, use the draw_box method of Bitmap instead");
return l_gfx_draw_box(L);
}
#endif
//! version 0.9c
/*! Bitmap:line(x1, y1, x2, y2, color)
Draws a line from (x1, y1) to (x2, y2)
with the color //color// using the currently selected blender.
*/
int l_gfx_line(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
int x1 = lua_tointeger(L, 2);
int y1 = lua_tointeger(L, 3);
int x2 = lua_tointeger(L, 4);
int y2 = lua_tointeger(L, 5);
int c = lua_tointeger(L, 6);
blitter.line(b, x1, y1, x2, y2, c);
#endif
return 0;
}
/*! Bitmap:linewu(x1, y1, x2, y2, color)
Draws a Wu-line from (x1, y1) to (x2, y2)
with the color //colour// using the currently selected blender.
*/
int l_gfx_linewu(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
lua_Number x1 = lua_tonumber(L, 2);
lua_Number y1 = lua_tonumber(L, 3);
lua_Number x2 = lua_tonumber(L, 4);
lua_Number y2 = lua_tonumber(L, 5);
int c = lua_tointeger(L, 6);
blitter.linewu(b, (float)x1, (float)y1, (float)x2, (float)y2, c);
#endif
return 0;
}
/*! Bitmap:putpixelwu(x1, y1, color)
Draws a Wu-pixel at position (x1, y1)
with the color //color// using the currently selected blender.
*/
int l_gfx_putpixelwu(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
lua_Number x = lua_tonumber(L, 2);
lua_Number y = lua_tonumber(L, 3);
int c = lua_tointeger(L, 4);
blitter.putpixelwu(b, (float)x, (float)y, c);
#endif
return 0;
}
/*! Bitmap:putpixel(x1, y1, color)
Draws a pixel at position (x1, y1)
with the color //color// using the currently selected blender.
*/
int l_gfx_putpixel(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
int x = lua_tointeger(L, 2);
int y = lua_tointeger(L, 3);
int cr = lua_tointeger(L, 4);
int cg = lua_tointeger(L, 5);
int cb = lua_tointeger(L, 6);
blitter.putpixel(b, x, y, makecol(cr, cg, cb));
#endif
return 0;
}
/*! Bitmap:hline(x1, y1, x2, color)
Draws a horizontal line from (x1, y1) to (x2, y1)
with the color //color// using the currently selected blender.
*/
int l_gfx_hline(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
int x1 = lua_tointeger(L, 2);
int y1 = lua_tointeger(L, 3);
int x2 = lua_tointeger(L, 4);
Pixel c = lua_tointeger(L, 5);
blitter.hline(b, x1, y1, x2, c);
#endif
return 0;
}
/*! color(r, g, b)
Returns a color
*/
int l_color(lua_State* L)
{
int r = lua_tointeger(L, 1);
int g = lua_tointeger(L, 2);
int b = lua_tointeger(L, 3);
lua_pushinteger(L, makecol(r, g, b));
return 1;
}
//! version any
/*! gfx_set_alpha(alpha)
Activates the alpha blender.
//alpha// is a value in [0, 255] that specifies the opacity
of things drawn after this is called.
*/
int l_gfx_set_alpha(lua_State* L)
{
#ifndef DEDICATED_ONLY
int alpha = lua_tointeger(L, 1);
blitter.set(BlitterContext::alpha(), alpha);
#endif
return 0;
}
//! version 0.9c
/*! gfx_set_alphach(alpha)
Activates the alphach blender.
//alpha// is a value in [0, 255] that specifies the opacity
of things drawn after this is called.
*/
int l_gfx_set_alphach(lua_State* L)
{
#ifndef DEDICATED_ONLY
int alpha = lua_tointeger(L, 1);
blitter.set(BlitterContext::AlphaChannel, alpha);
#endif
return 0;
}
//! version any
/*! gfx_set_add(alpha)
Activates the add blender.
//alpha// is a value in [0, 255] that specifies the scaling factor
of things drawn after this is called.
*/
int l_gfx_set_add(lua_State* L)
{
#ifndef DEDICATED_ONLY
int alpha = lua_tointeger(L, 1);
blitter.set(BlitterContext::add(), alpha);
#endif
return 0;
}
/*! gfx_reset_blending()
Deactivates any blender that was active.
Everything drawn after this is called will be drawn solid.
*/
int l_gfx_reset_blending(lua_State* L)
{
#ifndef DEDICATED_ONLY
blitter.set(BlitterContext::none());
#endif
return 0;
}
#ifndef DEDICATED_ONLY
/*! CViewport:bitmap()
(Known as get_bitmap before 0.9c)
Returns the HUD bitmap of this viewport.
*/
METHOD(CViewport, viewport_getBitmap, {
// Note: There was a separate CViewport::hud before.
// However, that was just the same reference as CViewport::dest.
context.pushFullReference(*p->dest, ALLEGRO_BITMAPMetaTable);
return 1;
})
#ifndef NO_DEPRECATED
int l_viewport_getBitmap_depr(lua_State* L)
{
LuaContext context(L);
LUA_WLOG_ONCE("get_bitmap is deprecated, use the bitmap method instead");
return l_viewport_getBitmap(L);
}
#endif
METHOD(CViewport, viewport_getGameBitmap, {
context.pushFullReference(*p->dest, ALLEGRO_BITMAPMetaTable);
return 1;
})
//! version 0.9c
/*! CViewport:from_map(x, y)
Converts the map coordinates (x, y) to
coordinates relative to the viewport bitmap and returns them.
*/
METHOD(CViewport, viewport_fromMap, {
lua_Integer x = lua_tointeger(context, 2);
lua_Integer y = lua_tointeger(context, 3);
IVec v(p->convertCoords(IVec(x, y)));
context.push(v.x);
context.push(v.y);
return 2;
})
//! version any
/*! Bitmap:w()
Returns the width of this bitmap.
*/
METHOD(ALLEGRO_BITMAP, bitmap_w, {
lua_pushinteger(context, p->w);
return 1;
})
/*! Bitmap:h()
Returns the width of this bitmap.
*/
METHOD(ALLEGRO_BITMAP, bitmap_h, {
lua_pushinteger(context, p->h);
return 1;
})
#endif
void initGfx(LuaContext& context)
{
context.functions()
#ifndef NO_DEPRECATED
("gfx_draw_box", l_gfx_draw_box_depr)
#endif
/*
("gfx_line", l_gfx_line)
("gfx_linewu", l_gfx_linewu)
("gfx_putpixelwu", l_gfx_putpixelwu)
("gfx_putpixel", l_gfx_putpixel)
("gfx_hline", l_gfx_hline)*/
//("gfx_vline", l_gfx_vline)
("color", l_color)
("gfx_set_alpha", l_gfx_set_alpha)
("gfx_set_alphach", l_gfx_set_alphach)
("gfx_set_add", l_gfx_set_add)
("gfx_reset_blending", l_gfx_reset_blending)
;
#ifndef DEDICATED_ONLY
// CViewport method and metatable
#ifndef NO_DEPRECATED
CLASS_(CViewport,
("get_bitmap", l_viewport_getBitmap_depr)
("bitmap", l_viewport_getBitmap)
("game_bitmap", l_viewport_getGameBitmap)
("from_map", l_viewport_fromMap)
)
#else
CLASS_(CViewport,
("bitmap", l_viewport_getBitmap)
("game_bitmap", l_viewport_getGameBitmap)
("from_map", l_viewport_fromMap)
)
#endif
// Bitmap method and metatable
CLASS(ALLEGRO_BITMAP,
("w", l_bitmap_w)
("h", l_bitmap_h)
("draw_box", l_gfx_draw_box)
("line", l_gfx_line)
("linewu", l_gfx_linewu)
("putpixelwu", l_gfx_putpixelwu)
("putpixel", l_gfx_putpixel)
("hline", l_gfx_hline)
)
#endif
}
}
<commit_msg>small fix<commit_after>#include "bindings-gfx.h"
#include "../luaapi/types.h"
#include "../luaapi/macros.h"
#include "../luaapi/classes.h"
#include "util/log.h"
#ifndef DEDICATED_ONLY
#include "CViewport.h"
#include "../gfx.h"
#endif
#include <cmath>
#include <iostream>
#include "gusanos/allegro.h"
using std::cerr;
using std::endl;
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
using boost::lexical_cast;
namespace LuaBindings
{
#ifndef DEDICATED_ONLY
LuaReference ALLEGRO_BITMAPMetaTable;
BlitterContext blitter;
#endif
/*! gfx_draw_box(bitmap, x1, y1, x2, y2, r, g, b)
//This function is deprecated in 0.9c and later. Use the draw_box method of Bitmap instead//.
*/
/*! Bitmap:draw_box(bitmap, x1, y1, x2, y2, color)
Draws a filled box with the corners (x1, y1) and (x2, y2)
with the color //color// using the currently selected blender.
*/
int l_gfx_draw_box(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
//ALLEGRO_BITMAP* b = *static_cast<ALLEGRO_BITMAP **>(lua_touserdata(L, 1));
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
// All images are doubleRes.
int x1 = int(lua_tonumber(L, 2) * 2);
int y1 = int(lua_tonumber(L, 3) * 2);
int x2 = int(lua_tonumber(L, 4) * 2);
int y2 = int(lua_tonumber(L, 5) * 2);
int c = lua_tointeger(L, 6);
#ifndef NO_DEPRECATED
if(lua_gettop(L) >= 8) // Deprecated
{
LUA_WLOG_ONCE("The r, g, b version of draw_box is deprecated, replace the r, g, b parameters by color(r, g, b)");
int g = lua_tointeger(L, 7);
int b = lua_tointeger(L, 8);
c = makecol(c, g, b);
}
#endif
blitter.rectfill(b, x1, y1, x2, y2, c);
#endif
return 0;
}
#ifndef NO_DEPRECATED
int l_gfx_draw_box_depr(lua_State* L)
{
LuaContext context(L);
LUA_WLOG_ONCE("gfx_draw_box is deprecated, use the draw_box method of Bitmap instead");
return l_gfx_draw_box(L);
}
#endif
//! version 0.9c
/*! Bitmap:line(x1, y1, x2, y2, color)
Draws a line from (x1, y1) to (x2, y2)
with the color //color// using the currently selected blender.
*/
int l_gfx_line(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
// All images are doubleRes.
int x1 = int(lua_tonumber(L, 2) * 2);
int y1 = int(lua_tonumber(L, 3) * 2);
int x2 = int(lua_tonumber(L, 4) * 2);
int y2 = int(lua_tonumber(L, 5) * 2);
int c = lua_tointeger(L, 6);
blitter.line(b, x1, y1, x2, y2, c);
#endif
return 0;
}
/*! Bitmap:linewu(x1, y1, x2, y2, color)
Draws a Wu-line from (x1, y1) to (x2, y2)
with the color //colour// using the currently selected blender.
*/
int l_gfx_linewu(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
// All images are doubleRes.
lua_Number x1 = lua_tonumber(L, 2) * 2;
lua_Number y1 = lua_tonumber(L, 3) * 2;
lua_Number x2 = lua_tonumber(L, 4) * 2;
lua_Number y2 = lua_tonumber(L, 5) * 2;
int c = lua_tointeger(L, 6);
blitter.linewu(b, (float)x1, (float)y1, (float)x2, (float)y2, c);
#endif
return 0;
}
/*! Bitmap:putpixelwu(x1, y1, color)
Draws a Wu-pixel at position (x1, y1)
with the color //color// using the currently selected blender.
*/
int l_gfx_putpixelwu(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
// All images are doubleRes.
lua_Number x = lua_tonumber(L, 2) * 2;
lua_Number y = lua_tonumber(L, 3) * 2;
int c = lua_tointeger(L, 4);
blitter.putpixelwu(b, (float)x, (float)y, c);
blitter.putpixelwu(b, (float)x+1, (float)y, c);
blitter.putpixelwu(b, (float)x, (float)y+1, c);
blitter.putpixelwu(b, (float)x+1, (float)y+1, c);
#endif
return 0;
}
/*! Bitmap:putpixel(x1, y1, color)
Draws a pixel at position (x1, y1)
with the color //color// using the currently selected blender.
*/
int l_gfx_putpixel(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
// All images are doubleRes.
int x = int(lua_tonumber(L, 2) * 2);
int y = int(lua_tonumber(L, 3) * 2);
int cr = lua_tointeger(L, 4);
int cg = lua_tointeger(L, 5);
int cb = lua_tointeger(L, 6);
int c = makecol(cr, cg, cb);
blitter.putpixel(b, x, y, c);
blitter.putpixel(b, x+1, y, c);
blitter.putpixel(b, x, y+1, c);
blitter.putpixel(b, x+1, y+1, c);
#endif
return 0;
}
/*! Bitmap:hline(x1, y1, x2, color)
Draws a horizontal line from (x1, y1) to (x2, y1)
with the color //color// using the currently selected blender.
*/
int l_gfx_hline(lua_State* L)
{
#ifndef DEDICATED_ONLY
LuaContext context(L);
ALLEGRO_BITMAP* b = ASSERT_OBJECT(ALLEGRO_BITMAP, 1);
// All images are doubleRes.
int x1 = int(lua_tonumber(L, 2) * 2);
int y1 = int(lua_tonumber(L, 3) * 2);
int x2 = int(lua_tonumber(L, 4) * 2);
Pixel c = lua_tointeger(L, 5);
blitter.hline(b, x1, y1, x2, c);
#endif
return 0;
}
/*! color(r, g, b)
Returns a color
*/
int l_color(lua_State* L)
{
int r = lua_tointeger(L, 1);
int g = lua_tointeger(L, 2);
int b = lua_tointeger(L, 3);
lua_pushinteger(L, makecol(r, g, b));
return 1;
}
//! version any
/*! gfx_set_alpha(alpha)
Activates the alpha blender.
//alpha// is a value in [0, 255] that specifies the opacity
of things drawn after this is called.
*/
int l_gfx_set_alpha(lua_State* L)
{
#ifndef DEDICATED_ONLY
int alpha = lua_tointeger(L, 1);
blitter.set(BlitterContext::alpha(), alpha);
#endif
return 0;
}
//! version 0.9c
/*! gfx_set_alphach(alpha)
Activates the alphach blender.
//alpha// is a value in [0, 255] that specifies the opacity
of things drawn after this is called.
*/
int l_gfx_set_alphach(lua_State* L)
{
#ifndef DEDICATED_ONLY
int alpha = lua_tointeger(L, 1);
blitter.set(BlitterContext::AlphaChannel, alpha);
#endif
return 0;
}
//! version any
/*! gfx_set_add(alpha)
Activates the add blender.
//alpha// is a value in [0, 255] that specifies the scaling factor
of things drawn after this is called.
*/
int l_gfx_set_add(lua_State* L)
{
#ifndef DEDICATED_ONLY
int alpha = lua_tointeger(L, 1);
blitter.set(BlitterContext::add(), alpha);
#endif
return 0;
}
/*! gfx_reset_blending()
Deactivates any blender that was active.
Everything drawn after this is called will be drawn solid.
*/
int l_gfx_reset_blending(lua_State* L)
{
#ifndef DEDICATED_ONLY
blitter.set(BlitterContext::none());
#endif
return 0;
}
#ifndef DEDICATED_ONLY
/*! CViewport:bitmap()
(Known as get_bitmap before 0.9c)
Returns the HUD bitmap of this viewport.
*/
METHOD(CViewport, viewport_getBitmap, {
// Note: There was a separate CViewport::hud before.
// However, that was just the same reference as CViewport::dest.
context.pushFullReference(*p->dest, ALLEGRO_BITMAPMetaTable);
return 1;
})
#ifndef NO_DEPRECATED
int l_viewport_getBitmap_depr(lua_State* L)
{
LuaContext context(L);
LUA_WLOG_ONCE("get_bitmap is deprecated, use the bitmap method instead");
return l_viewport_getBitmap(L);
}
#endif
METHOD(CViewport, viewport_getGameBitmap, {
context.pushFullReference(*p->dest, ALLEGRO_BITMAPMetaTable);
return 1;
})
//! version 0.9c
/*! CViewport:from_map(x, y)
Converts the map coordinates (x, y) to
coordinates relative to the viewport bitmap and returns them.
*/
METHOD(CViewport, viewport_fromMap, {
lua_Integer x = lua_tointeger(context, 2);
lua_Integer y = lua_tointeger(context, 3);
IVec v(p->convertCoords(IVec(x, y)));
context.push(v.x);
context.push(v.y);
return 2;
})
//! version any
/*! Bitmap:w()
Returns the width of this bitmap.
*/
METHOD(ALLEGRO_BITMAP, bitmap_w, {
// All images are doubleRes.
lua_pushinteger(context, p->w/2);
return 1;
})
/*! Bitmap:h()
Returns the width of this bitmap.
*/
METHOD(ALLEGRO_BITMAP, bitmap_h, {
// All images are doubleRes.
lua_pushinteger(context, p->h/2);
return 1;
})
#endif
void initGfx(LuaContext& context)
{
context.functions()
#ifndef NO_DEPRECATED
("gfx_draw_box", l_gfx_draw_box_depr)
#endif
/*
("gfx_line", l_gfx_line)
("gfx_linewu", l_gfx_linewu)
("gfx_putpixelwu", l_gfx_putpixelwu)
("gfx_putpixel", l_gfx_putpixel)
("gfx_hline", l_gfx_hline)*/
//("gfx_vline", l_gfx_vline)
("color", l_color)
("gfx_set_alpha", l_gfx_set_alpha)
("gfx_set_alphach", l_gfx_set_alphach)
("gfx_set_add", l_gfx_set_add)
("gfx_reset_blending", l_gfx_reset_blending)
;
#ifndef DEDICATED_ONLY
// CViewport method and metatable
#ifndef NO_DEPRECATED
CLASS_(CViewport,
("get_bitmap", l_viewport_getBitmap_depr)
("bitmap", l_viewport_getBitmap)
("game_bitmap", l_viewport_getGameBitmap)
("from_map", l_viewport_fromMap)
)
#else
CLASS_(CViewport,
("bitmap", l_viewport_getBitmap)
("game_bitmap", l_viewport_getGameBitmap)
("from_map", l_viewport_fromMap)
)
#endif
// Bitmap method and metatable
CLASS(ALLEGRO_BITMAP,
("w", l_bitmap_w)
("h", l_bitmap_h)
("draw_box", l_gfx_draw_box)
("line", l_gfx_line)
("linewu", l_gfx_linewu)
("putpixelwu", l_gfx_putpixelwu)
("putpixel", l_gfx_putpixel)
("hline", l_gfx_hline)
)
#endif
}
}
<|endoftext|> |
<commit_before><commit_msg>Fix replace INVOKE_PROPERTYPUT, put INVOKE_PROPERTYPUTREF instead<commit_after><|endoftext|> |
<commit_before>#include <openrave_ompl_bridge/OMPLPlannerRRTConnect.h>
#include <ompl/base/spaces/RealVectorStateSpace.h>
using namespace OpenRAVE;
namespace openrave_ompl_bridge
{
OMPLPlannerRRTConnect::OMPLPlannerRRTConnect(OpenRAVE::EnvironmentBasePtr penv) : OpenRAVE::PlannerBase(penv),
state_space_(new ompl::base::RealVectorStateSpace(0))
{
}
OMPLPlannerRRTConnect::~OMPLPlannerRRTConnect()
{
}
bool OMPLPlannerRRTConnect::InitPlan(OpenRAVE::RobotBasePtr robot, OpenRAVE::PlannerBase::PlannerParametersConstPtr params)
{
if(!CopyRobot(robot))
return false;
if(!CopyParameters(params))
return false;
if(!ResetStateSpaceDimensions())
return false;
if(!ResetStateSpaceBoundaries())
return false;
ResetSimpleSetup();
return true;
}
bool OMPLPlannerRRTConnect::InitPlan(OpenRAVE::RobotBasePtr robot, std::istream& input)
{
OMPLPlannerParametersRRTConnect* parameters = new OMPLPlannerParametersRRTConnect();
input >> (*parameters);
return InitPlan(robot, OpenRAVE::PlannerBase::PlannerParametersConstPtr(parameters));
}
OpenRAVE::PlannerStatus OMPLPlannerRRTConnect::PlanPath (OpenRAVE::TrajectoryBasePtr ptraj)
{
assert(ptraj);
assert(parameters_);
if(!EnsureInitializedPlan())
return OpenRAVE::PS_Failed;
if(!SolveWithTimelimit(parameters_->GetTimeLimit()))
return OpenRAVE::PS_Failed;
if(!SmoothenPath())
return OpenRAVE::PS_Failed;
if(!CopyFinalPath(ptraj))
return OpenRAVE::PS_Failed;
return OpenRAVE::PS_HasSolution;
}
OpenRAVE::PlannerBase::PlannerParametersConstPtr OMPLPlannerRRTConnect::GetParameters () const
{
return parameters_;
}
bool OMPLPlannerRRTConnect::CopyRobot(OpenRAVE::RobotBasePtr robot)
{
if(!robot)
{
RAVELOG_ERROR("Passed pointer to robot was NULL. Aborting!\n");
return false;
}
robot_ = robot;
return true;
}
bool OMPLPlannerRRTConnect::CopyParameters(OpenRAVE::PlannerBase::PlannerParametersConstPtr parameters)
{
if(!parameters)
{
RAVELOG_ERROR("Passed pointer to parameters was NULL. Aborting!\n");
return false;
}
parameters_->copy(parameters);
return true;
}
bool OMPLPlannerRRTConnect::ResetStateSpaceDimensions()
{
if(!HasActiveRobotDOF())
return false;
state_space_ = ompl::base::StateSpacePtr(new ompl::base::RealVectorStateSpace(GetRobotDOF()));
return true;
}
bool OMPLPlannerRRTConnect::ResetStateSpaceBoundaries()
{
if(!HasActiveRobotDOF())
return false;
ompl::base::RealVectorBounds bounds(GetRobotDOF());
std::vector<double> lower_limits, upper_limits;
if(!GetRobotActiveJointLimits(lower_limits, upper_limits))
return false;
assert(GetRobotDOF() == lower_limits.size());
assert(GetRobotDOF() == upper_limits.size());
for (unsigned int i=0; i<GetRobotDOF(); i++)
{
bounds.setLow(i, lower_limits[i]);
bounds.setHigh(i, upper_limits[i]);
}
state_space_->as<ompl::base::RealVectorStateSpace>()->setBounds(bounds);
return true;
}
void OMPLPlannerRRTConnect::ResetSimpleSetup()
{
assert(state_space_);
simple_setup_ = OMPLSimpleSetupPtr(new ompl::geometric::SimpleSetup(state_space_));
simple_setup_->setStateValidityChecker(boost::bind(&openrave_ompl_bridge::OMPLPlannerRRTConnect::IsStateValid, this, _1));
simple_setup_->setStartState(GetStartState());
simple_setup_->setGoalState(GetGoalState());
}
ompl::base::ScopedState<> OMPLPlannerRRTConnect::GetStartState()
{
assert(state_space_);
assert(parameters_);
std::vector<double> start_config = parameters_->GetStartConfiguration();
ompl::base::ScopedState<ompl::base::RealVectorStateSpace> start(state_space_);
assert(start_config.size() == GetStateSpaceDimensions());
for (unsigned int i=0; i<GetStateSpaceDimensions(); i++)
{
start->values[i] = start_config[i];
}
return start;
}
ompl::base::ScopedState<> OMPLPlannerRRTConnect::GetGoalState()
{
assert(state_space_);
assert(parameters_);
std::vector<double> goal_config = parameters_->GetGoalConfiguration();
ompl::base::ScopedState<ompl::base::RealVectorStateSpace> goal(state_space_);
assert(goal_config.size() == GetStateSpaceDimensions());
for (unsigned int i=0; i<GetStateSpaceDimensions(); i++)
{
goal->values[i] = goal_config[i];
}
return goal;
}
unsigned int OMPLPlannerRRTConnect::GetStateSpaceDimensions()
{
assert(state_space_);
return state_space_->as<ompl::base::RealVectorStateSpace>()->getDimension();
}
bool OMPLPlannerRRTConnect::EnsureInitializedPlan()
{
if(!simple_setup_)
{
RAVELOG_ERROR("Internal pointer to simple setup was NULL. Aborting!.\n");
return false;
}
return true;
}
bool OMPLPlannerRRTConnect::SolveWithTimelimit(double timelimit)
{
assert(simple_setup_);
return simple_setup_->solve(timelimit);
}
bool OMPLPlannerRRTConnect::SmoothenPath(double timelimit)
{
if(!EnsureSolutionPath())
return false;
simple_setup_->simplifySolution(timelimit);
return true;
}
bool OMPLPlannerRRTConnect::CopyFinalPath(OpenRAVE::TrajectoryBasePtr ptraj)
{
assert(ptraj);
if(!EnsureSolutionPath())
return false;
InitSolutionPathContainer(ptraj);
std::vector<ompl::base::State*> states = GetSolutionPath();
for (unsigned int i=0; i<states.size(); i++)
{
ptraj->Insert(i, TransformPathPoint(states[i]).q, true);
}
return true;
}
void OMPLPlannerRRTConnect::InitSolutionPathContainer(OpenRAVE::TrajectoryBasePtr ptraj)
{
assert(robot_);
ptraj->Init(robot_->GetActiveConfigurationSpecification());
}
bool OMPLPlannerRRTConnect::EnsureSolutionPath()
{
assert(simple_setup_);
if(!simple_setup_->haveSolutionPath())
{
RAVELOG_ERROR("Now solution path was found. Aborting!\n");
return false;
}
return true;
}
std::vector<ompl::base::State*> OMPLPlannerRRTConnect::GetSolutionPath()
{
assert(simple_setup_);
return simple_setup_->getSolutionPath().getStates();
}
OpenRAVE::TrajectoryBase::Point OMPLPlannerRRTConnect::TransformPathPoint(ompl::base::State* state)
{
const ompl::base::RealVectorStateSpace::StateType* state_cast = state->as<ompl::base::RealVectorStateSpace::StateType>();
assert(state_cast);
assert(GetStateSpaceDimensions() == GetRobotDOF());
OpenRAVE::TrajectoryBase::Point result;
for(unsigned int j = 0; j < GetRobotDOF(); j++)
result.q.push_back((*state_cast)[j]);
return result;
}
bool OMPLPlannerRRTConnect::IsStateValid(const ompl::base::State* state)
{
assert(state);
const ompl::base::RealVectorStateSpace::StateType* realVectorState = state->as<ompl::base::RealVectorStateSpace::StateType>();
assert(realVectorState);
std::vector<double> values;
for(unsigned int i = 0; i < GetRobotDOF(); i++)
{
values.push_back(realVectorState->values[i]);
}
return IsActiveRobotConfigurationInCollision(values);
}
unsigned int OMPLPlannerRRTConnect::GetRobotDOF()
{
if(!robot_)
{
RAVELOG_ERROR("No robot given to query for joints! \n");
return 0;
}
return robot_->GetActiveDOF();
}
bool OMPLPlannerRRTConnect::HasActiveRobotDOF()
{
return (GetRobotDOF() > 0);
}
bool OMPLPlannerRRTConnect::GetRobotActiveJointLimits(std::vector<double>& lower, std::vector<double>& upper)
{
if(!HasActiveRobotDOF())
return false;
robot_->GetActiveDOFLimits(lower, upper);
return true;
}
bool OMPLPlannerRRTConnect::IsActiveRobotConfigurationInCollision(std::vector<double>& joint_values)
{
assert(robot_);
assert(joint_values.size() == GetRobotDOF());
OpenRAVE::EnvironmentMutex::scoped_lock lockenv(GetEnv()->GetMutex());
robot_->SetActiveDOFValues(joint_values);
return (GetEnv()->CheckCollision(KinBodyConstPtr(robot_)) || robot_->CheckSelfCollision());
}
} /* namespace openrave_ompl_bridge */
<commit_msg>Found bug: Did not initialize planner parameters.<commit_after>#include <openrave_ompl_bridge/OMPLPlannerRRTConnect.h>
#include <ompl/base/spaces/RealVectorStateSpace.h>
using namespace OpenRAVE;
namespace openrave_ompl_bridge
{
OMPLPlannerRRTConnect::OMPLPlannerRRTConnect(OpenRAVE::EnvironmentBasePtr penv) : OpenRAVE::PlannerBase(penv),
state_space_(new ompl::base::RealVectorStateSpace(0)), parameters_(new OMPLPlannerParametersRRTConnect())
{
}
OMPLPlannerRRTConnect::~OMPLPlannerRRTConnect()
{
}
bool OMPLPlannerRRTConnect::InitPlan(OpenRAVE::RobotBasePtr robot, OpenRAVE::PlannerBase::PlannerParametersConstPtr params)
{
if(!CopyRobot(robot))
return false;
if(!CopyParameters(params))
return false;
if(!ResetStateSpaceDimensions())
return false;
if(!ResetStateSpaceBoundaries())
return false;
ResetSimpleSetup();
return true;
}
bool OMPLPlannerRRTConnect::InitPlan(OpenRAVE::RobotBasePtr robot, std::istream& input)
{
OMPLPlannerParametersRRTConnect* parameters = new OMPLPlannerParametersRRTConnect();
input >> (*parameters);
return InitPlan(robot, OpenRAVE::PlannerBase::PlannerParametersConstPtr(parameters));
}
OpenRAVE::PlannerStatus OMPLPlannerRRTConnect::PlanPath (OpenRAVE::TrajectoryBasePtr ptraj)
{
assert(ptraj);
assert(parameters_);
if(!EnsureInitializedPlan())
return OpenRAVE::PS_Failed;
if(!SolveWithTimelimit(parameters_->GetTimeLimit()))
return OpenRAVE::PS_Failed;
if(!SmoothenPath())
return OpenRAVE::PS_Failed;
if(!CopyFinalPath(ptraj))
return OpenRAVE::PS_Failed;
return OpenRAVE::PS_HasSolution;
}
OpenRAVE::PlannerBase::PlannerParametersConstPtr OMPLPlannerRRTConnect::GetParameters () const
{
return parameters_;
}
bool OMPLPlannerRRTConnect::CopyRobot(OpenRAVE::RobotBasePtr robot)
{
if(!robot)
{
RAVELOG_ERROR("Passed pointer to robot was NULL. Aborting!\n");
return false;
}
robot_ = robot;
return true;
}
bool OMPLPlannerRRTConnect::CopyParameters(OpenRAVE::PlannerBase::PlannerParametersConstPtr parameters)
{
if(!parameters)
{
RAVELOG_ERROR("Passed pointer to parameters was NULL. Aborting!\n");
return false;
}
parameters_->copy(parameters);
return true;
}
bool OMPLPlannerRRTConnect::ResetStateSpaceDimensions()
{
if(!HasActiveRobotDOF())
return false;
state_space_ = ompl::base::StateSpacePtr(new ompl::base::RealVectorStateSpace(GetRobotDOF()));
return true;
}
bool OMPLPlannerRRTConnect::ResetStateSpaceBoundaries()
{
if(!HasActiveRobotDOF())
return false;
ompl::base::RealVectorBounds bounds(GetRobotDOF());
std::vector<double> lower_limits, upper_limits;
if(!GetRobotActiveJointLimits(lower_limits, upper_limits))
return false;
assert(GetRobotDOF() == lower_limits.size());
assert(GetRobotDOF() == upper_limits.size());
for (unsigned int i=0; i<GetRobotDOF(); i++)
{
bounds.setLow(i, lower_limits[i]);
bounds.setHigh(i, upper_limits[i]);
}
state_space_->as<ompl::base::RealVectorStateSpace>()->setBounds(bounds);
return true;
}
void OMPLPlannerRRTConnect::ResetSimpleSetup()
{
assert(state_space_);
simple_setup_ = OMPLSimpleSetupPtr(new ompl::geometric::SimpleSetup(state_space_));
simple_setup_->setStateValidityChecker(boost::bind(&openrave_ompl_bridge::OMPLPlannerRRTConnect::IsStateValid, this, _1));
simple_setup_->setStartState(GetStartState());
simple_setup_->setGoalState(GetGoalState());
}
ompl::base::ScopedState<> OMPLPlannerRRTConnect::GetStartState()
{
assert(state_space_);
assert(parameters_);
std::vector<double> start_config = parameters_->GetStartConfiguration();
ompl::base::ScopedState<ompl::base::RealVectorStateSpace> start(state_space_);
assert(start_config.size() == GetStateSpaceDimensions());
for (unsigned int i=0; i<GetStateSpaceDimensions(); i++)
{
start->values[i] = start_config[i];
}
return start;
}
ompl::base::ScopedState<> OMPLPlannerRRTConnect::GetGoalState()
{
assert(state_space_);
assert(parameters_);
std::vector<double> goal_config = parameters_->GetGoalConfiguration();
ompl::base::ScopedState<ompl::base::RealVectorStateSpace> goal(state_space_);
assert(goal_config.size() == GetStateSpaceDimensions());
for (unsigned int i=0; i<GetStateSpaceDimensions(); i++)
{
goal->values[i] = goal_config[i];
}
return goal;
}
unsigned int OMPLPlannerRRTConnect::GetStateSpaceDimensions()
{
assert(state_space_);
return state_space_->as<ompl::base::RealVectorStateSpace>()->getDimension();
}
bool OMPLPlannerRRTConnect::EnsureInitializedPlan()
{
if(!simple_setup_)
{
RAVELOG_ERROR("Internal pointer to simple setup was NULL. Aborting!.\n");
return false;
}
return true;
}
bool OMPLPlannerRRTConnect::SolveWithTimelimit(double timelimit)
{
assert(simple_setup_);
return simple_setup_->solve(timelimit);
}
bool OMPLPlannerRRTConnect::SmoothenPath(double timelimit)
{
if(!EnsureSolutionPath())
return false;
simple_setup_->simplifySolution(timelimit);
return true;
}
bool OMPLPlannerRRTConnect::CopyFinalPath(OpenRAVE::TrajectoryBasePtr ptraj)
{
assert(ptraj);
if(!EnsureSolutionPath())
return false;
InitSolutionPathContainer(ptraj);
std::vector<ompl::base::State*> states = GetSolutionPath();
for (unsigned int i=0; i<states.size(); i++)
{
ptraj->Insert(i, TransformPathPoint(states[i]).q, true);
}
return true;
}
void OMPLPlannerRRTConnect::InitSolutionPathContainer(OpenRAVE::TrajectoryBasePtr ptraj)
{
assert(robot_);
ptraj->Init(robot_->GetActiveConfigurationSpecification());
}
bool OMPLPlannerRRTConnect::EnsureSolutionPath()
{
assert(simple_setup_);
if(!simple_setup_->haveSolutionPath())
{
RAVELOG_ERROR("Now solution path was found. Aborting!\n");
return false;
}
return true;
}
std::vector<ompl::base::State*> OMPLPlannerRRTConnect::GetSolutionPath()
{
assert(simple_setup_);
return simple_setup_->getSolutionPath().getStates();
}
OpenRAVE::TrajectoryBase::Point OMPLPlannerRRTConnect::TransformPathPoint(ompl::base::State* state)
{
const ompl::base::RealVectorStateSpace::StateType* state_cast = state->as<ompl::base::RealVectorStateSpace::StateType>();
assert(state_cast);
assert(GetStateSpaceDimensions() == GetRobotDOF());
OpenRAVE::TrajectoryBase::Point result;
for(unsigned int j = 0; j < GetRobotDOF(); j++)
result.q.push_back((*state_cast)[j]);
return result;
}
bool OMPLPlannerRRTConnect::IsStateValid(const ompl::base::State* state)
{
assert(state);
const ompl::base::RealVectorStateSpace::StateType* realVectorState = state->as<ompl::base::RealVectorStateSpace::StateType>();
assert(realVectorState);
std::vector<double> values;
for(unsigned int i = 0; i < GetRobotDOF(); i++)
{
values.push_back(realVectorState->values[i]);
}
return IsActiveRobotConfigurationInCollision(values);
}
unsigned int OMPLPlannerRRTConnect::GetRobotDOF()
{
if(!robot_)
{
RAVELOG_ERROR("No robot given to query for joints! \n");
return 0;
}
return robot_->GetActiveDOF();
}
bool OMPLPlannerRRTConnect::HasActiveRobotDOF()
{
return (GetRobotDOF() > 0);
}
bool OMPLPlannerRRTConnect::GetRobotActiveJointLimits(std::vector<double>& lower, std::vector<double>& upper)
{
if(!HasActiveRobotDOF())
return false;
robot_->GetActiveDOFLimits(lower, upper);
return true;
}
bool OMPLPlannerRRTConnect::IsActiveRobotConfigurationInCollision(std::vector<double>& joint_values)
{
assert(robot_);
assert(joint_values.size() == GetRobotDOF());
OpenRAVE::EnvironmentMutex::scoped_lock lockenv(GetEnv()->GetMutex());
robot_->SetActiveDOFValues(joint_values);
return (GetEnv()->CheckCollision(KinBodyConstPtr(robot_)) || robot_->CheckSelfCollision());
}
} /* namespace openrave_ompl_bridge */
<|endoftext|> |
<commit_before>/*
* This program 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.
*
* Written (W) 2012 Viktor Gal
* Copyright (C) 2012 Viktor Gal
*/
#include <typeinfo>
#include <shogun/classifier/svm/SVMOcas.h>
#include <shogun/classifier/svm/LatentLinearMachine.h>
#include <shogun/features/LatentFeatures.h>
#include <shogun/features/DenseFeatures.h>
using namespace shogun;
CLatentLinearMachine::CLatentLinearMachine ()
: argmax_h (NULL),
psi (NULL),
infer (NULL)
{
init ();
}
CLatentLinearMachine::~CLatentLinearMachine ()
{
SG_UNREF (m_latent_feats);
}
CLatentLinearMachine::CLatentLinearMachine (float64_t C,
CLatentFeatures* traindat,
CLabels* trainlab,
index_t psi_size)
: argmax_h (NULL),
psi (NULL),
infer (NULL),
m_latent_feats (traindat)
{
ASSERT (traindat != NULL);
ASSERT (trainlab != NULL);
init ();
m_C1 = m_C2 = C;
m_psi_size = psi_size;
set_labels (trainlab);
set_w (SGVector<float64_t> (m_psi_size));
/* create the temporal storage for PSI features */
SGMatrix<float64_t> psi_m (m_psi_size, m_latent_feats->get_num_vectors ());
((CDenseFeatures<float64_t>*)features)->set_feature_matrix (psi_m);
}
CLatentLabels* CLatentLinearMachine::apply ()
{
if (!features)
return NULL;
return NULL;
}
CLatentLabels* CLatentLinearMachine::apply (CFeatures* data)
{
try
{
CLatentFeatures* lf = dynamic_cast<CLatentFeatures*> (data);
int32_t num_examples = lf->get_num_vectors ();
SGMatrix<float64_t> psi_matrix (m_psi_size, num_examples);
CDenseFeatures<float64_t> psi_feats (psi_matrix);
CLatentLabels* labels = new CLatentLabels (num_examples);
for (int i = 0; i < num_examples; ++i)
{
CLatentData* x = lf->get_sample (i);
CLatentData* h = infer (*this, x);
labels->set_latent_label (i, h);
SGVector<float64_t> psi_feat = psi_feats.get_feature_vector (i);
psi (*this, x, h, psi_feat.vector);
float64_t y = w.dot (w.vector, psi_feat.vector, w.vlen);
labels->set_confidence (i, y);
}
return labels;
}
catch (const std::bad_cast& e)
{
SG_ERROR ("This object is not a LatentFeatures object: %s\n", e.what ());
}
return NULL;
}
void CLatentLinearMachine::set_argmax (argmax_func usr_argmax)
{
ASSERT (usr_argmax != NULL);
argmax_h = usr_argmax;
}
void CLatentLinearMachine::set_psi (psi_func usr_psi)
{
ASSERT (usr_psi != NULL);
psi = usr_psi;
}
void CLatentLinearMachine::default_argmax_h (CLatentLinearMachine& llm,
void* userData)
{
SGVector<float64_t> w = llm.get_w ();
CLatentFeatures* features = llm.get_latent_features ();
CLatentLabels* labels =
dynamic_cast<CLatentLabels*> (llm.get_labels ());
int32_t num = features->get_num_vectors ();
ASSERT (num > 0);
/* argmax_h only for positive examples */
for (int i = 0; i < num; ++i)
{
if (labels->get_confidence (i) == 1)
{
/* infer h and set it for the argmax_h <w,psi(x,h)> */
CLatentData* latent_data = llm.infer (llm, features->get_sample (i));
labels->set_latent_label (i, latent_data);
}
}
SG_UNREF (features);
}
void CLatentLinearMachine::set_infer (infer_func usr_infer)
{
ASSERT (usr_infer != NULL);
infer = usr_infer;
}
void CLatentLinearMachine::compute_psi ()
{
ASSERT (features != NULL);
int32_t num_vectors = features->get_num_vectors ();
for (int i = 0; i < num_vectors; ++i)
{
SGVector<float64_t> psi_feat = dynamic_cast<CDenseFeatures<float64_t>*>(features)->get_feature_vector (i);
CLatentData* label = (dynamic_cast<CLatentLabels*> (m_labels))->get_latent_label (i);
CLatentData* x = m_latent_feats->get_sample (i);
psi (*this, x, label, psi_feat.vector);
}
}
bool CLatentLinearMachine::train_machine (CFeatures* data)
{
if (psi == NULL)
SG_ERROR ("The PSI function is not implemented!\n");
if (infer == NULL)
SG_ERROR ("The Infer function is not implemented!\n");
try
{
SG_DEBUG ("Initialise PSI (x,h)\n");
compute_psi ();
/* do CCCP */
SG_DEBUG ("Starting CCCP\n");
float64_t decrement = 0.0, primal_obj = 0.0, prev_po = 0.0;
float64_t inner_eps = 0.5*m_C1*m_epsilon;
bool stop = false;
int32_t iter = 0;
while ((iter < 2)||(!stop&&(iter < m_max_iter)))
{
SG_DEBUG ("iteration: %d\n", iter);
/* do the SVM optimisation with fixed h* */
SG_DEBUG ("Do the inner loop of CCCP: optimize for w for fixed h*\n");
/* TODO: change code that it can support structural SVM! */
CSVMOcas svm (m_C1, features, m_labels);
svm.set_epsilon (inner_eps);
svm.train ();
/* calculate the decrement */
primal_obj = svm.compute_primal_objective ();
decrement = prev_po - primal_obj;
prev_po = primal_obj;
SG_DEBUG ("decrement: %f\n", decrement);
SG_DEBUG ("primal objective: %f\n", primal_obj);
/* check the stopping criterion */
stop = (inner_eps < (0.5*m_C1*m_epsilon+1E-8)) && (decrement < m_C1*m_epsilon);
inner_eps = -decrement*0.01;
inner_eps = CMath::max (inner_eps, 0.5*m_C1*m_epsilon);
SG_DEBUG ("inner epsilon: %f\n", inner_eps);
/* find argmaxH */
SG_DEBUG ("Find and set h_i = argmax_h (w, psi(x_i,h))\n");
SGVector<float64_t> cur_w = svm.get_w ();
memcpy (w.vector, cur_w.vector, cur_w.vlen*sizeof (float64_t));
argmax_h (*this, NULL);
SG_DEBUG ("Recalculating PSI (x,h) with the new h variables\n");
compute_psi ();
/* increment iteration counter */
iter++;
}
}
catch (const std::bad_cast& e)
{
SG_ERROR ("This object is not a LatentFeatures object: %s\n", e.what ());
}
return true;
}
void CLatentLinearMachine::init ()
{
m_C1 = m_C2 = 10.0;
m_epsilon = 1E-3;
m_max_iter = 400;
features = new CDenseFeatures<float64_t> ();
SG_REF (features);
if (argmax_h == NULL)
set_argmax (default_argmax_h);
m_parameters->add(&m_C1, "C1", "Cost constant 1.");
m_parameters->add(&m_C2, "C2", "Cost constant 2.");
m_parameters->add(&m_epsilon, "epsilon", "Convergence precision.");
m_parameters->add(&m_max_iter, "max_iter", "Maximum iterations.");
m_parameters->add(&m_psi_size, "psi_size", "PSI feature vector dimension.");
m_parameters->add((CSGObject**) &m_latent_feats, "latent_feats", "Latent features");
}
<commit_msg>Use the DenseLabels api for set/get labels<commit_after>/*
* This program 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.
*
* Written (W) 2012 Viktor Gal
* Copyright (C) 2012 Viktor Gal
*/
#include <typeinfo>
#include <shogun/classifier/svm/SVMOcas.h>
#include <shogun/classifier/svm/LatentLinearMachine.h>
#include <shogun/features/LatentFeatures.h>
#include <shogun/features/DenseFeatures.h>
using namespace shogun;
CLatentLinearMachine::CLatentLinearMachine ()
: argmax_h (NULL),
psi (NULL),
infer (NULL)
{
init ();
}
CLatentLinearMachine::~CLatentLinearMachine ()
{
SG_UNREF (m_latent_feats);
}
CLatentLinearMachine::CLatentLinearMachine (float64_t C,
CLatentFeatures* traindat,
CLabels* trainlab,
index_t psi_size)
: argmax_h (NULL),
psi (NULL),
infer (NULL),
m_latent_feats (traindat)
{
ASSERT (traindat != NULL);
ASSERT (trainlab != NULL);
init ();
m_C1 = m_C2 = C;
m_psi_size = psi_size;
set_labels (trainlab);
set_w (SGVector<float64_t> (m_psi_size));
/* create the temporal storage for PSI features */
SGMatrix<float64_t> psi_m (m_psi_size, m_latent_feats->get_num_vectors ());
((CDenseFeatures<float64_t>*)features)->set_feature_matrix (psi_m);
}
CLatentLabels* CLatentLinearMachine::apply ()
{
if (!features)
return NULL;
return NULL;
}
CLatentLabels* CLatentLinearMachine::apply (CFeatures* data)
{
try
{
CLatentFeatures* lf = dynamic_cast<CLatentFeatures*> (data);
int32_t num_examples = lf->get_num_vectors ();
SGMatrix<float64_t> psi_matrix (m_psi_size, num_examples);
CDenseFeatures<float64_t> psi_feats (psi_matrix);
CLatentLabels* labels = new CLatentLabels (num_examples);
for (int i = 0; i < num_examples; ++i)
{
CLatentData* x = lf->get_sample (i);
CLatentData* h = infer (*this, x);
labels->set_latent_label (i, h);
SGVector<float64_t> psi_feat = psi_feats.get_feature_vector (i);
psi (*this, x, h, psi_feat.vector);
float64_t y = w.dot (w.vector, psi_feat.vector, w.vlen);
labels->set_label (i, y);
}
return labels;
}
catch (const std::bad_cast& e)
{
SG_ERROR ("This object is not a LatentFeatures object: %s\n", e.what ());
}
return NULL;
}
void CLatentLinearMachine::set_argmax (argmax_func usr_argmax)
{
ASSERT (usr_argmax != NULL);
argmax_h = usr_argmax;
}
void CLatentLinearMachine::set_psi (psi_func usr_psi)
{
ASSERT (usr_psi != NULL);
psi = usr_psi;
}
void CLatentLinearMachine::default_argmax_h (CLatentLinearMachine& llm,
void* userData)
{
SGVector<float64_t> w = llm.get_w ();
CLatentFeatures* features = llm.get_latent_features ();
CLatentLabels* labels =
dynamic_cast<CLatentLabels*> (llm.get_labels ());
int32_t num = features->get_num_vectors ();
ASSERT (num > 0);
/* argmax_h only for positive examples */
for (int i = 0; i < num; ++i)
{
if (labels->get_label (i) == 1)
{
/* infer h and set it for the argmax_h <w,psi(x,h)> */
CLatentData* latent_data = llm.infer (llm, features->get_sample (i));
labels->set_latent_label (i, latent_data);
}
}
SG_UNREF (features);
}
void CLatentLinearMachine::set_infer (infer_func usr_infer)
{
ASSERT (usr_infer != NULL);
infer = usr_infer;
}
void CLatentLinearMachine::compute_psi ()
{
ASSERT (features != NULL);
int32_t num_vectors = features->get_num_vectors ();
for (int i = 0; i < num_vectors; ++i)
{
SGVector<float64_t> psi_feat = dynamic_cast<CDenseFeatures<float64_t>*>(features)->get_feature_vector (i);
CLatentData* label = (dynamic_cast<CLatentLabels*> (m_labels))->get_latent_label (i);
CLatentData* x = m_latent_feats->get_sample (i);
psi (*this, x, label, psi_feat.vector);
}
}
bool CLatentLinearMachine::train_machine (CFeatures* data)
{
if (psi == NULL)
SG_ERROR ("The PSI function is not implemented!\n");
if (infer == NULL)
SG_ERROR ("The Infer function is not implemented!\n");
try
{
SG_DEBUG ("Initialise PSI (x,h)\n");
compute_psi ();
/* do CCCP */
SG_DEBUG ("Starting CCCP\n");
float64_t decrement = 0.0, primal_obj = 0.0, prev_po = 0.0;
float64_t inner_eps = 0.5*m_C1*m_epsilon;
bool stop = false;
int32_t iter = 0;
while ((iter < 2)||(!stop&&(iter < m_max_iter)))
{
SG_DEBUG ("iteration: %d\n", iter);
/* do the SVM optimisation with fixed h* */
SG_DEBUG ("Do the inner loop of CCCP: optimize for w for fixed h*\n");
/* TODO: change code that it can support structural SVM! */
CSVMOcas svm (m_C1, features, m_labels);
svm.set_epsilon (inner_eps);
svm.train ();
/* calculate the decrement */
primal_obj = svm.compute_primal_objective ();
decrement = prev_po - primal_obj;
prev_po = primal_obj;
SG_DEBUG ("decrement: %f\n", decrement);
SG_DEBUG ("primal objective: %f\n", primal_obj);
/* check the stopping criterion */
stop = (inner_eps < (0.5*m_C1*m_epsilon+1E-8)) && (decrement < m_C1*m_epsilon);
inner_eps = -decrement*0.01;
inner_eps = CMath::max (inner_eps, 0.5*m_C1*m_epsilon);
SG_DEBUG ("inner epsilon: %f\n", inner_eps);
/* find argmaxH */
SG_DEBUG ("Find and set h_i = argmax_h (w, psi(x_i,h))\n");
SGVector<float64_t> cur_w = svm.get_w ();
memcpy (w.vector, cur_w.vector, cur_w.vlen*sizeof (float64_t));
argmax_h (*this, NULL);
SG_DEBUG ("Recalculating PSI (x,h) with the new h variables\n");
compute_psi ();
/* increment iteration counter */
iter++;
}
}
catch (const std::bad_cast& e)
{
SG_ERROR ("This object is not a LatentFeatures object: %s\n", e.what ());
}
return true;
}
void CLatentLinearMachine::init ()
{
m_C1 = m_C2 = 10.0;
m_epsilon = 1E-3;
m_max_iter = 400;
features = new CDenseFeatures<float64_t> ();
SG_REF (features);
if (argmax_h == NULL)
set_argmax (default_argmax_h);
m_parameters->add(&m_C1, "C1", "Cost constant 1.");
m_parameters->add(&m_C2, "C2", "Cost constant 2.");
m_parameters->add(&m_epsilon, "epsilon", "Convergence precision.");
m_parameters->add(&m_max_iter, "max_iter", "Maximum iterations.");
m_parameters->add(&m_psi_size, "psi_size", "PSI feature vector dimension.");
m_parameters->add((CSGObject**) &m_latent_feats, "latent_feats", "Latent features");
}
<|endoftext|> |
<commit_before>#ifndef INCLUDED_MSIHELPER_HXX
#define INCLUDED_MSIHELPER_HXX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#include <string>
/**
Get the value of the named property
@param handle
[in] a valid msi handle.
@param name
[in] the name of the property.
@param value
[out] receives thes value of the property.
@returns
<TRUE/>if the property was found.
*/
bool GetMsiProp(MSIHANDLE handle, LPCTSTR name, /*out*/std::wstring& value);
/**
Set the value of a binary property which can only
have the values "0" or "1" to "1".
@param handle
[in] a valid msi handle.
@param name
[in] the name of the property.
*/
void SetMsiProp(MSIHANDLE handle, LPCTSTR name);
/**
Set the value of a binary property which can only
have the values "0" or "1" to "0".
@param handle
[in] a valid msi handle.
@param name
[in] the name of the property.
*/
void UnsetMsiProp(MSIHANDLE handle, LPCTSTR name);
/**
Returns whether a certain property is set meaning
its value is "1". This method should be used for
binary properties whose value can be "0" or "1".
@returns
<TRUE/>if the value of the specified property is
"1" else if the property is not defined or its
value is other than "1" <FALSE/> will be returned.
*/
bool IsSetMsiProp(MSIHANDLE handle, LPCTSTR name);
/**
Query if this is an installation for all user or not.
@param handle
[in] a valid msi handle.
@returns
<TRUE/>if this is an all user installation
*/
bool IsAllUserInstallation(MSIHANDLE handle);
/**
Returns the destination folder of the office installation
as system path. The returned path contains a final '\'.
@param handle
[in] a valid msi handle.
@returns
the destination path of the office installation finalized
with a '\'.
*/
std::wstring GetOfficeInstallationPath(MSIHANDLE handle);
/**
Returns the absolute path of the office executable that
will be installed as system path.
@param handle
[in] a valid msi handle.
@returns
the absolute system path of the office executable (e.g.
(C:\Program Files\StarOffice 8\program\soffice.exe").
*/
std::wstring GetOfficeExecutablePath(MSIHANDLE handle);
/**
Get the name of the office that will be installed
(e.g. StarOffice 8, StarSuite 8, ...).
@param handle
[in] a valid msi handle.
@returns
the name of the office product that will be installed.
*/
std::wstring GetProductName(MSIHANDLE handle);
/**
Determine if the specified module is installed locally.
@param handle
[in] a valid msi handle.
@param name
[in] the name of the module.
@returns
<TRUE/>if the specified module is installed locally.
*/
bool IsModuleInstalled(MSIHANDLE handle, LPCTSTR name);
/**
Determine if the specified module is selected to be installed
locally.
@param handle
[in] a valid msi handle.
@param name
[in] the name of the module.
@returns
<TRUE/>if the specified module is about to be installed locally.
*/
bool IsModuleSelectedForInstallation(MSIHANDLE handle, LPCTSTR name);
/**
Determine if the specified module which is locally installed is
selected for deinstallation.
@param handle
[in] a valid msi handle.
@param name
[in] the name of the module.
@returns
<TRUE/>if the specified module is about to be deinstalled.
*/
bool IsModuleSelectedForDeinstallation(MSIHANDLE handle, LPCTSTR name);
/**
Determine whether this is a complete uninstallation or not.
@param handle
[in] a valid msi handle.
@returns
<TRUE/>if this is a complete deinstallation.
*/
bool IsCompleteDeinstallation(MSIHANDLE handle);
#endif
<commit_msg>INTEGRATION: CWS native36 (1.1.154); FILE MERGED 2006/01/17 13:12:16 is 1.1.154.1: #i60456# custom action in repair mode<commit_after>#ifndef INCLUDED_MSIHELPER_HXX
#define INCLUDED_MSIHELPER_HXX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#include <string>
/**
Get the value of the named property
@param handle
[in] a valid msi handle.
@param name
[in] the name of the property.
@param value
[out] receives thes value of the property.
@returns
<TRUE/>if the property was found.
*/
bool GetMsiProp(MSIHANDLE handle, LPCTSTR name, /*out*/std::wstring& value);
/**
Set the value of a binary property which can only
have the values "0" or "1" to "1".
@param handle
[in] a valid msi handle.
@param name
[in] the name of the property.
*/
void SetMsiProp(MSIHANDLE handle, LPCTSTR name);
/**
Set the value of a binary property which can only
have the values "0" or "1" to "0".
@param handle
[in] a valid msi handle.
@param name
[in] the name of the property.
*/
void UnsetMsiProp(MSIHANDLE handle, LPCTSTR name);
/**
Returns whether a certain property is set meaning
its value is "1". This method should be used for
binary properties whose value can be "0" or "1".
@returns
<TRUE/>if the value of the specified property is
"1" else if the property is not defined or its
value is other than "1" <FALSE/> will be returned.
*/
bool IsSetMsiProp(MSIHANDLE handle, LPCTSTR name);
/**
Returns whether a certain property is set meaning
its value is not empty. This method should be used for
properties, that can have different values.
@returns
<TRUE/>if the value of the specified property is
not empty. If it is empty <FALSE/> will be returned.
*/
bool IsMsiPropNotEmpty(MSIHANDLE handle, LPCTSTR name);
/**
Query if this is an installation for all user or not.
@param handle
[in] a valid msi handle.
@returns
<TRUE/>if this is an all user installation
*/
bool IsAllUserInstallation(MSIHANDLE handle);
/**
Returns the destination folder of the office installation
as system path. The returned path contains a final '\'.
@param handle
[in] a valid msi handle.
@returns
the destination path of the office installation finalized
with a '\'.
*/
std::wstring GetOfficeInstallationPath(MSIHANDLE handle);
/**
Returns the absolute path of the office executable that
will be installed as system path.
@param handle
[in] a valid msi handle.
@returns
the absolute system path of the office executable (e.g.
(C:\Program Files\StarOffice 8\program\soffice.exe").
*/
std::wstring GetOfficeExecutablePath(MSIHANDLE handle);
/**
Get the name of the office that will be installed
(e.g. StarOffice 8, StarSuite 8, ...).
@param handle
[in] a valid msi handle.
@returns
the name of the office product that will be installed.
*/
std::wstring GetProductName(MSIHANDLE handle);
/**
Determine if the specified module is installed locally.
@param handle
[in] a valid msi handle.
@param name
[in] the name of the module.
@returns
<TRUE/>if the specified module is installed locally.
*/
bool IsModuleInstalled(MSIHANDLE handle, LPCTSTR name);
/**
Determine if the specified module is selected to be installed
locally.
@param handle
[in] a valid msi handle.
@param name
[in] the name of the module.
@returns
<TRUE/>if the specified module is about to be installed locally.
*/
bool IsModuleSelectedForInstallation(MSIHANDLE handle, LPCTSTR name);
/**
Determine if the specified module which is locally installed is
selected for deinstallation.
@param handle
[in] a valid msi handle.
@param name
[in] the name of the module.
@returns
<TRUE/>if the specified module is about to be deinstalled.
*/
bool IsModuleSelectedForDeinstallation(MSIHANDLE handle, LPCTSTR name);
/**
Determine whether this is a complete uninstallation or not.
@param handle
[in] a valid msi handle.
@returns
<TRUE/>if this is a complete deinstallation.
*/
bool IsCompleteDeinstallation(MSIHANDLE handle);
#endif
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
* Authors:
* - Paul Asmuth <paul@zscale.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include "eventql/eventql.h"
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "eventql/util/io/filerepository.h"
#include "eventql/util/io/fileutil.h"
#include "eventql/util/application.h"
#include "eventql/util/logging.h"
#include "eventql/util/random.h"
#include "eventql/util/thread/eventloop.h"
#include "eventql/util/thread/threadpool.h"
#include "eventql/util/thread/FixedSizeThreadPool.h"
#include "eventql/util/wallclock.h"
#include "eventql/util/VFS.h"
#include "eventql/util/cli/flagparser.h"
#include "eventql/util/json/json.h"
#include "eventql/util/json/jsonrpc.h"
#include "eventql/util/http/httprouter.h"
#include "eventql/util/http/httpserver.h"
#include "eventql/util/http/httpconnectionpool.h"
#include "eventql/util/http/VFSFileServlet.h"
#include "eventql/util/cli/CLI.h"
#include "eventql/util/cli/flagparser.h"
#include "eventql/config/config_directory.h"
#include "eventql/config/config_directory_zookeeper.h"
using namespace eventql;
thread::EventLoop ev;
void cmd_cluster_status(const cli::FlagParser& flags) {
//ConfigDirectoryClient cclient(
// InetAddr::resolve(flags.getString("master")));
//auto cluster = cclient.fetchClusterConfig();
//iputs("Cluster config:\n$0", cluster.DebugString());
}
void cmd_cluster_add_server(const cli::FlagParser& flags) {
auto cdir = mkScoped(
new ZookeeperConfigDirectory(
flags.getString("zookeeper_addr"),
None<String>(),
""));
cdir->startAndJoin(flags.getString("cluster_name"));
ServerConfig cfg;
cfg.set_server_id(flags.getString("server_name"));
cfg.add_sha1_tokens(Random::singleton()->sha1().toString());
cdir->updateServerConfig(cfg);
cdir->stop();
}
void cmd_cluster_create(const cli::FlagParser& flags) {
auto cdir = mkScoped(
new ZookeeperConfigDirectory(
flags.getString("zookeeper_addr"),
None<String>(),
""));
cdir->startAndJoin(flags.getString("cluster_name"));
ClusterConfig cfg;
cdir->updateClusterConfig(cfg);
cdir->stop();
}
void cmd_namespace_create(const cli::FlagParser& flags) {
auto cdir = mkScoped(
new ZookeeperConfigDirectory(
flags.getString("zookeeper_addr"),
None<String>(),
""));
cdir->startAndJoin(flags.getString("cluster_name"));
NamespaceConfig cfg;
cfg.set_customer(flags.getString("namespace"));
cdir->updateNamespaceConfig(cfg);
cdir->stop();
}
int main(int argc, const char** argv) {
Application::init();
Application::logToStderr("evqlctl");
cli::FlagParser flags;
flags.defineFlag(
"loglevel",
cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
cli::CLI cli;
/* command: cluster_status */
auto cluster_status_cmd = cli.defineCommand("cluster-status");
cluster_status_cmd->onCall(
std::bind(&cmd_cluster_status, std::placeholders::_1));
cluster_status_cmd->flags().defineFlag(
"master",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"url",
"<addr>");
/* command: cluster_add_server */
auto cluster_add_server_cmd = cli.defineCommand("cluster-add-server");
cluster_add_server_cmd->onCall(
std::bind(&cmd_cluster_add_server, std::placeholders::_1));
cluster_add_server_cmd->flags().defineFlag(
"zookeeper_addr",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"url",
"<addr>");
cluster_add_server_cmd->flags().defineFlag(
"cluster_name",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
cluster_add_server_cmd->flags().defineFlag(
"server_name",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
/* command: cluster-create */
auto cluster_create_node_cmd = cli.defineCommand("cluster-create");
cluster_create_node_cmd->onCall(
std::bind(&cmd_cluster_create, std::placeholders::_1));
cluster_create_node_cmd->flags().defineFlag(
"zookeeper_addr",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"url",
"<addr>");
cluster_create_node_cmd->flags().defineFlag(
"cluster_name",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
/* command: namespace-create */
auto namespace_create_node_cmd = cli.defineCommand("namespace-create");
namespace_create_node_cmd->onCall(
std::bind(&cmd_namespace_create, std::placeholders::_1));
namespace_create_node_cmd->flags().defineFlag(
"zookeeper_addr",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"url",
"<addr>");
namespace_create_node_cmd->flags().defineFlag(
"cluster_name",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
namespace_create_node_cmd->flags().defineFlag(
"namespace",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
cli.call(flags.getArgv());
return 0;
}
<commit_msg>create nodes with 128 sha1 tokens for legacy compatibility<commit_after>/**
* Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
* Authors:
* - Paul Asmuth <paul@zscale.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include "eventql/eventql.h"
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "eventql/util/io/filerepository.h"
#include "eventql/util/io/fileutil.h"
#include "eventql/util/application.h"
#include "eventql/util/logging.h"
#include "eventql/util/random.h"
#include "eventql/util/thread/eventloop.h"
#include "eventql/util/thread/threadpool.h"
#include "eventql/util/thread/FixedSizeThreadPool.h"
#include "eventql/util/wallclock.h"
#include "eventql/util/VFS.h"
#include "eventql/util/cli/flagparser.h"
#include "eventql/util/json/json.h"
#include "eventql/util/json/jsonrpc.h"
#include "eventql/util/http/httprouter.h"
#include "eventql/util/http/httpserver.h"
#include "eventql/util/http/httpconnectionpool.h"
#include "eventql/util/http/VFSFileServlet.h"
#include "eventql/util/cli/CLI.h"
#include "eventql/util/cli/flagparser.h"
#include "eventql/config/config_directory.h"
#include "eventql/config/config_directory_zookeeper.h"
using namespace eventql;
thread::EventLoop ev;
void cmd_cluster_status(const cli::FlagParser& flags) {
//ConfigDirectoryClient cclient(
// InetAddr::resolve(flags.getString("master")));
//auto cluster = cclient.fetchClusterConfig();
//iputs("Cluster config:\n$0", cluster.DebugString());
}
void cmd_cluster_add_server(const cli::FlagParser& flags) {
auto cdir = mkScoped(
new ZookeeperConfigDirectory(
flags.getString("zookeeper_addr"),
None<String>(),
""));
cdir->startAndJoin(flags.getString("cluster_name"));
ServerConfig cfg;
cfg.set_server_id(flags.getString("server_name"));
for (size_t i = 0; i < 128; ++i) {
cfg.add_sha1_tokens(Random::singleton()->sha1().toString());
}
cdir->updateServerConfig(cfg);
cdir->stop();
}
void cmd_cluster_create(const cli::FlagParser& flags) {
auto cdir = mkScoped(
new ZookeeperConfigDirectory(
flags.getString("zookeeper_addr"),
None<String>(),
""));
cdir->startAndJoin(flags.getString("cluster_name"));
ClusterConfig cfg;
cdir->updateClusterConfig(cfg);
cdir->stop();
}
void cmd_namespace_create(const cli::FlagParser& flags) {
auto cdir = mkScoped(
new ZookeeperConfigDirectory(
flags.getString("zookeeper_addr"),
None<String>(),
""));
cdir->startAndJoin(flags.getString("cluster_name"));
NamespaceConfig cfg;
cfg.set_customer(flags.getString("namespace"));
cdir->updateNamespaceConfig(cfg);
cdir->stop();
}
int main(int argc, const char** argv) {
Application::init();
Application::logToStderr("evqlctl");
cli::FlagParser flags;
flags.defineFlag(
"loglevel",
cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
cli::CLI cli;
/* command: cluster_status */
auto cluster_status_cmd = cli.defineCommand("cluster-status");
cluster_status_cmd->onCall(
std::bind(&cmd_cluster_status, std::placeholders::_1));
cluster_status_cmd->flags().defineFlag(
"master",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"url",
"<addr>");
/* command: cluster_add_server */
auto cluster_add_server_cmd = cli.defineCommand("cluster-add-server");
cluster_add_server_cmd->onCall(
std::bind(&cmd_cluster_add_server, std::placeholders::_1));
cluster_add_server_cmd->flags().defineFlag(
"zookeeper_addr",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"url",
"<addr>");
cluster_add_server_cmd->flags().defineFlag(
"cluster_name",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
cluster_add_server_cmd->flags().defineFlag(
"server_name",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
/* command: cluster-create */
auto cluster_create_node_cmd = cli.defineCommand("cluster-create");
cluster_create_node_cmd->onCall(
std::bind(&cmd_cluster_create, std::placeholders::_1));
cluster_create_node_cmd->flags().defineFlag(
"zookeeper_addr",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"url",
"<addr>");
cluster_create_node_cmd->flags().defineFlag(
"cluster_name",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
/* command: namespace-create */
auto namespace_create_node_cmd = cli.defineCommand("namespace-create");
namespace_create_node_cmd->onCall(
std::bind(&cmd_namespace_create, std::placeholders::_1));
namespace_create_node_cmd->flags().defineFlag(
"zookeeper_addr",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"url",
"<addr>");
namespace_create_node_cmd->flags().defineFlag(
"cluster_name",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
namespace_create_node_cmd->flags().defineFlag(
"namespace",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
cli.call(flags.getArgv());
return 0;
}
<|endoftext|> |
<commit_before>#include "bct.h"
#include <cmath>
#include <cstdio>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
/*
* Returns a binary copy of the given vector.
*/
gsl_vector* bct::binary(const gsl_vector* v) {
gsl_vector* bv = gsl_vector_calloc(v->size);
for (int i = 0; i < v->size; i++) {
if (std::abs(gsl_vector_get(v, i)) > EPSILON) {
gsl_vector_set(bv, i, 1.0);
}
}
return bv;
}
/*
* Returns a binary copy of the given matrix.
*/
gsl_matrix* bct::binary(const gsl_matrix* m) {
gsl_matrix* bm = gsl_matrix_calloc(m->size1, m->size2);
for (int i = 0; i < m->size1; i++) {
for (int j = 0; j < m->size2; j++) {
if (std::abs(gsl_matrix_get(m, i, j)) > EPSILON) {
gsl_matrix_set(bm, i, j, 1.0);
}
}
}
return bm;
}
/*
* Returns the number of nonzero elements in the given vector.
*/
int bct::nnz(const gsl_vector* v) {
int count = 0;
for (int i = 0; i < v->size; i++) {
if (std::abs(gsl_vector_get(v, i)) > EPSILON) {
count++;
}
}
return count;
}
/*
* Returns the number of nonzero elements in the given matrix.
*/
int bct::nnz(const gsl_matrix* m) {
int count = 0;
for (int i = 0; i < m->size1; i++) {
for (int j = 0; j < m->size2; j++) {
if (std::abs(gsl_matrix_get(m, i, j)) > EPSILON) {
count++;
}
}
}
return count;
}
/*
* Returns a vector of indices of nonzero elements in the given vector.
*/
gsl_vector* bct::find(const gsl_vector* v) {
gsl_vector* nz = gsl_vector_alloc(nnz(v));
int pos = 0;
for (int i = 0; i < v->size; i++) {
if (std::abs(gsl_vector_get(v, i)) > EPSILON) {
gsl_vector_set(nz, pos, i);
pos++;
}
}
return nz;
}
/*
* Returns a matrix of size (rows->size, columns->size). Elements are copied
* from the specified rows and columns of m.
*/
gsl_matrix* bct::submatrix(const gsl_matrix* m, const gsl_vector* rows, const gsl_vector* columns) {
gsl_matrix* s = gsl_matrix_alloc(rows->size, columns->size);
for (int i = 0; i < rows->size; i++) {
for (int j = 0; j < columns->size; j++) {
gsl_matrix_set(s, i, j, gsl_matrix_get(m, gsl_vector_get(rows, i), gsl_vector_get(columns, j)));
}
}
return s;
}
/*
* Prints a vector using the given format for each element. This is only
* provided for debugging purposes. In other cases, use gsl_vector_fprintf.
*/
void bct::printf(const gsl_vector* v, const char* format) {
for (int i = 0; i < v->size; i++) {
std::printf(format, gsl_vector_get(v, i));
std::printf(" ");
}
std::printf("\n");
}
/*
* Prints a matrix using the given format for each element. This is only
* provided for debugging purposes. In other cases, use gsl_matrix_fprintf.
*/
void bct::printf(const gsl_matrix* m, const char* format) {
for (int i = 0; i < m->size1; i++) {
for (int j = 0; j < m->size2; j++) {
std::printf(format, gsl_matrix_get(m, i, j));
std::printf(" ");
}
std::printf("\n");
}
}
<commit_msg>Fixed bug in find when no nonzero elements exist.<commit_after>#include "bct.h"
#include <cassert>
#include <cmath>
#include <cstdio>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
/*
* Returns a binary copy of the given vector.
*/
gsl_vector* bct::binary(const gsl_vector* v) {
gsl_vector* bv = gsl_vector_calloc(v->size);
for (int i = 0; i < v->size; i++) {
if (std::abs(gsl_vector_get(v, i)) > EPSILON) {
gsl_vector_set(bv, i, 1.0);
}
}
return bv;
}
/*
* Returns a binary copy of the given matrix.
*/
gsl_matrix* bct::binary(const gsl_matrix* m) {
gsl_matrix* bm = gsl_matrix_calloc(m->size1, m->size2);
for (int i = 0; i < m->size1; i++) {
for (int j = 0; j < m->size2; j++) {
if (std::abs(gsl_matrix_get(m, i, j)) > EPSILON) {
gsl_matrix_set(bm, i, j, 1.0);
}
}
}
return bm;
}
/*
* Returns the number of nonzero elements in the given vector.
*/
int bct::nnz(const gsl_vector* v) {
int count = 0;
for (int i = 0; i < v->size; i++) {
if (std::abs(gsl_vector_get(v, i)) > EPSILON) {
count++;
}
}
return count;
}
/*
* Returns the number of nonzero elements in the given matrix.
*/
int bct::nnz(const gsl_matrix* m) {
int count = 0;
for (int i = 0; i < m->size1; i++) {
for (int j = 0; j < m->size2; j++) {
if (std::abs(gsl_matrix_get(m, i, j)) > EPSILON) {
count++;
}
}
}
return count;
}
/*
* Returns a vector of indices of nonzero elements in the given vector.
*/
gsl_vector* bct::find(const gsl_vector* v) {
int size = nnz(v);
assert(size > 0);
gsl_vector* nz = gsl_vector_alloc(size);
int pos = 0;
for (int i = 0; i < v->size; i++) {
if (std::abs(gsl_vector_get(v, i)) > EPSILON) {
gsl_vector_set(nz, pos, i);
pos++;
}
}
return nz;
}
/*
* Returns a matrix of size (rows->size, columns->size). Elements are copied
* from the specified rows and columns of m.
*/
gsl_matrix* bct::submatrix(const gsl_matrix* m, const gsl_vector* rows, const gsl_vector* columns) {
gsl_matrix* s = gsl_matrix_alloc(rows->size, columns->size);
for (int i = 0; i < rows->size; i++) {
for (int j = 0; j < columns->size; j++) {
gsl_matrix_set(s, i, j, gsl_matrix_get(m, gsl_vector_get(rows, i), gsl_vector_get(columns, j)));
}
}
return s;
}
/*
* Prints a vector using the given format for each element. This is only
* provided for debugging purposes. In other cases, use gsl_vector_fprintf.
*/
void bct::printf(const gsl_vector* v, const char* format) {
for (int i = 0; i < v->size; i++) {
std::printf(format, gsl_vector_get(v, i));
std::printf(" ");
}
std::printf("\n");
}
/*
* Prints a matrix using the given format for each element. This is only
* provided for debugging purposes. In other cases, use gsl_matrix_fprintf.
*/
void bct::printf(const gsl_matrix* m, const char* format) {
for (int i = 0; i < m->size1; i++) {
for (int j = 0; j < m->size2; j++) {
std::printf(format, gsl_matrix_get(m, i, j));
std::printf(" ");
}
std::printf("\n");
}
}
<|endoftext|> |
<commit_before>#include "ExponentialRand.h"
#include "UniformRand.h"
#include "../BasicRandGenerator.h"
template < typename RealType >
String ExponentialRand<RealType>::Name() const
{
return "Exponential(" + this->toStringWithPrecision(this->GetRate()) + ")";
}
template < typename RealType >
double ExponentialRand<RealType>::f(const RealType &x) const
{
return (x < 0.0) ? 0.0 : this->beta * std::exp(-this->beta * x);
}
template < typename RealType >
double ExponentialRand<RealType>::logf(const RealType & x) const
{
return (x < 0.0) ? -INFINITY : this->logBeta - this->beta * x;
}
template < typename RealType >
double ExponentialRand<RealType>::F(const RealType & x) const
{
return (x > 0.0) ? -std::expm1l(-this->beta * x) : 0.0;
}
template < typename RealType >
double ExponentialRand<RealType>::S(const RealType & x) const
{
return (x > 0.0) ? std::exp(-this->beta * x) : 1.0;
}
template < typename RealType >
RealType ExponentialRand<RealType>::Variate() const
{
return this->theta * StandardVariate(this->localRandGenerator);
}
template < typename RealType >
void ExponentialRand<RealType>::Sample(std::vector<RealType> &outputData) const
{
for (RealType & var : outputData)
var = this->Variate();
}
template < typename RealType >
RealType ExponentialRand<RealType>::StandardVariate(RandGenerator &randGenerator)
{
/// Ziggurat algorithm
size_t iter = 0;
do {
int stairId = randGenerator.Variate() & 255;
/// Get horizontal coordinate
RealType x = UniformRand<RealType>::StandardVariate(randGenerator) * ziggurat[stairId].second;
if (x < ziggurat[stairId + 1].second) /// if we are under the upper stair - accept
return x;
if (stairId == 0) /// if we catch the tail
return ziggurat[1].second + StandardVariate(randGenerator);
RealType height = ziggurat[stairId].first - ziggurat[stairId - 1].first;
if (ziggurat[stairId - 1].first + height * UniformRand<RealType>::StandardVariate(randGenerator) < std::exp(-x)) /// if we are under the curve - accept
return x;
/// rejection - go back
} while (++iter <= ProbabilityDistribution<RealType>::MAX_ITER_REJECTION);
/// fail due to some error
throw std::runtime_error("Exponential distribution: sampling failed");
}
template < typename RealType >
std::complex<double> ExponentialRand<RealType>::CFImpl(double t) const
{
return 1.0 / std::complex<double>(1.0, -this->theta * t);
}
template < typename RealType >
long double ExponentialRand<RealType>::Entropy() const
{
return 1.0 - this->logBeta;
}
template < typename RealType >
long double ExponentialRand<RealType>::Moment(int n) const
{
if (n < 0)
return 0;
if (n == 0)
return 1;
return std::exp(RandMath::lfact(n) - n * this->logBeta);
}
template class ExponentialRand<float>;
template class ExponentialRand<double>;
template class ExponentialRand<long double>;
<commit_msg>Update ExponentialRand.cpp<commit_after>#include "ExponentialRand.h"
#include "UniformRand.h"
#include "../BasicRandGenerator.h"
template < typename RealType >
String ExponentialRand<RealType>::Name() const
{
return "Exponential(" + this->toStringWithPrecision(this->GetRate()) + ")";
}
template < typename RealType >
double ExponentialRand<RealType>::SufficientStatistic(RealType x) const
{
return x;
}
template < typename RealType >
double ExponentialRand<RealType>::SourceParameters() const
{
return -this->beta;
}
template < typename RealType >
double ExponentialRand<RealType>::SourceToNatural(double rate) const
{
return -rate;
}
template < typename RealType >
double ExponentialRand<RealType>::LogNormalizer(double thetaP) const
{
return -std::log(-thetaP);
}
template < typename RealType >
double ExponentialRand<RealType>::LogNormalizerGradient(double thetaP) const
{
return -1.0 / thetaP;
}
template < typename RealType >
double ExponentialRand<RealType>::CarrierMeasure(RealType) const
{
return 0.0;
}
template < typename RealType >
double ExponentialRand<RealType>::f(const RealType &x) const
{
return (x < 0.0) ? 0.0 : this->beta * std::exp(-this->beta * x);
}
template < typename RealType >
double ExponentialRand<RealType>::logf(const RealType & x) const
{
return (x < 0.0) ? -INFINITY : this->logBeta - this->beta * x;
}
template < typename RealType >
double ExponentialRand<RealType>::F(const RealType & x) const
{
return (x > 0.0) ? -std::expm1l(-this->beta * x) : 0.0;
}
template < typename RealType >
double ExponentialRand<RealType>::S(const RealType & x) const
{
return (x > 0.0) ? std::exp(-this->beta * x) : 1.0;
}
template < typename RealType >
RealType ExponentialRand<RealType>::Variate() const
{
return this->theta * StandardVariate(this->localRandGenerator);
}
template < typename RealType >
void ExponentialRand<RealType>::Sample(std::vector<RealType> &outputData) const
{
for (RealType & var : outputData)
var = this->Variate();
}
template < typename RealType >
RealType ExponentialRand<RealType>::StandardVariate(RandGenerator &randGenerator)
{
/// Ziggurat algorithm
size_t iter = 0;
do {
int stairId = randGenerator.Variate() & 255;
/// Get horizontal coordinate
RealType x = UniformRand<RealType>::StandardVariate(randGenerator) * ziggurat[stairId].second;
if (x < ziggurat[stairId + 1].second) /// if we are under the upper stair - accept
return x;
if (stairId == 0) /// if we catch the tail
return ziggurat[1].second + StandardVariate(randGenerator);
RealType height = ziggurat[stairId].first - ziggurat[stairId - 1].first;
if (ziggurat[stairId - 1].first + height * UniformRand<RealType>::StandardVariate(randGenerator) < std::exp(-x)) /// if we are under the curve - accept
return x;
/// rejection - go back
} while (++iter <= ProbabilityDistribution<RealType>::MAX_ITER_REJECTION);
/// fail due to some error
throw std::runtime_error("Exponential distribution: sampling failed");
}
template < typename RealType >
std::complex<double> ExponentialRand<RealType>::CFImpl(double t) const
{
return 1.0 / std::complex<double>(1.0, -this->theta * t);
}
template < typename RealType >
long double ExponentialRand<RealType>::Entropy() const
{
return 1.0 - this->logBeta;
}
template < typename RealType >
long double ExponentialRand<RealType>::Moment(int n) const
{
if (n < 0)
return 0;
if (n == 0)
return 1;
return std::exp(RandMath::lfact(n) - n * this->logBeta);
}
template class ExponentialRand<float>;
template class ExponentialRand<double>;
template class ExponentialRand<long double>;
<|endoftext|> |
<commit_before>#include <Wire.h>
#include <EEPROM.h>
#include <Arduino.h>
#include <CmdMessenger.h>
#include <Adafruit_PWMServoDriver.h>
#define NUM_TELESCOPES 3
#define NUM_SERVOS 8
#define MOVE_WAIT_TIME 800
#define SWITCH_TELE0 2
#define SWITCH_TELE1 3
#define SWITCH_TELE2 4
#define OE_PIN 5
uint16_t positionsClosed[NUM_SERVOS] = {};
uint16_t positionsOpen[NUM_SERVOS] = {};
uint16_t positionsSet[NUM_SERVOS] = {};
uint8_t telescopeState[3] = {0, 0, 0};
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
CmdMessenger cmdMessenger = CmdMessenger(Serial, ',', ';');
enum{ // Closed Open
kAcknowledge, // 0
kError, // 1
kDebug, // 2
kSetServo, // 3 3,1,150; 3,1,400;
kStoreServo, // 4 4,1,0; 4,1,1;
kStateChange, // 5
kServoPosition // 6 0,1,0; 1,1,1;
};
void storePositions(){
uint8_t ee = 0;
uint8_t* p = (uint8_t*)(void*)&positionsClosed;
for (uint8_t i = 0; i < sizeof(positionsClosed); i++){
EEPROM.write(ee++, *p++);
}
ee = 100;
p = (uint8_t*)(void*)&positionsOpen;
for (uint8_t i = 0; i < sizeof(positionsOpen); i++){
EEPROM.write(ee++, *p++);
}
}
void loadPositions(){
uint8_t ee = 0;
uint8_t* p = (uint8_t*)(void*)&positionsClosed;
for (uint8_t i = 0; i < sizeof(positionsClosed); i++){
*p++ = EEPROM.read(ee++);
}
ee = 100;
p = (uint8_t*)(void*)&positionsOpen;
for (uint8_t i = 0; i < sizeof(positionsOpen); i++){
*p++ = EEPROM.read(ee++);
}
// Middel state, we don't know jet
for (uint8_t i = 0; i < NUM_SERVOS; i++){
positionsSet[i] = 300;
}
}
void OnSetServo(){
cmdMessenger.sendCmd(kDebug, "SetServo called");
uint8_t servo = cmdMessenger.readInt16Arg();
uint16_t position = cmdMessenger.readInt16Arg();
positionsSet[servo] = position;
pwm.setPWM(servo, 0, position);
cmdMessenger.sendCmd(kAcknowledge, "StoreServo moved");
}
void OnStoreServo(){
cmdMessenger.sendCmd(kDebug, "StoreServo called");
uint8_t servo = cmdMessenger.readInt16Arg();
uint8_t state = cmdMessenger.readInt16Arg();
if (state == 0) {
positionsClosed[servo] = positionsSet[servo];
}
if (state == 1) {
positionsOpen[servo] = positionsSet[servo];
}
storePositions();
cmdMessenger.sendCmd(kAcknowledge, "StoreServo stored");
}
void moveToState(uint8_t telescope, uint8_t state){
if (telescope == 0) {
if (state == 0){ // Close
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdEnd();
pwm.setPWM(1, 0, positionsOpen[1]); // Open Bahtinov
delay(MOVE_WAIT_TIME);
pwm.setPWM(0, 0, positionsClosed[0]); // Close Cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(1, 0, positionsClosed[1]); // Close Bahtinov
telescopeState[0] = 0;
} else if (state == 1){ // Open
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdEnd();
cmdMessenger.sendCmd(kStateChange, 1);
pwm.setPWM(1, 0, positionsOpen[1]); // Open Bahtinov
delay(MOVE_WAIT_TIME);
pwm.setPWM(0, 0, positionsOpen[0]); // Open Cover
telescopeState[0] = 1;
} else if (state == 2) { // Bahtinov
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdEnd();
cmdMessenger.sendCmd(kStateChange, 1);
pwm.setPWM(1, 0, positionsOpen[1]); // Open Bahtinov make sure its away
delay(MOVE_WAIT_TIME);
pwm.setPWM(0, 0, positionsOpen[0]); // Open cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(1, 0, positionsClosed[1]); // Close Bahtinov
telescopeState[0] = 2;
}
}
if (telescope == 1) {
if (state == 0){ // Close
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdEnd();
pwm.setPWM(4, 0, positionsOpen[4]); // Open Bahtinov
pwm.setPWM(5, 0, positionsOpen[5]); // Open Bahtinov
delay(MOVE_WAIT_TIME);
pwm.setPWM(2, 0, positionsClosed[2]); // Close Cover
pwm.setPWM(3, 0, positionsClosed[3]); // Close Cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(4, 0, positionsClosed[4]); // Close Bahtinov
pwm.setPWM(5, 0, positionsClosed[5]); // Close Bahtinov
telescopeState[1] = 0;
} else if (state == 1){ // Open
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdEnd();
pwm.setPWM(4, 0, positionsOpen[4]); // Open Bahtinov make sure its away
pwm.setPWM(5, 0, positionsOpen[5]); // Open Bahtinov make sure its away
delay(MOVE_WAIT_TIME);
pwm.setPWM(2, 0, positionsOpen[2]); // Open cover
pwm.setPWM(3, 0, positionsOpen[3]); // Open cover
telescopeState[1] = 1;
} else if (state == 2) { // Bahtinov
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdEnd();
pwm.setPWM(4, 0, positionsOpen[4]); // Open Bahtinov make sure its away
pwm.setPWM(5, 0, positionsOpen[5]); // Open Bahtinov make sure its away
delay(MOVE_WAIT_TIME);
pwm.setPWM(2, 0, positionsOpen[2]); // Open cover
pwm.setPWM(3, 0, positionsOpen[3]); // Open cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(4, 0, positionsClosed[4]); // Close Bahtinov
pwm.setPWM(5, 0, positionsClosed[5]); // Close Bahtinov
telescopeState[1] = 2;
}
}
if (telescope == 2) {
if (state == 0){ // Close
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdEnd();
pwm.setPWM(7, 0, positionsOpen[7]); // Open Bahtinov
delay(MOVE_WAIT_TIME);
pwm.setPWM(6, 0, positionsClosed[6]); // Close Cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(7, 0, positionsClosed[7]); // Close Bahtinov
telescopeState[2] = 0;
} else if (state == 1){ // Open
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdEnd();
pwm.setPWM(7, 0, positionsOpen[7]); // Open Bahtinov make sure its away
delay(MOVE_WAIT_TIME);
pwm.setPWM(6, 0, positionsOpen[6]); // Open Cover
telescopeState[2] = 1;
} else if (state == 2) { // Bahtinow
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdEnd();
pwm.setPWM(7, 0, positionsOpen[7]); // Open Bahtinov make sure its away
delay(MOVE_WAIT_TIME);
pwm.setPWM(6, 0, positionsOpen[6]); // Open cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(7, 0, positionsClosed[7]); // Close Bahtinov
telescopeState[2] = 2;
}
}
}
void OnServoPosition(){
cmdMessenger.sendCmd(kDebug, "move to position");
uint8_t telescope = cmdMessenger.readInt16Arg();
uint8_t state = cmdMessenger.readInt16Arg();
moveToState(telescope, state);
cmdMessenger.sendCmd(kAcknowledge, "position reached");
}
void attachCommandCallbacks(){
cmdMessenger.attach(kSetServo, OnSetServo);
cmdMessenger.attach(kStoreServo, OnStoreServo);
cmdMessenger.attach(kServoPosition, OnServoPosition);
}
void setup() {
pinMode(SWITCH_TELE0, INPUT_PULLUP);
pinMode(SWITCH_TELE1, INPUT_PULLUP);
pinMode(SWITCH_TELE2, INPUT_PULLUP);
pinMode(OE_PIN, OUTPUT);
digitalWrite(OE_PIN, HIGH); // disable
Serial.begin(9600);
cmdMessenger.printLfCr(true);
attachCommandCallbacks();
cmdMessenger.sendCmd(kDebug, "Arduino ready!");
loadPositions();
pwm.begin();
pwm.setPWMFreq(60); // Analog servos run at ~60 Hz updates
digitalWrite(OE_PIN, LOW); // enable
for (uint8_t i = 0; i < NUM_TELESCOPES; i++){
moveToState(i, 1); // Open
}
}
void loop() {
cmdMessenger.feedinSerialData();
if(!digitalRead(SWITCH_TELE0)){
moveToState(0, (telescopeState[0] + 1) % 3);
}
if(!digitalRead(SWITCH_TELE1)){
moveToState(1, (telescopeState[1] + 1) % 3);
}
if(!digitalRead(SWITCH_TELE2)){
moveToState(2, (telescopeState[2] + 1) % 3);
}
}
<commit_msg>Fixing Names<commit_after>#include <Wire.h>
#include <EEPROM.h>
#include <Arduino.h>
#include <CmdMessenger.h>
#include <Adafruit_PWMServoDriver.h>
#define NUM_TELESCOPES 3
#define NUM_SERVOS 8
#define MOVE_WAIT_TIME 800
#define SWITCH_TELE0 2
#define SWITCH_TELE1 3
#define SWITCH_TELE2 4
#define OE_PIN 5
uint16_t positionsClosed[NUM_SERVOS] = {};
uint16_t positionsOpen[NUM_SERVOS] = {};
uint16_t positionsSet[NUM_SERVOS] = {};
uint8_t telescopeState[3] = {0, 0, 0};
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
CmdMessenger cmdMessenger = CmdMessenger(Serial, ',', ';');
enum{ // Closed Open
kAcknowledge, // 0
kError, // 1
kDebug, // 2
kSetServo, // 3 3,1,150; 3,1,400;
kStoreServo, // 4 4,1,0; 4,1,1;
kStateChange, // 5
kTelescopePosition // 6 6,0,0; 6,0,1; 6,0,2;
};
void storePositions(){
uint8_t ee = 0;
uint8_t* p = (uint8_t*)(void*)&positionsClosed;
for (uint8_t i = 0; i < sizeof(positionsClosed); i++){
EEPROM.write(ee++, *p++);
}
ee = 100;
p = (uint8_t*)(void*)&positionsOpen;
for (uint8_t i = 0; i < sizeof(positionsOpen); i++){
EEPROM.write(ee++, *p++);
}
}
void loadPositions(){
uint8_t ee = 0;
uint8_t* p = (uint8_t*)(void*)&positionsClosed;
for (uint8_t i = 0; i < sizeof(positionsClosed); i++){
*p++ = EEPROM.read(ee++);
}
ee = 100;
p = (uint8_t*)(void*)&positionsOpen;
for (uint8_t i = 0; i < sizeof(positionsOpen); i++){
*p++ = EEPROM.read(ee++);
}
// Middel state, we don't know jet
for (uint8_t i = 0; i < NUM_SERVOS; i++){
positionsSet[i] = 300;
}
}
void OnSetServo(){
cmdMessenger.sendCmd(kDebug, "SetServo called");
uint8_t servo = cmdMessenger.readInt16Arg();
uint16_t position = cmdMessenger.readInt16Arg();
positionsSet[servo] = position;
pwm.setPWM(servo, 0, position);
cmdMessenger.sendCmd(kAcknowledge, "StoreServo moved");
}
void OnStoreServo(){
cmdMessenger.sendCmd(kDebug, "StoreServo called");
uint8_t servo = cmdMessenger.readInt16Arg();
uint8_t state = cmdMessenger.readInt16Arg();
if (state == 0) {
positionsClosed[servo] = positionsSet[servo];
}
if (state == 1) {
positionsOpen[servo] = positionsSet[servo];
}
storePositions();
cmdMessenger.sendCmd(kAcknowledge, "StoreServo stored");
}
void moveToState(uint8_t telescope, uint8_t state){
if (telescope == 0) {
if (state == 0){ // Close
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdEnd();
pwm.setPWM(1, 0, positionsOpen[1]); // Open Bahtinov
delay(MOVE_WAIT_TIME);
pwm.setPWM(0, 0, positionsClosed[0]); // Close Cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(1, 0, positionsClosed[1]); // Close Bahtinov
telescopeState[0] = 0;
} else if (state == 1){ // Open
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdEnd();
cmdMessenger.sendCmd(kStateChange, 1);
pwm.setPWM(1, 0, positionsOpen[1]); // Open Bahtinov
delay(MOVE_WAIT_TIME);
pwm.setPWM(0, 0, positionsOpen[0]); // Open Cover
telescopeState[0] = 1;
} else if (state == 2) { // Bahtinov
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdEnd();
cmdMessenger.sendCmd(kStateChange, 1);
pwm.setPWM(1, 0, positionsOpen[1]); // Open Bahtinov make sure its away
delay(MOVE_WAIT_TIME);
pwm.setPWM(0, 0, positionsOpen[0]); // Open cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(1, 0, positionsClosed[1]); // Close Bahtinov
telescopeState[0] = 2;
}
}
if (telescope == 1) {
if (state == 0){ // Close
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdEnd();
pwm.setPWM(4, 0, positionsOpen[4]); // Open Bahtinov
pwm.setPWM(5, 0, positionsOpen[5]); // Open Bahtinov
delay(MOVE_WAIT_TIME);
pwm.setPWM(2, 0, positionsClosed[2]); // Close Cover
pwm.setPWM(3, 0, positionsClosed[3]); // Close Cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(4, 0, positionsClosed[4]); // Close Bahtinov
pwm.setPWM(5, 0, positionsClosed[5]); // Close Bahtinov
telescopeState[1] = 0;
} else if (state == 1){ // Open
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdEnd();
pwm.setPWM(4, 0, positionsOpen[4]); // Open Bahtinov make sure its away
pwm.setPWM(5, 0, positionsOpen[5]); // Open Bahtinov make sure its away
delay(MOVE_WAIT_TIME);
pwm.setPWM(2, 0, positionsOpen[2]); // Open cover
pwm.setPWM(3, 0, positionsOpen[3]); // Open cover
telescopeState[1] = 1;
} else if (state == 2) { // Bahtinov
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdEnd();
pwm.setPWM(4, 0, positionsOpen[4]); // Open Bahtinov make sure its away
pwm.setPWM(5, 0, positionsOpen[5]); // Open Bahtinov make sure its away
delay(MOVE_WAIT_TIME);
pwm.setPWM(2, 0, positionsOpen[2]); // Open cover
pwm.setPWM(3, 0, positionsOpen[3]); // Open cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(4, 0, positionsClosed[4]); // Close Bahtinov
pwm.setPWM(5, 0, positionsClosed[5]); // Close Bahtinov
telescopeState[1] = 2;
}
}
if (telescope == 2) {
if (state == 0){ // Close
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdArg(0);
cmdMessenger.sendCmdEnd();
pwm.setPWM(7, 0, positionsOpen[7]); // Open Bahtinov
delay(MOVE_WAIT_TIME);
pwm.setPWM(6, 0, positionsClosed[6]); // Close Cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(7, 0, positionsClosed[7]); // Close Bahtinov
telescopeState[2] = 0;
} else if (state == 1){ // Open
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdArg(1);
cmdMessenger.sendCmdEnd();
pwm.setPWM(7, 0, positionsOpen[7]); // Open Bahtinov make sure its away
delay(MOVE_WAIT_TIME);
pwm.setPWM(6, 0, positionsOpen[6]); // Open Cover
telescopeState[2] = 1;
} else if (state == 2) { // Bahtinow
cmdMessenger.sendCmdStart(kStateChange);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdArg(2);
cmdMessenger.sendCmdEnd();
pwm.setPWM(7, 0, positionsOpen[7]); // Open Bahtinov make sure its away
delay(MOVE_WAIT_TIME);
pwm.setPWM(6, 0, positionsOpen[6]); // Open cover
delay(MOVE_WAIT_TIME);
pwm.setPWM(7, 0, positionsClosed[7]); // Close Bahtinov
telescopeState[2] = 2;
}
}
}
void OnTelescopePosition(){
cmdMessenger.sendCmd(kDebug, "move to position");
uint8_t telescope = cmdMessenger.readInt16Arg();
uint8_t state = cmdMessenger.readInt16Arg();
moveToState(telescope, state);
cmdMessenger.sendCmd(kAcknowledge, "position reached");
}
void attachCommandCallbacks( ){
cmdMessenger.attach(kSetServo, OnSetServo);
cmdMessenger.attach(kStoreServo, OnStoreServo);
cmdMessenger.attach(kTelescopePosition, OnTelescopePosition);
}
void setup() {
pinMode(SWITCH_TELE0, INPUT_PULLUP);
pinMode(SWITCH_TELE1, INPUT_PULLUP);
pinMode(SWITCH_TELE2, INPUT_PULLUP);
pinMode(OE_PIN, OUTPUT);
digitalWrite(OE_PIN, HIGH); // disable
Serial.begin(9600);
cmdMessenger.printLfCr(true);
attachCommandCallbacks();
cmdMessenger.sendCmd(kDebug, "Arduino ready!");
loadPositions();
pwm.begin();
pwm.setPWMFreq(60); // Analog servos run at ~60 Hz updates
digitalWrite(OE_PIN, LOW); // enable
for (uint8_t i = 0; i < NUM_TELESCOPES; i++){
moveToState(i, 1); // Open
}
}
void loop() {
cmdMessenger.feedinSerialData();
if(!digitalRead(SWITCH_TELE0)){
moveToState(0, (telescopeState[0] + 1) % 3);
}
if(!digitalRead(SWITCH_TELE1)){
moveToState(1, (telescopeState[1] + 1) % 3);
}
if(!digitalRead(SWITCH_TELE2)){
moveToState(2, (telescopeState[2] + 1) % 3);
}
}
<|endoftext|> |
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
commands/importcertificatescommand.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007, 2008 Klarälvdalens Datakonsult AB
Kleopatra 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 2 of the License, or
(at your option) any later version.
Kleopatra 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "importcertificatescommand.h"
#include "importcertificatescommand_p.h"
#include <kleo/cryptobackendfactory.h>
#include <kleo/importjob.h>
#include <gpgme++/global.h>
#include <gpgme++/importresult.h>
#include <KLocale>
#include <KMessageBox>
#include <KConfigGroup>
#include <QByteArray>
#include <QFile>
#include <QFileDialog>
#include <QPointer>
#include <QString>
#include <QWidget>
#include <QFileInfo>
#include <memory>
#include <cassert>
using namespace GpgME;
using namespace Kleo;
ImportCertificatesCommand::Private::Private( ImportCertificatesCommand * qq, KeyListController * c )
: Command::Private( qq, c ), cmsImportJob( 0 ), pgpImportJob( 0 )
{
}
ImportCertificatesCommand::Private::~Private() {}
#define d d_func()
#define q q_func()
ImportCertificatesCommand::ImportCertificatesCommand( KeyListController * p )
: Command( new Private( this, p ) )
{
}
ImportCertificatesCommand::ImportCertificatesCommand( QAbstractItemView * v, KeyListController * p )
: Command( v, new Private( this, p ) )
{
}
ImportCertificatesCommand::~ImportCertificatesCommand() {}
void ImportCertificatesCommand::Private::showDetails( QWidget * parent, const ImportResult & res, const QString & id ) {
// ### TODO: make a keylisting over Import::fingerprints(), then
// ### highlight imported certificates in view(), or maybe in a new tab?
const KLocalizedString normalLine = ki18n("<tr><td align=\"right\">%1</td><td>%2</td></tr>");
const KLocalizedString boldLine = ki18n("<tr><td align=\"right\"><b>%1</b></td><td>%2</td></tr>");
QStringList lines;
lines.push_back( normalLine.subs( i18n("Total number processed:") )
.subs( res.numConsidered() ).toString() );
lines.push_back( normalLine.subs( i18n("Imported:") )
.subs( res.numImported() ).toString() );
if ( res.newSignatures() )
lines.push_back( normalLine.subs( i18n("New signatures:") )
.subs( res.newSignatures() ).toString() );
if ( res.newUserIDs() )
lines.push_back( normalLine.subs( i18n("New user IDs:") )
.subs( res.newUserIDs() ).toString() );
if ( res.numKeysWithoutUserID() )
lines.push_back( normalLine.subs( i18n("Certificates without user IDs:") )
.subs( res.numKeysWithoutUserID() ).toString() );
if ( res.newSubkeys() )
lines.push_back( normalLine.subs( i18n("New subkeys:") )
.subs( res.newSubkeys() ).toString() );
if ( res.newRevocations() )
lines.push_back( boldLine.subs( i18n("Newly revoked:") )
.subs( res.newRevocations() ).toString() );
if ( res.notImported() )
lines.push_back( boldLine.subs( i18n("Not imported:") )
.subs( res.notImported() ).toString() );
if ( res.numUnchanged() )
lines.push_back( normalLine.subs( i18n("Unchanged:") )
.subs( res.numUnchanged() ).toString() );
if ( res.numSecretKeysConsidered() )
lines.push_back( normalLine.subs( i18n("Secret keys processed:") )
.subs( res.numSecretKeysConsidered() ).toString() );
if ( res.numSecretKeysImported() )
lines.push_back( normalLine.subs( i18n("Secret keys imported:") )
.subs( res.numSecretKeysImported() ).toString() );
if ( res.numSecretKeysConsidered() - res.numSecretKeysImported() - res.numSecretKeysUnchanged() > 0 )
lines.push_back( boldLine.subs( i18n("Secret keys <em>not</em> imported:") )
.subs( res.numSecretKeysConsidered()
- res.numSecretKeysImported()
- res.numSecretKeysUnchanged() ).toString() );
if ( res.numSecretKeysUnchanged() )
lines.push_back( normalLine.subs( i18n("Secret keys unchanged:") )
.subs( res.numSecretKeysUnchanged() ).toString() );
KMessageBox::information( parent,
id.isEmpty()
? i18n( "<qt><p>Detailed results of certificate import:</p>"
"<table>%1</table></qt>",
lines.join( QString() ) )
: i18n( "<qt><p>Detailed results of importing %1:</p>"
"<table>%2</table></qt>" ,
id, lines.join( QString() ) ),
i18n( "Certificate Import Result" ) );
}
void ImportCertificatesCommand::Private::showError( QWidget * parent, const Error & err, const QString & id ) {
assert( err );
assert( !err.isCanceled() );
const QString msg = id.isEmpty()
? i18n( "<qt><p>An error occurred while trying "
"to import the certificate:</p>"
"<p><b>%2</b></p></qt>",
QString::fromLocal8Bit( err.asString() ) )
: i18n( "<qt><p>An error occurred while trying "
"to import the certificate %1:</p>"
"<p><b>%2</b></p></qt>",
id, QString::fromLocal8Bit( err.asString() ) );
KMessageBox::error( parent, msg, i18n( "Certificate Import Failed" ) );
}
void ImportCertificatesCommand::Private::importResult( const ImportResult & result ) {
if ( result.error().code() )
if ( result.error().isCanceled() )
emit q->canceled();
else
showError( result.error() );
else
showDetails( result );
finished();
}
void ImportCertificatesCommand::Private::startImport( GpgME::Protocol protocol, const QByteArray & data, const QString & id ) {
assert( protocol != UnknownProtocol );
std::auto_ptr<ImportJob> job( CryptoBackendFactory::instance()->protocol( protocol )->importJob() );
assert( job.get() );
connect( job.get(), SIGNAL(result(GpgME::ImportResult)),
q, SLOT(importResult(GpgME::ImportResult)) );
connect( job.get(), SIGNAL(progress(QString,int,int)),
q, SIGNAL(progress(QString,int,int)) );
if ( const GpgME::Error err = job->start( data ) ) {
showError( err, id );
finished();
} else if ( err.isCanceled() ) {
emit q->canceled();
finished();
} else {
if ( protocol == CMS )
cmsImportJob = job.release();
else
pgpImportJob = job.release();
}
}
void ImportCertificatesCommand::doCancel() {
if ( d->cmsImportJob )
d->cmsImportJob->slotCancel();
if ( d->pgpImportJob )
d->pgpImportJob->slotCancel();
}
#undef d
#undef q
#include "moc_importcertificatescommand.cpp"
<commit_msg>SVN_SILENT fix string (s/%2/$1)<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
commands/importcertificatescommand.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007, 2008 Klarälvdalens Datakonsult AB
Kleopatra 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 2 of the License, or
(at your option) any later version.
Kleopatra 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "importcertificatescommand.h"
#include "importcertificatescommand_p.h"
#include <kleo/cryptobackendfactory.h>
#include <kleo/importjob.h>
#include <gpgme++/global.h>
#include <gpgme++/importresult.h>
#include <KLocale>
#include <KMessageBox>
#include <KConfigGroup>
#include <QByteArray>
#include <QFile>
#include <QFileDialog>
#include <QPointer>
#include <QString>
#include <QWidget>
#include <QFileInfo>
#include <memory>
#include <cassert>
using namespace GpgME;
using namespace Kleo;
ImportCertificatesCommand::Private::Private( ImportCertificatesCommand * qq, KeyListController * c )
: Command::Private( qq, c ), cmsImportJob( 0 ), pgpImportJob( 0 )
{
}
ImportCertificatesCommand::Private::~Private() {}
#define d d_func()
#define q q_func()
ImportCertificatesCommand::ImportCertificatesCommand( KeyListController * p )
: Command( new Private( this, p ) )
{
}
ImportCertificatesCommand::ImportCertificatesCommand( QAbstractItemView * v, KeyListController * p )
: Command( v, new Private( this, p ) )
{
}
ImportCertificatesCommand::~ImportCertificatesCommand() {}
void ImportCertificatesCommand::Private::showDetails( QWidget * parent, const ImportResult & res, const QString & id ) {
// ### TODO: make a keylisting over Import::fingerprints(), then
// ### highlight imported certificates in view(), or maybe in a new tab?
const KLocalizedString normalLine = ki18n("<tr><td align=\"right\">%1</td><td>%2</td></tr>");
const KLocalizedString boldLine = ki18n("<tr><td align=\"right\"><b>%1</b></td><td>%2</td></tr>");
QStringList lines;
lines.push_back( normalLine.subs( i18n("Total number processed:") )
.subs( res.numConsidered() ).toString() );
lines.push_back( normalLine.subs( i18n("Imported:") )
.subs( res.numImported() ).toString() );
if ( res.newSignatures() )
lines.push_back( normalLine.subs( i18n("New signatures:") )
.subs( res.newSignatures() ).toString() );
if ( res.newUserIDs() )
lines.push_back( normalLine.subs( i18n("New user IDs:") )
.subs( res.newUserIDs() ).toString() );
if ( res.numKeysWithoutUserID() )
lines.push_back( normalLine.subs( i18n("Certificates without user IDs:") )
.subs( res.numKeysWithoutUserID() ).toString() );
if ( res.newSubkeys() )
lines.push_back( normalLine.subs( i18n("New subkeys:") )
.subs( res.newSubkeys() ).toString() );
if ( res.newRevocations() )
lines.push_back( boldLine.subs( i18n("Newly revoked:") )
.subs( res.newRevocations() ).toString() );
if ( res.notImported() )
lines.push_back( boldLine.subs( i18n("Not imported:") )
.subs( res.notImported() ).toString() );
if ( res.numUnchanged() )
lines.push_back( normalLine.subs( i18n("Unchanged:") )
.subs( res.numUnchanged() ).toString() );
if ( res.numSecretKeysConsidered() )
lines.push_back( normalLine.subs( i18n("Secret keys processed:") )
.subs( res.numSecretKeysConsidered() ).toString() );
if ( res.numSecretKeysImported() )
lines.push_back( normalLine.subs( i18n("Secret keys imported:") )
.subs( res.numSecretKeysImported() ).toString() );
if ( res.numSecretKeysConsidered() - res.numSecretKeysImported() - res.numSecretKeysUnchanged() > 0 )
lines.push_back( boldLine.subs( i18n("Secret keys <em>not</em> imported:") )
.subs( res.numSecretKeysConsidered()
- res.numSecretKeysImported()
- res.numSecretKeysUnchanged() ).toString() );
if ( res.numSecretKeysUnchanged() )
lines.push_back( normalLine.subs( i18n("Secret keys unchanged:") )
.subs( res.numSecretKeysUnchanged() ).toString() );
KMessageBox::information( parent,
id.isEmpty()
? i18n( "<qt><p>Detailed results of certificate import:</p>"
"<table>%1</table></qt>",
lines.join( QString() ) )
: i18n( "<qt><p>Detailed results of importing %1:</p>"
"<table>%2</table></qt>" ,
id, lines.join( QString() ) ),
i18n( "Certificate Import Result" ) );
}
void ImportCertificatesCommand::Private::showError( QWidget * parent, const Error & err, const QString & id ) {
assert( err );
assert( !err.isCanceled() );
const QString msg = id.isEmpty()
? i18n( "<qt><p>An error occurred while trying "
"to import the certificate:</p>"
"<p><b>%1</b></p></qt>",
QString::fromLocal8Bit( err.asString() ) )
: i18n( "<qt><p>An error occurred while trying "
"to import the certificate %1:</p>"
"<p><b>%2</b></p></qt>",
id, QString::fromLocal8Bit( err.asString() ) );
KMessageBox::error( parent, msg, i18n( "Certificate Import Failed" ) );
}
void ImportCertificatesCommand::Private::importResult( const ImportResult & result ) {
if ( result.error().code() )
if ( result.error().isCanceled() )
emit q->canceled();
else
showError( result.error() );
else
showDetails( result );
finished();
}
void ImportCertificatesCommand::Private::startImport( GpgME::Protocol protocol, const QByteArray & data, const QString & id ) {
assert( protocol != UnknownProtocol );
std::auto_ptr<ImportJob> job( CryptoBackendFactory::instance()->protocol( protocol )->importJob() );
assert( job.get() );
connect( job.get(), SIGNAL(result(GpgME::ImportResult)),
q, SLOT(importResult(GpgME::ImportResult)) );
connect( job.get(), SIGNAL(progress(QString,int,int)),
q, SIGNAL(progress(QString,int,int)) );
if ( const GpgME::Error err = job->start( data ) ) {
showError( err, id );
finished();
} else if ( err.isCanceled() ) {
emit q->canceled();
finished();
} else {
if ( protocol == CMS )
cmsImportJob = job.release();
else
pgpImportJob = job.release();
}
}
void ImportCertificatesCommand::doCancel() {
if ( d->cmsImportJob )
d->cmsImportJob->slotCancel();
if ( d->pgpImportJob )
d->pgpImportJob->slotCancel();
}
#undef d
#undef q
#include "moc_importcertificatescommand.cpp"
<|endoftext|> |
<commit_before>/*
This file is part of Akregator.
Copyright (C) 2008 Frank Osterfeld <osterfeld@kde.org>
This program 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 2 of the License, or
(at your option) any later version.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "createfeedcommand.h"
#include "addfeeddialog.h"
#include "feed.h"
#include "feedpropertiesdialog.h"
#include "folder.h"
#include "subscriptionlistview.h"
#include <KInputDialog>
#include <KLocalizedString>
#include <KUrl>
#include <QPointer>
#include <QTimer>
#include <cassert>
using namespace Akregator;
class CreateFeedCommand::Private
{
CreateFeedCommand* const q;
public:
explicit Private( CreateFeedCommand* qq );
void doCreate();
Folder* m_rootFolder;
SubscriptionListView* m_subscriptionListView;
QString m_url;
Folder* m_parentFolder;
TreeNode* m_after;
bool m_autoexec;
};
CreateFeedCommand::Private::Private( CreateFeedCommand* qq )
: q( qq ),
m_rootFolder( 0 ),
m_subscriptionListView( 0 ),
m_parentFolder( 0 ),
m_after( 0 ),
m_autoexec( false )
{
}
void CreateFeedCommand::Private::doCreate()
{
assert( m_rootFolder );
assert( m_subscriptionListView );
QPointer<AddFeedDialog> afd = new AddFeedDialog( q->parentWidget(), "add_feed" );
afd->setUrl( KUrl::fromPercentEncoding( m_url.toLatin1() ) );
QPointer<QObject> thisPointer( q );
if ( m_autoexec )
afd->accept();
else
afd->exec();
if ( !thisPointer ) // "this" might have been deleted while exec()!
return;
Feed* const feed = afd->feed();
delete afd;
if ( !feed )
{
q->done();
return;
}
QPointer<FeedPropertiesDialog> dlg = new FeedPropertiesDialog( q->parentWidget(), "edit_feed" );
dlg->setFeed( feed );
dlg->selectFeedName();
if ( !m_autoexec && ( dlg->exec() != QDialog::Accepted || !thisPointer ) )
{
delete feed;
}
else
{
m_parentFolder = m_parentFolder ? m_parentFolder : m_rootFolder;
m_parentFolder->insertChild( feed, m_after );
m_subscriptionListView->ensureNodeVisible( feed );
}
delete dlg;
q->done();
}
CreateFeedCommand::CreateFeedCommand( QObject* parent ) : Command( parent ), d( new Private( this ) )
{
}
CreateFeedCommand::~CreateFeedCommand()
{
delete d;
}
void CreateFeedCommand::setSubscriptionListView( SubscriptionListView* view )
{
d->m_subscriptionListView = view;
}
void CreateFeedCommand::setRootFolder( Folder* rootFolder )
{
d->m_rootFolder = rootFolder;
}
void CreateFeedCommand::setUrl( const QString& url )
{
d->m_url = url;
}
void CreateFeedCommand::setPosition( Folder* parent, TreeNode* after )
{
d->m_parentFolder = parent;
d->m_after = after;
}
void CreateFeedCommand::setAutoExecute( bool autoexec )
{
d->m_autoexec = autoexec;
}
void CreateFeedCommand::doStart()
{
QTimer::singleShot( 0, this, SLOT( doCreate() ) );
}
void CreateFeedCommand::doAbort()
{
}
#include "createfeedcommand.moc"
<commit_msg>backport: QPointer-ize, should avoid a crash I got when adding a new feed<commit_after>/*
This file is part of Akregator.
Copyright (C) 2008 Frank Osterfeld <osterfeld@kde.org>
This program 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 2 of the License, or
(at your option) any later version.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "createfeedcommand.h"
#include "addfeeddialog.h"
#include "feed.h"
#include "feedpropertiesdialog.h"
#include "folder.h"
#include "subscriptionlistview.h"
#include <KInputDialog>
#include <KLocalizedString>
#include <KUrl>
#include <QPointer>
#include <QTimer>
#include <cassert>
using namespace Akregator;
class CreateFeedCommand::Private
{
CreateFeedCommand* const q;
public:
explicit Private( CreateFeedCommand* qq );
void doCreate();
QPointer<Folder> m_rootFolder;
QPointer<SubscriptionListView> m_subscriptionListView;
QString m_url;
QPointer<Folder> m_parentFolder;
QPointer<TreeNode> m_after;
bool m_autoexec;
};
CreateFeedCommand::Private::Private( CreateFeedCommand* qq )
: q( qq ),
m_rootFolder( 0 ),
m_subscriptionListView( 0 ),
m_parentFolder( 0 ),
m_after( 0 ),
m_autoexec( false )
{
}
void CreateFeedCommand::Private::doCreate()
{
assert( m_rootFolder );
assert( m_subscriptionListView );
QPointer<AddFeedDialog> afd = new AddFeedDialog( q->parentWidget(), "add_feed" );
afd->setUrl( KUrl::fromPercentEncoding( m_url.toLatin1() ) );
QPointer<QObject> thisPointer( q );
if ( m_autoexec )
afd->accept();
else
afd->exec();
if ( !thisPointer ) // "this" might have been deleted while exec()!
return;
Feed* const feed = afd->feed();
delete afd;
if ( !feed )
{
q->done();
return;
}
QPointer<FeedPropertiesDialog> dlg = new FeedPropertiesDialog( q->parentWidget(), "edit_feed" );
dlg->setFeed( feed );
dlg->selectFeedName();
if ( !m_autoexec && ( dlg->exec() != QDialog::Accepted || !thisPointer ) )
{
delete feed;
}
else
{
m_parentFolder = m_parentFolder ? m_parentFolder : m_rootFolder;
m_parentFolder->insertChild( feed, m_after );
m_subscriptionListView->ensureNodeVisible( feed );
}
delete dlg;
q->done();
}
CreateFeedCommand::CreateFeedCommand( QObject* parent ) : Command( parent ), d( new Private( this ) )
{
}
CreateFeedCommand::~CreateFeedCommand()
{
delete d;
}
void CreateFeedCommand::setSubscriptionListView( SubscriptionListView* view )
{
d->m_subscriptionListView = view;
}
void CreateFeedCommand::setRootFolder( Folder* rootFolder )
{
d->m_rootFolder = rootFolder;
}
void CreateFeedCommand::setUrl( const QString& url )
{
d->m_url = url;
}
void CreateFeedCommand::setPosition( Folder* parent, TreeNode* after )
{
d->m_parentFolder = parent;
d->m_after = after;
}
void CreateFeedCommand::setAutoExecute( bool autoexec )
{
d->m_autoexec = autoexec;
}
void CreateFeedCommand::doStart()
{
QTimer::singleShot( 0, this, SLOT( doCreate() ) );
}
void CreateFeedCommand::doAbort()
{
}
#include "createfeedcommand.moc"
<|endoftext|> |
<commit_before>XD<commit_msg>fixed smooth normal computation algorithm<commit_after>#include "CSmoothNormalGenerator.h"
#include <iostream>
#include <algorithm>
#include <array>
namespace irr
{
namespace asset
{
static inline bool operator<(uint32_t lhs, const IMeshManipulator::SSNGVertexData& rhs)
{
return lhs < rhs.hash;
}
static inline bool operator<(const IMeshManipulator::SSNGVertexData& lhs, uint32_t rhs)
{
return lhs.hash < rhs;
}
static inline bool compareVertexPosition(const core::vectorSIMDf& a, const core::vectorSIMDf& b, float epsilon)
{
const core::vectorSIMDf difference = core::abs(b - a);
return (difference.x <= epsilon && difference.y <= epsilon && difference.z <= epsilon);
}
static inline core::vector3df_SIMD getAngleWeight(const core::vector3df_SIMD & v1,
const core::vector3df_SIMD & v2,
const core::vector3df_SIMD & v3)
{
// Calculate this triangle's weight for each of its three vertices
// start by calculating the lengths of its sides
const float a = v2.getDistanceFromSQAsFloat(v3);
const float asqrt = sqrtf(a);
const float b = v1.getDistanceFromSQAsFloat(v3);
const float bsqrt = sqrtf(b);
const float c = v1.getDistanceFromSQAsFloat(v2);
const float csqrt = sqrtf(c);
// use them to find the angle at each vertex
return core::vector3df_SIMD(
acosf((b + c - a) / (2.f * bsqrt * csqrt)),
acosf((-b + c + a) / (2.f * asqrt * csqrt)),
acosf((b - c + a) / (2.f * bsqrt * asqrt)));
}
asset::ICPUMeshBuffer * irr::asset::CSmoothNormalGenerator::calculateNormals(asset::ICPUMeshBuffer * buffer, float epsilon, asset::E_VERTEX_ATTRIBUTE_ID normalAttrID, IMeshManipulator::VxCmpFunction vxcmp)
{
VertexHashMap vertexArray = setupData(buffer, epsilon);
processConnectedVertices(buffer, vertexArray, epsilon, normalAttrID, vxcmp);
return buffer;
}
CSmoothNormalGenerator::VertexHashMap::VertexHashMap(size_t _vertexCount, uint32_t _hashTableMaxSize, float _cellSize)
:hashTableMaxSize(_hashTableMaxSize),
cellSize(_cellSize)
{
assert((core::isPoT(hashTableMaxSize)));
vertices.reserve(_vertexCount);
buckets.reserve(_hashTableMaxSize + 1);
}
uint32_t CSmoothNormalGenerator::VertexHashMap::hash(const IMeshManipulator::SSNGVertexData & vertex) const
{
static constexpr uint32_t primeNumber1 = 73856093;
static constexpr uint32_t primeNumber2 = 19349663;
static constexpr uint32_t primeNumber3 = 83492791;
const core::vector3df_SIMD position = vertex.position / cellSize;
return ((static_cast<uint32_t>(position.x) * primeNumber1) ^
(static_cast<uint32_t>(position.y) * primeNumber2) ^
(static_cast<uint32_t>(position.z) * primeNumber3))& (hashTableMaxSize - 1);
}
uint32_t CSmoothNormalGenerator::VertexHashMap::hash(const core::vector3du32_SIMD & position) const
{
static constexpr uint32_t primeNumber1 = 73856093;
static constexpr uint32_t primeNumber2 = 19349663;
static constexpr uint32_t primeNumber3 = 83492791;
return ((position.x * primeNumber1) ^
(position.y * primeNumber2) ^
(position.z * primeNumber3))& (hashTableMaxSize - 1);
}
void CSmoothNormalGenerator::VertexHashMap::add(IMeshManipulator::SSNGVertexData && vertex)
{
vertex.hash = hash(vertex);
vertices.push_back(vertex);
}
CSmoothNormalGenerator::VertexHashMap::BucketBounds CSmoothNormalGenerator::VertexHashMap::getBucketBoundsByHash(uint32_t hash)
{
if (hash == invalidHash)
return { vertices.end(), vertices.end() };
core::vector<IMeshManipulator::SSNGVertexData>::iterator begin = std::lower_bound(vertices.begin(), vertices.end(), hash);
core::vector<IMeshManipulator::SSNGVertexData>::iterator end = std::upper_bound(vertices.begin(), vertices.end(), hash);
//bucket missing
if (begin == vertices.end())
return { vertices.end(), vertices.end() };
//bucket missing
if (begin->hash != hash)
return { vertices.end(), vertices.end() };
return { begin, end };
}
void CSmoothNormalGenerator::VertexHashMap::validate()
{
std::sort(vertices.begin(), vertices.end(), [](IMeshManipulator::SSNGVertexData & a, IMeshManipulator::SSNGVertexData & b) { return a.hash < b.hash; });
uint16_t prevHash = vertices[0].hash;
core::vector<IMeshManipulator::SSNGVertexData>::iterator prevBegin = vertices.begin();
buckets.push_back(prevBegin);
while (true)
{
core::vector<IMeshManipulator::SSNGVertexData>::iterator next = std::upper_bound(prevBegin, vertices.end(), prevHash);
buckets.push_back(next);
if (next == vertices.end())
break;
prevBegin = next;
prevHash = next->hash;
}
}
CSmoothNormalGenerator::VertexHashMap CSmoothNormalGenerator::setupData(asset::ICPUMeshBuffer * buffer, float epsilon)
{
const size_t idxCount = buffer->getIndexCount();
_IRR_DEBUG_BREAK_IF((idxCount % 3));
VertexHashMap vertices(idxCount, std::min(16u * 1024u, core::roundUpToPoT<unsigned int>(idxCount * 1.0f / 32.0f)), epsilon == 0.0f ? 0.00001f : epsilon * 1.00001f);
core::vector3df_SIMD faceNormal;
for (uint32_t i = 0; i < idxCount; i += 3)
{
//calculate face normal of parent triangle
core::vectorSIMDf v1 = buffer->getPosition(i);
core::vectorSIMDf v2 = buffer->getPosition(i + 1);
core::vectorSIMDf v3 = buffer->getPosition(i + 2);
faceNormal = core::cross(v2 - v1, v3 - v1);
faceNormal = core::normalize(faceNormal);
//set data for vertices
core::vector3df_SIMD angleWages = getAngleWeight(v1, v2, v3);
vertices.add({ i, 0, angleWages.x, v1, faceNormal });
vertices.add({ i + 1, 0, angleWages.y, v2, faceNormal });
vertices.add({ i + 2, 0, angleWages.z, v3, faceNormal });
}
vertices.validate();
return vertices;
}
void CSmoothNormalGenerator::processConnectedVertices(asset::ICPUMeshBuffer * buffer, VertexHashMap & vertexHashMap, float epsilon, asset::E_VERTEX_ATTRIBUTE_ID normalAttrID, IMeshManipulator::VxCmpFunction vxcmp)
{
for (uint32_t cell = 0; cell < vertexHashMap.getBucketCount() - 1; cell++)
{
VertexHashMap::BucketBounds processedBucket = vertexHashMap.getBucketBoundsById(cell);
for (core::vector<IMeshManipulator::SSNGVertexData>::iterator processedVertex = processedBucket.begin; processedVertex != processedBucket.end; processedVertex++)
{
std::array<uint32_t, 8> neighboringCells = vertexHashMap.getNeighboringCellHashes(*processedVertex);
core::vector3df_SIMD normal = processedVertex->parentTriangleFaceNormal * processedVertex->wage;
//iterate among all neighboring cells
for (int i = 0; i < 8; i++)
{
VertexHashMap::BucketBounds bounds = vertexHashMap.getBucketBoundsByHash(neighboringCells[i]);
for (; bounds.begin != bounds.end; bounds.begin++)
{
if (processedVertex != bounds.begin)
if (compareVertexPosition(processedVertex->position, bounds.begin->position, epsilon) &&
vxcmp(*processedVertex, *bounds.begin, buffer))
{
//TODO: better mean calculation algorithm
normal += bounds.begin->parentTriangleFaceNormal * bounds.begin->wage;
}
}
}
normal = core::normalize(core::vectorSIMDf(normal));
buffer->setAttribute(normal, normalAttrID, processedVertex->indexOffset);
}
}
}
std::array<uint32_t, 8> CSmoothNormalGenerator::VertexHashMap::getNeighboringCellHashes(const IMeshManipulator::SSNGVertexData & vertex)
{
std::array<uint32_t, 8> neighbourhood;
core::vectorSIMDf cellFloatCoord = vertex.position / cellSize - core::vectorSIMDf(0.5f);
core::vector3du32_SIMD neighbor = core::vector3du32_SIMD(static_cast<uint32_t>(cellFloatCoord.x), static_cast<uint32_t>(cellFloatCoord.y), static_cast<uint32_t>(cellFloatCoord.z));
//left bottom near
neighbourhood[0] = hash(neighbor);
//right bottom near
neighbor = neighbor + core::vector3du32_SIMD(1, 0, 0);
neighbourhood[1] = hash(neighbor);
//right bottom far
neighbor = neighbor + core::vector3du32_SIMD(0, 0, 1);
neighbourhood[2] = hash(neighbor);
//left bottom far
neighbor = neighbor - core::vector3du32_SIMD(1, 0, 0);
neighbourhood[3] = hash(neighbor);
//left top far
neighbor = neighbor + core::vector3du32_SIMD(0, 1, 0);
neighbourhood[4] = hash(neighbor);
//right top far
neighbor = neighbor + core::vector3du32_SIMD(1, 0, 0);
neighbourhood[5] = hash(neighbor);
//righ top near
neighbor = neighbor - core::vector3du32_SIMD(0, 0, 1);
neighbourhood[6] = hash(neighbor);
//left top near
neighbor = neighbor - core::vector3du32_SIMD(1, 0, 0);
neighbourhood[7] = hash(neighbor);
//erase duplicated hashes
for (int i = 0; i < 8; i++)
{
uint32_t currHash = neighbourhood[i];
for (int j = i + 1; j < 8; j++)
{
if (neighbourhood[j] == currHash)
neighbourhood[j] = invalidHash;
}
}
return neighbourhood;
}
}
}<|endoftext|> |
<commit_before>#include "CSmoothNormalGenerator.h"
#include <iostream>
#include <algorithm>
#include <array>
namespace irr
{
namespace asset
{
static inline bool operator<(uint32_t lhs, const IMeshManipulator::SSNGVertexData& rhs)
{
return lhs < rhs.hash;
}
static inline bool operator<(const IMeshManipulator::SSNGVertexData& lhs, uint32_t rhs)
{
return lhs.hash < rhs;
}
static inline bool compareVertexPosition(const core::vectorSIMDf& a, const core::vectorSIMDf& b, float epsilon)
{
const core::vectorSIMDf difference = core::abs(b - a);
return (difference.x <= epsilon && difference.y <= epsilon && difference.z <= epsilon);
}
static inline core::vector3df_SIMD getAngleWeight(const core::vector3df_SIMD & v1,
const core::vector3df_SIMD & v2,
const core::vector3df_SIMD & v3)
{
// Calculate this triangle's weight for each of its three vertices
// start by calculating the lengths of its sides
const float a = v2.getDistanceFromSQAsFloat(v3);
const float asqrt = sqrtf(a);
const float b = v1.getDistanceFromSQAsFloat(v3);
const float bsqrt = sqrtf(b);
const float c = v1.getDistanceFromSQAsFloat(v2);
const float csqrt = sqrtf(c);
// use them to find the angle at each vertex
return core::vector3df_SIMD(
acosf((b + c - a) / (2.f * bsqrt * csqrt)),
acosf((-b + c + a) / (2.f * asqrt * csqrt)),
acosf((b - c + a) / (2.f * bsqrt * asqrt)));
}
asset::ICPUMeshBuffer* irr::asset::CSmoothNormalGenerator::calculateNormals(asset::ICPUMeshBuffer* buffer, float epsilon, asset::E_VERTEX_ATTRIBUTE_ID normalAttrID, IMeshManipulator::VxCmpFunction vxcmp)
{
VertexHashMap vertexArray = setupData(buffer, epsilon);
processConnectedVertices(buffer, vertexArray, epsilon, normalAttrID, vxcmp);
return buffer;
}
CSmoothNormalGenerator::VertexHashMap::VertexHashMap(size_t _vertexCount, uint32_t _hashTableMaxSize, float _cellSize)
:hashTableMaxSize(_hashTableMaxSize),
cellSize(_cellSize)
{
assert((core::isPoT(hashTableMaxSize)));
vertices.reserve(_vertexCount);
buckets.reserve(_hashTableMaxSize+1);
}
uint32_t CSmoothNormalGenerator::VertexHashMap::hash(const IMeshManipulator::SSNGVertexData& vertex) const
{
static constexpr uint32_t primeNumber1 = 73856093;
static constexpr uint32_t primeNumber2 = 19349663;
static constexpr uint32_t primeNumber3 = 83492791;
const core::vector3df_SIMD position = vertex.position / cellSize;
return ((static_cast<uint32_t>(position.x) * primeNumber1) ^
(static_cast<uint32_t>(position.y) * primeNumber2) ^
(static_cast<uint32_t>(position.z) * primeNumber3)) & (hashTableMaxSize - 1);
}
uint32_t CSmoothNormalGenerator::VertexHashMap::hash(const core::vector3du32_SIMD& position) const
{
static constexpr uint32_t primeNumber1 = 73856093;
static constexpr uint32_t primeNumber2 = 19349663;
static constexpr uint32_t primeNumber3 = 83492791;
return ((position.x * primeNumber1) ^
(position.y * primeNumber2) ^
(position.z * primeNumber3)) & (hashTableMaxSize - 1);
}
void CSmoothNormalGenerator::VertexHashMap::add(IMeshManipulator::SSNGVertexData&& vertex)
{
vertex.hash = hash(vertex);
vertices.push_back(vertex);
}
CSmoothNormalGenerator::VertexHashMap::BucketBounds CSmoothNormalGenerator::VertexHashMap::getBucketBoundsByHash(uint32_t hash)
{
if (hash == invalidHash)
return { vertices.end(), vertices.end() };
core::vector<IMeshManipulator::SSNGVertexData>::iterator begin = std::lower_bound(vertices.begin(), vertices.end(), hash);
core::vector<IMeshManipulator::SSNGVertexData>::iterator end = std::upper_bound(vertices.begin(), vertices.end(), hash);
//bucket missing
if(begin == vertices.end())
return { vertices.end(), vertices.end() };
//bucket missing
if (begin->hash != hash)
return { vertices.end(), vertices.end() };
return { begin, end };
}
void CSmoothNormalGenerator::VertexHashMap::validate()
{
std::sort(vertices.begin(), vertices.end(), [](IMeshManipulator::SSNGVertexData& a, IMeshManipulator::SSNGVertexData& b) { return a.hash < b.hash; });
uint16_t prevHash = vertices[0].hash;
core::vector<IMeshManipulator::SSNGVertexData>::iterator prevBegin = vertices.begin();
buckets.push_back(prevBegin);
while (true)
{
core::vector<IMeshManipulator::SSNGVertexData>::iterator next = std::upper_bound(prevBegin, vertices.end(), prevHash);
buckets.push_back(next);
if (next == vertices.end())
break;
prevBegin = next;
prevHash = next->hash;
}
}
CSmoothNormalGenerator::VertexHashMap CSmoothNormalGenerator::setupData(asset::ICPUMeshBuffer * buffer, float epsilon)
{
const size_t idxCount = buffer->getIndexCount();
_IRR_DEBUG_BREAK_IF((idxCount % 3));
VertexHashMap vertices(idxCount, std::min(16u * 1024u, core::roundUpToPoT<unsigned int>(idxCount * 1.0f/32.0f)), epsilon == 0.0f ? 0.00001f : epsilon * 1.00001f);
core::vector3df_SIMD faceNormal;
for (uint32_t i = 0; i < idxCount; i += 3)
{
//calculate face normal of parent triangle
core::vectorSIMDf v1 = buffer->getPosition(i);
core::vectorSIMDf v2 = buffer->getPosition(i + 1);
core::vectorSIMDf v3 = buffer->getPosition(i + 2);
faceNormal = core::cross(v2 - v1, v3 - v1);
faceNormal = core::normalize(faceNormal);
//set data for vertices
core::vector3df_SIMD angleWages = getAngleWeight(v1, v2, v3);
vertices.add({ i, 0, angleWages.x, v1, faceNormal});
vertices.add({ i + 1, 0, angleWages.y, v2, faceNormal});
vertices.add({ i + 2, 0, angleWages.z, v3, faceNormal});
}
vertices.validate();
return vertices;
}
void CSmoothNormalGenerator::processConnectedVertices(asset::ICPUMeshBuffer * buffer, VertexHashMap & vertexHashMap, float epsilon, asset::E_VERTEX_ATTRIBUTE_ID normalAttrID, IMeshManipulator::VxCmpFunction vxcmp)
{
for (uint32_t cell = 0; cell < vertexHashMap.getBucketCount() - 1; cell++)
{
VertexHashMap::BucketBounds processedBucket = vertexHashMap.getBucketBoundsById(cell);
for (core::vector<IMeshManipulator::SSNGVertexData>::iterator processedVertex = processedBucket.begin; processedVertex != processedBucket.end; processedVertex++)
{
std::array<uint32_t, 8> neighboringCells = vertexHashMap.getNeighboringCellHashes(*processedVertex);
core::vector3df_SIMD normal = processedVertex->parentTriangleFaceNormal * processedVertex->wage;
//iterate among all neighboring cells
for (int i = 0; i < 8; i++)
{
VertexHashMap::BucketBounds bounds = vertexHashMap.getBucketBoundsByHash(neighboringCells[i]);
for (; bounds.begin != bounds.end; bounds.begin++)
{
if (processedVertex != bounds.begin)
if (compareVertexPosition(processedVertex->position, bounds.begin->position, epsilon) &&
vxcmp(*processedVertex, *bounds.begin, buffer))
{
//TODO: better mean calculation algorithm
normal += bounds.begin->parentTriangleFaceNormal * bounds.begin->wage;
}
}
}
normal = core::normalize(core::vectorSIMDf(normal));
buffer->setAttribute(normal, normalAttrID, processedVertex->indexOffset);
}
}
}
std::array<uint32_t, 8> CSmoothNormalGenerator::VertexHashMap::getNeighboringCellHashes(const IMeshManipulator::SSNGVertexData& vertex)
{
std::array<uint32_t, 8> neighbourhood;
core::vectorSIMDf cellFloatCoord = vertex.position / cellSize - core::vectorSIMDf(0.5f);
core::vector3du32_SIMD neighbor = core::vector3du32_SIMD(static_cast<uint32_t>(cellFloatCoord.x), static_cast<uint32_t>(cellFloatCoord.y), static_cast<uint32_t>(cellFloatCoord.z));
//left bottom near
neighbourhood[0] = hash(neighbor);
//right bottom near
neighbor = neighbor + core::vector3du32_SIMD(1, 0, 0);
neighbourhood[1] = hash(neighbor);
//right bottom far
neighbor = neighbor + core::vector3du32_SIMD(0, 0, 1);
neighbourhood[2] = hash(neighbor);
//left bottom far
neighbor = neighbor - core::vector3du32_SIMD(1, 0, 0);
neighbourhood[3] = hash(neighbor);
//left top far
neighbor = neighbor + core::vector3du32_SIMD(0, 1, 0);
neighbourhood[4] = hash(neighbor);
//right top far
neighbor = neighbor + core::vector3du32_SIMD(1, 0, 0);
neighbourhood[5] = hash(neighbor);
//righ top near
neighbor = neighbor - core::vector3du32_SIMD(0, 0, 1);
neighbourhood[6] = hash(neighbor);
//left top near
neighbor = neighbor - core::vector3du32_SIMD(1, 0, 0);
neighbourhood[7] = hash(neighbor);
//erase duplicated hashes
for (int i = 0; i < 8; i++)
{
uint32_t currHash = neighbourhood[i];
for (int j = i + 1; j < 8; j++)
{
if (neighbourhood[j] == currHash)
neighbourhood[j] = invalidHash;
}
}
return neighbourhood;
}
}
}<commit_msg>dont look at this<commit_after>XD<|endoftext|> |
<commit_before>// generic C
#include <cassert>
#include <cstdlib>
// Catch2
#include <catch.hpp>
// MIPT-MIPS modules
#include "../bpu.h"
TEST_CASE( "Initialization: WrongParameters")
{
// Check failing with wrong input values
CHECK_THROWS_AS( BaseBP::create_bp( "saturating_three_bits", 128, 16), BPInvalidMode);
CHECK_THROWS_AS( BaseBP::create_bp( "saturating_two_bits", 100, 20), BPInvalidMode);
}
TEST_CASE( "Static, all branches not taken")
{
auto bp = BaseBP::create_bp( "always_not_taken", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, false, target));
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == PC + 4);
}
TEST_CASE( "Static, all branches taken")
{
auto bp = BaseBP::create_bp( "always_taken", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "One bit predictor")
{
auto bp = BaseBP::create_bp( "saturating_one_bit", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Two bit predictor, basic")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Two bit predictor, advanced")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
Addr PC = 12;
Addr target = 28;
// Learn
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// "Over" - learning
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// Moderate "Un" - learning
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// Strong "un" - learning
bp->update( BPInterface( PC, false, NO_VAL32));
bp->update( BPInterface( PC, false, NO_VAL32));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
// Learn again
bp->update( BPInterface( PC, true, target));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Adaptive two bit prediction")
{
}
TEST_CASE( "Cache Miss")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
// Check default cache miss behaviour
Addr PC = 12;
CHECK_FALSE(bp->is_taken(PC));
PC = 16;
CHECK_FALSE(bp->is_taken(PC));
PC = 20;
CHECK_FALSE(bp->is_taken(PC));
PC = 12;
CHECK_FALSE(bp->is_taken(PC));
}
TEST_CASE( "Overload: LRU")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
const Addr PCconst = 16;
Addr target = 48;
// Trying to make it forget the PCconst
for ( int i = 0; i < 1000; i++)
{
bp->update( BPInterface( i, false, NO_VAL32));
if ( i % 50 == 0)
bp->update( BPInterface( PCconst, true, target));
}
// Checking some random PC and PCConst
Addr PC = 4;
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->is_taken(PCconst) );
CHECK( bp->get_target(PCconst) == target);
}
<commit_msg>add TN, T, T history to test always not taken mode<commit_after>// generic C
#include <cassert>
#include <cstdlib>
// Catch2
#include <catch.hpp>
// MIPT-MIPS modules
#include "../bpu.h"
TEST_CASE( "Initialization: WrongParameters")
{
// Check failing with wrong input values
CHECK_THROWS_AS( BaseBP::create_bp( "saturating_three_bits", 128, 16), BPInvalidMode);
CHECK_THROWS_AS( BaseBP::create_bp( "saturating_two_bits", 100, 20), BPInvalidMode);
}
TEST_CASE( "Static, all branches not taken")
{
auto bp = BaseBP::create_bp( "always_not_taken", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, true, target));
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == PC + 4);
}
TEST_CASE( "Static, all branches taken")
{
auto bp = BaseBP::create_bp( "always_taken", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "One bit predictor")
{
auto bp = BaseBP::create_bp( "saturating_one_bit", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Two bit predictor, basic")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Two bit predictor, advanced")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
Addr PC = 12;
Addr target = 28;
// Learn
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// "Over" - learning
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// Moderate "Un" - learning
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// Strong "un" - learning
bp->update( BPInterface( PC, false, NO_VAL32));
bp->update( BPInterface( PC, false, NO_VAL32));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
// Learn again
bp->update( BPInterface( PC, true, target));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Adaptive two bit prediction")
{
}
TEST_CASE( "Cache Miss")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
// Check default cache miss behaviour
Addr PC = 12;
CHECK_FALSE(bp->is_taken(PC));
PC = 16;
CHECK_FALSE(bp->is_taken(PC));
PC = 20;
CHECK_FALSE(bp->is_taken(PC));
PC = 12;
CHECK_FALSE(bp->is_taken(PC));
}
TEST_CASE( "Overload: LRU")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
const Addr PCconst = 16;
Addr target = 48;
// Trying to make it forget the PCconst
for ( int i = 0; i < 1000; i++)
{
bp->update( BPInterface( i, false, NO_VAL32));
if ( i % 50 == 0)
bp->update( BPInterface( PCconst, true, target));
}
// Checking some random PC and PCConst
Addr PC = 4;
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->is_taken(PCconst) );
CHECK( bp->get_target(PCconst) == target);
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include <cctype>
#include <list>
#include "Types.hpp"
#include "Utils.hpp"
#include "Parser.hpp"
#include "Operators.hpp"
#include "Lexer.hpp"
#include "Branches.hpp"
using std::string;
using std::ios_base;
using std::list;
using namespace eddic;
//TODO Review this method
ParseNode* Parser::parseInstruction() {
if(lexer.isIf()) {
return parseIf();
}
if(!lexer.isWord()) {
throw CompilerException("An instruction can only start with a call or an assignation");
}
string word = lexer.getCurrentToken();
if(!lexer.next()) {
throw CompilerException("Incomplete instruction");
}
if(lexer.isLeftParenth()) { //is a call
return parseCall(word);
} else if(lexer.isWord()) { //is a declaration
return parseDeclaration(word);
} else if(lexer.isAssign()) { //is an assign
return parseAssignment(word);
} else if(lexer.isSwap()){
return parseSwap(word);
} else {
throw CompilerException("Not an instruction");
}
}
Program* Parser::parse() {
Program* program = new Program();
while(lexer.next()) {
program->addLast(parseInstruction());
}
return program;
}
inline static void assertNextIsRightParenth(Lexer& lexer, const string& message) {
if(!lexer.next() || !lexer.isRightParenth()) {
throw CompilerException(message);
}
}
inline static void assertNextIsLeftParenth(Lexer& lexer, const string& message) {
if(!lexer.next() || !lexer.isLeftParenth()) {
throw CompilerException(message);
}
}
inline static void assertNextIsRightBrace(Lexer& lexer, const string& message) {
if(!lexer.next() || !lexer.isRightBrace()) {
throw CompilerException(message);
}
}
inline static void assertNextIsLeftBrace(Lexer& lexer, const string& message) {
if(!lexer.next() || !lexer.isLeftBrace()) {
throw CompilerException(message);
}
}
inline static void assertNextIsStop(Lexer& lexer, const string& message) {
if(!lexer.next() || !lexer.isStop()) {
throw CompilerException(message);
}
}
ParseNode* Parser::parseCall(const string& call) {
if(call != "Print" && call != "Println") {
throw CompilerException("The call \"" + call + "\" does not exist");
}
Value* value = parseValue();
assertNextIsRightParenth(lexer, "The call must be closed with a right parenth");
assertNextIsStop(lexer, "Every instruction must be closed by a semicolon");
if(call == "Print"){
return new Print(value);
} else {
return new Println(value);
}
}
ParseNode* Parser::parseDeclaration(const string& typeName) {
if(typeName != "int" && typeName != "string") {
throw CompilerException("Invalid type");
}
Type type;
if(typeName == "int") {
type = INT;
} else {
type = STRING;
}
string variable = lexer.getCurrentToken();
if(!lexer.next() || !lexer.isAssign()) {
throw CompilerException("A variable declaration must followed by '='");
}
Value* value = parseValue();
assertNextIsStop(lexer, "Every instruction must be closed by a semicolon");
return new Declaration(type, variable, value);
}
ParseNode* Parser::parseAssignment(const string& variable) {
Value* value = parseValue();
assertNextIsStop(lexer, "Every instruction must be closed by a semicolon");
return new Assignment(variable, value);
}
ParseNode* Parser::parseSwap(const string& lhs) {
if(!lexer.next() || !lexer.isWord()){
throw CompilerException("Can only swap two variables");
}
string rhs = lexer.getCurrentToken();
assertNextIsStop(lexer, "Every instruction must be closed by a semicolon");
return new Swap(lhs, rhs);
}
ParseNode* Parser::parseIf() {
assertNextIsLeftParenth(lexer, "An if instruction must be followed by a condition surrounded by parenth");
Condition* condition = parseCondition();
assertNextIsRightParenth(lexer, "The condition of the if must be closed by a right parenth");
assertNextIsLeftBrace(lexer, "Waiting for a left brace");
If* block = new If(condition);
lexer.next();
while(!lexer.isRightBrace()) {
block->addLast(parseInstruction());
lexer.next();
}
if(!lexer.isRightBrace()) {
throw CompilerException("If body must be closed with right brace");
}
while(true) {
if(lexer.next()) {
if(lexer.isElse()) {
lexer.next();
if(lexer.isIf()) {
block->addElseIf(parseElseIf());
} else {
lexer.pushBack();
block->setElse(parseElse());
break;
}
} else {
lexer.pushBack();
break;
}
} else {
break;
}
}
return block;
}
ElseIf* Parser::parseElseIf() {
assertNextIsLeftParenth(lexer, "An else if instruction must be followed by a condition surrounded by parenth");
Condition* condition = parseCondition();
assertNextIsRightParenth(lexer, "The condition of the else if must be closed by a right parenth");
assertNextIsLeftBrace(lexer, "Waiting for a left brace");
ElseIf* block = new ElseIf(condition);
lexer.next();
while(!lexer.isRightBrace()) {
block->addLast(parseInstruction());
lexer.next();
}
if(!lexer.isRightBrace()) {
throw CompilerException("Else ff body must be closed with right brace");
}
return block;
}
Else* Parser::parseElse() {
Else* block = new Else();
assertNextIsLeftBrace(lexer, "else statement must be followed by left brace");
while(lexer.next() && !lexer.isRightBrace()) {
block->addLast(parseInstruction());
}
if(!lexer.isRightBrace()) {
throw CompilerException("else body must be closed with right brace");
}
return block;
}
enum Operator {
ADD, MUL, SUB, DIV, MOD, ERROR
};
class Part {
public:
virtual bool isResolved() = 0;
virtual Operator getOperator() {
return ERROR;
}
virtual Value* getValue() {
return NULL;
}
};
class Resolved : public Part {
public:
Resolved(Value* v) : value(v) {}
bool isResolved() {
return true;
}
Value* getValue() {
return value;
}
private:
Value* value;
};
class Unresolved : public Part {
public:
Unresolved(Operator o) : op(o) {}
bool isResolved() {
return false;
}
Operator getOperator() {
return op;
}
private:
Operator op;
};
int priority(Operator op) {
switch(op) {
case MUL:
case DIV:
case MOD:
return 10;
case ADD:
case SUB:
return 0;
default:
return -1; //TODO should never happen
}
}
Value* Parser::parseValue() {
list<Part*> parts;
while(true) {
if(!lexer.next()) {
throw CompilerException("Waiting for a value");
}
Value* node = NULL;
if(lexer.isLitteral()) {
string litteral = lexer.getCurrentToken();
node = new Litteral(litteral);
} else if(lexer.isWord()) {
string variableRight = lexer.getCurrentToken();
node = new VariableValue(variableRight);
} else if(lexer.isInteger()) {
string integer = lexer.getCurrentToken();
int value = toNumber<int>(integer);
node = new Integer(value);
} else {
throw CompilerException("Invalid value");
}
parts.push_back(new Resolved(node));
if(!lexer.next()) {
break;
}
if(lexer.isAddition()) {
parts.push_back(new Unresolved(ADD));
} else if(lexer.isSubtraction()) {
parts.push_back(new Unresolved(SUB));
} else if(lexer.isMultiplication()) {
parts.push_back(new Unresolved(MUL));
} else if(lexer.isDivision()) {
parts.push_back(new Unresolved(DIV));
} else if(lexer.isModulo()) {
parts.push_back(new Unresolved(MOD));
} else {
lexer.pushBack();
break;
}
}
while(parts.size() > 1) {
int i = 0;
int debug = 0;
int maxPriority = -1;
list<Part*>::iterator it, end, max;
for(it = parts.begin(), end = parts.end(); it != end; ++it) {
Part* part = *it;
if(!part->isResolved()) {
if(priority(part->getOperator()) > maxPriority) {
maxPriority = priority(part->getOperator());
max = it;
i = debug;
}
}
debug++;
}
list<Part*>::iterator first = max;
--first;
Part* left = *first;
Part* center = *max;
++max;
Part* right = *max;
Value* lhs = left->getValue();
Operator op = center->getOperator();
Value* rhs = right->getValue();
Value* value = NULL;
if(op == ADD) {
value = new Addition(lhs, rhs);
} else if(op == SUB) {
value = new Subtraction(lhs, rhs);
} else if(op == MUL) {
value = new Multiplication(lhs, rhs);
} else if(op == DIV) {
value = new Division(lhs, rhs);
} else if(op == MOD) {
value = new Modulo(lhs, rhs);
}
parts.erase(first, ++max);
parts.insert(max, new Resolved(value));
}
Value* value = (*parts.begin())->getValue();
parts.clear();
return value;
}
Condition* Parser::parseCondition() {
lexer.next();
if(lexer.isTrue()) {
return new Condition(TRUE_VALUE);
} else if(lexer.isFalse()) {
return new Condition(FALSE_VALUE);
} else {
lexer.pushBack();
}
Value* lhs = parseValue();
if(!lexer.next()) {
throw CompilerException("waiting for a boolean operator");
}
BooleanCondition operation;
if(lexer.isGreater()) {
operation = GREATER_OPERATOR;
} else if(lexer.isLess()) {
operation = LESS_OPERATOR;
} else if(lexer.isEquals()) {
operation = EQUALS_OPERATOR;
} else if(lexer.isNotEquals()) {
operation = NOT_EQUALS_OPERATOR;
} else if(lexer.isGreaterOrEquals()) {
operation = GREATER_EQUALS_OPERATOR;
} else if(lexer.isLessOrEquals()) {
operation = LESS_EQUALS_OPERATOR;
} else {
throw CompilerException("waiting for a boolean operator");
}
Value* rhs = parseValue();
return new Condition(operation, lhs, rhs);
}
<commit_msg>Remove old debug code in the Parser<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include <cctype>
#include <list>
#include "Types.hpp"
#include "Utils.hpp"
#include "Parser.hpp"
#include "Operators.hpp"
#include "Lexer.hpp"
#include "Branches.hpp"
using std::string;
using std::ios_base;
using std::list;
using namespace eddic;
//TODO Review this method
ParseNode* Parser::parseInstruction() {
if(lexer.isIf()) {
return parseIf();
}
if(!lexer.isWord()) {
throw CompilerException("An instruction can only start with a call or an assignation");
}
string word = lexer.getCurrentToken();
if(!lexer.next()) {
throw CompilerException("Incomplete instruction");
}
if(lexer.isLeftParenth()) { //is a call
return parseCall(word);
} else if(lexer.isWord()) { //is a declaration
return parseDeclaration(word);
} else if(lexer.isAssign()) { //is an assign
return parseAssignment(word);
} else if(lexer.isSwap()){
return parseSwap(word);
} else {
throw CompilerException("Not an instruction");
}
}
Program* Parser::parse() {
Program* program = new Program();
while(lexer.next()) {
program->addLast(parseInstruction());
}
return program;
}
inline static void assertNextIsRightParenth(Lexer& lexer, const string& message) {
if(!lexer.next() || !lexer.isRightParenth()) {
throw CompilerException(message);
}
}
inline static void assertNextIsLeftParenth(Lexer& lexer, const string& message) {
if(!lexer.next() || !lexer.isLeftParenth()) {
throw CompilerException(message);
}
}
inline static void assertNextIsRightBrace(Lexer& lexer, const string& message) {
if(!lexer.next() || !lexer.isRightBrace()) {
throw CompilerException(message);
}
}
inline static void assertNextIsLeftBrace(Lexer& lexer, const string& message) {
if(!lexer.next() || !lexer.isLeftBrace()) {
throw CompilerException(message);
}
}
inline static void assertNextIsStop(Lexer& lexer, const string& message) {
if(!lexer.next() || !lexer.isStop()) {
throw CompilerException(message);
}
}
ParseNode* Parser::parseCall(const string& call) {
if(call != "Print" && call != "Println") {
throw CompilerException("The call \"" + call + "\" does not exist");
}
Value* value = parseValue();
assertNextIsRightParenth(lexer, "The call must be closed with a right parenth");
assertNextIsStop(lexer, "Every instruction must be closed by a semicolon");
if(call == "Print"){
return new Print(value);
} else {
return new Println(value);
}
}
ParseNode* Parser::parseDeclaration(const string& typeName) {
if(typeName != "int" && typeName != "string") {
throw CompilerException("Invalid type");
}
Type type;
if(typeName == "int") {
type = INT;
} else {
type = STRING;
}
string variable = lexer.getCurrentToken();
if(!lexer.next() || !lexer.isAssign()) {
throw CompilerException("A variable declaration must followed by '='");
}
Value* value = parseValue();
assertNextIsStop(lexer, "Every instruction must be closed by a semicolon");
return new Declaration(type, variable, value);
}
ParseNode* Parser::parseAssignment(const string& variable) {
Value* value = parseValue();
assertNextIsStop(lexer, "Every instruction must be closed by a semicolon");
return new Assignment(variable, value);
}
ParseNode* Parser::parseSwap(const string& lhs) {
if(!lexer.next() || !lexer.isWord()){
throw CompilerException("Can only swap two variables");
}
string rhs = lexer.getCurrentToken();
assertNextIsStop(lexer, "Every instruction must be closed by a semicolon");
return new Swap(lhs, rhs);
}
ParseNode* Parser::parseIf() {
assertNextIsLeftParenth(lexer, "An if instruction must be followed by a condition surrounded by parenth");
Condition* condition = parseCondition();
assertNextIsRightParenth(lexer, "The condition of the if must be closed by a right parenth");
assertNextIsLeftBrace(lexer, "Waiting for a left brace");
If* block = new If(condition);
lexer.next();
while(!lexer.isRightBrace()) {
block->addLast(parseInstruction());
lexer.next();
}
if(!lexer.isRightBrace()) {
throw CompilerException("If body must be closed with right brace");
}
while(true) {
if(lexer.next()) {
if(lexer.isElse()) {
lexer.next();
if(lexer.isIf()) {
block->addElseIf(parseElseIf());
} else {
lexer.pushBack();
block->setElse(parseElse());
break;
}
} else {
lexer.pushBack();
break;
}
} else {
break;
}
}
return block;
}
ElseIf* Parser::parseElseIf() {
assertNextIsLeftParenth(lexer, "An else if instruction must be followed by a condition surrounded by parenth");
Condition* condition = parseCondition();
assertNextIsRightParenth(lexer, "The condition of the else if must be closed by a right parenth");
assertNextIsLeftBrace(lexer, "Waiting for a left brace");
ElseIf* block = new ElseIf(condition);
lexer.next();
while(!lexer.isRightBrace()) {
block->addLast(parseInstruction());
lexer.next();
}
if(!lexer.isRightBrace()) {
throw CompilerException("Else ff body must be closed with right brace");
}
return block;
}
Else* Parser::parseElse() {
Else* block = new Else();
assertNextIsLeftBrace(lexer, "else statement must be followed by left brace");
while(lexer.next() && !lexer.isRightBrace()) {
block->addLast(parseInstruction());
}
if(!lexer.isRightBrace()) {
throw CompilerException("else body must be closed with right brace");
}
return block;
}
enum Operator {
ADD, MUL, SUB, DIV, MOD, ERROR
};
class Part {
public:
virtual bool isResolved() = 0;
virtual Operator getOperator() {
return ERROR;
}
virtual Value* getValue() {
return NULL;
}
};
class Resolved : public Part {
public:
Resolved(Value* v) : value(v) {}
bool isResolved() {
return true;
}
Value* getValue() {
return value;
}
private:
Value* value;
};
class Unresolved : public Part {
public:
Unresolved(Operator o) : op(o) {}
bool isResolved() {
return false;
}
Operator getOperator() {
return op;
}
private:
Operator op;
};
int priority(Operator op) {
switch(op) {
case MUL:
case DIV:
case MOD:
return 10;
case ADD:
case SUB:
return 0;
default:
return -1; //TODO should never happen
}
}
Value* Parser::parseValue() {
list<Part*> parts;
while(true) {
if(!lexer.next()) {
throw CompilerException("Waiting for a value");
}
Value* node = NULL;
if(lexer.isLitteral()) {
string litteral = lexer.getCurrentToken();
node = new Litteral(litteral);
} else if(lexer.isWord()) {
string variableRight = lexer.getCurrentToken();
node = new VariableValue(variableRight);
} else if(lexer.isInteger()) {
string integer = lexer.getCurrentToken();
int value = toNumber<int>(integer);
node = new Integer(value);
} else {
throw CompilerException("Invalid value");
}
parts.push_back(new Resolved(node));
if(!lexer.next()) {
break;
}
if(lexer.isAddition()) {
parts.push_back(new Unresolved(ADD));
} else if(lexer.isSubtraction()) {
parts.push_back(new Unresolved(SUB));
} else if(lexer.isMultiplication()) {
parts.push_back(new Unresolved(MUL));
} else if(lexer.isDivision()) {
parts.push_back(new Unresolved(DIV));
} else if(lexer.isModulo()) {
parts.push_back(new Unresolved(MOD));
} else {
lexer.pushBack();
break;
}
}
while(parts.size() > 1) {
int maxPriority = -1;
list<Part*>::iterator it, end, max;
for(it = parts.begin(), end = parts.end(); it != end; ++it) {
Part* part = *it;
if(!part->isResolved()) {
if(priority(part->getOperator()) > maxPriority) {
maxPriority = priority(part->getOperator());
max = it;
}
}
}
list<Part*>::iterator first = max;
--first;
Part* left = *first;
Part* center = *max;
++max;
Part* right = *max;
Value* lhs = left->getValue();
Operator op = center->getOperator();
Value* rhs = right->getValue();
Value* value = NULL;
if(op == ADD) {
value = new Addition(lhs, rhs);
} else if(op == SUB) {
value = new Subtraction(lhs, rhs);
} else if(op == MUL) {
value = new Multiplication(lhs, rhs);
} else if(op == DIV) {
value = new Division(lhs, rhs);
} else if(op == MOD) {
value = new Modulo(lhs, rhs);
}
parts.erase(first, ++max);
parts.insert(max, new Resolved(value));
}
Value* value = (*parts.begin())->getValue();
parts.clear();
return value;
}
Condition* Parser::parseCondition() {
lexer.next();
if(lexer.isTrue()) {
return new Condition(TRUE_VALUE);
} else if(lexer.isFalse()) {
return new Condition(FALSE_VALUE);
} else {
lexer.pushBack();
}
Value* lhs = parseValue();
if(!lexer.next()) {
throw CompilerException("waiting for a boolean operator");
}
BooleanCondition operation;
if(lexer.isGreater()) {
operation = GREATER_OPERATOR;
} else if(lexer.isLess()) {
operation = LESS_OPERATOR;
} else if(lexer.isEquals()) {
operation = EQUALS_OPERATOR;
} else if(lexer.isNotEquals()) {
operation = NOT_EQUALS_OPERATOR;
} else if(lexer.isGreaterOrEquals()) {
operation = GREATER_EQUALS_OPERATOR;
} else if(lexer.isLessOrEquals()) {
operation = LESS_EQUALS_OPERATOR;
} else {
throw CompilerException("waiting for a boolean operator");
}
Value* rhs = parseValue();
return new Condition(operation, lhs, rhs);
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
#include <ssl.h>
#include <nanoPAL.h>
#include "mbedtls.h"
int ssl_pending_internal( int sd )
{
(void)sd;
int avail = 0;
//mbedTLS_NFContext* context= (mbedTLS_NFContext*)SOCKET_DRIVER.GetSocketSslData(sd);
//mbedtls_ssl_context *ssl = context->ssl;
// if(ssl == NULL || ssl == (void*)SSL_SOCKET_ATTEMPTED_CONNECT)
// {
// return SOCK_SOCKET_ERROR;
// }
//avail = SSL_pending(ssl); /* send SSL/TLS close_notify */
return avail;
}
<commit_msg>Implement mbed TLS ssl_pending_internal<commit_after>//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
#include <ssl.h>
#include <nanoPAL.h>
#include "mbedtls.h"
int ssl_pending_internal( int sd )
{
mbedTLS_NFContext* context= (mbedTLS_NFContext*)SOCKET_DRIVER.GetSocketSslData(sd);
mbedtls_ssl_context *ssl = context->ssl;
if(ssl == NULL)
{
return SOCK_SOCKET_ERROR;
}
return mbedtls_ssl_check_pending(ssl);
}
<|endoftext|> |
<commit_before><commit_msg>Simplify some code that loops over all pixels of a bitmap.<commit_after><|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. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// Constant magnetic field class
// Used by AliRun class
// Author:
//-------------------------------------------------------------------------
#include <stdlib.h>
#include "AliLog.h"
#include "AliMagFC.h"
ClassImp(AliMagFC)
//________________________________________
AliMagFC::AliMagFC()
:AliMagF(),
fCompensator(kFALSE),
fBeamType(kBeamTypepp),
fBeamEnergy(0),
fQuadGradient(0),
fDipoleField(0),
fCCorrField(0),
fACorr1Field(0),
fACorr2Field(0)
{
//
// Default constructor
//
}
//________________________________________
AliMagFC::AliMagFC(const char *name, const char *title, Int_t integ,
Float_t factor, Float_t fmax)
: AliMagF(name,title,integ,factor,fmax),
fCompensator(kFALSE),
fBeamType(kBeamTypepp),
fBeamEnergy(7000.),
fQuadGradient(0),
fDipoleField(0),
fCCorrField(0),
fACorr1Field(0),
fACorr2Field(0)
{
//
// Standard constructor
//
fType = kConst;
fMap = 1;
}
//________________________________________
void AliMagFC::Field(Float_t *x, Float_t *b) const
{
//
// Method to return the field in a point
//
b[0]=b[1]=b[2]=0;
if(fMap==1) {
if(TMath::Abs(x[2])<700 && x[0]*x[0]+(x[1]+30)*(x[1]+30) < 560*560) {
b[2]=2;
}
else {
if(-725 >= x[2] && x[2] >= -1225 ){
Float_t dz = TMath::Abs(-975-x[2])*0.01;
b[0] = - (1-0.1*dz*dz)*7;
if(fFactor!=1) {
b[0]*=fFactor;
b[1]*=fFactor;
b[2]*=fFactor;
}
}
else {
ZDCField(x, b);
}
}
}
else {
AliFatal(Form("Invalid field map for constant field %d",fMap));
}
}
//___________________________________________________
void AliMagFC::ZDCField(Float_t *x, Float_t *b) const
{
// ---- This is the ZDC part
Float_t rad2 = x[0] * x[0] + x[1] * x[1];
static Bool_t init = kFALSE;
if (! init) {
init = kTRUE;
//////////////////////////////////////////////////////////////////////
// ---- Magnetic field values (according to beam type and energy) ----
if(fBeamType==kBeamTypepp && fBeamEnergy == 5000.){
// p-p @ 5+5 TeV
fQuadGradient = 15.7145;
fDipoleField = 27.0558;
// SIDE C
fCCorrField = 9.7017;
// SIDE A
fACorr1Field = -13.2143;
fACorr2Field = -11.9909;
} else if (fBeamType == kBeamTypepp && fBeamEnergy == 450.) {
// p-p 0.45+0.45 TeV
Float_t const kEnergyRatio = fBeamEnergy / 7000.;
fQuadGradient = 22.0002 * kEnergyRatio;
fDipoleField = 37.8781 * kEnergyRatio;
// SIDE C
fCCorrField = 9.6908;
// SIDE A
fACorr1Field = -13.2014;
fACorr2Field = -9.6908;
} else if ((fBeamType == kBeamTypepp && fBeamEnergy == 7000.) ||
(fBeamType == kBeamTypeAA))
{
// Pb-Pb @ 2.7+2.7 TeV or p-p @ 7+7 TeV
fQuadGradient = 22.0002;
fDipoleField = 37.8781;
// SIDE C
fCCorrField = 9.6908;
// SIDE A
fACorr1Field = -13.2014;
fACorr2Field = -9.6908;
}
printf("Machine field %5d %13.3f %13.3f \n", fBeamType, fBeamEnergy, fDipoleField);
}
// SIDE C **************************************************
if(x[2]<0.){
if(x[2] < kCCorrBegin && x[2] > kCCorrEnd && rad2 < kCCorrSqRadius){
if (fFactor != 0.) {
b[0] = fCCorrField;
b[1] = 0.;
b[2] = 0.;
}
}
else if(x[2] < kCQ1Begin && x[2] > kCQ1End && rad2 < kCQ1SqRadius){
b[0] = fQuadGradient*x[1];
b[1] = fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] < kCQ2Begin && x[2] > kCQ2End && rad2 < kCQ2SqRadius){
b[0] = -fQuadGradient*x[1];
b[1] = -fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] < kCQ3Begin && x[2] > kCQ3End && rad2 < kCQ3SqRadius){
b[0] = -fQuadGradient*x[1];
b[1] = -fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] < kCQ4Begin && x[2] > kCQ4End && rad2 < kCQ4SqRadius){
b[0] = fQuadGradient*x[1];
b[1] = fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] < kCD1Begin && x[2] > kCD1End && rad2 < kCD1SqRadius){
b[1] = fDipoleField;
b[2] = 0.;
b[2] = 0.;
}
else if(x[2] < kCD2Begin && x[2] > kCD2End){
if(((x[0]-kCD2XCentre1)*(x[0]-kCD2XCentre1)+(x[1]*x[1]))<kCD2SqRadius
|| ((x[0]-kCD2XCentre2)*(x[0]-kCD2XCentre2)+(x[1]*x[1]))<kCD2SqRadius){
b[1] = -fDipoleField;
b[2] = 0.;
b[2] = 0.;
}
}
}
// SIDE A **************************************************
else{
if(fCompensator && (x[2] > kACorr1Begin && x[2] < kACorr1End) && rad2 < kCCorr1SqRadius) {
// Compensator magnet at z = 1075 m
if (fFactor != 0.) {
b[0] = fACorr1Field;
b[1] = 0.;
b[2] = 0.;
}
return;
}
if(x[2] > kACorr2Begin && x[2] < kACorr2End && rad2 < kCCorr2SqRadius){
if (fFactor != 0.) {
b[0] = fACorr2Field;
b[1] = 0.;
b[2] = 0.;
}
}
else if(x[2] > kAQ1Begin && x[2] < kAQ1End && rad2 < kAQ1SqRadius){
// First quadrupole of inner triplet de-focussing in x-direction
b[0] = -fQuadGradient*x[1];
b[1] = -fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] > kAQ2Begin && x[2] < kAQ2End && rad2 < kAQ2SqRadius){
b[0] = fQuadGradient*x[1];
b[1] = fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] > kAQ3Begin && x[2] < kAQ3End && rad2 < kAQ3SqRadius){
b[0] = fQuadGradient*x[1];
b[1] = fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] > kAQ4Begin && x[2] < kAQ4End && rad2 < kAQ4SqRadius){
b[0] = -fQuadGradient*x[1];
b[1] = -fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] > kAD1Begin && x[2] < kAD1End && rad2 < kAD1SqRadius){
b[0] = 0.;
b[1] = -fDipoleField;
b[2] = 0.;
}
else if(x[2] > kAD2Begin && x[2] < kAD2End){
if(((x[0]-kAD2XCentre1)*(x[0]-kAD2XCentre1)+(x[1]*x[1])) < kAD2SqRadius
|| ((x[0]-kAD2XCentre2)*(x[0]-kAD2XCentre2)+(x[1]*x[1])) < kAD2SqRadius){
b[1] = fDipoleField;
}
}
}
}
<commit_msg>Debug message removed.<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. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// Constant magnetic field class
// Used by AliRun class
// Author:
//-------------------------------------------------------------------------
#include <stdlib.h>
#include "AliLog.h"
#include "AliMagFC.h"
ClassImp(AliMagFC)
//________________________________________
AliMagFC::AliMagFC()
:AliMagF(),
fCompensator(kFALSE),
fBeamType(kBeamTypepp),
fBeamEnergy(0),
fQuadGradient(0),
fDipoleField(0),
fCCorrField(0),
fACorr1Field(0),
fACorr2Field(0)
{
//
// Default constructor
//
}
//________________________________________
AliMagFC::AliMagFC(const char *name, const char *title, Int_t integ,
Float_t factor, Float_t fmax)
: AliMagF(name,title,integ,factor,fmax),
fCompensator(kFALSE),
fBeamType(kBeamTypepp),
fBeamEnergy(7000.),
fQuadGradient(0),
fDipoleField(0),
fCCorrField(0),
fACorr1Field(0),
fACorr2Field(0)
{
//
// Standard constructor
//
fType = kConst;
fMap = 1;
}
//________________________________________
void AliMagFC::Field(Float_t *x, Float_t *b) const
{
//
// Method to return the field in a point
//
b[0]=b[1]=b[2]=0;
if(fMap==1) {
if(TMath::Abs(x[2])<700 && x[0]*x[0]+(x[1]+30)*(x[1]+30) < 560*560) {
b[2]=2;
}
else {
if(-725 >= x[2] && x[2] >= -1225 ){
Float_t dz = TMath::Abs(-975-x[2])*0.01;
b[0] = - (1-0.1*dz*dz)*7;
if(fFactor!=1) {
b[0]*=fFactor;
b[1]*=fFactor;
b[2]*=fFactor;
}
}
else {
ZDCField(x, b);
}
}
}
else {
AliFatal(Form("Invalid field map for constant field %d",fMap));
}
}
//___________________________________________________
void AliMagFC::ZDCField(Float_t *x, Float_t *b) const
{
// ---- This is the ZDC part
Float_t rad2 = x[0] * x[0] + x[1] * x[1];
static Bool_t init = kFALSE;
if (! init) {
init = kTRUE;
//////////////////////////////////////////////////////////////////////
// ---- Magnetic field values (according to beam type and energy) ----
if(fBeamType==kBeamTypepp && fBeamEnergy == 5000.){
// p-p @ 5+5 TeV
fQuadGradient = 15.7145;
fDipoleField = 27.0558;
// SIDE C
fCCorrField = 9.7017;
// SIDE A
fACorr1Field = -13.2143;
fACorr2Field = -11.9909;
} else if (fBeamType == kBeamTypepp && fBeamEnergy == 450.) {
// p-p 0.45+0.45 TeV
Float_t const kEnergyRatio = fBeamEnergy / 7000.;
fQuadGradient = 22.0002 * kEnergyRatio;
fDipoleField = 37.8781 * kEnergyRatio;
// SIDE C
fCCorrField = 9.6908;
// SIDE A
fACorr1Field = -13.2014;
fACorr2Field = -9.6908;
} else if ((fBeamType == kBeamTypepp && fBeamEnergy == 7000.) ||
(fBeamType == kBeamTypeAA))
{
// Pb-Pb @ 2.7+2.7 TeV or p-p @ 7+7 TeV
fQuadGradient = 22.0002;
fDipoleField = 37.8781;
// SIDE C
fCCorrField = 9.6908;
// SIDE A
fACorr1Field = -13.2014;
fACorr2Field = -9.6908;
}
}
// SIDE C **************************************************
if(x[2]<0.){
if(x[2] < kCCorrBegin && x[2] > kCCorrEnd && rad2 < kCCorrSqRadius){
if (fFactor != 0.) {
b[0] = fCCorrField;
b[1] = 0.;
b[2] = 0.;
}
}
else if(x[2] < kCQ1Begin && x[2] > kCQ1End && rad2 < kCQ1SqRadius){
b[0] = fQuadGradient*x[1];
b[1] = fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] < kCQ2Begin && x[2] > kCQ2End && rad2 < kCQ2SqRadius){
b[0] = -fQuadGradient*x[1];
b[1] = -fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] < kCQ3Begin && x[2] > kCQ3End && rad2 < kCQ3SqRadius){
b[0] = -fQuadGradient*x[1];
b[1] = -fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] < kCQ4Begin && x[2] > kCQ4End && rad2 < kCQ4SqRadius){
b[0] = fQuadGradient*x[1];
b[1] = fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] < kCD1Begin && x[2] > kCD1End && rad2 < kCD1SqRadius){
b[1] = fDipoleField;
b[2] = 0.;
b[2] = 0.;
}
else if(x[2] < kCD2Begin && x[2] > kCD2End){
if(((x[0]-kCD2XCentre1)*(x[0]-kCD2XCentre1)+(x[1]*x[1]))<kCD2SqRadius
|| ((x[0]-kCD2XCentre2)*(x[0]-kCD2XCentre2)+(x[1]*x[1]))<kCD2SqRadius){
b[1] = -fDipoleField;
b[2] = 0.;
b[2] = 0.;
}
}
}
// SIDE A **************************************************
else{
if(fCompensator && (x[2] > kACorr1Begin && x[2] < kACorr1End) && rad2 < kCCorr1SqRadius) {
// Compensator magnet at z = 1075 m
if (fFactor != 0.) {
b[0] = fACorr1Field;
b[1] = 0.;
b[2] = 0.;
}
return;
}
if(x[2] > kACorr2Begin && x[2] < kACorr2End && rad2 < kCCorr2SqRadius){
if (fFactor != 0.) {
b[0] = fACorr2Field;
b[1] = 0.;
b[2] = 0.;
}
}
else if(x[2] > kAQ1Begin && x[2] < kAQ1End && rad2 < kAQ1SqRadius){
// First quadrupole of inner triplet de-focussing in x-direction
b[0] = -fQuadGradient*x[1];
b[1] = -fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] > kAQ2Begin && x[2] < kAQ2End && rad2 < kAQ2SqRadius){
b[0] = fQuadGradient*x[1];
b[1] = fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] > kAQ3Begin && x[2] < kAQ3End && rad2 < kAQ3SqRadius){
b[0] = fQuadGradient*x[1];
b[1] = fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] > kAQ4Begin && x[2] < kAQ4End && rad2 < kAQ4SqRadius){
b[0] = -fQuadGradient*x[1];
b[1] = -fQuadGradient*x[0];
b[2] = 0.;
}
else if(x[2] > kAD1Begin && x[2] < kAD1End && rad2 < kAD1SqRadius){
b[0] = 0.;
b[1] = -fDipoleField;
b[2] = 0.;
}
else if(x[2] > kAD2Begin && x[2] < kAD2End){
if(((x[0]-kAD2XCentre1)*(x[0]-kAD2XCentre1)+(x[1]*x[1])) < kAD2SqRadius
|| ((x[0]-kAD2XCentre2)*(x[0]-kAD2XCentre2)+(x[1]*x[1])) < kAD2SqRadius){
b[1] = fDipoleField;
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_LOCAL_HH
// dune-fem-tools includes, should be removed in the end!
//#include <dune/fem-tools/grid/entity.hh>
namespace Dune
{
namespace DetailedDiscretizations
{
namespace DiscreteFunction
{
template< class DiscreteFunctionImp >
class LocalConst
{
public:
typedef DiscreteFunctionImp
DiscreteFunctionType;
typedef LocalConst< DiscreteFunctionType >
ThisType;
typedef typename DiscreteFunctionType::DiscreteFunctionSpaceType
DiscreteFunctionSpaceType;
typedef typename DiscreteFunctionSpaceType::GridViewType::template Codim< 0 >::Iterator::Entity
EntityType;
typedef typename DiscreteFunctionType::DomainType
DomainType;
typedef typename DiscreteFunctionType::RangeFieldType
RangeFieldType;
typedef typename DiscreteFunctionType::RangeType
RangeType;
typedef typename DiscreteFunctionType::JacobianRangeType
JacobianRangeType;
private:
typedef typename DiscreteFunctionSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType
LocalBaseFunctionSetType;
public:
LocalConst( const DiscreteFunctionType& discreteFunction, const EntityType& entity )
: discreteFunction_( discreteFunction ),
entity_( entity ),
localBaseFunctionSet_( discreteFunction_.space().baseFunctionSet().local( entity_ ) ),
size_( localBaseFunctionSet_.size() ),
order_( localBaseFunctionSet_.order() )
{
}
//! copy constructor
LocalConst( const ThisType& other )
: discreteFunction_( other.discreteFunction() ),
entity_( other.entity() ),
localBaseFunctionSet_( discreteFunction_.space().baseFunctionSet().local( entity_ ) ),
size_( localBaseFunctionSet_.size() ),
order_( localBaseFunctionSet_.order() )
{
}
const DiscreteFunctionType& discreteFunction() const
{
return discreteFunction_;
}
const EntityType& entity() const
{
return entity_;
}
const RangeFieldType& operator[]( const unsigned int localDofNumber ) const
{
const unsigned int globalDofNumber = discreteFunction_.space().map().toGlobal( entity_, localDofNumber );
return discreteFunction_[globalDofNumber];
}
int order() const
{
return order_;
}
unsigned int size() const
{
return size_;
}
void evaluate( const DomainType& x, RangeType& ret) const
{
std::vector< RangeType > baseFunctionValues( size(), RangeType( 0.0 ) );
localBaseFunctionSet_.evaluate( x, baseFunctionValues );
ret = 0.0;
for( unsigned int i = 0; i < size(); ++i )
{
baseFunctionValues[i] *= operator[](i);
ret += baseFunctionValues[i];
}
}
void jacobian( const DomainType& x, JacobianRangeType& ret ) const
{
std::vector< JacobianRangeType > baseFunctionJacobianValues( size(), JacobianRangeType( 0.0 ) );
localBaseFunctionSet_.jacobian( x, baseFunctionJacobianValues );
ret = 0.0;
for( unsigned int i = 0; i < size(); ++i )
{
baseFunctionJacobianValues[i] *= operator[](i);
ret += baseFunctionJacobianValues[i];
}
}
private:
//! assignment operator
ThisType& operator=( const ThisType& );
const DiscreteFunctionType& discreteFunction_;
const EntityType& entity_;
const LocalBaseFunctionSetType localBaseFunctionSet_;
const unsigned int size_;
const int order_;
}; // end class LocalConst
template< class DiscreteFunctionImp >
class Local
: public LocalConst< DiscreteFunctionImp >
{
public:
typedef DiscreteFunctionImp
DiscreteFunctionType;
typedef Local< DiscreteFunctionType >
ThisType;
typedef LocalConst< DiscreteFunctionType >
BaseType;
typedef typename BaseType::DiscreteFunctionSpaceType
DiscreteFunctionSpaceType;
typedef typename BaseType::EntityType
EntityType;
typedef typename BaseType::DomainType
DomainType;
typedef typename BaseType::RangeFieldType
RangeFieldType;
typedef typename BaseType::RangeType
RangeType;
typedef typename BaseType::JacobianRangeType
JacobianRangeType;
Local( DiscreteFunctionType& discreteFunction, const EntityType& entity )
: BaseType( const_cast< const DiscreteFunctionType& >( discreteFunction ), entity ),
discreteFunction_( discreteFunction )
{
}
using BaseType::entity;
using BaseType::operator[];
RangeFieldType& operator[]( const unsigned int localDofNumber )
{
const unsigned int globalDofNumber = discreteFunction_.space().map().toGlobal( entity(), localDofNumber );
return discreteFunction_[globalDofNumber];
}
using BaseType::order;
using BaseType::size;
using BaseType::evaluate;
using BaseType::jacobian;
private:
DiscreteFunctionType& discreteFunction_;
}; // end class Local
} // end namespace DiscreteFunction
} // end namespace DetailedDiscretizations
} // end namespace Dune
#endif // DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_LOCAL_HH
<commit_msg>[discretefunction.local] minor change<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_LOCAL_HH
// dune-fem-tools includes, should be removed in the end!
//#include <dune/fem-tools/grid/entity.hh>
namespace Dune
{
namespace DetailedDiscretizations
{
namespace DiscreteFunction
{
template< class DiscreteFunctionImp >
class LocalConst
{
public:
typedef DiscreteFunctionImp
DiscreteFunctionType;
typedef LocalConst< DiscreteFunctionType >
ThisType;
typedef typename DiscreteFunctionType::DiscreteFunctionSpaceType
DiscreteFunctionSpaceType;
typedef typename DiscreteFunctionSpaceType::EntityType EntityType;
typedef typename DiscreteFunctionType::DomainType
DomainType;
typedef typename DiscreteFunctionType::RangeFieldType
RangeFieldType;
typedef typename DiscreteFunctionType::RangeType
RangeType;
typedef typename DiscreteFunctionType::JacobianRangeType
JacobianRangeType;
private:
typedef typename DiscreteFunctionSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType
LocalBaseFunctionSetType;
public:
LocalConst( const DiscreteFunctionType& discreteFunction, const EntityType& entity )
: discreteFunction_( discreteFunction ),
entity_( entity ),
localBaseFunctionSet_( discreteFunction_.space().baseFunctionSet().local( entity_ ) ),
size_( localBaseFunctionSet_.size() ),
order_( localBaseFunctionSet_.order() )
{
}
//! copy constructor
LocalConst( const ThisType& other )
: discreteFunction_( other.discreteFunction() ),
entity_( other.entity() ),
localBaseFunctionSet_( discreteFunction_.space().baseFunctionSet().local( entity_ ) ),
size_( localBaseFunctionSet_.size() ),
order_( localBaseFunctionSet_.order() )
{
}
const DiscreteFunctionType& discreteFunction() const
{
return discreteFunction_;
}
const EntityType& entity() const
{
return entity_;
}
const RangeFieldType& operator[]( const unsigned int localDofNumber ) const
{
const unsigned int globalDofNumber = discreteFunction_.space().map().toGlobal( entity_, localDofNumber );
return discreteFunction_[globalDofNumber];
}
int order() const
{
return order_;
}
unsigned int size() const
{
return size_;
}
void evaluate( const DomainType& x, RangeType& ret) const
{
std::vector< RangeType > baseFunctionValues( size(), RangeType( 0.0 ) );
localBaseFunctionSet_.evaluate( x, baseFunctionValues );
ret = 0.0;
for( unsigned int i = 0; i < size(); ++i )
{
baseFunctionValues[i] *= operator[](i);
ret += baseFunctionValues[i];
}
}
void jacobian( const DomainType& x, JacobianRangeType& ret ) const
{
std::vector< JacobianRangeType > baseFunctionJacobianValues( size(), JacobianRangeType( 0.0 ) );
localBaseFunctionSet_.jacobian( x, baseFunctionJacobianValues );
ret = 0.0;
for( unsigned int i = 0; i < size(); ++i )
{
baseFunctionJacobianValues[i] *= operator[](i);
ret += baseFunctionJacobianValues[i];
}
}
private:
//! assignment operator
ThisType& operator=( const ThisType& );
const DiscreteFunctionType& discreteFunction_;
const EntityType& entity_;
const LocalBaseFunctionSetType localBaseFunctionSet_;
const unsigned int size_;
const int order_;
}; // end class LocalConst
template< class DiscreteFunctionImp >
class Local
: public LocalConst< DiscreteFunctionImp >
{
public:
typedef DiscreteFunctionImp
DiscreteFunctionType;
typedef Local< DiscreteFunctionType >
ThisType;
typedef LocalConst< DiscreteFunctionType >
BaseType;
typedef typename BaseType::DiscreteFunctionSpaceType
DiscreteFunctionSpaceType;
typedef typename BaseType::EntityType
EntityType;
typedef typename BaseType::DomainType
DomainType;
typedef typename BaseType::RangeFieldType
RangeFieldType;
typedef typename BaseType::RangeType
RangeType;
typedef typename BaseType::JacobianRangeType
JacobianRangeType;
Local( DiscreteFunctionType& discreteFunction, const EntityType& entity )
: BaseType( const_cast< const DiscreteFunctionType& >( discreteFunction ), entity ),
discreteFunction_( discreteFunction )
{
}
using BaseType::entity;
using BaseType::operator[];
RangeFieldType& operator[]( const unsigned int localDofNumber )
{
const unsigned int globalDofNumber = discreteFunction_.space().map().toGlobal( entity(), localDofNumber );
return discreteFunction_[globalDofNumber];
}
using BaseType::order;
using BaseType::size;
using BaseType::evaluate;
using BaseType::jacobian;
private:
DiscreteFunctionType& discreteFunction_;
}; // end class Local
} // end namespace DiscreteFunction
} // end namespace DetailedDiscretizations
} // end namespace Dune
#endif // DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_LOCAL_HH
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "YamlSubstIstream.hxx"
#include "SubstIstream.hxx"
#include "FailIstream.hxx"
#include "UnusedPtr.hxx"
#include "pool/pool.hxx"
#include "util/IterableSplitString.hxx"
#include "util/RuntimeError.hxx"
#include "util/StringView.hxx"
#include <yaml-cpp/node/parse.h>
#include <yaml-cpp/node/node.h>
#include <yaml-cpp/node/iterator.h>
#include <yaml-cpp/node/impl.h>
#include <yaml-cpp/node/convert.h>
#include <yaml-cpp/node/detail/impl.h>
static YAML::Node
ResolveYamlPathSegment(const YAML::Node &parent, StringView segment)
{
if (parent.IsMap()) {
auto result = parent[std::string(segment.data, segment.size).c_str()];
if (!result)
throw FormatRuntimeError("YAML path segment '%.*s' does not exist",
int(segment.size), segment.data);
return result;
} else
throw FormatRuntimeError("Failed to resolve YAML path segment '%.*s'",
int(segment.size), segment.data);
}
static YAML::Node
ResolveYamlPath(YAML::Node node, StringView path)
{
for (StringView s : IterableSplitString(path, '.')) {
if (s.empty())
continue;
node = ResolveYamlPathSegment(node, s);
}
return node;
}
static YAML::Node
ResolveYamlMap(YAML::Node node, StringView path)
{
node = ResolveYamlPath(node, path);
if (!node.IsMap())
throw path.empty()
? std::runtime_error("Not a YAML map")
: FormatRuntimeError("Path '%.*s' is not a YAML map",
int(path.size), path.data);
return node;
}
static auto
MakePrefix(const char *_prefix)
{
std::string prefix = "{[";
if (_prefix != nullptr)
prefix += _prefix;
return prefix;
}
static SubstTree
LoadYamlMap(struct pool &pool, const char *_prefix,
const YAML::Node &node) noexcept
{
assert(node.IsMap());
const auto prefix = MakePrefix(_prefix);
SubstTree tree;
for (const auto &i : node) {
if (!i.first.IsScalar() || !i.second.IsScalar())
continue;
const auto name = prefix + i.first.as<std::string>() + "]}";
const auto value = i.second.as<std::string>();
tree.Add(pool, p_strndup(&pool, name.data(), name.length()),
{p_strndup(&pool, value.data(), value.length()), value.length()});
}
return tree;
}
UnusedIstreamPtr
NewYamlSubstIstream(struct pool &pool, UnusedIstreamPtr input,
const char *prefix,
const YAML::Node &yaml_node, const char *yaml_map_path)
{
return istream_subst_new(&pool, std::move(input),
LoadYamlMap(pool, prefix,
ResolveYamlMap(yaml_node,
yaml_map_path)));
}
static SubstTree
LoadYamlFile(struct pool &pool, const char *prefix,
const char *file_path, const char *map_path)
try {
return LoadYamlMap(pool, prefix,
ResolveYamlMap(YAML::LoadFile(file_path), map_path));
} catch (...) {
std::throw_with_nested(FormatRuntimeError("Failed to load YAML file '%s'",
file_path));
}
UnusedIstreamPtr
NewYamlSubstIstream(struct pool &pool, UnusedIstreamPtr input,
const char *prefix,
const char *yaml_file, const char *yaml_map_path)
{
return istream_subst_new(&pool, std::move(input),
LoadYamlFile(pool, prefix,
yaml_file, yaml_map_path));
}
<commit_msg>istream/YamlSubst: move code to LoadYamlMap() overload<commit_after>/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "YamlSubstIstream.hxx"
#include "SubstIstream.hxx"
#include "FailIstream.hxx"
#include "UnusedPtr.hxx"
#include "pool/pool.hxx"
#include "util/IterableSplitString.hxx"
#include "util/RuntimeError.hxx"
#include "util/StringView.hxx"
#include <yaml-cpp/node/parse.h>
#include <yaml-cpp/node/node.h>
#include <yaml-cpp/node/iterator.h>
#include <yaml-cpp/node/impl.h>
#include <yaml-cpp/node/convert.h>
#include <yaml-cpp/node/detail/impl.h>
static YAML::Node
ResolveYamlPathSegment(const YAML::Node &parent, StringView segment)
{
if (parent.IsMap()) {
auto result = parent[std::string(segment.data, segment.size).c_str()];
if (!result)
throw FormatRuntimeError("YAML path segment '%.*s' does not exist",
int(segment.size), segment.data);
return result;
} else
throw FormatRuntimeError("Failed to resolve YAML path segment '%.*s'",
int(segment.size), segment.data);
}
static YAML::Node
ResolveYamlPath(YAML::Node node, StringView path)
{
for (StringView s : IterableSplitString(path, '.')) {
if (s.empty())
continue;
node = ResolveYamlPathSegment(node, s);
}
return node;
}
static YAML::Node
ResolveYamlMap(YAML::Node node, StringView path)
{
node = ResolveYamlPath(node, path);
if (!node.IsMap())
throw path.empty()
? std::runtime_error("Not a YAML map")
: FormatRuntimeError("Path '%.*s' is not a YAML map",
int(path.size), path.data);
return node;
}
static auto
MakePrefix(const char *_prefix)
{
std::string prefix = "{[";
if (_prefix != nullptr)
prefix += _prefix;
return prefix;
}
static void
LoadYamlMap(struct pool &pool, SubstTree &tree,
const std::string &prefix,
const YAML::Node &node) noexcept
{
assert(node.IsMap());
for (const auto &i : node) {
if (!i.first.IsScalar() || !i.second.IsScalar())
continue;
const auto name = prefix + i.first.as<std::string>() + "]}";
const auto value = i.second.as<std::string>();
tree.Add(pool, p_strndup(&pool, name.data(), name.length()),
{p_strndup(&pool, value.data(), value.length()), value.length()});
}
}
static SubstTree
LoadYamlMap(struct pool &pool, const char *_prefix,
const YAML::Node &node) noexcept
{
assert(node.IsMap());
const auto prefix = MakePrefix(_prefix);
SubstTree tree;
LoadYamlMap(pool, tree, prefix, node);
return tree;
}
UnusedIstreamPtr
NewYamlSubstIstream(struct pool &pool, UnusedIstreamPtr input,
const char *prefix,
const YAML::Node &yaml_node, const char *yaml_map_path)
{
return istream_subst_new(&pool, std::move(input),
LoadYamlMap(pool, prefix,
ResolveYamlMap(yaml_node,
yaml_map_path)));
}
static SubstTree
LoadYamlFile(struct pool &pool, const char *prefix,
const char *file_path, const char *map_path)
try {
return LoadYamlMap(pool, prefix,
ResolveYamlMap(YAML::LoadFile(file_path), map_path));
} catch (...) {
std::throw_with_nested(FormatRuntimeError("Failed to load YAML file '%s'",
file_path));
}
UnusedIstreamPtr
NewYamlSubstIstream(struct pool &pool, UnusedIstreamPtr input,
const char *prefix,
const char *yaml_file, const char *yaml_map_path)
{
return istream_subst_new(&pool, std::move(input),
LoadYamlFile(pool, prefix,
yaml_file, yaml_map_path));
}
<|endoftext|> |
<commit_before>#ifndef DUNE_FUNCTIONALS_DISCRETEFUNCTIONSPACE_FINITEELEMENT_HH
#define DUNE_FUNCTIONALS_DISCRETEFUNCTIONSPACE_FINITEELEMENT_HH
// dune-fem includes
#include <dune/fem/space/lagrangespace.hh>
// dune-functionals includes
#include <dune/functionals/common/localbasefunctionprovider.hh>
namespace Dune {
namespace Functionals {
namespace DiscreteFunctionSpace {
template <class FunctionSpaceImp, class GridPartImp, int polOrder>
class ContinuousFiniteElement
{
public:
typedef FunctionSpaceImp FunctionSpaceType;
typedef GridPartImp GridPartType;
typedef Dune::LagrangeDiscreteFunctionSpace<FunctionSpaceType, GridPartType, polOrder> HostSpaceType;
typedef typename HostSpaceType::RangeFieldType RangeFieldType;
typedef typename HostSpaceType::EntityType EntityType;
typedef Dune::Functionals::Common::LocalBaseFunctionProvider<HostSpaceType> LocalBaseFunctionProviderType;
ContinuousFiniteElement(GridPartType& gridPart)
: gridPart_(gridPart)
, hostSpace_(gridPart)
, localBaseFunctionProvider_(hostSpace_)
{
}
const GridPartType& gridPart() const
{
return gridPart_;
}
const HostSpaceType& hostSpace() const
{
return hostSpace_;
}
const LocalBaseFunctionProviderType& localBaseFunctionProvider() const
{
return localBaseFunctionProvider_;
}
private:
const GridPartType& gridPart_;
const HostSpaceType hostSpace_;
const LocalBaseFunctionProviderType localBaseFunctionProvider_;
}; // end class ContinuousFiniteElement
} // end namespace DiscreteFunctionSpace
} // end namespace Functionals
} // end namespace Dune
#endif // DUNE_FUNCTIONALS_DISCRETEFUNCTIONSPACE_FINITEELEMENT_HH
<commit_msg>added LocalBasefucntion to DiscreteFunctionSPace::ContinuousFiniteElement<commit_after>#ifndef DUNE_FUNCTIONALS_DISCRETEFUNCTIONSPACE_FINITEELEMENT_HH
#define DUNE_FUNCTIONALS_DISCRETEFUNCTIONSPACE_FINITEELEMENT_HH
// dune-fem includes
#include <dune/fem/space/lagrangespace.hh>
// dune-functionals includes
#include <dune/functionals/common/localbasefunction.hh>
namespace Dune {
namespace Functionals {
namespace DiscreteFunctionSpace {
template <class FunctionSpaceImp, class GridPartImp, int polOrder>
class ContinuousFiniteElement
{
public:
typedef FunctionSpaceImp FunctionSpaceType;
typedef GridPartImp GridPartType;
typedef Dune::LagrangeDiscreteFunctionSpace<FunctionSpaceType, GridPartType, polOrder> HostSpaceType;
typedef Dune::Functionals::Common::LocalBaseFunction<HostSpaceType> LocalBaseFunctionType;
typedef typename HostSpaceType::EntityType EntityType;
ContinuousFiniteElement(GridPartType& gridPart)
: gridPart_(gridPart)
, hostSpace_(gridPart)
{
}
const GridPartType& gridPart() const
{
return gridPart_;
}
const HostSpaceType& hostSpace() const
{
return hostSpace_;
}
const LocalBaseFunctionType localBaseFunction(const EntityType& entity, const unsigned int localDoFNumber) const
{
return LocalBaseFunctionType(entity, hostSpace_.baseFunctionSet(entity), localDoFNumber);
}
private:
const GridPartType& gridPart_;
const HostSpaceType hostSpace_;
}; // end class ContinuousFiniteElement
} // end namespace DiscreteFunctionSpace
} // end namespace Functionals
} // end namespace Dune
#endif // DUNE_FUNCTIONALS_DISCRETEFUNCTIONSPACE_FINITEELEMENT_HH
<|endoftext|> |
<commit_before>#ifndef UTIL_VARIANT_HPP
#define UTIL_VARIANT_HPP
#include <utility>
#include <typeinfo>
#include <type_traits>
#include <algorithm> // std::move/swap
#include <stdexcept> // runtime_error
#include <new> // operator new
#include <cstddef> // size_t
#include <iosfwd>
#ifdef NDEBUG
#define VARIANT_INLINE inline __attribute__((always_inline))
#else
#define VARIANT_INLINE __attribute__((noinline))
#endif
namespace util {
namespace detail {
static constexpr std::size_t invalid_value = std::size_t(-1);
template <typename T, typename...Types>
struct type_traits;
template <typename T, typename First, typename...Types>
struct type_traits<T, First, Types...>
{
static constexpr std::size_t id = std::is_same<T, First>::value ? sizeof...(Types) : type_traits<T, Types...>::id;
};
template <typename T>
struct type_traits<T>
{
static constexpr std::size_t id = invalid_value;
};
template <typename T, typename...Types>
struct is_valid_type;
template <typename T, typename First, typename... Types>
struct is_valid_type<T,First,Types...>
{
static constexpr bool value = std::is_same<T,First>::value
|| is_valid_type<T,Types...>::value;
};
template <typename T>
struct is_valid_type<T> : std::false_type {};
}
template <std::size_t arg1, std::size_t ... others>
struct static_max;
template <std::size_t arg>
struct static_max<arg>
{
static const std::size_t value = arg;
};
template <std::size_t arg1, std::size_t arg2, std::size_t ... others>
struct static_max<arg1, arg2, others...>
{
static const std::size_t value = arg1 >= arg2 ? static_max<arg1, others...>::value :
static_max<arg2, others...>::value;
};
template<typename... Types>
struct variant_helper;
template<typename T, typename... Types>
struct variant_helper<T, Types...>
{
VARIANT_INLINE static void destroy(const std::size_t id, void * data)
{
if (id == sizeof...(Types))
{
reinterpret_cast<T*>(data)->~T();
}
else
{
variant_helper<Types...>::destroy(id, data);
}
}
VARIANT_INLINE static void move(const std::size_t old_id, void * old_value, void * new_value)
{
if (old_id == sizeof...(Types))
{
new (new_value) T(std::move(*reinterpret_cast<T*>(old_value)));
//std::memcpy(new_v, old_v, sizeof(T));
// ^^ DANGER: this should only be considered for relocatable types e.g built-in types
// Also, I don't see any measurable performance benefit just yet
}
else
{
variant_helper<Types...>::move(old_id, old_value, new_value);
}
}
VARIANT_INLINE static void copy(const std::size_t old_id, const void * old_value, void * new_value)
{
if (old_id == sizeof...(Types))
{
new (new_value) T(*reinterpret_cast<const T*>(old_value));
}
else
{
variant_helper<Types...>::copy(old_id, old_value, new_value);
}
}
};
template<> struct variant_helper<>
{
VARIANT_INLINE static void destroy(const std::size_t, void *) {}
VARIANT_INLINE static void move(const std::size_t, void *, void *) {}
VARIANT_INLINE static void copy(const std::size_t, const void *, void *) {}
};
namespace detail {
template <typename F, typename V, typename...Types>
struct dispatcher;
template <typename F, typename V, typename T, typename...Types>
struct dispatcher<F,V,T,Types...>
{
typedef typename std::result_of<F(V const&)>::type result_type;
VARIANT_INLINE static result_type apply(V const& v, F f)
{
if (v.get_type_id() == sizeof...(Types))
{
return f(v. template get<T>());
}
else
{
return dispatcher<F,V,Types...>::apply(v, f);
}
}
};
template<typename F,typename V>
struct dispatcher<F,V>
{
typedef typename std::result_of<F(V const&)>::type result_type;
VARIANT_INLINE static result_type apply(V const&, F)
{
throw std::runtime_error("dispatch: FAIL");
}
};
// comparator functors
struct equal_comp
{
template <typename T>
bool operator()(T const& lhs, T const& rhs) const
{
return lhs == rhs;
}
};
struct less_comp
{
template <typename T>
bool operator()(const T& lhs, const T& rhs) const
{
return lhs < rhs;
}
};
template <typename Variant, typename Comp>
struct comparer
{
public:
explicit comparer(Variant const& lhs) noexcept
: lhs_(lhs) {}
comparer& operator=(const comparer&) = delete;
// visitor
template<typename T>
bool operator()(T const& rhs_content) const
{
T const& lhs_content = lhs_.template get<T>();
return Comp()(lhs_content, rhs_content);
}
private:
Variant const& lhs_;
};
// operator<< helper
template <typename Out>
struct printer
{
public:
explicit printer(Out & out)
: out_(out) {}
printer& operator=(const printer&) = delete;
// visitor
template <typename T>
void operator()(const T& operand) const
{
out_ << operand;
}
private:
Out & out_;
};
} // detail
template<typename... Types>
struct variant
{
private:
static const std::size_t data_size = static_max<sizeof(Types)...>::value;
static const std::size_t data_align = static_max<alignof(Types)...>::value;
using data_t = typename std::aligned_storage<data_size, data_align>::type;
using helper_t = variant_helper<Types...>;
std::size_t type_id;
data_t data;
public:
VARIANT_INLINE variant()
: type_id(detail::invalid_value) {}
template <typename T>
VARIANT_INLINE explicit variant(T const& val) noexcept
: type_id(detail::type_traits<T, Types...>::id)
{
static_assert(detail::is_valid_type<T,Types...>::value, "Not a valid type for this variant");
new (&data) T(val);
}
template <typename T>
VARIANT_INLINE variant(T && val) noexcept
: type_id(detail::type_traits<T,Types...>::id)
{
static_assert(detail::is_valid_type<T,Types...>::value, "Not a valid type for this variant");
new (&data) T(std::forward<T>(val)); // nothrow
}
VARIANT_INLINE variant(variant<Types...> const& old)
: type_id(old.type_id)
{
helper_t::copy(old.type_id, &old.data, &data);
}
VARIANT_INLINE variant(variant<Types...>&& old) noexcept
: type_id(old.type_id)
{
helper_t::move(old.type_id, &old.data, &data);
}
friend void swap(variant<Types...> & first, variant<Types...> & second)
{
using std::swap; //enable ADL
swap(first.type_id, second.type_id);
swap(first.data, second.data);
}
VARIANT_INLINE variant<Types...>& operator= (variant<Types...> other)
{
swap(*this, other);
return *this;
}
template<typename T>
VARIANT_INLINE void is() const
{
return (type_id == detail::type_traits<T, Types...>::id);
}
VARIANT_INLINE void valid() const
{
return (type_id != detail::invalid_value);
}
template<typename T, typename... Args>
VARIANT_INLINE void set(Args&&... args)
{
helper_t::destroy(type_id, &data);
new (&data) T(std::forward<Args>(args)...);
type_id = detail::type_traits<T,Types...>::id;
}
template<typename T>
VARIANT_INLINE T& get()
{
if (type_id == detail::type_traits<T,Types...>::id)
{
return *reinterpret_cast<T*>(&data);
}
else
{
throw std::runtime_error("in get()");
}
}
template<typename T>
VARIANT_INLINE T const& get() const
{
if (type_id == detail::type_traits<T,Types...>::id)
{
return *reinterpret_cast<T const*>(&data);
}
else
{
throw std::runtime_error("in get()");
}
}
VARIANT_INLINE std::size_t get_type_id() const
{
return type_id;
}
// visitor
template <typename F, typename V>
typename std::result_of<F(V const&)>::type
VARIANT_INLINE static visit(V const& v, F f)
{
return detail::dispatcher<F, V, Types...>::apply(v, f);
}
~variant() noexcept
{
helper_t::destroy(type_id, &data);
}
// comparison operators
// equality
VARIANT_INLINE bool operator==(variant const& rhs) const
{
if (this->get_type_id() != rhs.get_type_id())
return false;
detail::comparer<variant, detail::equal_comp> visitor(*this);
return visit(rhs, visitor);
}
// less than
VARIANT_INLINE bool operator<(variant const& rhs) const
{
if (this->get_type_id() != rhs.get_type_id())
{
return this->get_type_id() < rhs.get_type_id();
// ^^ borrowed from boost::variant
}
detail::comparer<variant, detail::less_comp> visitor(*this);
return visit(rhs, visitor);
}
};
// unary visitor interface
template <typename V, typename F>
typename std::result_of<F(V const&)>::type
VARIANT_INLINE static apply_visitor(V const& v, F f)
{
return V::visit(v,f);
}
// operator<<
template <typename charT, typename traits, typename Variant>
VARIANT_INLINE std::basic_ostream<charT,traits>&
operator<< (std::basic_ostream<charT,traits>& out, Variant const& rhs)
{
detail::printer<std::basic_ostream<charT,traits> > visitor(out);
apply_visitor(rhs, visitor);
return out;
}
}
#endif // UTIL_VARIANT_HPP
<commit_msg>changing const keyword position to 'T const &'<commit_after>#ifndef UTIL_VARIANT_HPP
#define UTIL_VARIANT_HPP
#include <utility>
#include <typeinfo>
#include <type_traits>
#include <algorithm> // std::move/swap
#include <stdexcept> // runtime_error
#include <new> // operator new
#include <cstddef> // size_t
#include <iosfwd>
#ifdef NDEBUG
#define VARIANT_INLINE inline __attribute__((always_inline))
#else
#define VARIANT_INLINE __attribute__((noinline))
#endif
namespace util {
namespace detail {
static constexpr std::size_t invalid_value = std::size_t(-1);
template <typename T, typename...Types>
struct type_traits;
template <typename T, typename First, typename...Types>
struct type_traits<T, First, Types...>
{
static constexpr std::size_t id = std::is_same<T, First>::value ? sizeof...(Types) : type_traits<T, Types...>::id;
};
template <typename T>
struct type_traits<T>
{
static constexpr std::size_t id = invalid_value;
};
template <typename T, typename...Types>
struct is_valid_type;
template <typename T, typename First, typename... Types>
struct is_valid_type<T,First,Types...>
{
static constexpr bool value = std::is_same<T,First>::value
|| is_valid_type<T,Types...>::value;
};
template <typename T>
struct is_valid_type<T> : std::false_type {};
}
template <std::size_t arg1, std::size_t ... others>
struct static_max;
template <std::size_t arg>
struct static_max<arg>
{
static const std::size_t value = arg;
};
template <std::size_t arg1, std::size_t arg2, std::size_t ... others>
struct static_max<arg1, arg2, others...>
{
static const std::size_t value = arg1 >= arg2 ? static_max<arg1, others...>::value :
static_max<arg2, others...>::value;
};
template<typename... Types>
struct variant_helper;
template<typename T, typename... Types>
struct variant_helper<T, Types...>
{
VARIANT_INLINE static void destroy(const std::size_t id, void * data)
{
if (id == sizeof...(Types))
{
reinterpret_cast<T*>(data)->~T();
}
else
{
variant_helper<Types...>::destroy(id, data);
}
}
VARIANT_INLINE static void move(const std::size_t old_id, void * old_value, void * new_value)
{
if (old_id == sizeof...(Types))
{
new (new_value) T(std::move(*reinterpret_cast<T*>(old_value)));
//std::memcpy(new_v, old_v, sizeof(T));
// ^^ DANGER: this should only be considered for relocatable types e.g built-in types
// Also, I don't see any measurable performance benefit just yet
}
else
{
variant_helper<Types...>::move(old_id, old_value, new_value);
}
}
VARIANT_INLINE static void copy(const std::size_t old_id, const void * old_value, void * new_value)
{
if (old_id == sizeof...(Types))
{
new (new_value) T(*reinterpret_cast<const T*>(old_value));
}
else
{
variant_helper<Types...>::copy(old_id, old_value, new_value);
}
}
};
template<> struct variant_helper<>
{
VARIANT_INLINE static void destroy(const std::size_t, void *) {}
VARIANT_INLINE static void move(const std::size_t, void *, void *) {}
VARIANT_INLINE static void copy(const std::size_t, const void *, void *) {}
};
namespace detail {
template <typename F, typename V, typename...Types>
struct dispatcher;
template <typename F, typename V, typename T, typename...Types>
struct dispatcher<F,V,T,Types...>
{
typedef typename std::result_of<F(V const&)>::type result_type;
VARIANT_INLINE static result_type apply(V const& v, F f)
{
if (v.get_type_id() == sizeof...(Types))
{
return f(v. template get<T>());
}
else
{
return dispatcher<F,V,Types...>::apply(v, f);
}
}
};
template<typename F,typename V>
struct dispatcher<F,V>
{
typedef typename std::result_of<F(V const&)>::type result_type;
VARIANT_INLINE static result_type apply(V const&, F)
{
throw std::runtime_error("dispatch: FAIL");
}
};
// comparator functors
struct equal_comp
{
template <typename T>
bool operator()(T const& lhs, T const& rhs) const
{
return lhs == rhs;
}
};
struct less_comp
{
template <typename T>
bool operator()(const T& lhs, const T& rhs) const
{
return lhs < rhs;
}
};
template <typename Variant, typename Comp>
struct comparer
{
public:
explicit comparer(Variant const& lhs) noexcept
: lhs_(lhs) {}
comparer& operator=(const comparer&) = delete;
// visitor
template<typename T>
bool operator()(T const& rhs_content) const
{
T const& lhs_content = lhs_.template get<T>();
return Comp()(lhs_content, rhs_content);
}
private:
Variant const& lhs_;
};
// operator<< helper
template <typename Out>
struct printer
{
public:
explicit printer(Out & out)
: out_(out) {}
printer& operator=(printer const &) = delete;
// visitor
template <typename T>
void operator()( T const & operand) const
{
out_ << operand;
}
private:
Out & out_;
};
} // detail
template<typename... Types>
struct variant
{
private:
static const std::size_t data_size = static_max<sizeof(Types)...>::value;
static const std::size_t data_align = static_max<alignof(Types)...>::value;
using data_t = typename std::aligned_storage<data_size, data_align>::type;
using helper_t = variant_helper<Types...>;
std::size_t type_id;
data_t data;
public:
VARIANT_INLINE variant()
: type_id(detail::invalid_value) {}
template <typename T>
VARIANT_INLINE explicit variant(T const& val) noexcept
: type_id(detail::type_traits<T, Types...>::id)
{
static_assert(detail::is_valid_type<T,Types...>::value, "Not a valid type for this variant");
new (&data) T(val);
}
template <typename T>
VARIANT_INLINE variant(T && val) noexcept
: type_id(detail::type_traits<T,Types...>::id)
{
static_assert(detail::is_valid_type<T,Types...>::value, "Not a valid type for this variant");
new (&data) T(std::forward<T>(val)); // nothrow
}
VARIANT_INLINE variant(variant<Types...> const& old)
: type_id(old.type_id)
{
helper_t::copy(old.type_id, &old.data, &data);
}
VARIANT_INLINE variant(variant<Types...>&& old) noexcept
: type_id(old.type_id)
{
helper_t::move(old.type_id, &old.data, &data);
}
friend void swap(variant<Types...> & first, variant<Types...> & second)
{
using std::swap; //enable ADL
swap(first.type_id, second.type_id);
swap(first.data, second.data);
}
VARIANT_INLINE variant<Types...>& operator= (variant<Types...> other)
{
swap(*this, other);
return *this;
}
template<typename T>
VARIANT_INLINE void is() const
{
return (type_id == detail::type_traits<T, Types...>::id);
}
VARIANT_INLINE void valid() const
{
return (type_id != detail::invalid_value);
}
template<typename T, typename... Args>
VARIANT_INLINE void set(Args&&... args)
{
helper_t::destroy(type_id, &data);
new (&data) T(std::forward<Args>(args)...);
type_id = detail::type_traits<T,Types...>::id;
}
template<typename T>
VARIANT_INLINE T& get()
{
if (type_id == detail::type_traits<T,Types...>::id)
{
return *reinterpret_cast<T*>(&data);
}
else
{
throw std::runtime_error("in get()");
}
}
template<typename T>
VARIANT_INLINE T const& get() const
{
if (type_id == detail::type_traits<T,Types...>::id)
{
return *reinterpret_cast<T const*>(&data);
}
else
{
throw std::runtime_error("in get()");
}
}
VARIANT_INLINE std::size_t get_type_id() const
{
return type_id;
}
// visitor
template <typename F, typename V>
typename std::result_of<F(V const&)>::type
VARIANT_INLINE static visit(V const& v, F f)
{
return detail::dispatcher<F, V, Types...>::apply(v, f);
}
~variant() noexcept
{
helper_t::destroy(type_id, &data);
}
// comparison operators
// equality
VARIANT_INLINE bool operator==(variant const& rhs) const
{
if (this->get_type_id() != rhs.get_type_id())
return false;
detail::comparer<variant, detail::equal_comp> visitor(*this);
return visit(rhs, visitor);
}
// less than
VARIANT_INLINE bool operator<(variant const& rhs) const
{
if (this->get_type_id() != rhs.get_type_id())
{
return this->get_type_id() < rhs.get_type_id();
// ^^ borrowed from boost::variant
}
detail::comparer<variant, detail::less_comp> visitor(*this);
return visit(rhs, visitor);
}
};
// unary visitor interface
template <typename V, typename F>
typename std::result_of<F(V const&)>::type
VARIANT_INLINE static apply_visitor(V const& v, F f)
{
return V::visit(v,f);
}
// operator<<
template <typename charT, typename traits, typename Variant>
VARIANT_INLINE std::basic_ostream<charT,traits>&
operator<< (std::basic_ostream<charT,traits>& out, Variant const& rhs)
{
detail::printer<std::basic_ostream<charT,traits> > visitor(out);
apply_visitor(rhs, visitor);
return out;
}
}
#endif // UTIL_VARIANT_HPP
<|endoftext|> |
<commit_before>/**
* \file
* \brief InterruptUnmaskingLock class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-04-28
*/
#ifndef INCLUDE_DISTORTOS_ARCHITECTURE_INTERRUPTUNMASKINGLOCK_HPP_
#define INCLUDE_DISTORTOS_ARCHITECTURE_INTERRUPTUNMASKINGLOCK_HPP_
#include "distortos/architecture/InterruptMaskingUnmaskingLock.hpp"
#include "distortos/architecture/disableInterruptMasking.hpp"
namespace distortos
{
namespace architecture
{
/// InterruptUnmaskingLock class is a RAII wrapper for disableInterruptMasking() / restoreInterruptMasking()
using InterruptUnmaskingLock = InterruptMaskingUnmaskingLock<disableInterruptMasking>;
} // namespace architecture
} // namespace distortos
#endif // INCLUDE_DISTORTOS_ARCHITECTURE_INTERRUPTUNMASKINGLOCK_HPP_
<commit_msg>InterruptUnmaskingLock: implement it as proper class instead of type alias<commit_after>/**
* \file
* \brief InterruptUnmaskingLock class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-05-07
*/
#ifndef INCLUDE_DISTORTOS_ARCHITECTURE_INTERRUPTUNMASKINGLOCK_HPP_
#define INCLUDE_DISTORTOS_ARCHITECTURE_INTERRUPTUNMASKINGLOCK_HPP_
#include "distortos/architecture/InterruptMaskingUnmaskingLock.hpp"
#include "distortos/architecture/disableInterruptMasking.hpp"
namespace distortos
{
namespace architecture
{
/// InterruptUnmaskingLock class is a RAII wrapper for disableInterruptMasking() / restoreInterruptMasking()
class InterruptUnmaskingLock : private InterruptMaskingUnmaskingLock<disableInterruptMasking>
{
};
} // namespace architecture
} // namespace distortos
#endif // INCLUDE_DISTORTOS_ARCHITECTURE_INTERRUPTUNMASKINGLOCK_HPP_
<|endoftext|> |
<commit_before>#pragma warning (disable:4996)
#define WIN32_LEAN_AND_MEAN
#pragma comment (lib, "Shlwapi.lib")
#include <Windows.h>
#include <Shlwapi.h>
#include <unordered_map>
#include <mutex>
#include <queue>
using namespace std;
#define BUF_SIZE MAX_PATH * 3
long long CurrentTime()
{
long long t;
GetSystemTimeAsFileTime((LPFILETIME) &t);
return t;
}
BOOL unhook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PBYTE pOrgBytes)
{
FARPROC pFunc;
DWORD dwOldProtect;
// API ּ Ѵ
pFunc = GetProcAddress(GetModuleHandle(szDllName), szFuncName);
// ڵ (5 byte) WRITE Ӽ ߰
VirtualProtect((LPVOID) pFunc, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// Unhook
memcpy(pFunc, pOrgBytes, 5);
// Ӽ
VirtualProtect((LPVOID) pFunc, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
BOOL hook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PROC pfnNew, PBYTE pOrgBytes)
{
FARPROC pfnOrg;
DWORD dwOldProtect, dwAddress;
BYTE pBuf[5] = { 0xE9, 0, };
PBYTE pByte;
// ŷ API ּҸ Ѵ
pfnOrg = (FARPROC) GetProcAddress(GetModuleHandle(szDllName), szFuncName);
pByte = (PBYTE) pfnOrg;
// ̹ ŷǾ ִٸ return FALSE
if (pByte[0] == 0xE9)
return FALSE;
// 5 byte ġ Ͽ WRITE Ӽ ߰
VirtualProtect((LPVOID) pfnOrg, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// ڵ (5 byte)
memcpy(pOrgBytes, pfnOrg, 5);
// JMP ּҰ (E9 XXXX)
// => XXXX = pfnNew - pfnOrg - 5
dwAddress = (DWORD) pfnNew - (DWORD) pfnOrg - 5;
memcpy(&pBuf[1], &dwAddress, 4);
// Hook - 5 byte ġ(JMP XXXX)
memcpy(pfnOrg, pBuf, 5);
// Ӽ
VirtualProtect((LPVOID) pfnOrg, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
mutex STLMutex;
HANDLE hPipe;
volatile bool bCancelPipeThread;
volatile bool bPipeConnected;
queue<string> MessageQueue;
HANDLE hQueuePushed;
DWORD WINAPI PipeThread(LPVOID lParam)
{
hPipe = CreateNamedPipeA("\\\\.\\pipe\\osu!Lyrics", PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_MESSAGE | PIPE_WAIT, 1, BUF_SIZE * 5, 0, INFINITE, NULL);
// û Ŭ̾Ʈ
while (!bCancelPipeThread)
{
// ConnectNamedPipe Ŭ̾Ʈ :
// Ҵ DisconnectNamedPipe
if (ConnectNamedPipe(hPipe, NULL) || GetLastError() == ERROR_PIPE_CONNECTED)
{
bPipeConnected = true;
STLMutex.lock();
bool empty = MessageQueue.empty();
STLMutex.unlock();
// ť 3ʰ ٷ ȣ ٽ ٸ
if (empty && WaitForSingleObject(hQueuePushed, 3000) != WAIT_OBJECT_0)
{
continue;
}
STLMutex.lock();
string message = MessageQueue.front();
STLMutex.unlock();
OVERLAPPED overlapped = {};
if (WriteFileEx(hPipe, message.c_str(), message.length(), &overlapped, [](DWORD, DWORD, LPOVERLAPPED) {}))
{
STLMutex.lock();
MessageQueue.pop();
STLMutex.unlock();
continue;
}
}
bPipeConnected = false;
DisconnectNamedPipe(hPipe);
}
// Ŭ̾Ʈ
bPipeConnected = false;
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
return 0;
}
typedef BOOL (WINAPI *tReadFile)(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
tReadFile pReadFile;
mutex HookMutex;
BYTE pReadFileHook[5];
unordered_map<string, string> AudioInfo;
// osu! ReadFile ȣϸ osu!Lyrics
BOOL WINAPI hkReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
long long calledAt = CurrentTime();
HookMutex.lock();
unhook_by_code("kernel32.dll", "ReadFile", pReadFileHook);
BOOL result = pReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileHook);
HookMutex.unlock();
if (!result)
{
return FALSE;
}
char path[MAX_PATH];
DWORD pathLength = GetFinalPathNameByHandle(hFile, path, MAX_PATH, VOLUME_NAME_DOS);
// 1: \\?\D:\Games\osu!\...
DWORD seekPosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - *lpNumberOfBytesRead;
// д Ʈ ̰ պκ оٸ:
// AudioFilename պκп / ڵ !
if (strnicmp(".osu", &path[pathLength - 4], 4) == 0 && seekPosition == 0)
{
// strtok ҽ ϹǷ ϴ
char *buffer = strdup((char *) lpBuffer);
char *line = strtok(buffer, "\n");
while (line != NULL)
{
// Ʈ
if (strnicmp(line, "AudioFilename:", 14) == 0)
{
char *beatmapDir = strdup(path);
PathRemoveFileSpec(beatmapDir);
char audioPath[MAX_PATH];
// get value & trim
int i = 14;
for (; line[i] == ' '; i++);
buffer[0] = '\0';
strncat(buffer, &line[i], strlen(line) - i - 1);
PathCombine(audioPath, beatmapDir, buffer);
// ˻ ҹ ϹǷ
WIN32_FIND_DATA fdata;
FindClose(FindFirstFile(audioPath, &fdata));
PathRemoveFileSpec(audioPath);
PathCombine(audioPath, audioPath, fdata.cFileName);
STLMutex.lock();
AudioInfo.insert(make_pair(string(audioPath), string(path)));
STLMutex.unlock();
free(beatmapDir);
break;
}
line = strtok(NULL, "\n");
}
free(buffer);
}
else
{
STLMutex.lock();
// [ audioPath, beatmapPath ]
unordered_map<string, string>::iterator pair = AudioInfo.find(string(path));
bool found = pair != AudioInfo.end();
STLMutex.unlock();
if (found)
{
char message[BUF_SIZE];
sprintf(message, "%llx|%s|%lx|%s\n", calledAt, &path[4], seekPosition, &pair->second[4]);
STLMutex.lock();
MessageQueue.push(string(message));
STLMutex.unlock();
SetEvent(hQueuePushed);
}
}
return TRUE;
}
HANDLE hPipeThread;
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
hPipeThread = CreateThread(NULL, 0, PipeThread, NULL, 0, NULL);
hQueuePushed = CreateEventA(NULL, TRUE, FALSE, NULL);
HookMutex.lock();
pReadFile = (tReadFile) GetProcAddress(GetModuleHandle("kernel32.dll"), "ReadFile");
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileHook);
HookMutex.unlock();
}
else if (fdwReason == DLL_PROCESS_DETACH)
{
HookMutex.lock();
unhook_by_code("kernel32.dll", "ReadFile", pReadFileHook);
HookMutex.unlock();
bCancelPipeThread = true;
DisconnectNamedPipe(hPipe);
WaitForSingleObject(hPipeThread, INFINITE);
CloseHandle(hQueuePushed);
CloseHandle(hPipeThread);
}
return TRUE;
}<commit_msg>follow 5414e510d9db98fc01c70c90292a7da02b210b34<commit_after>#pragma warning (disable:4996)
#define WIN32_LEAN_AND_MEAN
#pragma comment (lib, "Shlwapi.lib")
#include <Windows.h>
#include <Shlwapi.h>
#include <unordered_map>
#include <mutex>
#include <queue>
using namespace std;
#define BUF_SIZE MAX_PATH * 3
long long CurrentTime()
{
long long t;
GetSystemTimeAsFileTime((LPFILETIME) &t);
return t;
}
BOOL unhook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PBYTE pOrgBytes)
{
FARPROC pFunc;
DWORD dwOldProtect;
// API ּ Ѵ
pFunc = GetProcAddress(GetModuleHandle(szDllName), szFuncName);
// ڵ (5 byte) WRITE Ӽ ߰
VirtualProtect((LPVOID) pFunc, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// Unhook
memcpy(pFunc, pOrgBytes, 5);
// Ӽ
VirtualProtect((LPVOID) pFunc, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
BOOL hook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PROC pfnNew, PBYTE pOrgBytes)
{
FARPROC pfnOrg;
DWORD dwOldProtect, dwAddress;
BYTE pBuf[5] = { 0xE9, 0, };
PBYTE pByte;
// ŷ API ּҸ Ѵ
pfnOrg = (FARPROC) GetProcAddress(GetModuleHandle(szDllName), szFuncName);
pByte = (PBYTE) pfnOrg;
// ̹ ŷǾ ִٸ return FALSE
if (pByte[0] == 0xE9)
return FALSE;
// 5 byte ġ Ͽ WRITE Ӽ ߰
VirtualProtect((LPVOID) pfnOrg, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// ڵ (5 byte)
memcpy(pOrgBytes, pfnOrg, 5);
// JMP ּҰ (E9 XXXX)
// => XXXX = pfnNew - pfnOrg - 5
dwAddress = (DWORD) pfnNew - (DWORD) pfnOrg - 5;
memcpy(&pBuf[1], &dwAddress, 4);
// Hook - 5 byte ġ(JMP XXXX)
memcpy(pfnOrg, pBuf, 5);
// Ӽ
VirtualProtect((LPVOID) pfnOrg, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
mutex STLMutex;
HANDLE hPipe;
volatile bool bCancelPipeThread;
volatile bool bPipeConnected;
queue<string> MessageQueue;
HANDLE hQueuePushed;
DWORD WINAPI PipeThread(LPVOID lParam)
{
hPipe = CreateNamedPipeA("\\\\.\\pipe\\osu!Lyrics", PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_MESSAGE | PIPE_WAIT, 1, BUF_SIZE * 5, 0, INFINITE, NULL);
// û Ŭ̾Ʈ
while (!bCancelPipeThread)
{
// ConnectNamedPipe Ŭ̾Ʈ :
// Ҵ DisconnectNamedPipe
if (ConnectNamedPipe(hPipe, NULL) || GetLastError() == ERROR_PIPE_CONNECTED)
{
bPipeConnected = true;
STLMutex.lock();
bool empty = MessageQueue.empty();
STLMutex.unlock();
if (empty)
{
// ť 3ʰ ٷ ȣ ٽ ٸ
WaitForSingleObject(hQueuePushed, 3000);
continue;
}
STLMutex.lock();
string message = MessageQueue.front();
STLMutex.unlock();
OVERLAPPED overlapped = {};
if (WriteFileEx(hPipe, message.c_str(), message.length(), &overlapped, [](DWORD, DWORD, LPOVERLAPPED) {}))
{
STLMutex.lock();
MessageQueue.pop();
STLMutex.unlock();
continue;
}
}
bPipeConnected = false;
DisconnectNamedPipe(hPipe);
}
// Ŭ̾Ʈ
bPipeConnected = false;
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
return 0;
}
typedef BOOL (WINAPI *tReadFile)(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
tReadFile pReadFile;
mutex HookMutex;
BYTE pReadFileHook[5];
unordered_map<string, string> AudioInfo;
// osu! ReadFile ȣϸ osu!Lyrics
BOOL WINAPI hkReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
long long calledAt = CurrentTime();
HookMutex.lock();
unhook_by_code("kernel32.dll", "ReadFile", pReadFileHook);
BOOL result = pReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileHook);
HookMutex.unlock();
if (!result)
{
return FALSE;
}
char path[MAX_PATH];
DWORD pathLength = GetFinalPathNameByHandle(hFile, path, MAX_PATH, VOLUME_NAME_DOS);
// 1: \\?\D:\Games\osu!\...
DWORD seekPosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - *lpNumberOfBytesRead;
// д Ʈ ̰ պκ оٸ:
// AudioFilename պκп / ڵ !
if (strnicmp(".osu", &path[pathLength - 4], 4) == 0 && seekPosition == 0)
{
// strtok ҽ ϹǷ ϴ
char *buffer = strdup((char *) lpBuffer);
char *line = strtok(buffer, "\n");
while (line != NULL)
{
// Ʈ
if (strnicmp(line, "AudioFilename:", 14) == 0)
{
char *beatmapDir = strdup(path);
PathRemoveFileSpec(beatmapDir);
char audioPath[MAX_PATH];
// get value & trim
int i = 14;
for (; line[i] == ' '; i++);
buffer[0] = '\0';
strncat(buffer, &line[i], strlen(line) - i - 1);
PathCombine(audioPath, beatmapDir, buffer);
// ˻ ҹ ϹǷ
WIN32_FIND_DATA fdata;
FindClose(FindFirstFile(audioPath, &fdata));
PathRemoveFileSpec(audioPath);
PathCombine(audioPath, audioPath, fdata.cFileName);
STLMutex.lock();
AudioInfo.insert(make_pair(string(audioPath), string(path)));
STLMutex.unlock();
free(beatmapDir);
break;
}
line = strtok(NULL, "\n");
}
free(buffer);
}
else
{
STLMutex.lock();
// [ audioPath, beatmapPath ]
unordered_map<string, string>::iterator pair = AudioInfo.find(string(path));
bool found = pair != AudioInfo.end();
STLMutex.unlock();
if (found)
{
char message[BUF_SIZE];
sprintf(message, "%llx|%s|%lx|%s\n", calledAt, &path[4], seekPosition, &pair->second[4]);
STLMutex.lock();
MessageQueue.push(string(message));
STLMutex.unlock();
SetEvent(hQueuePushed);
}
}
return TRUE;
}
HANDLE hPipeThread;
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
hPipeThread = CreateThread(NULL, 0, PipeThread, NULL, 0, NULL);
hQueuePushed = CreateEventA(NULL, TRUE, FALSE, NULL);
HookMutex.lock();
pReadFile = (tReadFile) GetProcAddress(GetModuleHandle("kernel32.dll"), "ReadFile");
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileHook);
HookMutex.unlock();
}
else if (fdwReason == DLL_PROCESS_DETACH)
{
HookMutex.lock();
unhook_by_code("kernel32.dll", "ReadFile", pReadFileHook);
HookMutex.unlock();
bCancelPipeThread = true;
DisconnectNamedPipe(hPipe);
WaitForSingleObject(hPipeThread, INFINITE);
CloseHandle(hQueuePushed);
CloseHandle(hPipeThread);
}
return TRUE;
}<|endoftext|> |
<commit_before>/**
* Copyright (c) 2017 Neon Edge Game
* File Name: Player.cpp
* Header File Name: Player.h
* Class Name: Player
* Objective: manages the behavior of some aspects of the player.
*/
#include "Player.h"
#include "Projectile.h"
#include <assert.h>
/**
Objective: constructor of the class Player.
@param ItensManager* itemManager
@param int x - coordinate of the player.
@param int y - coordinate of the player.
@return Player - instance of the class Player.
*/
Player::Player(ItemsManager* itemManager, int x, int y): Character(x,y){
inputComponent = nullptr;
this->itemManager = itemManager ;
// Sets the default enabled skills.
skills[0] = false;
skills[1] = false;
skills[2] = true;
skills[3] = true;
skills[4] = true;
skills[5] = false;
skills[6] = false;
skillPoints = 0;
energy = 5; // Sets the energy of the player to 5.
regenCD = 500; // The time of the cool down regeneration in miliseconds.
isCrouching = false; // Default state: standing.
isStading = true;
name = "Player"; // Sets the Player's name.
hitpoints = MAX_HITPOINTS; // Sets the hitpoints of the player to 10.
}
/**
* Objective: destructor of the class Player.
*
* @param none.
* @return none.
*/
Player::~Player() {
}
/**
* Objective: checks if is a player.
*
* @param none.
* @return bool - returns TRUE.
*/
bool Player::IsPlayer() {
return true;
}
/**
* Objective: gets the energy of player.
*
* @param none.
* @return int energy - returns the amount of energy of the player.
*/
int Player::GetEnergy() {
return energy;
}
/**
* Objective: performs the action of crouch.
*
* @param: none.
* @return: none.
*/
void Player::Crouch() {
if (isStading) {
isStading = false;
assert(soundComponent != nullptr);
soundComponent->SoundCrouching(); // Performs the crouching sound in case that the player is
// standing.
} else {
// It does nothing.
}
isCrouching = true;
}
/**
* Objective: performs the action of stand.
*
* @param none.
* @return none.
*/
void Player::Stand() {
isCrouching = false;
isStading = true;
}
/**
* Objective: checks if the player is crouching or not.
*
* @param none.
* @return bool crouching - return true if the player is crouching.
*/
bool Player::IsCrouching() {
return isCrouching;
}
/**
* Objective: performs an action due to an item used by the player.
*
* @param string itemName - the name of the item.
* @return none.
*/
void Player::EvalItem(std::string itemName) {
assert(itemName != "");
// Heals the hitpoints of the player by 25% of the total.
if (itemName == "Healing Potion 25") {
hitpoints += MAX_HITPOINTS*0.25;
clamp(hitpoints, 0, MAX_HITPOINTS);
} else
// Heals the hitpoints of the player by 50% of the total.
if (itemName == "Healing Potion 50") {
hitpoints += MAX_HITPOINTS*0.5;
clamp(hitpoints, 0, MAX_HITPOINTS);
} else
// Adds 2 energy points.
if (itemName == "Energy Potion 25") {
energy += 2;
clamp(energy, 0, 5);
} else
// Adds 5 energy points.
if (itemName == "Energy Potion 50") {
energy += 5;
clamp(energy, 0, 5);
} else
// Adds 1 point to the skills.
if (itemName == "Skill Coin") {
skillPoints++;
} else {
// It does nothing.
}
}
/**
* Objective: manages the reactions of other objects in collision with the player.
*
* @param GameObject* other - the object that is in collision with the player.
* @return none.
*/
void Player::NotifyObjectCollision(GameObject* other) {
assert(other != nullptr);
Character::NotifyObjectCollision(other);
// The player gets damaged if the object is attacking.
if (other->IsCharacter() && !other->IsPlayer()) {
Character* c = (Character*) other;
if (c->Attacking()) {
Damage(c->Power());
} else {
// It does nothing.
}
} else
// It does nothing.
if (other->Is("Projectile")) {
Projectile* p = (Projectile*) other;
if (!(p->GetOwner() == "Gallahad")) {
Damage(p->Power());
} else {
// It does nothing.
}
} else
// Restores some energy of the player.
if (other->Is("Energy")) {
if (isCrouching && !regenCD.IsRunning()) {
regenCD.Start();
energy += 1;
clamp(energy, 0, 5);
} else {
// It does nothing.
}
} else
// Restores some hitpoints of the player.
if (other->Is("Life")) {
if (isCrouching && !regenCD.IsRunning()) {
regenCD.Start();
hitpoints += 1;
clamp(hitpoints, 0, 10);
} else {
// It does nothing.
}
} else {
// It does nothing.
}
}
/**
* Objective: updates the time of the cool down regeneration.
*
* @param float dt - the amount of time to cool down the regeneration.
* @return none.
*/
void Player::UpdateTimers(float dt) {
assert(dt >= FLOAT_MIN_SIZE && dt <= FLOAT_MAX_SIZE);
Character::UpdateTimers(dt);
regenCD.Update(dt);
}
void Player::Update(TileMap* map, float dt) {
assert(dt >= FLOAT_MIN_SIZE && dt <= FLOAT_MAX_SIZE);
assert(map != nullptr);
UpdateTimers(dt);
inputComponent->Update(this, dt);
physicsComponent.Update(this, map, dt);
if (OutOfBounds(map)) {
SetPosition(Vec2(startingX, startingY));
} else {
// It does nothing.
}
graphicsComponent->Update(this, dt);
}
<commit_msg>Aplicação 2 de Log e verificação de retorno.<commit_after>/**
* Copyright (c) 2017 Neon Edge Game
* File Name: Player.cpp
* Header File Name: Player.h
* Class Name: Player
* Objective: manages the behavior of some aspects of the player.
*/
#include "Player.h"
#include "Projectile.h"
#include "Logger.h"
#include <assert.h>
/**
Objective: constructor of the class Player.
@param ItensManager* itemManager
@param int x - coordinate of the player.
@param int y - coordinate of the player.
@return Player - instance of the class Player.
*/
Player::Player(ItemsManager* itemManager, int x, int y): Character(x,y){
inputComponent = nullptr;
this->itemManager = itemManager ;
// Sets the default enabled skills.
skills[0] = false;
skills[1] = false;
skills[2] = true;
skills[3] = true;
skills[4] = true;
skills[5] = false;
skills[6] = false;
skillPoints = 0;
energy = 5; // Sets the energy of the player to 5.
regenCD = 500; // The time of the cool down regeneration in miliseconds.
isCrouching = false; // Default state: standing.
isStading = true;
name = "Player"; // Sets the Player's name.
hitpoints = MAX_HITPOINTS; // Sets the hitpoints of the player to 10.
Log::instance.info("Player builder started!");
}
/**
* Objective: destructor of the class Player.
*
* @param none.
* @return none.
*/
Player::~Player() {
}
/**
* Objective: checks if is a player.
*
* @param none.
* @return bool - returns TRUE.
*/
bool Player::IsPlayer() {
return true;
}
/**
* Objective: gets the energy of player.
*
* @param none.
* @return int energy - returns the amount of energy of the player.
*/
int Player::GetEnergy() {
assert(energy >= 0 && energy <= 5);
return energy;
}
/**
* Objective: performs the action of crouch.
*
* @param: none.
* @return: none.
*/
void Player::Crouch() {
if (isStading) {
isStading = false;
assert(soundComponent != nullptr);
soundComponent->SoundCrouching(); // Performs the crouching sound in case that the player is
// standing.
} else {
Log::instance.info("Player is already crouching");
}
isCrouching = true;
}
/**
* Objective: performs the action of stand.
*
* @param none.
* @return none.
*/
void Player::Stand() {
isCrouching = false;
isStading = true;
}
/**
* Objective: checks if the player is crouching or not.
*
* @param none.
* @return bool crouching - return true if the player is crouching.
*/
bool Player::IsCrouching() {
assert(isCrouching == true || isCrouching == false);
return isCrouching;
}
/**
* Objective: performs an action due to an item used by the player.
*
* @param string itemName - the name of the item.
* @return none.
*/
void Player::EvalItem(std::string itemName) {
assert(itemName != "");
// Heals the hitpoints of the player by 25% of the total.
if (itemName == "Healing Potion 25") {
hitpoints += MAX_HITPOINTS*0.25;
clamp(hitpoints, 0, MAX_HITPOINTS);
} else
// Heals the hitpoints of the player by 50% of the total.
if (itemName == "Healing Potion 50") {
hitpoints += MAX_HITPOINTS*0.5;
clamp(hitpoints, 0, MAX_HITPOINTS);
} else
// Adds 2 energy points.
if (itemName == "Energy Potion 25") {
energy += 2;
clamp(energy, 0, 5);
} else
// Adds 5 energy points.
if (itemName == "Energy Potion 50") {
energy += 5;
clamp(energy, 0, 5);
} else
// Adds 1 point to the skills.
if (itemName == "Skill Coin") {
skillPoints++;
} else {
Log::instance.error("No valid item");
}
}
/**
* Objective: manages the reactions of other objects in collision with the player.
*
* @param GameObject* other - the object that is in collision with the player.
* @return none.
*/
void Player::NotifyObjectCollision(GameObject* other) {
assert(other != nullptr);
Log::instance.info("Collision of objects, NotifyObjectCollision in Player");
Character::NotifyObjectCollision(other);
// The player gets damaged if the object is attacking.
if (other->IsCharacter() && !other->IsPlayer()) {
Character* c = (Character*) other;
if (c->Attacking()) {
Damage(c->Power());
} else {
// It does nothing.
}
} else if (other->Is("Projectile")) {
Projectile* p = (Projectile*) other;
if (!(p->GetOwner() == "Gallahad")) {
Damage(p->Power());
} else {
// It does nothing.
}
} else
// Restores some energy of the player.
if (other->Is("Energy")) {
if (isCrouching && !regenCD.IsRunning()) {
regenCD.Start();
energy += 1;
clamp(energy, 0, 5);
} else {
// It does nothing.
}
} else
// Restores some hitpoints of the player.
if (other->Is("Life")) {
if (isCrouching && !regenCD.IsRunning()) {
regenCD.Start();
hitpoints += 1;
clamp(hitpoints, 0, 10);
} else {
// It does nothing.
}
} else {
Log::instance.error("Collision with Player not expected");
}
}
/**
* Objective: updates the time of the cool down regeneration.
*
* @param float dt - the amount of time to cool down the regeneration.
* @return none.
*/
void Player::UpdateTimers(float dt) {
assert(dt >= FLOAT_MIN_SIZE && dt <= FLOAT_MAX_SIZE);
Character::UpdateTimers(dt);
regenCD.Update(dt);
}
void Player::Update(TileMap* map, float dt) {
assert(dt >= FLOAT_MIN_SIZE && dt <= FLOAT_MAX_SIZE);
assert(map != nullptr);
UpdateTimers(dt);
inputComponent->Update(this, dt);
physicsComponent.Update(this, map, dt);
if (OutOfBounds(map)) {
SetPosition(Vec2(startingX, startingY));
Log::instance.warning("Outdated limits!");
} else {
// It does nothing.
}
graphicsComponent->Update(this, dt);
}
<|endoftext|> |
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_TESTCASES_ESV2007_HH
#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_ESV2007_HH
#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif
#include <dune/stuff/functions/ESV2007.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/hdd/linearelliptic/problems/ESV2007.hh>
#include "base.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace TestCases {
template< class GridType >
class ESV2007
: public Base< GridType >
{
typedef Base< GridType > BaseType;
static_assert(BaseType::dimDomain == 2, "This test case is only available in 2d!");
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef double RangeFieldType;
static const unsigned int dimRange = 1;
typedef Problems::ESV2007< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;
typedef Stuff::Functions::ESV2007::Testcase1ExactSolution
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ExactSolutionType;
typedef Stuff::LocalizableFunctionInterface < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange >
FunctionType;
ESV2007(const size_t num_refinements = 3)
: BaseType(create_initial_grid(), num_refinements)
, boundary_info_cfg_(Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config())
, problem_(3)
, exact_solution_(2, problem_.static_id() + ".exact_solution")
{}
void print_header(std::ostream& out = std::cout) const
{
out << "+==================================================================+\n"
<< "|+================================================================+|\n"
<< "|| Testcase ESV2007: smooth data, homogeneous dirichlet ||\n"
<< "|| (see testcase 1, page 23 in Ern, Stephansen, Vohralik, 2007) ||\n"
<< "|+----------------------------------------------------------------+|\n"
<< "|| domain = [-1, 1] x [-1, 1] ||\n"
<< "|| diffusion = 1 ||\n"
<< "|| force = 1/2 pi^2 cos(1/2 pi x) cos(1/2 pi y) ||\n"
<< "|| dirichlet = 0 ||\n"
<< "|| exact solution = cos(1/2 pi x) cos(1/2 pi y) ||\n"
<< "|+================================================================+|\n"
<< "+==================================================================+" << std::endl;
} // ... print_header(...)
const Stuff::Common::Configuration& boundary_info() const
{
return boundary_info_cfg_;
}
const ProblemType& problem() const
{
return problem_;
}
bool provides_exact_solution() const
{
return true;
}
const ExactSolutionType& exact_solution() const
{
return exact_solution_;
}
private:
static std::shared_ptr< GridType > create_initial_grid()
{
Dune::Stuff::Grid::Providers::Cube< GridType > grid_provider(-1, 1, 4);
auto grid = grid_provider.grid_ptr();
#if HAVE_ALUGRID
if (std::is_same< GridType, Dune::ALUConformGrid< 2, 2 > >::value
|| std::is_same< GridType, Dune::ALUGrid< 2, 2, Dune::simplex, Dune::conforming > >::value)
grid->globalRefine(1);
#endif // HAVE_ALUGRID
grid->globalRefine(1);
return grid;
} // ... create_initial_grid(...)
const Stuff::Common::Configuration boundary_info_cfg_;
const ProblemType problem_;
const ExactSolutionType exact_solution_;
}; // class ESV2007
#if HAVE_DUNE_GRID_MULTISCALE
template< class GridType >
class ESV2007Multiscale
: public MultiscaleCubeBase< GridType >
{
typedef MultiscaleCubeBase< GridType > BaseType;
static_assert(BaseType::dimDomain == 2, "This test case is only available in 2d!");
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef double RangeFieldType;
static const unsigned int dimRange = 1;
typedef Problems::ESV2007< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;
typedef Stuff::Functions::ESV2007::Testcase1ExactSolution
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ExactSolutionType;
typedef Stuff::LocalizableFunctionInterface < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange >
FunctionType;
ESV2007Multiscale(const std::string num_partitions = "[1 1 1]", const size_t num_refinements = 3)
: BaseType(initial_grid_cfg(num_partitions), initial_refinements(), num_refinements)
, boundary_info_cfg_(Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config())
, problem_(3)
, exact_solution_(2, problem_.static_id() + ".exact_solution")
{}
void print_header(std::ostream& out = std::cout) const
{
out << "+==================================================================+\n"
<< "|+================================================================+|\n"
<< "|| Testcase ESV2007: smooth data, homogeneous dirichlet ||\n"
<< "|| (see testcase 1, page 23 in Ern, Stephansen, Vohralik, 2007) ||\n"
<< "|+----------------------------------------------------------------+|\n"
<< "|| domain = [-1, 1] x [-1, 1] ||\n"
<< "|| diffusion = 1 ||\n"
<< "|| force = 1/2 pi^2 cos(1/2 pi x) cos(1/2 pi y) ||\n"
<< "|| dirichlet = 0 ||\n"
<< "|| exact solution = cos(1/2 pi x) cos(1/2 pi y) ||\n"
<< "|+================================================================+|\n"
<< "+==================================================================+" << std::endl;
} // ... print_header(...)
const Stuff::Common::Configuration& boundary_info() const
{
return boundary_info_cfg_;
}
const ProblemType& problem() const
{
return problem_;
}
bool provides_exact_solution() const
{
return true;
}
const ExactSolutionType& exact_solution() const
{
return exact_solution_;
}
private:
static Stuff::Common::Configuration initial_grid_cfg(const std::string num_partitions)
{
Stuff::Common::Configuration grid_cfg = Stuff::Grid::Providers::Cube< GridType >::default_config();
grid_cfg["lower_left"] = "-1";
grid_cfg["upper_right"] = "1";
grid_cfg["num_elements"] = "4";
grid_cfg["num_partitions"] = num_partitions;
return grid_cfg;
} // ... initial_grid_cfg(...)
static int initial_refinements()
{
int ret = 1;
#if HAVE_ALUGRID
if (std::is_same< GridType, ALUConformGrid< 2, 2 > >::value
|| std::is_same< GridType, ALUGrid< 2, 2, simplex, conforming > >::value)
ret += 1;
#endif // HAVE_ALUGRID
return ret;
} // ... initial_refinements()
const Stuff::Common::Configuration boundary_info_cfg_;
const ProblemType problem_;
const ExactSolutionType exact_solution_;
}; // class ESV2007Multiscale
#endif // HAVE_DUNE_GRID_MULTISCALE
} // namespace TestCases
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_TESTCASES_ESV2007_HH
<commit_msg>[linearelliptic.testcases.ESV2007] reduced code duplication<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_TESTCASES_ESV2007_HH
#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_ESV2007_HH
#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif
#include <dune/stuff/functions/ESV2007.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/hdd/linearelliptic/problems/ESV2007.hh>
#include "base.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace TestCases {
namespace internal {
template< class GridType >
class ESV2007Base
{
static_assert(GridType::dimension == 2, "This test case is only available in 2d!");
public:
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
typedef double RangeFieldType;
static const unsigned int dimRange = 1;
typedef Problems::ESV2007< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;
typedef Stuff::Functions::ESV2007::Testcase1ExactSolution
< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ExactSolutionType;
typedef Stuff::LocalizableFunctionInterface < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange >
FunctionType;
protected:
static const size_t default_num_refinements = 3;
static int initial_refinements()
{
int ret = 1;
#if HAVE_ALUGRID
if (std::is_same< GridType, ALUConformGrid< 2, 2 > >::value
|| std::is_same< GridType, ALUGrid< 2, 2, simplex, conforming > >::value)
ret += 1;
#endif // HAVE_ALUGRID
return ret;
} // ... initial_refinements()
public:
ESV2007Base()
: boundary_info_cfg_(Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config())
, problem_(3)
, exact_solution_(2, problem_.static_id() + ".exact_solution")
{}
void print_header(std::ostream& out = std::cout) const
{
out << "+==================================================================+\n"
<< "|+================================================================+|\n"
<< "|| Testcase ESV2007: smooth data, homogeneous dirichlet ||\n"
<< "|| (see testcase 1, page 23 in Ern, Stephansen, Vohralik, 2007) ||\n"
<< "|+----------------------------------------------------------------+|\n"
<< "|| domain = [-1, 1] x [-1, 1] ||\n"
<< "|| diffusion = 1 ||\n"
<< "|| force = 1/2 pi^2 cos(1/2 pi x) cos(1/2 pi y) ||\n"
<< "|| dirichlet = 0 ||\n"
<< "|| exact solution = cos(1/2 pi x) cos(1/2 pi y) ||\n"
<< "|+================================================================+|\n"
<< "+==================================================================+" << std::endl;
} // ... print_header(...)
const Stuff::Common::Configuration& boundary_info() const
{
return boundary_info_cfg_;
}
const ProblemType& problem() const
{
return problem_;
}
bool provides_exact_solution() const
{
return true;
}
const ExactSolutionType& exact_solution() const
{
return exact_solution_;
}
private:
const Stuff::Common::Configuration boundary_info_cfg_;
const ProblemType problem_;
const ExactSolutionType exact_solution_;
}; // class ESV2007
} // namespace internal
template< class GridType >
class ESV2007
: public internal::ESV2007Base< GridType >
, public Base< GridType >
{
typedef internal::ESV2007Base< GridType > ESV2007BaseType;
typedef Base< GridType > TestCaseBaseType;
private:
static std::shared_ptr< GridType > create_initial_grid(const int refinements)
{
Stuff::Grid::Providers::Cube< GridType > grid_provider(-1, 1, 4);
auto grid = grid_provider.grid_ptr();
grid->globalRefine(refinements);
return grid;
} // ... create_initial_grid(...)
public:
ESV2007(const size_t num_refinements = ESV2007BaseType::default_num_refinements)
: TestCaseBaseType(create_initial_grid(ESV2007BaseType::initial_refinements()), num_refinements)
{}
}; // class ESV2007
#if HAVE_DUNE_GRID_MULTISCALE
template< class GridType >
class ESV2007Multiscale
: public internal::ESV2007Base< GridType >
, public MultiscaleCubeBase< GridType >
{
typedef internal::ESV2007Base< GridType > ESV2007BaseType;
typedef MultiscaleCubeBase< GridType > TestCaseBaseType;
private:
static Stuff::Common::Configuration initial_grid_cfg(const std::string num_partitions)
{
Stuff::Common::Configuration grid_cfg = Stuff::Grid::Providers::Cube< GridType >::default_config();
grid_cfg["lower_left"] = "-1";
grid_cfg["upper_right"] = "1";
grid_cfg["num_elements"] = "4";
grid_cfg["num_partitions"] = num_partitions;
return grid_cfg;
} // ... initial_grid_cfg(...)
public:
ESV2007Multiscale(const std::string num_partitions = "[1 1 1]",
const size_t num_refinements = ESV2007BaseType::default_num_refinements)
: TestCaseBaseType(initial_grid_cfg(num_partitions), ESV2007BaseType::initial_refinements(), num_refinements)
{}
}; // class ESV2007Multiscale
#endif // HAVE_DUNE_GRID_MULTISCALE
} // namespace TestCases
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_TESTCASES_ESV2007_HH
<|endoftext|> |
<commit_before>#pragma warning (disable:4996)
#define WIN32_LEAN_AND_MEAN
#pragma comment (lib, "Shlwapi.lib")
#include <Windows.h>
#include <Shlwapi.h>
#include <unordered_map>
#include <mutex>
#include <queue>
using namespace std;
#define BUF_SIZE MAX_PATH * 3
long long CurrentTime()
{
long long t;
GetSystemTimeAsFileTime((LPFILETIME) &t);
return t;
}
BOOL unhook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PBYTE pOrgBytes)
{
FARPROC pFunc;
DWORD dwOldProtect;
// API ּ Ѵ
pFunc = GetProcAddress(GetModuleHandle(szDllName), szFuncName);
// ڵ (5 byte) WRITE Ӽ ߰
VirtualProtect((LPVOID) pFunc, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// Unhook
memcpy(pFunc, pOrgBytes, 5);
// Ӽ
VirtualProtect((LPVOID) pFunc, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
BOOL hook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PROC pfnNew, PBYTE pOrgBytes)
{
FARPROC pfnOrg;
DWORD dwOldProtect, dwAddress;
BYTE pBuf[5] = { 0xE9, 0, };
PBYTE pByte;
// ŷ API ּҸ Ѵ
pfnOrg = (FARPROC) GetProcAddress(GetModuleHandle(szDllName), szFuncName);
pByte = (PBYTE) pfnOrg;
// ̹ ŷǾ ִٸ return FALSE
if (pByte[0] == 0xE9)
return FALSE;
// 5 byte ġ Ͽ WRITE Ӽ ߰
VirtualProtect((LPVOID) pfnOrg, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// ڵ (5 byte)
memcpy(pOrgBytes, pfnOrg, 5);
// JMP ּҰ (E9 XXXX)
// => XXXX = pfnNew - pfnOrg - 5
dwAddress = (DWORD) pfnNew - (DWORD) pfnOrg - 5;
memcpy(&pBuf[1], &dwAddress, 4);
// Hook - 5 byte ġ(JMP XXXX)
memcpy(pfnOrg, pBuf, 5);
// Ӽ
VirtualProtect((LPVOID) pfnOrg, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
mutex QueueMutex;
HANDLE hPipe;
volatile bool bCancelPipeThread;
volatile bool bPipeConnected;
queue<string*> MessageQueue;
HANDLE hQueuePushed;
DWORD WINAPI PipeThread(LPVOID lParam)
{
hPipe = CreateNamedPipeA("\\\\.\\pipe\\osu!Lyrics", PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_MESSAGE | PIPE_WAIT, 1, BUF_SIZE, 0, INFINITE, NULL);
// û Ŭ̾Ʈ
while (!bCancelPipeThread)
{
// ConnectNamedPipe Ŭ̾Ʈ :
// Ҵ DisconnectNamedPipe
if (ConnectNamedPipe(hPipe, NULL) || GetLastError() == ERROR_PIPE_CONNECTED)
{
bPipeConnected = true;
if (MessageQueue.empty())
{
// ť 3ʰ ٷ ȣ ٽ ٸ
WaitForSingleObject(hQueuePushed, 3000);
continue;
}
QueueMutex.lock();
string *message = MessageQueue.front();
MessageQueue.pop();
QueueMutex.unlock();
OVERLAPPED overlapped = {};
if (WriteFileEx(hPipe, message->c_str(), message->length(), &overlapped, [](DWORD, DWORD, LPOVERLAPPED) {}))
{
delete message;
continue;
}
}
QueueMutex.lock();
while (MessageQueue.empty())
{
MessageQueue.pop();
}
QueueMutex.unlock();
bPipeConnected = false;
DisconnectNamedPipe(hPipe);
}
// Ŭ̾Ʈ
bPipeConnected = false;
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
return 0;
}
typedef BOOL (WINAPI *tReadFile)(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
tReadFile pReadFile;
mutex HookMutex;
BYTE pReadFileHook[5];
unordered_map<string, string> AudioInfo;
// osu! ReadFile ȣϸ osu!Lyrics
BOOL WINAPI hkReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
long long calledAt = CurrentTime();
HookMutex.lock();
unhook_by_code("kernel32.dll", "ReadFile", pReadFileHook);
BOOL result = pReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileHook);
HookMutex.unlock();
if (!result)
{
return FALSE;
}
char path[MAX_PATH];
DWORD pathLength = GetFinalPathNameByHandle(hFile, path, MAX_PATH, VOLUME_NAME_DOS);
// 1: \\?\D:\Games\osu!\...
DWORD seekPosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - *lpNumberOfBytesRead;
// д Ʈ ̰ պκ оٸ:
// AudioFilename պκп / ڵ !
if (strnicmp(".osu", &path[pathLength - 4], 4) == 0 && seekPosition == 0)
{
// strtok ҽ ϹǷ ϴ
char *buffer = strdup((char *) lpBuffer);
char *line = strtok(buffer, "\n");
while (line != NULL)
{
// Ʈ
if (strnicmp(line, "AudioFilename:", 14) == 0)
{
char *beatmapDir = strdup(path);
PathRemoveFileSpec(beatmapDir);
char audioPath[MAX_PATH];
// get value & trim
int i = 14;
for (; line[i] == ' '; i++);
buffer[0] = '\0';
strncat(buffer, &line[i], strlen(line) - i - 1);
PathCombine(audioPath, beatmapDir, buffer);
// ˻ ҹ ϹǷ
WIN32_FIND_DATA fdata;
FindClose(FindFirstFile(audioPath, &fdata));
PathRemoveFileSpec(audioPath);
PathCombine(audioPath, audioPath, fdata.cFileName);
AudioInfo.insert(make_pair(string(audioPath), string(path)));
free(beatmapDir);
break;
}
line = strtok(NULL, "\n");
}
free(buffer);
}
// 縦 ʴٴ :
// osu! ÷̿ ϰ ... ڿ
else if (bPipeConnected)
{
// [ audioPath, beatmapPath ]
unordered_map<string, string>::iterator pair = AudioInfo.find(string(path));
bool found = pair != AudioInfo.end();
if (found)
{
char message[BUF_SIZE];
sprintf(message, "%llx|%s|%lx|%s\n", calledAt, &path[4], seekPosition, &pair->second[4]);
QueueMutex.lock();
MessageQueue.push(new string(message));
QueueMutex.unlock();
SetEvent(hQueuePushed);
}
}
return TRUE;
}
HANDLE hPipeThread;
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
hPipeThread = CreateThread(NULL, 0, PipeThread, NULL, 0, NULL);
hQueuePushed = CreateEventA(NULL, TRUE, FALSE, NULL);
HookMutex.lock();
pReadFile = (tReadFile) GetProcAddress(GetModuleHandle("kernel32.dll"), "ReadFile");
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileHook);
HookMutex.unlock();
}
else if (fdwReason == DLL_PROCESS_DETACH)
{
HookMutex.lock();
unhook_by_code("kernel32.dll", "ReadFile", pReadFileHook);
HookMutex.unlock();
bCancelPipeThread = true;
DisconnectNamedPipe(hPipe);
WaitForSingleObject(hPipeThread, INFINITE);
CloseHandle(hQueuePushed);
CloseHandle(hPipeThread);
}
return TRUE;
}<commit_msg>코드 클린업 - 3. 그리고 남은 큐들을 팝할때 동적할당된 메모리를 헤제하지 않았던 버그 수정.<commit_after>#pragma warning (disable:4996)
#define WIN32_LEAN_AND_MEAN
#pragma comment (lib, "Shlwapi.lib")
#include <Windows.h>
#include <Shlwapi.h>
#include <unordered_map>
#include <mutex>
#include <queue>
using namespace std;
#define BUF_SIZE MAX_PATH * 3
long long CurrentTime()
{
long long t;
GetSystemTimeAsFileTime((LPFILETIME) &t);
return t;
}
BOOL unhook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PBYTE pOrgBytes)
{
FARPROC pFunc;
DWORD dwOldProtect;
// API ּ Ѵ
pFunc = GetProcAddress(GetModuleHandle(szDllName), szFuncName);
// ڵ (5 byte) WRITE Ӽ ߰
VirtualProtect((LPVOID) pFunc, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// Unhook
memcpy(pFunc, pOrgBytes, 5);
// Ӽ
VirtualProtect((LPVOID) pFunc, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
BOOL hook_by_code(LPCTSTR szDllName, LPCTSTR szFuncName, PROC pfnNew, PBYTE pOrgBytes)
{
FARPROC pfnOrg;
DWORD dwOldProtect, dwAddress;
BYTE pBuf[5] = { 0xE9, 0, };
PBYTE pByte;
// ŷ API ּҸ Ѵ
pfnOrg = (FARPROC) GetProcAddress(GetModuleHandle(szDllName), szFuncName);
pByte = (PBYTE) pfnOrg;
// ̹ ŷǾ ִٸ return FALSE
if (pByte[0] == 0xE9)
return FALSE;
// 5 byte ġ Ͽ WRITE Ӽ ߰
VirtualProtect((LPVOID) pfnOrg, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
// ڵ (5 byte)
memcpy(pOrgBytes, pfnOrg, 5);
// JMP ּҰ (E9 XXXX)
// => XXXX = pfnNew - pfnOrg - 5
dwAddress = (DWORD) pfnNew - (DWORD) pfnOrg - 5;
memcpy(&pBuf[1], &dwAddress, 4);
// Hook - 5 byte ġ(JMP XXXX)
memcpy(pfnOrg, pBuf, 5);
// Ӽ
VirtualProtect((LPVOID) pfnOrg, 5, dwOldProtect, &dwOldProtect);
return TRUE;
}
mutex QueueMutex;
HANDLE hPipe;
volatile bool bCancelPipeThread;
volatile bool bPipeConnected;
queue<string*> MessageQueue;
HANDLE hQueuePushed;
DWORD WINAPI PipeThread(LPVOID lParam)
{
hPipe = CreateNamedPipeA("\\\\.\\pipe\\osu!Lyrics", PIPE_ACCESS_OUTBOUND,
PIPE_TYPE_MESSAGE | PIPE_WAIT, 1, BUF_SIZE, 0, INFINITE, NULL);
// û Ŭ̾Ʈ
while (!bCancelPipeThread)
{
// ConnectNamedPipe Ŭ̾Ʈ :
// Ҵ DisconnectNamedPipe
if (ConnectNamedPipe(hPipe, NULL) || GetLastError() == ERROR_PIPE_CONNECTED)
{
bPipeConnected = true;
if (MessageQueue.empty())
{
// ť 3ʰ ٷ ȣ ٽ ٸ
WaitForSingleObject(hQueuePushed, 3000);
continue;
}
QueueMutex.lock();
string *message = MessageQueue.front();
MessageQueue.pop();
QueueMutex.unlock();
OVERLAPPED overlapped = {};
if (WriteFileEx(hPipe, message->c_str(), message->length(), &overlapped, [](DWORD, DWORD, LPOVERLAPPED) {}))
{
delete message;
continue;
}
}
QueueMutex.lock();
bPipeConnected = false;
DisconnectNamedPipe(hPipe);
while (!MessageQueue.empty())
{
string *message = MessageQueue.front();
delete message;
MessageQueue.pop();
}
QueueMutex.unlock();
}
// Ŭ̾Ʈ
bPipeConnected = false;
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
return 0;
}
typedef BOOL (WINAPI *tReadFile)(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
tReadFile pReadFile;
mutex HookMutex;
BYTE pReadFileHook[5];
unordered_map<string, string> AudioInfo;
// osu! ReadFile ȣϸ osu!Lyrics
BOOL WINAPI hkReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
long long calledAt = CurrentTime();
HookMutex.lock();
unhook_by_code("kernel32.dll", "ReadFile", pReadFileHook);
BOOL result = pReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileHook);
HookMutex.unlock();
if (!result)
{
return FALSE;
}
char path[MAX_PATH];
DWORD pathLength = GetFinalPathNameByHandle(hFile, path, MAX_PATH, VOLUME_NAME_DOS);
// 1: \\?\D:\Games\osu!\...
DWORD seekPosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - *lpNumberOfBytesRead;
// д Ʈ ̰ պκ оٸ:
// AudioFilename պκп / ڵ !
if (strnicmp(".osu", &path[pathLength - 4], 4) == 0 && seekPosition == 0)
{
// strtok ҽ ϹǷ ϴ
char *buffer = strdup((char *) lpBuffer);
char *line = strtok(buffer, "\n");
while (line != NULL)
{
// Ʈ
if (strnicmp(line, "AudioFilename:", 14) == 0)
{
char *beatmapDir = strdup(path);
PathRemoveFileSpec(beatmapDir);
char audioPath[MAX_PATH];
// get value & trim
int i = 14;
for (; line[i] == ' '; i++);
buffer[0] = '\0';
strncat(buffer, &line[i], strlen(line) - i - 1);
PathCombine(audioPath, beatmapDir, buffer);
// ˻ ҹ ϹǷ
WIN32_FIND_DATA fdata;
FindClose(FindFirstFile(audioPath, &fdata));
PathRemoveFileSpec(audioPath);
PathCombine(audioPath, audioPath, fdata.cFileName);
AudioInfo.insert(make_pair(string(audioPath), string(path)));
free(beatmapDir);
break;
}
line = strtok(NULL, "\n");
}
free(buffer);
}
// 縦 ʴٴ :
// osu! ÷̿ ϰ ... ڿ
else if (bPipeConnected)
{
// [ audioPath, beatmapPath ]
unordered_map<string, string>::iterator pair = AudioInfo.find(string(path));
bool found = pair != AudioInfo.end();
if (found)
{
char message[BUF_SIZE];
sprintf(message, "%llx|%s|%lx|%s\n", calledAt, &path[4], seekPosition, &pair->second[4]);
QueueMutex.lock();
MessageQueue.push(new string(message));
QueueMutex.unlock();
SetEvent(hQueuePushed);
}
}
return TRUE;
}
HANDLE hPipeThread;
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
hPipeThread = CreateThread(NULL, 0, PipeThread, NULL, 0, NULL);
hQueuePushed = CreateEventA(NULL, TRUE, FALSE, NULL);
HookMutex.lock();
pReadFile = (tReadFile) GetProcAddress(GetModuleHandle("kernel32.dll"), "ReadFile");
hook_by_code("kernel32.dll", "ReadFile", (PROC) hkReadFile, pReadFileHook);
HookMutex.unlock();
}
else if (fdwReason == DLL_PROCESS_DETACH)
{
HookMutex.lock();
unhook_by_code("kernel32.dll", "ReadFile", pReadFileHook);
HookMutex.unlock();
bCancelPipeThread = true;
DisconnectNamedPipe(hPipe);
WaitForSingleObject(hPipeThread, INFINITE);
CloseHandle(hQueuePushed);
CloseHandle(hPipeThread);
}
return TRUE;
}<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstddef>
#include <cstring>
#include <cmath>
#include <cctype>
// Tries to parse a floating point number located at s.
//
// s_end should be a location in the string where reading should absolutely
// stop. For example at the end of the string, to prevent buffer overflows.
//
// Parses the following EBNF grammar:
// sign = "+" | "-" ;
// END = ? anything not in digit ?
// digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
// integer = [sign] , digit , {digit} ;
// decimal = integer , ["." , integer] ;
// float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ;
//
// Valid strings are for example:
// -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2
//
// If the parsing is a success, result is set to the parsed value and true
// is returned.
//
// The function is greedy and will parse until any of the following happens:
// - a non-conforming character is encountered.
// - s_end is reached.
//
// The following situations triggers a failure:
// - s >= s_end.
// - parse failure.
//
bool tryParseDouble(const char *s, const char *s_end, double *result)
{
if (s >= s_end)
{
return false;
}
double mantissa = 0.0;
// This exponent is base 2 rather than 10.
// However the exponent we parse is supposed to be one of ten,
// thus we must take care to convert the exponent/and or the
// mantissa to a * 2^E, where a is the mantissa and E is the
// exponent.
// To get the final double we will use ldexp, it requires the
// exponent to be in base 2.
int exponent = 0;
// NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED
// TO JUMP OVER DEFINITIONS.
char sign = '+';
char exp_sign = '+';
char const *curr = s;
// How many characters were read in a loop.
int read = 0;
// Tells whether a loop terminated due to reaching s_end.
bool end_not_reached = false;
/*
BEGIN PARSING.
*/
// Find out what sign we've got.
if (*curr == '+' || *curr == '-')
{
sign = *curr;
curr++;
}
else if (isdigit(*curr)) { /* Pass through. */ }
else
{
goto fail;
}
// Read the integer part.
while ((end_not_reached = (curr != s_end)) && isdigit(*curr))
{
mantissa *= 10;
mantissa += static_cast<int>(*curr - 0x30);
curr++; read++;
}
// We must make sure we actually got something.
if (read == 0)
goto fail;
// We allow numbers of form "#", "###" etc.
if (!end_not_reached)
goto assemble;
// Read the decimal part.
if (*curr == '.')
{
curr++;
read = 1;
while ((end_not_reached = (curr != s_end)) && isdigit(*curr))
{
// NOTE: Don't use powf here, it will absolutely murder precision.
mantissa += static_cast<int>(*curr - 0x30) * pow(10, -read);
read++; curr++;
}
}
else if (*curr == 'e' || *curr == 'E') {}
else
{
goto assemble;
}
if (!end_not_reached)
goto assemble;
// Read the exponent part.
if (*curr == 'e' || *curr == 'E')
{
curr++;
// Figure out if a sign is present and if it is.
if ((end_not_reached = (curr != s_end)) && (*curr == '+' || *curr == '-'))
{
exp_sign = *curr;
curr++;
}
else if (isdigit(*curr)) { /* Pass through. */ }
else
{
// Empty E is not allowed.
goto fail;
}
read = 0;
while ((end_not_reached = (curr != s_end)) && isdigit(*curr))
{
exponent *= 10;
exponent += static_cast<int>(*curr - 0x30);
curr++; read++;
}
exponent *= (exp_sign == '+'? 1 : -1);
if (read == 0)
goto fail;
}
assemble:
*result = (sign == '+'? 1 : -1) * ldexp(mantissa * pow(5, exponent), exponent);
return true;
fail:
return false;
}
void testParsing(const char *input, bool expectedRes, double expectedValue)
{
double val = 0.0;
bool res = tryParseDouble(input, input + strlen(input), &val);
if (res != expectedRes || fabs(val - expectedValue) > 0.000001)
{
printf("% 20s failed, returned %d and value % 10.5f.\n\t\tExpected value was % 10.5f\n------\n", input, res, val, expectedValue);
}
}
int main(int argc, char const *argv[])
{
testParsing("0", true, 0.0);
testParsing("-0", true, 0.0);
testParsing("+0", true, 0.0);
testParsing("1", true, 1.0);
testParsing("+1", true, 1.0);
testParsing("-1", true, -1.0);
testParsing("-1.08", true, -1.08);
testParsing("100.0823blabla", true, 100.0823);
testParsing("34.0E-2\04", true, 34.0e-2);
testParsing("+34.23E2\032", true, 34.23E2);
testParsing("10.023", true, 10.023);
testParsing("1.0e+23", true, 1.e+23);
testParsing("10e+23", true, 10e+23);
testParsing("20301.000", true, 20301.000);
testParsing("-41044.000", true, -41044.000);
testParsing("-93558.000", true, -93558.000);
testParsing("-79620.000", true, -79620.000);
testParsing("5257.000", true, 5257.000);
testParsing("-7145.000", true, -7145.000);
testParsing("-77314.000", true, -77314.000);
testParsing("-27131.000", true, -27131.000);
testParsing("52744.000", true, 52744.000);
testParsing("48106.000", true, 48106.000);
testParsing("42939.000", true, 42939.000);
testParsing("41187.000", true, 41187.000);
testParsing("70851.000", true, 70851.000);
testParsing("-90431.000", true, -90431.000);
testParsing("-13564.000", true, -13564.000);
testParsing("27150.000", true, 27150.000);
testParsing("71992.000", true, 71992.000);
testParsing("-42845.000", true, -42845.000);
testParsing("24806.000", true, 24806.000);
testParsing("30753.000", true, 30753.000);
testParsing("1.658500e+04", true, 1.658500e+04);
testParsing("9.572500e+04", true, 9.572500e+04);
testParsing("-5.888600e+04", true, -5.888600e+04);
testParsing("-2.998000e+04", true, -2.998000e+04);
testParsing("-4.842700e+04", true, -4.842700e+04);
testParsing("9.575400e+04", true, 9.575400e+04);
testParsing("-8.311500e+04", true, -8.311500e+04);
testParsing("-3.770800e+04", true, -3.770800e+04);
testParsing("-3.141600e+04", true, -3.141600e+04);
testParsing("-4.673700e+04", true, -4.673700e+04);
testParsing("-5.112400e+04", true, -5.112400e+04);
testParsing("7.111000e+03", true, 7.111000e+03);
testParsing("-3.727000e+03", true, -3.727000e+03);
testParsing("6.940700e+04", true, 6.940700e+04);
testParsing("-3.635100e+04", true, -3.635100e+04);
testParsing("2.762100e+04", true, 2.762100e+04);
testParsing("-1.512600e+04", true, -1.512600e+04);
testParsing("3.338000e+03", true, 3.338000e+03);
testParsing("7.598100e+04", true, 7.598100e+04);
testParsing("-8.198400e+04", true, -8.198400e+04);
testParsing("-", false, 0.0);
testParsing(" +", false, 0.0);
testParsing("", false, 0.0);
testParsing(".232", false, 0.0);
testParsing(".232E2", false, 0.0);
testParsing(".232", false, 0.0);
testParsing(".", false, 0.0);
testParsing(".E", false, 0.0);
testParsing("233.E", false, 0.0);
testParsing("233.323E-", false, 0.0);
testParsing("233.323E+", false, 0.0);
return 0;
}<commit_msg>Removed stray parser test file.<commit_after><|endoftext|> |
<commit_before>#ifndef UTILITY_HPP
# define UTILITY_HPP
#include <cstddef>
#include <type_traits>
namespace generic
{
// as_const
template<typename T> constexpr inline T const& as_const(T& t) { return t; }
// contains
template <class Container, class Key>
inline bool contains(Container const& c, Key const& key)
{
return c.end() != c.find(key);
}
// indices
template <::std::size_t...> struct indices { };
namespace detail
{
template<class, class> struct catenate_indices;
template <::std::size_t ...Is, ::std::size_t ...Js>
struct catenate_indices<indices<Is...>, indices<Js...> >
{
using indices_type = indices<Is..., Js...>;
};
template <::std::size_t, ::std::size_t, typename = void>
struct expand_indices;
template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if<A == B>::type>
{
using indices_type = indices<A>;
};
template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if<A != B>::type>
{
static_assert(A < B, "A > B");
using indices_type = typename catenate_indices<
typename expand_indices<A, (A + B) / 2>::indices_type,
typename expand_indices<(A + B) / 2 + 1, B>::indices_type
>::indices_type;
};
}
template <::std::size_t A>
struct make_indices : detail::expand_indices<0, A - 1>::indices_type
{
};
template <>
struct make_indices<0> : indices<>
{
};
template <::std::size_t A, ::std::size_t B>
struct make_indices_range : detail::expand_indices<A, B - 1>::indices_type
{
};
template <::std::size_t A>
struct make_indices_range<A, A> : indices<>
{
};
// sequences
template <::std::size_t I, typename A, typename ...B>
struct type_at : type_at<I - 1, B...>
{
};
template <typename A, typename ...B>
struct type_at<0, A, B...>
{
using type = A;
};
template <typename A, typename ...B>
struct front
{
using type = A;
};
template <typename A, typename ...B>
struct back : back<B...>
{
};
template <typename A>
struct back<A>
{
using type = A;
};
template <class A, class ...B>
struct all_of : ::std::integral_constant<bool, A{} && all_of<B...>{}>
{
};
template <class A>
struct all_of<A> : ::std::integral_constant<bool, A{}>
{
};
}
#endif // UTILITY_HPP
<commit_msg>some fixes<commit_after>#ifndef UTILITY_HPP
# define UTILITY_HPP
#include <cstddef>
#include <type_traits>
namespace generic
{
// as_const
template<typename T> constexpr inline T const& as_const(T& t) { return t; }
// contains
template <class Container, class Key>
inline bool contains(Container const& c, Key const& key)
{
return c.end() != c.find(key);
}
// indices
template <::std::size_t...> struct indices { };
namespace detail
{
template<class, class> struct catenate_indices;
template <::std::size_t ...Is, ::std::size_t ...Js>
struct catenate_indices<indices<Is...>, indices<Js...> >
{
using type = indices<Is..., Js...>;
};
template <::std::size_t, ::std::size_t, typename = void>
struct expand_indices;
template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if<A == B>::type>
{
using type = indices<A>;
};
template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if<A != B>::type>
{
static_assert(A < B, "A > B");
using type = typename catenate_indices<
typename expand_indices<A, (A + B) / 2>::type,
typename expand_indices<(A + B) / 2 + 1, B>::type
>::type;
};
}
template <::std::size_t A>
struct make_indices : detail::expand_indices<0, A - 1>::type
{
};
template <>
struct make_indices<0> : indices<>
{
};
template <::std::size_t A, ::std::size_t B>
struct make_indices_range : detail::expand_indices<A, B - 1>::type
{
};
template <::std::size_t A>
struct make_indices_range<A, A> : indices<>
{
};
// sequences
template <::std::size_t I, typename A, typename ...B>
struct type_at : type_at<I - 1, B...>
{
};
template <typename A, typename ...B>
struct type_at<0, A, B...>
{
using type = A;
};
template <typename A, typename ...B>
struct front
{
using type = A;
};
template <typename A, typename ...B>
struct back : back<B...>
{
};
template <typename A>
struct back<A>
{
using type = A;
};
template <class A, class ...B>
struct all_of : ::std::integral_constant<bool, A{} && all_of<B...>{}>
{
};
template <class A>
struct all_of<A> : ::std::integral_constant<bool, A{}>
{
};
}
#endif // UTILITY_HPP
<|endoftext|> |
<commit_before>#ifndef SIMPLE_WEB_UTILITY_HPP
#define SIMPLE_WEB_UTILITY_HPP
#include "status_code.hpp"
#include <atomic>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
namespace SimpleWeb {
inline bool case_insensitive_equal(const std::string &str1, const std::string &str2) noexcept {
return str1.size() == str2.size() &&
std::equal(str1.begin(), str1.end(), str2.begin(), [](char a, char b) {
return tolower(a) == tolower(b);
});
}
class CaseInsensitiveEqual {
public:
bool operator()(const std::string &str1, const std::string &str2) const noexcept {
return case_insensitive_equal(str1, str2);
}
};
// Based on https://stackoverflow.com/questions/2590677/how-do-i-combine-hash-values-in-c0x/2595226#2595226
class CaseInsensitiveHash {
public:
size_t operator()(const std::string &str) const noexcept {
size_t h = 0;
std::hash<int> hash;
for(auto c : str)
h ^= hash(tolower(c)) + 0x9e3779b9 + (h << 6) + (h >> 2);
return h;
}
};
typedef std::unordered_multimap<std::string, std::string, CaseInsensitiveHash, CaseInsensitiveEqual> CaseInsensitiveMultimap;
/// Percent encoding and decoding
class Percent {
public:
/// Returns percent-encoded string
static std::string encode(const std::string &value) noexcept {
static auto hex_chars = "0123456789ABCDEF";
std::string result;
result.reserve(value.size()); // Minimum size of result
for(auto &chr : value) {
if(chr == ' ')
result += '+';
else if(chr == '!' || chr == '#' || chr == '$' || (chr >= '&' && chr <= ',') || (chr >= '/' && chr <= ';') || chr == '=' || chr == '?' || chr == '@' || chr == '[' || chr == ']')
result += std::string("%") + hex_chars[chr >> 4] + hex_chars[chr & 15];
else
result += chr;
}
return result;
}
/// Returns percent-decoded string
static std::string decode(const std::string &value) noexcept {
std::string result;
result.reserve(value.size() / 3 + (value.size() % 3)); // Minimum size of result
for(size_t i = 0; i < value.size(); ++i) {
auto &chr = value[i];
if(chr == '%' && i + 2 < value.size()) {
auto hex = value.substr(i + 1, 2);
auto decoded_chr = static_cast<char>(std::strtol(hex.c_str(), nullptr, 16));
result += decoded_chr;
i += 2;
}
else if(chr == '+')
result += ' ';
else
result += chr;
}
return result;
}
};
/// Query string creation and parsing
class QueryString {
public:
/// Returns query string created from given field names and values
static std::string create(const CaseInsensitiveMultimap &fields) noexcept {
std::string result;
bool first = true;
for(auto &field : fields) {
result += (!first ? "&" : "") + field.first + '=' + Percent::encode(field.second);
first = false;
}
return result;
}
/// Returns query keys with percent-decoded values.
static CaseInsensitiveMultimap parse(const std::string &query_string) noexcept {
CaseInsensitiveMultimap result;
if(query_string.empty())
return result;
size_t name_pos = 0;
auto name_end_pos = std::string::npos;
auto value_pos = std::string::npos;
for(size_t c = 0; c < query_string.size(); ++c) {
if(query_string[c] == '&') {
auto name = query_string.substr(name_pos, (name_end_pos == std::string::npos ? c : name_end_pos) - name_pos);
if(!name.empty()) {
auto value = value_pos == std::string::npos ? std::string() : query_string.substr(value_pos, c - value_pos);
result.emplace(std::move(name), Percent::decode(value));
}
name_pos = c + 1;
name_end_pos = std::string::npos;
value_pos = std::string::npos;
}
else if(query_string[c] == '=') {
name_end_pos = c;
value_pos = c + 1;
}
}
if(name_pos < query_string.size()) {
auto name = query_string.substr(name_pos, name_end_pos - name_pos);
if(!name.empty()) {
auto value = value_pos >= query_string.size() ? std::string() : query_string.substr(value_pos);
result.emplace(std::move(name), Percent::decode(value));
}
}
return result;
}
};
class HttpHeader {
public:
/// Parse header fields
static void parse(std::istream &stream, CaseInsensitiveMultimap &header) {
std::string line;
getline(stream, line);
size_t param_end;
while((param_end = line.find(':')) != std::string::npos) {
size_t value_start = param_end + 1;
if(value_start < line.size()) {
if(line[value_start] == ' ')
value_start++;
if(value_start < line.size())
header.emplace(line.substr(0, param_end), line.substr(value_start, line.size() - value_start - 1));
}
getline(stream, line);
}
}
};
class RequestMessage {
public:
/// Parse request line and header fields
static bool parse(std::istream &stream, std::string &method, std::string &path, std::string &query_string, std::string &version, CaseInsensitiveMultimap &header) noexcept {
header.clear();
std::string line;
getline(stream, line);
size_t method_end;
if((method_end = line.find(' ')) != std::string::npos) {
method = line.substr(0, method_end);
size_t query_start = std::string::npos;
size_t path_and_query_string_end = std::string::npos;
for(size_t i = method_end + 1; i < line.size(); ++i) {
if(line[i] == '?' && (i + 1) < line.size())
query_start = i + 1;
else if(line[i] == ' ') {
path_and_query_string_end = i;
break;
}
}
if(path_and_query_string_end != std::string::npos) {
if(query_start != std::string::npos) {
path = line.substr(method_end + 1, query_start - method_end - 2);
query_string = line.substr(query_start, path_and_query_string_end - query_start);
}
else
path = line.substr(method_end + 1, path_and_query_string_end - method_end - 1);
size_t protocol_end;
if((protocol_end = line.find('/', path_and_query_string_end + 1)) != std::string::npos) {
if(line.compare(path_and_query_string_end + 1, protocol_end - path_and_query_string_end - 1, "HTTP") != 0)
return false;
version = line.substr(protocol_end + 1, line.size() - protocol_end - 2);
}
else
return false;
HttpHeader::parse(stream, header);
}
else
return false;
}
else
return false;
return true;
}
};
class ResponseMessage {
public:
/// Parse status line and header fields
static bool parse(std::istream &stream, std::string &version, std::string &status_code, CaseInsensitiveMultimap &header) noexcept {
header.clear();
std::string line;
getline(stream, line);
size_t version_end = line.find(' ');
if(version_end != std::string::npos) {
if(5 < line.size())
version = line.substr(5, version_end - 5);
else
return false;
if((version_end + 1) < line.size())
status_code = line.substr(version_end + 1, line.size() - (version_end + 1) - 1);
else
return false;
HttpHeader::parse(stream, header);
}
else
return false;
return true;
}
};
} // namespace SimpleWeb
#ifdef __SSE2__
#include <emmintrin.h>
namespace SimpleWeb {
inline void spin_loop_pause() noexcept { _mm_pause(); }
} // namespace SimpleWeb
// TODO: need verification that the following checks are correct:
#elif defined(_MSC_VER) && _MSC_VER >= 1800 && (defined(_M_X64) || defined(_M_IX86))
#include <intrin.h>
namespace SimpleWeb {
inline void spin_loop_pause() noexcept { _mm_pause(); }
} // namespace SimpleWeb
#else
namespace SimpleWeb {
inline void spin_loop_pause() noexcept {}
} // namespace SimpleWeb
#endif
namespace SimpleWeb {
/// Makes it possible to for instance cancel Asio handlers without stopping asio::io_service
class ScopeRunner {
/// Scope count that is set to -1 if scopes are to be canceled
std::atomic<long> count;
public:
class SharedLock {
friend class ScopeRunner;
std::atomic<long> &count;
SharedLock(std::atomic<long> &count) noexcept : count(count) {}
SharedLock &operator=(const SharedLock &) = delete;
SharedLock(const SharedLock &) = delete;
public:
~SharedLock() noexcept {
count.fetch_sub(1);
}
};
ScopeRunner() noexcept : count(0) {}
/// Returns nullptr if scope should be exited, or a shared lock otherwise
std::unique_ptr<SharedLock> continue_lock() noexcept {
long expected = count;
while(expected >= 0 && !count.compare_exchange_weak(expected, expected + 1))
spin_loop_pause();
if(expected < 0)
return nullptr;
else
return std::unique_ptr<SharedLock>(new SharedLock(count));
}
/// Blocks until all shared locks are released, then prevents future shared locks
void stop() noexcept {
long expected = 0;
while(!count.compare_exchange_weak(expected, -1)) {
if(expected < 0)
return;
expected = 0;
spin_loop_pause();
}
}
};
} // namespace SimpleWeb
#endif // SIMPLE_WEB_UTILITY_HPP
<commit_msg>Added noexcept to HttpHeader::parse<commit_after>#ifndef SIMPLE_WEB_UTILITY_HPP
#define SIMPLE_WEB_UTILITY_HPP
#include "status_code.hpp"
#include <atomic>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
namespace SimpleWeb {
inline bool case_insensitive_equal(const std::string &str1, const std::string &str2) noexcept {
return str1.size() == str2.size() &&
std::equal(str1.begin(), str1.end(), str2.begin(), [](char a, char b) {
return tolower(a) == tolower(b);
});
}
class CaseInsensitiveEqual {
public:
bool operator()(const std::string &str1, const std::string &str2) const noexcept {
return case_insensitive_equal(str1, str2);
}
};
// Based on https://stackoverflow.com/questions/2590677/how-do-i-combine-hash-values-in-c0x/2595226#2595226
class CaseInsensitiveHash {
public:
size_t operator()(const std::string &str) const noexcept {
size_t h = 0;
std::hash<int> hash;
for(auto c : str)
h ^= hash(tolower(c)) + 0x9e3779b9 + (h << 6) + (h >> 2);
return h;
}
};
typedef std::unordered_multimap<std::string, std::string, CaseInsensitiveHash, CaseInsensitiveEqual> CaseInsensitiveMultimap;
/// Percent encoding and decoding
class Percent {
public:
/// Returns percent-encoded string
static std::string encode(const std::string &value) noexcept {
static auto hex_chars = "0123456789ABCDEF";
std::string result;
result.reserve(value.size()); // Minimum size of result
for(auto &chr : value) {
if(chr == ' ')
result += '+';
else if(chr == '!' || chr == '#' || chr == '$' || (chr >= '&' && chr <= ',') || (chr >= '/' && chr <= ';') || chr == '=' || chr == '?' || chr == '@' || chr == '[' || chr == ']')
result += std::string("%") + hex_chars[chr >> 4] + hex_chars[chr & 15];
else
result += chr;
}
return result;
}
/// Returns percent-decoded string
static std::string decode(const std::string &value) noexcept {
std::string result;
result.reserve(value.size() / 3 + (value.size() % 3)); // Minimum size of result
for(size_t i = 0; i < value.size(); ++i) {
auto &chr = value[i];
if(chr == '%' && i + 2 < value.size()) {
auto hex = value.substr(i + 1, 2);
auto decoded_chr = static_cast<char>(std::strtol(hex.c_str(), nullptr, 16));
result += decoded_chr;
i += 2;
}
else if(chr == '+')
result += ' ';
else
result += chr;
}
return result;
}
};
/// Query string creation and parsing
class QueryString {
public:
/// Returns query string created from given field names and values
static std::string create(const CaseInsensitiveMultimap &fields) noexcept {
std::string result;
bool first = true;
for(auto &field : fields) {
result += (!first ? "&" : "") + field.first + '=' + Percent::encode(field.second);
first = false;
}
return result;
}
/// Returns query keys with percent-decoded values.
static CaseInsensitiveMultimap parse(const std::string &query_string) noexcept {
CaseInsensitiveMultimap result;
if(query_string.empty())
return result;
size_t name_pos = 0;
auto name_end_pos = std::string::npos;
auto value_pos = std::string::npos;
for(size_t c = 0; c < query_string.size(); ++c) {
if(query_string[c] == '&') {
auto name = query_string.substr(name_pos, (name_end_pos == std::string::npos ? c : name_end_pos) - name_pos);
if(!name.empty()) {
auto value = value_pos == std::string::npos ? std::string() : query_string.substr(value_pos, c - value_pos);
result.emplace(std::move(name), Percent::decode(value));
}
name_pos = c + 1;
name_end_pos = std::string::npos;
value_pos = std::string::npos;
}
else if(query_string[c] == '=') {
name_end_pos = c;
value_pos = c + 1;
}
}
if(name_pos < query_string.size()) {
auto name = query_string.substr(name_pos, name_end_pos - name_pos);
if(!name.empty()) {
auto value = value_pos >= query_string.size() ? std::string() : query_string.substr(value_pos);
result.emplace(std::move(name), Percent::decode(value));
}
}
return result;
}
};
class HttpHeader {
public:
/// Parse header fields
static void parse(std::istream &stream, CaseInsensitiveMultimap &header) noexcept {
std::string line;
getline(stream, line);
size_t param_end;
while((param_end = line.find(':')) != std::string::npos) {
size_t value_start = param_end + 1;
if(value_start < line.size()) {
if(line[value_start] == ' ')
value_start++;
if(value_start < line.size())
header.emplace(line.substr(0, param_end), line.substr(value_start, line.size() - value_start - 1));
}
getline(stream, line);
}
}
};
class RequestMessage {
public:
/// Parse request line and header fields
static bool parse(std::istream &stream, std::string &method, std::string &path, std::string &query_string, std::string &version, CaseInsensitiveMultimap &header) noexcept {
header.clear();
std::string line;
getline(stream, line);
size_t method_end;
if((method_end = line.find(' ')) != std::string::npos) {
method = line.substr(0, method_end);
size_t query_start = std::string::npos;
size_t path_and_query_string_end = std::string::npos;
for(size_t i = method_end + 1; i < line.size(); ++i) {
if(line[i] == '?' && (i + 1) < line.size())
query_start = i + 1;
else if(line[i] == ' ') {
path_and_query_string_end = i;
break;
}
}
if(path_and_query_string_end != std::string::npos) {
if(query_start != std::string::npos) {
path = line.substr(method_end + 1, query_start - method_end - 2);
query_string = line.substr(query_start, path_and_query_string_end - query_start);
}
else
path = line.substr(method_end + 1, path_and_query_string_end - method_end - 1);
size_t protocol_end;
if((protocol_end = line.find('/', path_and_query_string_end + 1)) != std::string::npos) {
if(line.compare(path_and_query_string_end + 1, protocol_end - path_and_query_string_end - 1, "HTTP") != 0)
return false;
version = line.substr(protocol_end + 1, line.size() - protocol_end - 2);
}
else
return false;
HttpHeader::parse(stream, header);
}
else
return false;
}
else
return false;
return true;
}
};
class ResponseMessage {
public:
/// Parse status line and header fields
static bool parse(std::istream &stream, std::string &version, std::string &status_code, CaseInsensitiveMultimap &header) noexcept {
header.clear();
std::string line;
getline(stream, line);
size_t version_end = line.find(' ');
if(version_end != std::string::npos) {
if(5 < line.size())
version = line.substr(5, version_end - 5);
else
return false;
if((version_end + 1) < line.size())
status_code = line.substr(version_end + 1, line.size() - (version_end + 1) - 1);
else
return false;
HttpHeader::parse(stream, header);
}
else
return false;
return true;
}
};
} // namespace SimpleWeb
#ifdef __SSE2__
#include <emmintrin.h>
namespace SimpleWeb {
inline void spin_loop_pause() noexcept { _mm_pause(); }
} // namespace SimpleWeb
// TODO: need verification that the following checks are correct:
#elif defined(_MSC_VER) && _MSC_VER >= 1800 && (defined(_M_X64) || defined(_M_IX86))
#include <intrin.h>
namespace SimpleWeb {
inline void spin_loop_pause() noexcept { _mm_pause(); }
} // namespace SimpleWeb
#else
namespace SimpleWeb {
inline void spin_loop_pause() noexcept {}
} // namespace SimpleWeb
#endif
namespace SimpleWeb {
/// Makes it possible to for instance cancel Asio handlers without stopping asio::io_service
class ScopeRunner {
/// Scope count that is set to -1 if scopes are to be canceled
std::atomic<long> count;
public:
class SharedLock {
friend class ScopeRunner;
std::atomic<long> &count;
SharedLock(std::atomic<long> &count) noexcept : count(count) {}
SharedLock &operator=(const SharedLock &) = delete;
SharedLock(const SharedLock &) = delete;
public:
~SharedLock() noexcept {
count.fetch_sub(1);
}
};
ScopeRunner() noexcept : count(0) {}
/// Returns nullptr if scope should be exited, or a shared lock otherwise
std::unique_ptr<SharedLock> continue_lock() noexcept {
long expected = count;
while(expected >= 0 && !count.compare_exchange_weak(expected, expected + 1))
spin_loop_pause();
if(expected < 0)
return nullptr;
else
return std::unique_ptr<SharedLock>(new SharedLock(count));
}
/// Blocks until all shared locks are released, then prevents future shared locks
void stop() noexcept {
long expected = 0;
while(!count.compare_exchange_weak(expected, -1)) {
if(expected < 0)
return;
expected = 0;
spin_loop_pause();
}
}
};
} // namespace SimpleWeb
#endif // SIMPLE_WEB_UTILITY_HPP
<|endoftext|> |
<commit_before>#include "dg/analysis/ReachingDefinitions/SemisparseRda.h"
#include "dg/llvm/analysis/ReachingDefinitions/ReachingDefinitions.h"
#include "LLVMRDBuilder.h"
#include "LLVMRDBuilderDense.h"
#include "LLVMRDBuilderSemisparse.h"
namespace dg {
namespace analysis {
namespace rd {
LLVMReachingDefinitions::~LLVMReachingDefinitions() {
delete builder;
}
void LLVMReachingDefinitions::initializeSparseRDA() {
builder = new LLVMRDBuilderSemisparse(m, pta, _options);
root = builder->build();
RDA = std::unique_ptr<ReachingDefinitionsAnalysis>(new SemisparseRda(root));
}
void LLVMReachingDefinitions::initializeDenseRDA() {
builder = new LLVMRDBuilderDense(m, pta, _options);
root = builder->build();
RDA = std::unique_ptr<ReachingDefinitionsAnalysis>(
new ReachingDefinitionsAnalysis(root));
}
RDNode *LLVMReachingDefinitions::getNode(const llvm::Value *val) {
return builder->getNode(val);
}
// let the user get the nodes map, so that we can
// map the points-to informatio back to LLVM nodes
const std::unordered_map<const llvm::Value *, RDNode *>&
LLVMReachingDefinitions::getNodesMap() const {
return builder->getNodesMap();
}
const std::unordered_map<const llvm::Value *, RDNode *>&
LLVMReachingDefinitions::getMapping() const {
return builder->getMapping();
}
RDNode *LLVMReachingDefinitions::getMapping(const llvm::Value *val) {
return builder->getMapping(val);
}
const RDNode *LLVMReachingDefinitions::getMapping(const llvm::Value *val) const {
return builder->getMapping(val);
}
std::set<llvm::Value *>
LLVMReachingDefinitions::getLLVMReachingDefinitions(llvm::Value *where, llvm::Value *what,
const Offset offset, const Offset len) {
std::set<RDNode *> rdDefs;
std::set<llvm::Value *> defs;
auto loc = getMapping(where);
if (!loc) {
llvm::errs() << "[RD] error: no mapping for: " << *where << "\n";
return defs;
}
auto val = getMapping(what);
if (!val) {
llvm::errs() << "[RD] error: no mapping for: " << *what << "\n";
return defs;
}
loc->getReachingDefinitions(val, offset, len, rdDefs);
if (rdDefs.empty()) {
llvm::GlobalVariable *GV = llvm::dyn_cast<llvm::GlobalVariable>(what);
if (!GV || !GV->hasInitializer()) {
static std::set<const llvm::Value *> reported;
if (reported.insert(what).second) {
llvm::errs() << "[RD] error: no reaching definition for: " << *what;
llvm::errs() << " in: " << *where;
llvm::errs() << " off: " << *offset << ", len: " << *len << "\n";
}
} else {
// this is global variable and the last definition
// is the initialization
defs.insert(GV);
}
}
// Get reaching definitions for UNKNOWN_MEMORY, those can be our definitions.
loc->getReachingDefinitions(rd::UNKNOWN_MEMORY, Offset::UNKNOWN,
Offset::UNKNOWN, rdDefs);
//map the values
for (RDNode *nd : rdDefs) {
auto llvmvalue = nd->getUserData<llvm::Value>();
assert(llvmvalue);
defs.insert(llvmvalue);
}
return defs;
}
} // namespace rd
} // namespace dg
} // namespace analysis
<commit_msg>add missing include<commit_after>#include <llvm/IR/GlobalVariable.h>
#include "dg/analysis/ReachingDefinitions/SemisparseRda.h"
#include "dg/llvm/analysis/ReachingDefinitions/ReachingDefinitions.h"
#include "LLVMRDBuilder.h"
#include "LLVMRDBuilderDense.h"
#include "LLVMRDBuilderSemisparse.h"
namespace dg {
namespace analysis {
namespace rd {
LLVMReachingDefinitions::~LLVMReachingDefinitions() {
delete builder;
}
void LLVMReachingDefinitions::initializeSparseRDA() {
builder = new LLVMRDBuilderSemisparse(m, pta, _options);
root = builder->build();
RDA = std::unique_ptr<ReachingDefinitionsAnalysis>(new SemisparseRda(root));
}
void LLVMReachingDefinitions::initializeDenseRDA() {
builder = new LLVMRDBuilderDense(m, pta, _options);
root = builder->build();
RDA = std::unique_ptr<ReachingDefinitionsAnalysis>(
new ReachingDefinitionsAnalysis(root));
}
RDNode *LLVMReachingDefinitions::getNode(const llvm::Value *val) {
return builder->getNode(val);
}
// let the user get the nodes map, so that we can
// map the points-to informatio back to LLVM nodes
const std::unordered_map<const llvm::Value *, RDNode *>&
LLVMReachingDefinitions::getNodesMap() const {
return builder->getNodesMap();
}
const std::unordered_map<const llvm::Value *, RDNode *>&
LLVMReachingDefinitions::getMapping() const {
return builder->getMapping();
}
RDNode *LLVMReachingDefinitions::getMapping(const llvm::Value *val) {
return builder->getMapping(val);
}
const RDNode *LLVMReachingDefinitions::getMapping(const llvm::Value *val) const {
return builder->getMapping(val);
}
std::set<llvm::Value *>
LLVMReachingDefinitions::getLLVMReachingDefinitions(llvm::Value *where, llvm::Value *what,
const Offset offset, const Offset len) {
std::set<RDNode *> rdDefs;
std::set<llvm::Value *> defs;
auto loc = getMapping(where);
if (!loc) {
llvm::errs() << "[RD] error: no mapping for: " << *where << "\n";
return defs;
}
auto val = getMapping(what);
if (!val) {
llvm::errs() << "[RD] error: no mapping for: " << *what << "\n";
return defs;
}
loc->getReachingDefinitions(val, offset, len, rdDefs);
if (rdDefs.empty()) {
llvm::GlobalVariable *GV = llvm::dyn_cast<llvm::GlobalVariable>(what);
if (!GV || !GV->hasInitializer()) {
static std::set<const llvm::Value *> reported;
if (reported.insert(what).second) {
llvm::errs() << "[RD] error: no reaching definition for: " << *what;
llvm::errs() << " in: " << *where;
llvm::errs() << " off: " << *offset << ", len: " << *len << "\n";
}
} else {
// this is global variable and the last definition
// is the initialization
defs.insert(GV);
}
}
// Get reaching definitions for UNKNOWN_MEMORY, those can be our definitions.
loc->getReachingDefinitions(rd::UNKNOWN_MEMORY, Offset::UNKNOWN,
Offset::UNKNOWN, rdDefs);
//map the values
for (RDNode *nd : rdDefs) {
auto llvmvalue = nd->getUserData<llvm::Value>();
assert(llvmvalue);
defs.insert(llvmvalue);
}
return defs;
}
} // namespace rd
} // namespace dg
} // namespace analysis
<|endoftext|> |
<commit_before>#include "videosourcefactory.h"
#include "iobserver.h"
#include "iobservable.h"
#include <thread>
#include <chrono>
#include <iostream>
#include <cstring>
#include <fstream>
#include <vector>
gg::Device device;
gg::ColourSpace colour;
size_t test_duration; // seconds
float frame_rate_to_check;
std::string report_filename("");
using namespace std::chrono;
typedef time_point<system_clock> timestamp;
typedef std::vector< timestamp > timestamps;
//!
//! \brief This gg::IObserver implementor
//! records a timestamp every time it is
//! updated.
//!
//! It can then be used to check the frame
//! rate of the gg::IObservable it was
//! attached to.
//!
class FrameRateTimer : public gg::IObserver
{
protected:
timestamps _timestamps;
public:
void update(gg::VideoFrame & frame) override
{
_timestamps.push_back(system_clock::now());
}
//!
//! \brief Get statistics based on currently
//! available timestamp collection
//! \param max_frame_rate fps
//! \param min_frame_rate fps
//! \param avg_frame_rate fps
//! \param n_timestamps
//! \return \c true if timestamps are available
//! AND meaningful, such that the computations
//! can be carried out, \c false otherwise
//!
bool statistics(float & max_frame_rate,
float & min_frame_rate,
float & avg_frame_rate,
size_t & n_timestamps)
{
if (_timestamps.empty() or _timestamps.size() < 10)
return false;
n_timestamps = _timestamps.size();
// unit: sec
float min_duration = std::numeric_limits<float>::max(),
max_duration = std::numeric_limits<float>::min(),
sum_durations = 0.0;
for (size_t i = 0; i < _timestamps.size() - 1; i++)
{
duration<float> difference = _timestamps[i + 1] - _timestamps[i];
float cur_duration = difference.count();
sum_durations += cur_duration;
if (cur_duration < min_duration)
min_duration = cur_duration;
else if (cur_duration > max_duration)
max_duration = cur_duration;
}
if (min_duration <= 0.0 or max_duration <= 0.0
or sum_durations <= 0.0)
return false;
max_frame_rate = 1.0 / min_duration;
min_frame_rate = 1.0 / max_duration;
avg_frame_rate = (n_timestamps - 1) / sum_durations;
return true;
}
//!
//! \brief Output collected timestamps, as well
//! as computed statistics to CSV file with \c
//! filename
//! \param filename nop if empty
//! \sa statistics()
//! \throw std::ios_base::failure in case the
//! (non-empty) \c filename does not point to a
//! valid file, writeable by user
//!
void report(std::string filename)
{
float max_fr, min_fr, avg_fr;
size_t n_timestamps;
if (not statistics(max_fr, min_fr, avg_fr, n_timestamps))
// nothing to output
return;
std::ofstream outfile;
outfile.open(filename);
if (not outfile.is_open())
throw std::ios_base::failure(
filename.append(" could not be opened"));
std::string delimiter(",\n");
outfile << n_timestamps << delimiter;
outfile << max_fr << delimiter;
outfile << min_fr << delimiter;
outfile << avg_fr << delimiter;
for (timestamp ts: _timestamps)
{
std::time_t t = system_clock::to_time_t(ts);
outfile << std::ctime(&t) << delimiter;
}
outfile.close();
}
};
bool parse_args(int argc, char * argv[])
{
if (argc < 5)
return false;
if (std::strcmp(argv[1], "DVI") == 0)
device = gg::DVI2PCIeDuo_DVI;
else if (std::strcmp(argv[1], "SDI") == 0)
device = gg::DVI2PCIeDuo_SDI;
else
return false;
if (std::strcmp(argv[2], "BGRA") == 0)
colour = gg::BGRA;
else if (std::strcmp(argv[2], "I420") == 0)
colour = gg::I420;
else
return false;
int test_duration_ = std::atoi(argv[3]);
if (test_duration_ <= 0)
return false;
else
test_duration = test_duration_;
double frame_rate_to_check_ = std::atof(argv[4]);
if (frame_rate_to_check_ <= 0.0)
return false;
else
frame_rate_to_check = frame_rate_to_check_;
if (argc >= 6)
report_filename = std::string(argv[5]);
return true;
}
void synopsis(int argc, char * argv[])
{
printf("%s DVI | SDI BGRA | I420 <test_duration>"
" <frame_rate_to_check> [ <report_filename> ]"
"\n",
argv[0]);
}
int main(int argc, char * argv[])
{
if (not parse_args(argc, argv))
{
synopsis(argc, argv);
return EXIT_FAILURE;
}
// gg::VideoSourceFactory & source_fac = gg::VideoSourceFactory::get_instance();
// IVideoSource * epiphan = source_fac.get_device(device, colour);
FrameRateTimer timer;
// epiphan->attach(timer);
// std::this_thread::sleep_for(std::chrono::seconds(duration));
// epiphan->detach(timer);
float max_fr, min_fr, avg_fr;
size_t n_timestamps;
if (not timer.statistics(max_fr, min_fr, avg_fr, n_timestamps))
return EXIT_FAILURE;
timer.report(report_filename);
return ( avg_fr >= frame_rate_to_check and
min_fr >= frame_rate_to_check ) ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>Issue #117: implemented advanced reporting of timestamp information<commit_after>#include "videosourcefactory.h"
#include "iobserver.h"
#include "iobservable.h"
#include <thread>
#include <chrono>
#include <iostream>
#include <cstring>
#include <fstream>
#include <vector>
#include <ctime>
gg::Device device;
gg::ColourSpace colour;
size_t test_duration; // seconds
float frame_rate_to_check;
std::string report_filename("");
using namespace std::chrono;
typedef time_point<system_clock> timestamp;
typedef std::vector< timestamp > timestamps;
//!
//! \brief This gg::IObserver implementor
//! records a timestamp every time it is
//! updated.
//!
//! It can then be used to check the frame
//! rate of the gg::IObservable it was
//! attached to.
//!
class FrameRateTimer : public gg::IObserver
{
protected:
timestamps _timestamps;
public:
void update(gg::VideoFrame & frame) override
{
_timestamps.push_back(system_clock::now());
}
//!
//! \brief Get statistics based on currently
//! available timestamp collection
//! \param max_frame_rate fps
//! \param min_frame_rate fps
//! \param avg_frame_rate fps
//! \param n_timestamps
//! \return \c true if timestamps are available
//! AND meaningful, such that the computations
//! can be carried out, \c false otherwise
//!
bool statistics(float & max_frame_rate,
float & min_frame_rate,
float & avg_frame_rate,
size_t & n_timestamps)
{
if (_timestamps.empty() or _timestamps.size() < 10)
return false;
n_timestamps = _timestamps.size();
// unit: sec
float min_duration = std::numeric_limits<float>::max(),
max_duration = std::numeric_limits<float>::min(),
sum_durations = 0.0;
for (size_t i = 0; i < _timestamps.size() - 1; i++)
{
float cur_duration = duration_ms(_timestamps[i], _timestamps[i + 1]);
sum_durations += cur_duration;
if (cur_duration < min_duration)
min_duration = cur_duration;
else if (cur_duration > max_duration)
max_duration = cur_duration;
}
if (min_duration <= 0.0 or max_duration <= 0.0
or sum_durations <= 0.0)
return false;
max_frame_rate = 1.0 / min_duration;
min_frame_rate = 1.0 / max_duration;
avg_frame_rate = (n_timestamps - 1) / sum_durations;
return true;
}
//!
//! \brief Output timestamp for each \c update()
//! call as well as the time duration between
//! each consecutive call pair, as well as the
//! computed statistics to CSV file with \c
//! filename
//! \param filename nop if empty
//! \sa statistics()
//! \throw std::ios_base::failure in case the
//! (non-empty) \c filename does not point to a
//! valid file, writeable by user
//!
void report(std::string filename)
{
// Open file
std::ofstream outfile;
outfile.open(filename);
if (not outfile.is_open())
throw std::ios_base::failure(
filename.append(" could not be opened"));
// CSV format
std::string delimiter(", ");
// Get statistics
float max_fr, min_fr, avg_fr;
size_t n_timestamps;
if (statistics(max_fr, min_fr, avg_fr, n_timestamps))
{
// Write header
outfile << "Nr. of timestamps" << delimiter
<< "Max. frame rate (fps)" << delimiter
<< "Min. frame rate (fps)" << delimiter
<< "Avg. frame rate (fps)" << std::endl;
// Write data
outfile << n_timestamps << delimiter
<< max_fr << delimiter
<< min_fr << delimiter
<< avg_fr << std::endl;
}
else
outfile << "Statistics could not be computed"
<< std::endl;
// Write timestamps and inter-frame durations
if (n_timestamps > 0)
{
char buffer [80];
typedef duration<int, std::ratio_multiply<hours::period, std::ratio<24> >::type> days;
// Write header
outfile << "Frame timestamp (date-time)" << delimiter
<< "Inter-frame duration (ms)" << std::endl;
// Write data
for (timestamp ts : _timestamps)
{
// Nicely format date-time for human-readability
time_t tt = system_clock::to_time_t(ts);
tm local_tm = *localtime(&tt);
strftime (buffer, 80, "%Y/%m/%d %H:%M:%S", &local_tm);
// Append millisecond resolution to human-readable timestamp
system_clock::duration tp = ts.time_since_epoch();
days d = duration_cast<days>(tp);
tp -= d;
hours h = duration_cast<hours>(tp);
tp -= h;
minutes m = duration_cast<minutes>(tp);
tp -= m;
seconds s = duration_cast<seconds>(tp);
tp -= s;
milliseconds ms = duration_cast<milliseconds>(tp);
tp -= ms;
sprintf(buffer, "%s.%03lu", buffer, ms.count());
// Current inter-frame duration
float cur_duration = duration_ms(_timestamps[0], ts);
// Debugging output
std::cout << d.count() << "d " << h.count() << ':'
<< m.count() << ':' << s.count() << '.' << ms.count();
std::cout << " " << tp.count() << "["
<< system_clock::duration::period::num << '/'
<< system_clock::duration::period::den << "]";
std::cout << " " << cur_duration << "ms [inter-frame]";
std::cout << std::endl;
// Actual output to CSV file
outfile << buffer << delimiter
<< cur_duration << std::endl;
}
}
else
outfile << "No timestamps"
<< std::endl;
// Close file
outfile.close();
}
protected:
//!
//! \brief Get duration between two timestamps in milliseconds
//! \param t0
//! \param t1
//! \return
//!
float duration_ms(const timestamp & t0, const timestamp & t1)
{
duration<float> difference = duration_cast<seconds>(t1 - t0);
return difference.count();
}
};
bool parse_args(int argc, char * argv[])
{
if (argc < 5)
return false;
if (std::strcmp(argv[1], "DVI") == 0)
device = gg::DVI2PCIeDuo_DVI;
else if (std::strcmp(argv[1], "SDI") == 0)
device = gg::DVI2PCIeDuo_SDI;
else
return false;
if (std::strcmp(argv[2], "BGRA") == 0)
colour = gg::BGRA;
else if (std::strcmp(argv[2], "I420") == 0)
colour = gg::I420;
else
return false;
int test_duration_ = std::atoi(argv[3]);
if (test_duration_ <= 0)
return false;
else
test_duration = test_duration_;
double frame_rate_to_check_ = std::atof(argv[4]);
if (frame_rate_to_check_ <= 0.0)
return false;
else
frame_rate_to_check = frame_rate_to_check_;
if (argc >= 6)
report_filename = std::string(argv[5]);
return true;
}
void synopsis(int argc, char * argv[])
{
printf("%s DVI | SDI BGRA | I420 <test_duration>"
" <frame_rate_to_check> [ <report_filename> ]"
"\n",
argv[0]);
}
int main(int argc, char * argv[])
{
if (not parse_args(argc, argv))
{
synopsis(argc, argv);
return EXIT_FAILURE;
}
// gg::VideoSourceFactory & source_fac = gg::VideoSourceFactory::get_instance();
// IVideoSource * epiphan = source_fac.get_device(device, colour);
FrameRateTimer timer;
// epiphan->attach(timer);
// std::this_thread::sleep_for(std::chrono::seconds(duration));
// epiphan->detach(timer);
float max_fr, min_fr, avg_fr;
size_t n_timestamps;
if (not timer.statistics(max_fr, min_fr, avg_fr, n_timestamps))
return EXIT_FAILURE;
timer.report(report_filename);
return ( avg_fr >= frame_rate_to_check and
min_fr >= frame_rate_to_check ) ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/string.h"
#include "common/globals.h"
#include "common/tag.h"
#include "common/compileInfo.h"
#include "common/defaultValues.h"
#include "rest/HttpHeaders.h"
#include "rest/rest.h"
#include "openssl/opensslv.h"
#include "ngsi/ParseData.h"
#include "rest/ConnectionInfo.h"
#include "rapidjson/rapidjson.h"
#include "serviceRoutines/versionTreat.h"
/* ****************************************************************************
*
* version -
*/
static char versionString[30] = { 'a', 'l', 'p', 'h', 'a', 0 };
/* ****************************************************************************
*
* libVersions -
*/
std::string libVersions(void)
{
std::string total = "\"libversions\": {\n";
std::string boost = " \"boost\": ";
std::string curl = " \"libcurl\": ";
std::string mhd = " \"libmicrohttpd\": ";
std::string ssl = " \"openssl\": ";
std::string rjson = " \"rapidjson\": ";
char mhdVersion[64];
char* curlVersion = curl_version();
snprintf(mhdVersion, sizeof(mhdVersion), "0x%08x", MHD_VERSION);
total += boost + "\"" + BOOST_LIB_VERSION "\"" + ",\n";
total += curl + "\"" + curlVersion + "\"" + ",\n";
total += mhd + "\"" + MHD_get_version() + "\"" + ",\n";
total += ssl + "\"" + SHLIB_VERSION_NUMBER "\"" + ",\n";
total += rjson + "\"" + RAPIDJSON_VERSION_STRING "\"" + "\n";
return total;
}
/* ****************************************************************************
*
* versionSet -
*/
void versionSet(const char* version)
{
strncpy(versionString, version, sizeof(versionString));
}
/* ****************************************************************************
*
* versionGet -
*/
char* versionGet()
{
return versionString;
}
/* ****************************************************************************
*
* versionTreat -
*/
std::string versionTreat
(
ConnectionInfo* ciP,
int components,
std::vector<std::string>& compV,
ParseData* parseDataP
)
{
if (isOriginAllowedForCORS(ciP->httpHeaders.origin))
{
ciP->httpHeader.push_back(HTTP_ACCESS_CONTROL_ALLOW_ORIGIN);
// If any origin is allowed, the header is always sent with the value "*"
if (strcmp(corsOrigin, "__ALL") == 0)
{
ciP->httpHeaderValue.push_back("*");
}
// If a specific origin is allowed, the header is only sent if the origins match
else
{
ciP->httpHeaderValue.push_back(corsOrigin);
}
ciP->httpHeader.push_back(HTTP_ACCESS_CONTROL_EXPOSE_HEADERS);
ciP->httpHeaderValue.push_back(CORS_EXPOSED_HEADERS);
}
std::string out = "";
std::string indent = "";
#ifdef UNIT_TEST
std::string uptime = "0 d, 0 h, 0 m, 0 s";
#else
std::string uptime = parsedUptime(getTimer()->getCurrentTime() - startTime);
#endif
out += "{\n";
out += "\"orion\" : {\n";
out += " \"version\" : \"" + std::string(versionString) + "\",\n";
out += " \"uptime\" : \"" + std::string(uptime) + "\",\n";
out += " \"git_hash\" : \"" + std::string(GIT_HASH) + "\",\n";
out += " \"compile_time\" : \"" + std::string(COMPILE_TIME) + "\",\n";
out += " \"compiled_by\" : \"" + std::string(COMPILED_BY) + "\",\n";
out += " \"compiled_in\" : \"" + std::string(COMPILED_IN) + "\",\n";
out += " \"release_date\" : \"" + std::string(RELEASE_DATE) + "\",\n";
out += " \"doc\" : \"" + std::string(API_DOC) + "\"," "\n" + " " + libVersions();
out += " }\n";
out += "}\n";
out += "}\n";
ciP->httpStatusCode = SccOk;
return out;
}
<commit_msg>Update versionTreat.cpp<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/string.h"
#include "common/globals.h"
#include "common/tag.h"
#include "common/compileInfo.h"
#include "common/defaultValues.h"
#include "rest/HttpHeaders.h"
#include "rest/rest.h"
#include "openssl/opensslv.h"
#include "ngsi/ParseData.h"
#include "rest/ConnectionInfo.h"
#include "rapidjson/rapidjson.h"
#include "serviceRoutines/versionTreat.h"
/* ****************************************************************************
*
* version -
*/
static char versionString[30] = { 'a', 'l', 'p', 'h', 'a', 0 };
/* ****************************************************************************
*
* libVersions -
*/
std::string libVersions(void)
{
std::string total = "\"libversions\": {\n";
std::string boost = " \"boost\": ";
std::string curl = " \"libcurl\": ";
std::string mhd = " \"libmicrohttpd\": ";
std::string ssl = " \"openssl\": ";
std::string rjson = " \"rapidjson\": ";
char* curlVersion = curl_version();
total += boost + "\"" + BOOST_LIB_VERSION "\"" + ",\n";
total += curl + "\"" + curlVersion + "\"" + ",\n";
total += mhd + "\"" + MHD_get_version() + "\"" + ",\n";
total += ssl + "\"" + SHLIB_VERSION_NUMBER "\"" + ",\n";
total += rjson + "\"" + RAPIDJSON_VERSION_STRING "\"" + "\n";
return total;
}
/* ****************************************************************************
*
* versionSet -
*/
void versionSet(const char* version)
{
strncpy(versionString, version, sizeof(versionString));
}
/* ****************************************************************************
*
* versionGet -
*/
char* versionGet()
{
return versionString;
}
/* ****************************************************************************
*
* versionTreat -
*/
std::string versionTreat
(
ConnectionInfo* ciP,
int components,
std::vector<std::string>& compV,
ParseData* parseDataP
)
{
if (isOriginAllowedForCORS(ciP->httpHeaders.origin))
{
ciP->httpHeader.push_back(HTTP_ACCESS_CONTROL_ALLOW_ORIGIN);
// If any origin is allowed, the header is always sent with the value "*"
if (strcmp(corsOrigin, "__ALL") == 0)
{
ciP->httpHeaderValue.push_back("*");
}
// If a specific origin is allowed, the header is only sent if the origins match
else
{
ciP->httpHeaderValue.push_back(corsOrigin);
}
ciP->httpHeader.push_back(HTTP_ACCESS_CONTROL_EXPOSE_HEADERS);
ciP->httpHeaderValue.push_back(CORS_EXPOSED_HEADERS);
}
std::string out = "";
std::string indent = "";
#ifdef UNIT_TEST
std::string uptime = "0 d, 0 h, 0 m, 0 s";
#else
std::string uptime = parsedUptime(getTimer()->getCurrentTime() - startTime);
#endif
out += "{\n";
out += "\"orion\" : {\n";
out += " \"version\" : \"" + std::string(versionString) + "\",\n";
out += " \"uptime\" : \"" + std::string(uptime) + "\",\n";
out += " \"git_hash\" : \"" + std::string(GIT_HASH) + "\",\n";
out += " \"compile_time\" : \"" + std::string(COMPILE_TIME) + "\",\n";
out += " \"compiled_by\" : \"" + std::string(COMPILED_BY) + "\",\n";
out += " \"compiled_in\" : \"" + std::string(COMPILED_IN) + "\",\n";
out += " \"release_date\" : \"" + std::string(RELEASE_DATE) + "\",\n";
out += " \"doc\" : \"" + std::string(API_DOC) + "\"," "\n" + " " + libVersions();
out += " }\n";
out += "}\n";
out += "}\n";
ciP->httpStatusCode = SccOk;
return out;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include "bobuniverse.h"
#include <vector>
#include <stdlib.h>
#include <time.h>
#define INITIALDISTANCE 60
#define SETPOINT 30
#define AUTOMATICSTOP 1000
#define GENERATIONS 200
#define INDIVIDUALS 40
#define CROMO 4
#define GENES 4
#define KEEP 6
#define FLOATADJUST 10000000.0
#define PERCENTADJUST (FLOATADJUST/10)
#define MAXVALUE (10*FLOATADJUST)
#define KIADJUST 10.0
#define KDADJUST 10.0
/* Cromo dictionary */
#define BASEVALUE 0
#define KP 1
#define KI 2
#define KD 3
/* cross dictionary */
#define MOTHER 0
#define FATHER 1
#define COUPLE 2
#define DEBUGLEVEL 1
void generateGens(int bobsGens[INDIVIDUALS][CROMO][GENES]);
void getHealth(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS]);
int getPower(int bobsGens[INDIVIDUALS][CROMO][GENES], int individual, int error, int sum, int delta);
void printPopulation(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS], int generation);
void getCromosum(int bobsGens[INDIVIDUALS][CROMO][GENES], int cromosum[CROMO], int individual);
void clearCromosum(int cromosum[CROMO]);
void orderByHealth(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS], int start, int end);
void cross(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS]);
std::vector<Universe> myBob(INDIVIDUALS, Universe(INITIALDISTANCE, SETPOINT));
int main(void)
{
int bobsGens[INDIVIDUALS][CROMO][GENES], health[INDIVIDUALS];
int generation;
srand(time(NULL));
generateGens(bobsGens);
for(generation = 0; generation < GENERATIONS; generation++)
{
getHealth(bobsGens, health);
if(DEBUGLEVEL>1)
printPopulation(bobsGens, health, generation);
orderByHealth(bobsGens, health, 0, (INDIVIDUALS-1));
if(DEBUGLEVEL)
{
if(DEBUGLEVEL > 1)
printf("\n Ordered \n");
printPopulation(bobsGens, health, generation);
}
cross(bobsGens, health);
if(DEBUGLEVEL > 2)
{
printf("\n After crossing \n");
printPopulation(bobsGens, health, generation);
}
}
return 0;
}
void generateGens(int bobsGens[INDIVIDUALS][CROMO][GENES])
{
int x, y, z;
for(x = 0; x < INDIVIDUALS; x++)
{
if(DEBUGLEVEL > 1)
printf("\n INDIVIDUAL %d\n", x);
for(y = 0; y < CROMO; y++)
{
if(DEBUGLEVEL > 1)
printf("\n CROMO %d: ", y);
for(z = 0; z < GENES; z++)
{
bobsGens[x][y][z] = rand()%(int)(MAXVALUE/CROMO);
if(DEBUGLEVEL > 1)
{
if(!y)
printf("%f ", (bobsGens[x][y][z]/FLOATADJUST));
else
printf("%f ", (bobsGens[x][y][z] / PERCENTADJUST));
}
}
}
}
return ;
}
void getHealth(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS])
{
int individual, error, lasterror, power, distance, sum, delta, status, counter = 0;
for(individual = 0; individual < INDIVIDUALS; individual++)
{
counter = sum = delta = lasterror = 0;
status = myBob[individual].getStatus();
while(status == 1 && counter < AUTOMATICSTOP)
{
distance = myBob[individual].getDistance();
error = distance - SETPOINT;
sum = sum + error;
if(error == 0 || (error >= 0 && lasterror <= 0) || (error <= 0 && lasterror >= 0))
{
sum = 0;
}
power = getPower(bobsGens, individual, error, sum, delta);
myBob[individual].move(power);
status = myBob[individual].getStatus();
counter++;
if(DEBUGLEVEL > 3)
printf("distance: %d error: %d sum: %d delta: %d power: %d \n", distance, error, sum, delta, power);
delta = error - lasterror;
lasterror = error;
}
status = myBob[individual].getStatus();
if(status == -1)
{
health[individual] = 1;
if(DEBUGLEVEL < 0)
printf("\n individual :%d crash the wall\n", individual);
}
else
{
if(status == 1)
{
health[individual] = 1;
if(DEBUGLEVEL < 0)
printf("\n individual :%d timeout\n", individual);
}
else
{
health[individual] = AUTOMATICSTOP - counter;
if(DEBUGLEVEL < 0)
printf("\n individual :%d success with health %d", individual, health[individual]);
}
}
myBob[individual].restart(INITIALDISTANCE, SETPOINT);
}
return ;
}
int getPower(int bobsGens[INDIVIDUALS][CROMO][GENES], int individual, int error, int sum, int delta)
{
int cromosum[CROMO] = {0};
int power;
float kp, ki, kd;
getCromosum(bobsGens, cromosum, individual);
kp = (cromosum[BASEVALUE]/FLOATADJUST) * ((cromosum[KP]/PERCENTADJUST) / 100.0);
ki = (cromosum[BASEVALUE]/FLOATADJUST) * ((cromosum[KI]/PERCENTADJUST) / (100.0*KIADJUST));
kd = (cromosum[BASEVALUE]/FLOATADJUST) * ((cromosum[KD]/PERCENTADJUST) / (100.0*KDADJUST));
if(DEBUGLEVEL > 5)
printf("\n\n%f %f %f\n\n", kp, ki, kd);
power = (error*kp) + (sum*ki) + (delta*kp);
return power;
}
void printPopulation(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS], int generation)
{
int individual, genes;
int cromosum[CROMO] = {0};
float kp, ki, kd;
printf("\n-------------- Generation %d --------------\n\n", generation);
for(individual = 0; individual < INDIVIDUALS; individual++)
{
printf(" --- Individual --- %d\n", individual);
getCromosum(bobsGens, cromosum, individual);
kp = (cromosum[BASEVALUE]/FLOATADJUST) * ((cromosum[KP]/PERCENTADJUST) / 100.0);
ki = (cromosum[BASEVALUE]/FLOATADJUST) * ((cromosum[KI]/PERCENTADJUST) / (100.0*KIADJUST));
kd = (cromosum[BASEVALUE]/FLOATADJUST) * ((cromosum[KD]/PERCENTADJUST) / (100.0*KDADJUST));
printf(" KP: %f KI: %f KD: %f Health: %d\n", kp, ki, kd, health[individual]);
clearCromosum(cromosum);
}
return ;
}
void getCromosum(int bobsGens[INDIVIDUALS][CROMO][GENES], int cromosum[CROMO], int individual)
{
int cromo, gene;
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES; gene++)
{
cromosum[cromo] += bobsGens[individual][cromo][gene];
}
}
return ;
}
void clearCromosum(int cromosum[CROMO])
{
int cromo;
for(cromo = 0; cromo < CROMO; cromo++)
cromosum[cromo] = 0;
return ;
}
void orderByHealth(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS], int start, int end)
{
int pivot, cromo, gene, aux, aux2[CROMO][GENES], i, j, half;
i = start;
j = end;
half = (int) ((i + j) / 2);
pivot = health[half];
do{
while (health[i] < pivot)
i = i + 1;
while (health[j] > pivot)
j = j - 1;
if(i <= j){
// Saving in aux
aux = health[i];
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES; gene++)
aux2[cromo][gene] = bobsGens[i][cromo][gene];
}
// Replacing places
health[i] = health[j];
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES; gene++)
bobsGens[i][cromo][gene] = bobsGens[j][cromo][gene];
}
// Updating j with aux
health[j] = aux;
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES; gene++)
bobsGens[j][cromo][gene] = aux2[cromo][gene];
}
i = i + 1;
j = j - 1;
}
}while(j > i);
if(start < j)
orderByHealth(bobsGens, health, start, j);
if(i < end)
orderByHealth(bobsGens, health, i, end);
return ;
}
void cross(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS])
{
int luck, cromo, gene, individual, match[COUPLE], accumulatedHealth[INDIVIDUALS], sons[INDIVIDUALS][CROMO][GENES], x;
accumulatedHealth[0] = health[0];
for(individual = 1; individual < INDIVIDUALS; individual++)
accumulatedHealth[individual] = accumulatedHealth[individual-1] + health[individual];
for(individual = 0; individual < (INDIVIDUALS-KEEP); individual++)
{
luck = rand()%accumulatedHealth[INDIVIDUALS-1];
for(x = INDIVIDUALS; x >= 0; x--) // > probability to came from right
{
if(luck > (accumulatedHealth[x]))
break;
}
match[MOTHER] = x+1;
do
{
luck = rand()%accumulatedHealth[INDIVIDUALS-1];
for(x = INDIVIDUALS; x >= 0; x--) // > probability to came from right
{
if(luck > (accumulatedHealth[x]))
break;
}
match[FATHER] = x+1;
}while(match[MOTHER] == match[FATHER]);
if(DEBUGLEVEL > 2)
printf("CROSS: match found for: %d %d\n", match[MOTHER], match[FATHER]);
// Each couple generates 2 sons, each sons have half genes from mother and half from father for each cromo
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES/2; gene++)
sons[individual][cromo][gene] = bobsGens[match[MOTHER]][cromo][gene];
for(; gene < GENES; gene++)
sons[individual][cromo][gene] = bobsGens[match[FATHER]][cromo][gene];
}
// Second son
individual++;
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES/2; gene++)
sons[individual][cromo][gene] = bobsGens[match[FATHER]][cromo][gene];
for(; gene < GENES; gene++)
sons[individual][cromo][gene] = bobsGens[match[MOTHER]][cromo][gene];
}
}
// Generation Update
for(individual = 0; individual < (INDIVIDUALS-KEEP); individual++)
{
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES; gene++)
bobsGens[individual][cromo][gene] = sons[individual][cromo][gene];
}
}
return ;
}
<commit_msg>Removing BASEVALUE from cromo<commit_after>#include <stdio.h>
#include "bobuniverse.h"
#include <vector>
#include <stdlib.h>
#include <time.h>
#define INITIALDISTANCE 60
#define SETPOINT 30
#define AUTOMATICSTOP 1000
#define GENERATIONS 30
#define INDIVIDUALS 30
#define CROMO 3
#define GENES 4
#define KEEP 4
#define FLOATADJUST 10000000.0
#define PERCENTADJUST (FLOATADJUST/10)
#define MAXVALUE (10*FLOATADJUST)
#define KIADJUST 10.0
#define KDADJUST 10.0
#define KBASE 10.0
/* Cromo dictionary */
#define KP 0
#define KI 1
#define KD 2
/* cross dictionary */
#define MOTHER 0
#define FATHER 1
#define COUPLE 2
#define DEBUGLEVEL 1
void generateGens(int bobsGens[INDIVIDUALS][CROMO][GENES]);
void getHealth(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS]);
int getPower(int bobsGens[INDIVIDUALS][CROMO][GENES], int individual, int error, int sum, int delta);
void printPopulation(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS], int generation);
void getCromosum(int bobsGens[INDIVIDUALS][CROMO][GENES], int cromosum[CROMO], int individual);
void clearCromosum(int cromosum[CROMO]);
void orderByHealth(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS], int start, int end);
void cross(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS]);
std::vector<Universe> myBob(INDIVIDUALS, Universe(INITIALDISTANCE, SETPOINT));
int main(void)
{
int bobsGens[INDIVIDUALS][CROMO][GENES], health[INDIVIDUALS];
int generation;
srand(time(NULL));
generateGens(bobsGens);
for(generation = 0; generation < GENERATIONS; generation++)
{
getHealth(bobsGens, health);
if(DEBUGLEVEL>1)
printPopulation(bobsGens, health, generation);
orderByHealth(bobsGens, health, 0, (INDIVIDUALS-1));
if(DEBUGLEVEL)
{
if(DEBUGLEVEL > 1)
printf("\n Ordered \n");
printPopulation(bobsGens, health, generation);
}
cross(bobsGens, health);
if(DEBUGLEVEL > 2)
{
printf("\n After crossing \n");
printPopulation(bobsGens, health, generation);
}
}
return 0;
}
void generateGens(int bobsGens[INDIVIDUALS][CROMO][GENES])
{
int x, y, z;
for(x = 0; x < INDIVIDUALS; x++)
{
if(DEBUGLEVEL > 1)
printf("\n INDIVIDUAL %d\n", x);
for(y = 0; y < CROMO; y++)
{
if(DEBUGLEVEL > 1)
printf("\n CROMO %d: ", y);
for(z = 0; z < GENES; z++)
{
bobsGens[x][y][z] = rand()%(int)(MAXVALUE/CROMO);
if(DEBUGLEVEL > 1)
{
printf("%f ", (bobsGens[x][y][z] / PERCENTADJUST));
}
}
}
}
return ;
}
void getHealth(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS])
{
int individual, error, lasterror, power, distance, sum, delta, status, counter = 0;
for(individual = 0; individual < INDIVIDUALS; individual++)
{
counter = sum = delta = lasterror = 0;
status = myBob[individual].getStatus();
while(status == 1 && counter < AUTOMATICSTOP)
{
distance = myBob[individual].getDistance();
error = distance - SETPOINT;
sum = sum + error;
if(error == 0 || (error >= 0 && lasterror <= 0) || (error <= 0 && lasterror >= 0))
{
sum = 0;
}
power = getPower(bobsGens, individual, error, sum, delta);
myBob[individual].move(power);
status = myBob[individual].getStatus();
counter++;
if(DEBUGLEVEL > 3)
printf("distance: %d error: %d sum: %d delta: %d power: %d \n", distance, error, sum, delta, power);
delta = error - lasterror;
lasterror = error;
}
status = myBob[individual].getStatus();
if(status == -1)
{
health[individual] = 1;
if(DEBUGLEVEL < 0)
printf("\n individual :%d crash the wall\n", individual);
}
else
{
if(status == 1)
{
health[individual] = 1;
if(DEBUGLEVEL < 0)
printf("\n individual :%d timeout\n", individual);
}
else
{
health[individual] = AUTOMATICSTOP - counter;
if(DEBUGLEVEL < 0)
printf("\n individual :%d success with health %d", individual, health[individual]);
}
}
myBob[individual].restart(INITIALDISTANCE, SETPOINT);
}
return ;
}
int getPower(int bobsGens[INDIVIDUALS][CROMO][GENES], int individual, int error, int sum, int delta)
{
int cromosum[CROMO] = {0};
int power;
float kp, ki, kd;
getCromosum(bobsGens, cromosum, individual);
kp = KBASE * ((cromosum[KP]/PERCENTADJUST) / 100.0);
ki = KBASE * ((cromosum[KI]/PERCENTADJUST) / (100.0*KIADJUST));
kd = KBASE * ((cromosum[KD]/PERCENTADJUST) / (100.0*KDADJUST));
if(DEBUGLEVEL > 5)
printf("\n\n%f %f %f\n\n", kp, ki, kd);
power = (error*kp) + (sum*ki) + (delta*kp);
return power;
}
void printPopulation(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS], int generation)
{
int individual, genes;
int cromosum[CROMO] = {0};
float kp, ki, kd;
printf("\n-------------- Generation %d --------------\n\n", generation);
for(individual = 0; individual < INDIVIDUALS; individual++)
{
printf(" --- Individual --- %d\n", individual);
getCromosum(bobsGens, cromosum, individual);
kp = KBASE * ((cromosum[KP]/PERCENTADJUST) / 100.0);
ki = KBASE * ((cromosum[KI]/PERCENTADJUST) / (100.0*KIADJUST));
kd = KBASE * ((cromosum[KD]/PERCENTADJUST) / (100.0*KDADJUST));
printf(" KP: %f KI: %f KD: %f Health: %d\n", kp, ki, kd, health[individual]);
clearCromosum(cromosum);
}
return ;
}
void getCromosum(int bobsGens[INDIVIDUALS][CROMO][GENES], int cromosum[CROMO], int individual)
{
int cromo, gene;
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES; gene++)
{
cromosum[cromo] += bobsGens[individual][cromo][gene];
}
}
return ;
}
void clearCromosum(int cromosum[CROMO])
{
int cromo;
for(cromo = 0; cromo < CROMO; cromo++)
cromosum[cromo] = 0;
return ;
}
void orderByHealth(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS], int start, int end)
{
int pivot, cromo, gene, aux, aux2[CROMO][GENES], i, j, half;
i = start;
j = end;
half = (int) ((i + j) / 2);
pivot = health[half];
do{
while (health[i] < pivot)
i = i + 1;
while (health[j] > pivot)
j = j - 1;
if(i <= j){
// Saving in aux
aux = health[i];
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES; gene++)
aux2[cromo][gene] = bobsGens[i][cromo][gene];
}
// Replacing places
health[i] = health[j];
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES; gene++)
bobsGens[i][cromo][gene] = bobsGens[j][cromo][gene];
}
// Updating j with aux
health[j] = aux;
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES; gene++)
bobsGens[j][cromo][gene] = aux2[cromo][gene];
}
i = i + 1;
j = j - 1;
}
}while(j > i);
if(start < j)
orderByHealth(bobsGens, health, start, j);
if(i < end)
orderByHealth(bobsGens, health, i, end);
return ;
}
void cross(int bobsGens[INDIVIDUALS][CROMO][GENES], int health[INDIVIDUALS])
{
int luck, cromo, gene, individual, match[COUPLE], accumulatedHealth[INDIVIDUALS], sons[INDIVIDUALS][CROMO][GENES], x;
accumulatedHealth[0] = health[0];
for(individual = 1; individual < INDIVIDUALS; individual++)
accumulatedHealth[individual] = accumulatedHealth[individual-1] + health[individual];
for(individual = 0; individual < (INDIVIDUALS-KEEP); individual++)
{
luck = rand()%accumulatedHealth[INDIVIDUALS-1];
for(x = INDIVIDUALS-1; x >= 0; x--) // > probability to came from right
{
if(luck > (accumulatedHealth[x]))
break;
}
match[MOTHER] = x+1;
do
{
luck = rand()%accumulatedHealth[INDIVIDUALS-1];
for(x = INDIVIDUALS-1; x >= 0; x--) // > probability to came from right
{
if(luck > (accumulatedHealth[x]))
break;
}
match[FATHER] = x+1;
}while(match[MOTHER] == match[FATHER]);
if(DEBUGLEVEL > 2)
printf("CROSS: match found for: %d %d\n", match[MOTHER], match[FATHER]);
// Each couple generates 2 sons, each sons have half genes from mother and half from father for each cromo
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES/2; gene++)
sons[individual][cromo][gene] = bobsGens[match[MOTHER]][cromo][gene];
for(; gene < GENES; gene++)
sons[individual][cromo][gene] = bobsGens[match[FATHER]][cromo][gene];
}
// Second son
individual++;
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES/2; gene++)
sons[individual][cromo][gene] = bobsGens[match[FATHER]][cromo][gene];
for(; gene < GENES; gene++)
sons[individual][cromo][gene] = bobsGens[match[MOTHER]][cromo][gene];
}
}
// Generation Update
for(individual = 0; individual < (INDIVIDUALS-KEEP); individual++)
{
for(cromo = 0; cromo < CROMO; cromo++)
{
for(gene = 0; gene < GENES; gene++)
bobsGens[individual][cromo][gene] = sons[individual][cromo][gene];
}
}
return ;
}
<|endoftext|> |
<commit_before>#ifndef ENTT_REGISTRY_HPP
#define ENTT_REGISTRY_HPP
#include <tuple>
#include <vector>
#include <bitset>
#include <utility>
#include <cstddef>
#include <iterator>
#include <cassert>
#include <type_traits>
#include "sparse_set.hpp"
#include "ident.hpp"
namespace entt {
template<typename, std::size_t...>
class View;
template<typename Pool, std::size_t Ident, std::size_t... Other>
class View<Pool, Ident, Other...> final {
using pool_type = Pool;
using mask_type = std::bitset<std::tuple_size<Pool>::value + 1>;
using underlying_iterator_type = typename std::tuple_element_t<Ident, Pool>::iterator_type;
class ViewIterator;
public:
using iterator_type = ViewIterator;
using entity_type = typename std::tuple_element_t<Ident, Pool>::index_type;
using size_type = typename std::tuple_element_t<Ident, Pool>::size_type;
private:
class ViewIterator {
inline bool valid() const noexcept {
return ((mask[*begin] & bitmask) == bitmask);
}
public:
using value_type = entity_type;
ViewIterator(underlying_iterator_type begin, underlying_iterator_type end, const mask_type &bitmask, const mask_type *mask) noexcept
: begin{begin}, end{end}, bitmask{bitmask}, mask{mask}
{
if(begin != end && !valid()) {
++(*this);
}
}
ViewIterator & operator++() noexcept {
++begin;
while(begin != end && !valid()) { ++begin; }
return *this;
}
ViewIterator operator++(int) noexcept {
ViewIterator orig = *this;
return ++(*this), orig;
}
bool operator==(const ViewIterator &other) const noexcept {
return other.begin == begin;
}
bool operator!=(const ViewIterator &other) const noexcept {
return !(*this == other);
}
value_type operator*() const noexcept {
return *begin;
}
private:
underlying_iterator_type begin;
underlying_iterator_type end;
const mask_type bitmask;
const mask_type *mask;
};
template<std::size_t Idx>
void prefer(size_type &size) noexcept {
auto &&cpool = std::get<Idx>(*pool);
auto sz = cpool.size();
if(sz < size) {
from = cpool.begin();
to = cpool.end();
size = sz;
}
}
public:
explicit View(const pool_type *pool, const mask_type *mask) noexcept
: from{std::get<Ident>(*pool).begin()},
to{std::get<Ident>(*pool).end()},
pool{pool},
mask{mask}
{
using accumulator_type = int[];
size_type size = std::get<Ident>(*pool).size();
bitmask.set(Ident);
accumulator_type types = { 0, (bitmask.set(Other), 0)... };
accumulator_type pref = { 0, (prefer<Other>(size), 0)... };
(void)types, (void)pref;
}
iterator_type begin() const noexcept {
return ViewIterator{from, to, bitmask, mask};
}
iterator_type end() const noexcept {
return ViewIterator{to, to, bitmask, mask};
}
void reset() noexcept {
using accumulator_type = int[];
auto &&cpool = std::get<Ident>(*pool);
from = cpool.begin();
to = cpool.end();
size_type size = cpool.size();
accumulator_type accumulator = { 0, (prefer<Other>(size), 0)... };
(void)accumulator;
}
private:
underlying_iterator_type from;
underlying_iterator_type to;
const pool_type *pool;
const mask_type *mask;
mask_type bitmask;
};
template<typename Pool, std::size_t Ident>
class View<Pool, Ident> final {
using pool_type = std::tuple_element_t<Ident, Pool>;
public:
using iterator_type = typename pool_type::iterator_type;
using entity_type = typename pool_type::index_type;
using size_type = typename pool_type::size_type;
using raw_type = typename pool_type::type;
explicit View(const Pool *pool) noexcept
: pool{&std::get<Ident>(*pool)}
{}
raw_type * raw() noexcept {
return pool->raw();
}
const raw_type * raw() const noexcept {
return pool->raw();
}
const entity_type * data() const noexcept {
return pool->data();
}
size_type size() const noexcept {
return pool->size();
}
iterator_type begin() const noexcept {
return pool->begin();
}
iterator_type end() const noexcept {
return pool->end();
}
private:
const pool_type *pool;
};
template<typename Entity, typename... Component>
class Registry {
using pool_type = std::tuple<SparseSet<Entity, Component>...>;
using mask_type = std::bitset<sizeof...(Component)+1>;
static constexpr auto validity_bit = sizeof...(Component);
public:
using entity_type = Entity;
using size_type = typename std::vector<mask_type>::size_type;
template<typename... Comp>
using view_type = View<pool_type, ident<Component...>.template get<Comp>()...>;
private:
template<typename Comp>
void clone(entity_type to, entity_type from) {
constexpr auto index = ident<Component...>.template get<Comp>();
if(entities[from].test(index)) {
assign<Comp>(to, std::get<index>(pool).get(from));
}
}
template<typename Comp>
void sync(entity_type to, entity_type from) {
constexpr auto index = ident<Component...>.template get<Comp>();
bool src = entities[from].test(index);
bool dst = entities[to].test(index);
if(src && dst) {
copy<Comp>(to, from);
} else if(src) {
clone<Comp>(to, from);
} else if(dst) {
remove<Comp>(to);
}
}
public:
explicit Registry() = default;
~Registry() = default;
Registry(const Registry &) = delete;
Registry(Registry &&) = delete;
Registry & operator=(const Registry &) = delete;
Registry & operator=(Registry &&) = delete;
template<typename Comp>
size_type size() const noexcept {
constexpr auto index = ident<Component...>.template get<Comp>();
return std::get<index>(pool).size();
}
size_type size() const noexcept {
return entities.size() - available.size();
}
template<typename Comp>
size_type capacity() const noexcept {
constexpr auto index = ident<Component...>.template get<Comp>();
return std::get<index>(pool).capacity();
}
size_type capacity() const noexcept {
return entities.size();
}
template<typename Comp>
bool empty() const noexcept {
constexpr auto index = ident<Component...>.template get<Comp>();
return std::get<index>(pool).empty();
}
bool empty() const noexcept {
return entities.empty();
}
bool valid(entity_type entity) const noexcept {
return (entity < entities.size() && entities[entity].test(validity_bit));
}
template<typename... Comp>
entity_type create() noexcept {
using accumulator_type = int[];
auto entity = create();
accumulator_type accumulator = { 0, (assign<Comp>(entity), 0)... };
(void)accumulator;
return entity;
}
entity_type create() noexcept {
entity_type entity;
if(available.empty()) {
entity = entity_type(entities.size());
entities.emplace_back();
} else {
entity = available.back();
available.pop_back();
}
entities[entity].set(validity_bit);
return entity;
}
void destroy(entity_type entity) {
assert(valid(entity));
using accumulator_type = int[];
accumulator_type accumulator = { 0, (reset<Component>(entity), 0)... };
available.push_back(entity);
entities[entity].reset();
(void)accumulator;
}
template<typename Comp, typename... Args>
Comp & assign(entity_type entity, Args... args) {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
entities[entity].set(index);
return std::get<index>(pool).construct(entity, args...);
}
template<typename Comp>
void remove(entity_type entity) {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
entities[entity].reset(index);
std::get<index>(pool).destroy(entity);
}
template<typename... Comp>
bool has(entity_type entity) const noexcept {
assert(valid(entity));
using accumulator_type = bool[];
bool all = true;
auto &mask = entities[entity];
accumulator_type accumulator = { true, (all = all && mask.test(ident<Component...>.template get<Comp>()))... };
(void)accumulator;
return all;
}
template<typename Comp>
const Comp & get(entity_type entity) const noexcept {
constexpr auto index = ident<Component...>.template get<Comp>();
return std::get<index>(pool).get(entity);
}
template<typename Comp>
Comp & get(entity_type entity) noexcept {
constexpr auto index = ident<Component...>.template get<Comp>();
return std::get<index>(pool).get(entity);
}
template<typename Comp, typename... Args>
Comp & replace(entity_type entity, Args... args) {
constexpr auto index = ident<Component...>.template get<Comp>();
return (std::get<index>(pool).get(entity) = Comp{args...});
}
template<typename Comp, typename... Args>
Comp & accomodate(entity_type entity, Args... args) {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
return (entities[entity].test(index)
? this->template replace<Comp>(entity, std::forward<Args>(args)...)
: this->template assign<Comp>(entity, std::forward<Args>(args)...));
}
entity_type clone(entity_type from) {
assert(valid(from));
using accumulator_type = int[];
auto to = create();
accumulator_type accumulator = { 0, (clone<Component>(to, from), 0)... };
(void)accumulator;
return to;
}
template<typename Comp>
Comp & copy(entity_type to, entity_type from) {
constexpr auto index = ident<Component...>.template get<Comp>();
auto &&cpool = std::get<index>(pool);
return (cpool.get(to) = cpool.get(from));
}
void copy(entity_type to, entity_type from) {
using accumulator_type = int[];
accumulator_type accumulator = { 0, (sync<Component>(to, from), 0)... };
(void)accumulator;
}
template<typename Comp>
void swap(entity_type lhs, entity_type rhs) {
std::get<ident<Component...>.template get<Comp>()>(pool).swap(lhs, rhs);
}
template<typename Comp, typename Compare>
void sort(Compare compare) {
std::get<ident<Component...>.template get<Comp>()>(pool).sort(std::move(compare));
}
template<typename To, typename From>
void sort() {
auto &&to = std::get<ident<Component...>.template get<To>()>(pool);
auto &&from = std::get<ident<Component...>.template get<From>()>(pool);
to.respect(from);
}
template<typename Comp>
void reset(entity_type entity) {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
if(entities[entity].test(index)) {
remove<Comp>(entity);
}
}
template<typename Comp>
void reset() {
constexpr auto index = ident<Component...>.template get<Comp>();
for(entity_type entity = 0, last = entity_type(entities.size()); entity < last; ++entity) {
if(entities[entity].test(index)) {
remove<Comp>(entity);
}
}
}
void reset() {
using accumulator_type = int[];
accumulator_type acc = { 0, (std::get<ident<Component...>.template get<Component>()>(pool).reset(), 0)... };
entities.clear();
available.clear();
(void)acc;
}
template<typename... Comp>
std::enable_if_t<(sizeof...(Comp) == 1), view_type<Comp...>>
view() noexcept { return view_type<Comp...>{&pool}; }
template<typename... Comp>
std::enable_if_t<(sizeof...(Comp) > 1), view_type<Comp...>>
view() noexcept { return view_type<Comp...>{&pool, entities.data()}; }
private:
std::vector<mask_type> entities;
std::vector<entity_type> available;
pool_type pool;
};
template<typename... Component>
using DefaultRegistry = Registry<std::uint32_t, Component...>;
}
#endif // ENTT_REGISTRY_HPP
<commit_msg>minor changes<commit_after>#ifndef ENTT_REGISTRY_HPP
#define ENTT_REGISTRY_HPP
#include <tuple>
#include <vector>
#include <bitset>
#include <utility>
#include <cstddef>
#include <iterator>
#include <cassert>
#include <type_traits>
#include "sparse_set.hpp"
#include "ident.hpp"
namespace entt {
template<typename, std::size_t...>
class View;
template<typename Pool, std::size_t Ident, std::size_t... Other>
class View<Pool, Ident, Other...> final {
using pool_type = Pool;
using mask_type = std::bitset<std::tuple_size<Pool>::value + 1>;
using underlying_iterator_type = typename std::tuple_element_t<Ident, Pool>::iterator_type;
class ViewIterator;
public:
using iterator_type = ViewIterator;
using entity_type = typename std::tuple_element_t<Ident, Pool>::index_type;
using size_type = typename std::tuple_element_t<Ident, Pool>::size_type;
private:
class ViewIterator {
inline bool valid() const noexcept {
return ((mask[*begin] & bitmask) == bitmask);
}
public:
using value_type = entity_type;
ViewIterator(underlying_iterator_type begin, underlying_iterator_type end, const mask_type &bitmask, const mask_type *mask) noexcept
: begin{begin}, end{end}, bitmask{bitmask}, mask{mask}
{
if(begin != end && !valid()) {
++(*this);
}
}
ViewIterator & operator++() noexcept {
++begin;
while(begin != end && !valid()) { ++begin; }
return *this;
}
ViewIterator operator++(int) noexcept {
ViewIterator orig = *this;
return ++(*this), orig;
}
bool operator==(const ViewIterator &other) const noexcept {
return other.begin == begin;
}
bool operator!=(const ViewIterator &other) const noexcept {
return !(*this == other);
}
value_type operator*() const noexcept {
return *begin;
}
private:
underlying_iterator_type begin;
underlying_iterator_type end;
const mask_type bitmask;
const mask_type *mask;
};
template<std::size_t Idx>
void prefer(size_type &size) noexcept {
auto &&cpool = std::get<Idx>(*pool);
auto sz = cpool.size();
if(sz < size) {
from = cpool.begin();
to = cpool.end();
size = sz;
}
}
public:
explicit View(const pool_type *pool, const mask_type *mask) noexcept
: from{std::get<Ident>(*pool).begin()},
to{std::get<Ident>(*pool).end()},
pool{pool},
mask{mask}
{
using accumulator_type = int[];
size_type size = std::get<Ident>(*pool).size();
bitmask.set(Ident);
accumulator_type types = { 0, (bitmask.set(Other), 0)... };
accumulator_type pref = { 0, (prefer<Other>(size), 0)... };
(void)types, (void)pref;
}
iterator_type begin() const noexcept {
return ViewIterator{from, to, bitmask, mask};
}
iterator_type end() const noexcept {
return ViewIterator{to, to, bitmask, mask};
}
void reset() noexcept {
using accumulator_type = int[];
auto &&cpool = std::get<Ident>(*pool);
from = cpool.begin();
to = cpool.end();
size_type size = cpool.size();
accumulator_type accumulator = { 0, (prefer<Other>(size), 0)... };
(void)accumulator;
}
private:
underlying_iterator_type from;
underlying_iterator_type to;
const pool_type *pool;
const mask_type *mask;
mask_type bitmask;
};
template<typename Pool, std::size_t Ident>
class View<Pool, Ident> final {
using pool_type = std::tuple_element_t<Ident, Pool>;
public:
using iterator_type = typename pool_type::iterator_type;
using entity_type = typename pool_type::index_type;
using size_type = typename pool_type::size_type;
using raw_type = typename pool_type::type;
explicit View(const Pool *pool) noexcept
: pool{&std::get<Ident>(*pool)}
{}
raw_type * raw() noexcept {
return pool->raw();
}
const raw_type * raw() const noexcept {
return pool->raw();
}
const entity_type * data() const noexcept {
return pool->data();
}
size_type size() const noexcept {
return pool->size();
}
iterator_type begin() const noexcept {
return pool->begin();
}
iterator_type end() const noexcept {
return pool->end();
}
private:
const pool_type *pool;
};
template<typename Entity, typename... Component>
class Registry {
using pool_type = std::tuple<SparseSet<Entity, Component>...>;
using mask_type = std::bitset<sizeof...(Component)+1>;
static constexpr auto validity_bit = sizeof...(Component);
public:
using entity_type = Entity;
using size_type = typename std::vector<mask_type>::size_type;
template<typename... Comp>
using view_type = View<pool_type, ident<Component...>.template get<Comp>()...>;
private:
template<typename Comp>
void clone(entity_type to, entity_type from) {
constexpr auto index = ident<Component...>.template get<Comp>();
if(entities[from].test(index)) {
assign<Comp>(to, std::get<index>(pool).get(from));
}
}
template<typename Comp>
void sync(entity_type to, entity_type from) {
constexpr auto index = ident<Component...>.template get<Comp>();
bool src = entities[from].test(index);
bool dst = entities[to].test(index);
if(src && dst) {
copy<Comp>(to, from);
} else if(src) {
clone<Comp>(to, from);
} else if(dst) {
remove<Comp>(to);
}
}
public:
explicit Registry() = default;
~Registry() = default;
Registry(const Registry &) = delete;
Registry(Registry &&) = delete;
Registry & operator=(const Registry &) = delete;
Registry & operator=(Registry &&) = delete;
template<typename Comp>
size_type size() const noexcept {
constexpr auto index = ident<Component...>.template get<Comp>();
return std::get<index>(pool).size();
}
size_type size() const noexcept {
return entities.size() - available.size();
}
template<typename Comp>
size_type capacity() const noexcept {
constexpr auto index = ident<Component...>.template get<Comp>();
return std::get<index>(pool).capacity();
}
size_type capacity() const noexcept {
return entities.size();
}
template<typename Comp>
bool empty() const noexcept {
constexpr auto index = ident<Component...>.template get<Comp>();
return std::get<index>(pool).empty();
}
bool empty() const noexcept {
return entities.empty();
}
bool valid(entity_type entity) const noexcept {
return (entity < entities.size() && entities[entity].test(validity_bit));
}
template<typename... Comp>
entity_type create() noexcept {
using accumulator_type = int[];
auto entity = create();
accumulator_type accumulator = { 0, (assign<Comp>(entity), 0)... };
(void)accumulator;
return entity;
}
entity_type create() noexcept {
entity_type entity;
if(available.empty()) {
entity = entity_type(entities.size());
entities.emplace_back();
} else {
entity = available.back();
available.pop_back();
}
entities[entity].set(validity_bit);
return entity;
}
void destroy(entity_type entity) {
assert(valid(entity));
using accumulator_type = int[];
accumulator_type accumulator = { 0, (reset<Component>(entity), 0)... };
available.push_back(entity);
entities[entity].reset();
(void)accumulator;
}
template<typename Comp, typename... Args>
Comp & assign(entity_type entity, Args... args) {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
entities[entity].set(index);
return std::get<index>(pool).construct(entity, args...);
}
template<typename Comp>
void remove(entity_type entity) {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
entities[entity].reset(index);
std::get<index>(pool).destroy(entity);
}
template<typename... Comp>
bool has(entity_type entity) const noexcept {
assert(valid(entity));
using accumulator_type = bool[];
bool all = true;
auto &mask = entities[entity];
accumulator_type accumulator = { true, (all = all && mask.test(ident<Component...>.template get<Comp>()))... };
(void)accumulator;
return all;
}
template<typename Comp>
const Comp & get(entity_type entity) const noexcept {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
return std::get<index>(pool).get(entity);
}
template<typename Comp>
Comp & get(entity_type entity) noexcept {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
return std::get<index>(pool).get(entity);
}
template<typename Comp, typename... Args>
Comp & replace(entity_type entity, Args... args) {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
return (std::get<index>(pool).get(entity) = Comp{args...});
}
template<typename Comp, typename... Args>
Comp & accomodate(entity_type entity, Args... args) {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
return (entities[entity].test(index)
? this->template replace<Comp>(entity, std::forward<Args>(args)...)
: this->template assign<Comp>(entity, std::forward<Args>(args)...));
}
entity_type clone(entity_type from) {
assert(valid(from));
using accumulator_type = int[];
auto to = create();
accumulator_type accumulator = { 0, (clone<Component>(to, from), 0)... };
(void)accumulator;
return to;
}
template<typename Comp>
Comp & copy(entity_type to, entity_type from) {
assert(valid(to));
assert(valid(from));
constexpr auto index = ident<Component...>.template get<Comp>();
auto &&cpool = std::get<index>(pool);
return (cpool.get(to) = cpool.get(from));
}
void copy(entity_type to, entity_type from) {
assert(valid(to));
assert(valid(from));
using accumulator_type = int[];
accumulator_type accumulator = { 0, (sync<Component>(to, from), 0)... };
(void)accumulator;
}
template<typename Comp>
void swap(entity_type lhs, entity_type rhs) {
assert(valid(lhs));
assert(valid(rhs));
std::get<ident<Component...>.template get<Comp>()>(pool).swap(lhs, rhs);
}
template<typename Comp, typename Compare>
void sort(Compare compare) {
std::get<ident<Component...>.template get<Comp>()>(pool).sort(std::move(compare));
}
template<typename To, typename From>
void sort() {
auto &&to = std::get<ident<Component...>.template get<To>()>(pool);
auto &&from = std::get<ident<Component...>.template get<From>()>(pool);
to.respect(from);
}
template<typename Comp>
void reset(entity_type entity) {
assert(valid(entity));
constexpr auto index = ident<Component...>.template get<Comp>();
if(entities[entity].test(index)) {
remove<Comp>(entity);
}
}
template<typename Comp>
void reset() {
constexpr auto index = ident<Component...>.template get<Comp>();
for(entity_type entity = 0, last = entity_type(entities.size()); entity < last; ++entity) {
if(entities[entity].test(index)) {
remove<Comp>(entity);
}
}
}
void reset() {
using accumulator_type = int[];
accumulator_type acc = { 0, (std::get<ident<Component...>.template get<Component>()>(pool).reset(), 0)... };
entities.clear();
available.clear();
(void)acc;
}
template<typename... Comp>
std::enable_if_t<(sizeof...(Comp) == 1), view_type<Comp...>>
view() noexcept { return view_type<Comp...>{&pool}; }
template<typename... Comp>
std::enable_if_t<(sizeof...(Comp) > 1), view_type<Comp...>>
view() noexcept { return view_type<Comp...>{&pool, entities.data()}; }
private:
std::vector<mask_type> entities;
std::vector<entity_type> available;
pool_type pool;
};
template<typename... Component>
using DefaultRegistry = Registry<std::uint32_t, Component...>;
}
#endif // ENTT_REGISTRY_HPP
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "Basics/WorkMonitor.h"
#include <velocypack/Builder.h>
#include <velocypack/Value.h>
#include <velocypack/velocypack-aliases.h>
#include "Aql/QueryList.h"
#include "Basics/ConditionLocker.h"
#include "GeneralServer/RestHandler.h"
#include "Logger/Logger.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
#include "VocBase/vocbase.h"
using namespace arangodb;
using namespace arangodb::rest;
// -----------------------------------------------------------------------------
// --SECTION-- WorkMonitor
// -----------------------------------------------------------------------------
void WorkMonitor::run() {
CONDITION_LOCKER(guard, _waiter);
uint32_t const maxSleep = 100 * 1000;
uint32_t const minSleep = 100;
uint32_t s = minSleep;
// clean old entries and create summary if requested
while (!isStopping()) {
try {
bool found = false;
WorkDescription* desc;
// handle freeable work descriptions
while (_freeableWorkDescription.pop(desc)) {
found = true;
if (desc != nullptr) {
deleteWorkDescription(desc, false);
}
}
if (found) {
s = minSleep;
} else if (s < maxSleep) {
s *= 2;
}
// handle cancel requests
{
MUTEX_LOCKER(guard, _cancelLock);
if (!_cancelIds.empty()) {
for (auto thread : _threads) {
cancelWorkDescriptions(thread);
}
_cancelIds.clear();
}
}
// handle work descriptions requests -- hac - handler and callback
std::pair<std::shared_ptr<rest::RestHandler>, std::function<void()>>* hac;
while (_workOverview.pop(hac)) {
VPackBuilder builder;
builder.add(VPackValue(VPackValueType::Object));
builder.add("time", VPackValue(TRI_microtime()));
builder.add("work", VPackValue(VPackValueType::Array));
{
MUTEX_LOCKER(guard, _threadsLock);
for (auto& thread : _threads) {
WorkDescription* desc = thread->workDescription();
if (desc != nullptr) {
builder.add(VPackValue(VPackValueType::Object));
vpackWorkDescription(&builder, desc);
builder.close();
}
}
}
builder.close();
builder.close();
addWorkOverview(hac->first, builder.steal());
hac->second(); // callback
delete hac;
}
} catch (...) {
// must prevent propagation of exceptions from here
}
guard.wait(s);
}
// indicate that we stopped the work monitor, freeWorkDescription
// should directly delete old entries
_stopped.store(true);
// cleanup old entries
WorkDescription* desc;
while (_freeableWorkDescription.pop(desc)) {
if (desc != nullptr) {
deleteWorkDescription(desc, false);
}
}
while (_emptyWorkDescription.pop(desc)) {
if (desc != nullptr) {
delete desc;
}
}
clearAllHandlers();
}
void WorkMonitor::clearAllHandlers() {
std::shared_ptr<rest::RestHandler>* shared;
while (_workOverview.pop(shared)) {
delete shared;
}
_waiter.broadcast();
}
void WorkMonitor::pushHandler(std::shared_ptr<RestHandler> handler) {
WorkDescription* desc = createWorkDescription(WorkType::HANDLER);
TRI_ASSERT(desc->_type == WorkType::HANDLER);
new (&desc->_data._handler._handler) std::shared_ptr<RestHandler>(handler);
new (&desc->_data._handler._canceled) std::atomic<bool>(false);
activateWorkDescription(desc);
RestHandler::CURRENT_HANDLER = handler.get();
}
void WorkMonitor::popHandler() {
WorkDescription* desc = deactivateWorkDescription();
TRI_ASSERT(desc != nullptr);
TRI_ASSERT(desc->_type == WorkType::HANDLER);
TRI_ASSERT(desc->_data._handler._handler != nullptr);
try {
freeWorkDescription(desc);
} catch (...) {
// just to prevent throwing exceptions from here, as this method
// will be called in destructors...
}
// TODO(fc) we might have a stack of handlers
RestHandler::CURRENT_HANDLER = nullptr;
}
bool WorkMonitor::cancelAql(WorkDescription* desc) {
auto type = desc->_type;
if (type != WorkType::AQL_STRING && type != WorkType::AQL_ID) {
return true;
}
TRI_vocbase_t* vocbase = desc->_data._aql._vocbase;
if (vocbase != nullptr) {
uint64_t id = desc->_data._aql._id;
LOG(WARN) << "cancel query " << id << " in " << vocbase;
auto queryList = vocbase->queryList();
auto res = queryList->kill(id);
if (res != TRI_ERROR_NO_ERROR) {
LOG(DEBUG) << "cannot kill query " << id;
}
}
desc->_data._aql._canceled.store(true);
return true;
}
void WorkMonitor::deleteHandler(WorkDescription* desc) {
TRI_ASSERT(desc->_type == WorkType::HANDLER);
desc->_data._handler._handler
.std::shared_ptr<rest::RestHandler>::~shared_ptr<rest::RestHandler>();
desc->_data._handler._canceled.std::atomic<bool>::~atomic<bool>();
}
void WorkMonitor::vpackHandler(VPackBuilder* b, WorkDescription* desc) {
RestHandler* handler = desc->_data._handler._handler.get();
GeneralRequest const* request = handler->request();
b->add("type", VPackValue("http-handler"));
b->add("protocol", VPackValue(request->protocol()));
b->add("method",
VPackValue(HttpRequest::translateMethod(request->requestType())));
b->add("url", VPackValue(request->fullUrl()));
b->add("httpVersion", VPackValue((int)request->protocolVersion()));
b->add("database", VPackValue(request->databaseName()));
b->add("user", VPackValue(request->user()));
b->add("taskId", VPackValue(request->clientTaskId()));
if (handler->_statistics != nullptr) {
b->add("startTime", VPackValue(handler->_statistics->_requestStart));
} else {
LOG_TOPIC(DEBUG, Logger::COMMUNICATION)
<< "WorkMonitor::vpackHandler - missing statistics";
}
auto& info = request->connectionInfo();
b->add("server", VPackValue(VPackValueType::Object));
b->add("address", VPackValue(info.serverAddress));
b->add("port", VPackValue(info.serverPort));
b->close();
b->add("client", VPackValue(VPackValueType::Object));
b->add("address", VPackValue(info.clientAddress));
b->add("port", VPackValue(info.clientPort));
b->close();
b->add("endpoint", VPackValue(VPackValueType::Object));
b->add("address", VPackValue(info.endpoint));
b->add("type", VPackValue(info.portType()));
b->close();
}
void WorkMonitor::addWorkOverview(
std::shared_ptr<RestHandler> handler,
std::shared_ptr<velocypack::Buffer<uint8_t>> buffer) {
auto response = handler->response();
velocypack::Slice slice(buffer->data());
response->setResponseCode(rest::ResponseCode::OK);
response->setPayload(slice, true, VPackOptions::Defaults);
}
// -----------------------------------------------------------------------------
// --SECTION-- HandlerWorkStack
// -----------------------------------------------------------------------------
HandlerWorkStack::HandlerWorkStack(std::shared_ptr<RestHandler> handler)
: _handler(handler) {
WorkMonitor::pushHandler(_handler);
}
HandlerWorkStack::~HandlerWorkStack() { WorkMonitor::popHandler(); }
<commit_msg>try to fix compile warning<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "Basics/WorkMonitor.h"
#include <velocypack/Builder.h>
#include <velocypack/Value.h>
#include <velocypack/velocypack-aliases.h>
#include "Aql/QueryList.h"
#include "Basics/ConditionLocker.h"
#include "GeneralServer/RestHandler.h"
#include "Logger/Logger.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
#include "VocBase/vocbase.h"
using namespace arangodb;
using namespace arangodb::rest;
// -----------------------------------------------------------------------------
// --SECTION-- WorkMonitor
// -----------------------------------------------------------------------------
void WorkMonitor::run() {
CONDITION_LOCKER(guard, _waiter);
uint32_t const maxSleep = 100 * 1000;
uint32_t const minSleep = 100;
uint32_t s = minSleep;
// clean old entries and create summary if requested
while (!isStopping()) {
try {
bool found = false;
WorkDescription* desc;
// handle freeable work descriptions
while (_freeableWorkDescription.pop(desc)) {
found = true;
if (desc != nullptr) {
deleteWorkDescription(desc, false);
}
}
if (found) {
s = minSleep;
} else if (s < maxSleep) {
s *= 2;
}
// handle cancel requests
{
MUTEX_LOCKER(guard, _cancelLock);
if (!_cancelIds.empty()) {
for (auto thread : _threads) {
cancelWorkDescriptions(thread);
}
_cancelIds.clear();
}
}
// handle work descriptions requests -- hac - handler and callback
std::pair<std::shared_ptr<rest::RestHandler>, std::function<void()>>* hac;
while (_workOverview.pop(hac)) {
VPackBuilder builder;
builder.add(VPackValue(VPackValueType::Object));
builder.add("time", VPackValue(TRI_microtime()));
builder.add("work", VPackValue(VPackValueType::Array));
{
MUTEX_LOCKER(guard, _threadsLock);
for (auto& thread : _threads) {
WorkDescription* desc = thread->workDescription();
if (desc != nullptr) {
builder.add(VPackValue(VPackValueType::Object));
vpackWorkDescription(&builder, desc);
builder.close();
}
}
}
builder.close();
builder.close();
addWorkOverview(hac->first, builder.steal());
hac->second(); // callback
delete hac;
}
} catch (...) {
// must prevent propagation of exceptions from here
}
guard.wait(s);
}
// indicate that we stopped the work monitor, freeWorkDescription
// should directly delete old entries
_stopped.store(true);
// cleanup old entries
WorkDescription* desc;
while (_freeableWorkDescription.pop(desc)) {
if (desc != nullptr) {
deleteWorkDescription(desc, false);
}
}
while (_emptyWorkDescription.pop(desc)) {
if (desc != nullptr) {
delete desc;
}
}
clearAllHandlers();
}
void WorkMonitor::clearAllHandlers() {
std::shared_ptr<rest::RestHandler>* shared;
while (_workOverview.pop(shared)) {
delete shared;
}
_waiter.broadcast();
}
void WorkMonitor::pushHandler(std::shared_ptr<RestHandler> handler) {
WorkDescription* desc = createWorkDescription(WorkType::HANDLER);
TRI_ASSERT(desc->_type == WorkType::HANDLER);
new (&desc->_data._handler._handler) std::shared_ptr<RestHandler>(handler);
new (&desc->_data._handler._canceled) std::atomic<bool>(false);
activateWorkDescription(desc);
RestHandler::CURRENT_HANDLER = handler.get();
}
void WorkMonitor::popHandler() {
WorkDescription* desc = deactivateWorkDescription();
TRI_ASSERT(desc != nullptr);
TRI_ASSERT(desc->_type == WorkType::HANDLER);
TRI_ASSERT(desc->_data._handler._handler != nullptr);
try {
freeWorkDescription(desc);
} catch (...) {
// just to prevent throwing exceptions from here, as this method
// will be called in destructors...
}
// TODO(fc) we might have a stack of handlers
RestHandler::CURRENT_HANDLER = nullptr;
}
bool WorkMonitor::cancelAql(WorkDescription* desc) {
auto type = desc->_type;
if (type != WorkType::AQL_STRING && type != WorkType::AQL_ID) {
return true;
}
TRI_vocbase_t* vocbase = desc->_data._aql._vocbase;
if (vocbase != nullptr) {
uint64_t id = desc->_data._aql._id;
LOG(WARN) << "cancel query " << id << " in " << vocbase;
auto queryList = vocbase->queryList();
auto res = queryList->kill(id);
if (res != TRI_ERROR_NO_ERROR) {
LOG(DEBUG) << "cannot kill query " << id;
}
}
desc->_data._aql._canceled.store(true);
return true;
}
void WorkMonitor::deleteHandler(WorkDescription* desc) {
TRI_ASSERT(desc->_type == WorkType::HANDLER);
desc->_data._handler._handler
.std::shared_ptr<rest::RestHandler>::~shared_ptr<rest::RestHandler>();
desc->_data._handler._canceled.std::atomic<bool>::~atomic();
}
void WorkMonitor::vpackHandler(VPackBuilder* b, WorkDescription* desc) {
RestHandler* handler = desc->_data._handler._handler.get();
GeneralRequest const* request = handler->request();
b->add("type", VPackValue("http-handler"));
b->add("protocol", VPackValue(request->protocol()));
b->add("method",
VPackValue(HttpRequest::translateMethod(request->requestType())));
b->add("url", VPackValue(request->fullUrl()));
b->add("httpVersion", VPackValue((int)request->protocolVersion()));
b->add("database", VPackValue(request->databaseName()));
b->add("user", VPackValue(request->user()));
b->add("taskId", VPackValue(request->clientTaskId()));
if (handler->_statistics != nullptr) {
b->add("startTime", VPackValue(handler->_statistics->_requestStart));
} else {
LOG_TOPIC(DEBUG, Logger::COMMUNICATION)
<< "WorkMonitor::vpackHandler - missing statistics";
}
auto& info = request->connectionInfo();
b->add("server", VPackValue(VPackValueType::Object));
b->add("address", VPackValue(info.serverAddress));
b->add("port", VPackValue(info.serverPort));
b->close();
b->add("client", VPackValue(VPackValueType::Object));
b->add("address", VPackValue(info.clientAddress));
b->add("port", VPackValue(info.clientPort));
b->close();
b->add("endpoint", VPackValue(VPackValueType::Object));
b->add("address", VPackValue(info.endpoint));
b->add("type", VPackValue(info.portType()));
b->close();
}
void WorkMonitor::addWorkOverview(
std::shared_ptr<RestHandler> handler,
std::shared_ptr<velocypack::Buffer<uint8_t>> buffer) {
auto response = handler->response();
velocypack::Slice slice(buffer->data());
response->setResponseCode(rest::ResponseCode::OK);
response->setPayload(slice, true, VPackOptions::Defaults);
}
// -----------------------------------------------------------------------------
// --SECTION-- HandlerWorkStack
// -----------------------------------------------------------------------------
HandlerWorkStack::HandlerWorkStack(std::shared_ptr<RestHandler> handler)
: _handler(handler) {
WorkMonitor::pushHandler(_handler);
}
HandlerWorkStack::~HandlerWorkStack() { WorkMonitor::popHandler(); }
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs04.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mrs04.C
/// @brief Run and manage the DDR4 MRS04 loading
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
namespace ddr4
{
///
/// @brief mrs04_data ctor
/// @param[in] a fapi2::TARGET_TYPE_DIMM target
/// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
mrs04_data::mrs04_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ):
iv_max_pd_mode(0),
iv_temp_refresh_range(0),
iv_temp_ref_mode(0),
iv_vref_mon(0),
iv_cs_cmd_latency(0),
iv_ref_abort(0),
iv_rd_pre_train_mode(0),
iv_rd_preamble(0),
iv_wr_preamble(0),
iv_ppr(0)
{
FAPI_TRY( mss::eff_max_powerdown_mode(i_target, iv_max_pd_mode) );
FAPI_TRY( mss::mrw_temp_refresh_range(iv_temp_refresh_range) );
FAPI_TRY( mss::eff_temp_refresh_mode(i_target, iv_temp_ref_mode) );
FAPI_TRY( mss::eff_internal_vref_monitor(i_target, iv_vref_mon) );
FAPI_TRY( mss::eff_cs_cmd_latency(i_target, iv_cs_cmd_latency) );
FAPI_TRY( mss::eff_self_ref_abort(i_target, iv_ref_abort) );
FAPI_TRY( mss::eff_rd_preamble_train(i_target, iv_rd_pre_train_mode) );
FAPI_TRY( mss::eff_rd_preamble(i_target, iv_rd_preamble) );
FAPI_TRY( mss::eff_wr_preamble(i_target, iv_wr_preamble) );
FAPI_TRY( mss::eff_dram_ppr(i_target, iv_ppr) );
FAPI_INF("MR4 attributes: MAX_PD: 0x%x, TEMP_REFRESH_RANGE: 0x%x, TEMP_REF_MODE: 0x%x "
"VREF_MON: 0x%x, CSL: 0x%x, REF_ABORT: 0x%x, RD_PTM: 0x%x, RD_PRE: 0x%x, "
"WR_PRE: 0x%x, PPR: 0x%x",
iv_max_pd_mode, iv_temp_refresh_range, iv_temp_ref_mode, iv_vref_mon,
iv_cs_cmd_latency, iv_ref_abort,
iv_rd_pre_train_mode, iv_rd_preamble, iv_wr_preamble, iv_ppr);
o_rc = fapi2::FAPI2_RC_SUCCESS;
return;
fapi_try_exit:
o_rc = fapi2::current_err;
FAPI_ERR("unable to get attributes for mrs0");
return;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs04
/// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank thes rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs04(const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
// Check to make sure our ctor worked ok
mrs04_data l_data( i_target, fapi2::current_err );
FAPI_TRY( fapi2::current_err, "Unable to construct MRS04 data from attributes");
FAPI_TRY( mrs04(i_target, l_data, io_inst, i_rank) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs04, data object as input
/// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM>
/// @param[in] i_data an mrs04_data object, filled in
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs04(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs04_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
constexpr uint64_t CS_CMD_COUNT = 9;
// 0 3 4 5 6 8
constexpr uint8_t cs_cmd_latency_map[CS_CMD_COUNT] = { 0b000, 0, 0, 0b001, 0b010, 0b011, 0b100, 0, 0b101 };
fapi2::buffer<uint8_t> l_cs_cmd_latency_buffer;
FAPI_ASSERT( (i_data.iv_cs_cmd_latency < CS_CMD_COUNT),
fapi2::MSS_BAD_MR_PARAMETER()
.set_MR_NUMBER(4)
.set_PARAMETER(CS_CMD_LATENCY)
.set_PARAMETER_VALUE(i_data.iv_cs_cmd_latency)
.set_DIMM_IN_ERROR(i_target),
"Bad value for CS to CMD/ADDR Latency: %d (%s)", i_data.iv_cs_cmd_latency, mss::c_str(i_target));
l_cs_cmd_latency_buffer = cs_cmd_latency_map[i_data.iv_cs_cmd_latency];
io_inst.arr0.writeBit<A1>(i_data.iv_max_pd_mode);
io_inst.arr0.writeBit<A2>(i_data.iv_temp_refresh_range);
io_inst.arr0.writeBit<A3>(i_data.iv_temp_ref_mode);
io_inst.arr0.writeBit<A4>(i_data.iv_vref_mon);
mss::swizzle<A6, 3, 7>(l_cs_cmd_latency_buffer, io_inst.arr0);
io_inst.arr0.writeBit<A9>(i_data.iv_ref_abort);
io_inst.arr0.writeBit<A10>(i_data.iv_rd_pre_train_mode);
io_inst.arr0.writeBit<A11>(i_data.iv_rd_preamble);
io_inst.arr0.writeBit<A12>(i_data.iv_wr_preamble);
io_inst.arr0.writeBit<A13>(i_data.iv_ppr);
FAPI_INF("MR4: 0x%016llx", uint64_t(io_inst.arr0));
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Given a CCS instruction which contains address bits with an encoded MRS4,
/// decode and trace the contents
/// @param[in] i_inst the CCS instruction
/// @param[in] i_rank ths rank in question
/// @return void
///
fapi2::ReturnCode mrs04_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank)
{
uint8_t l_max_pd_mode = i_inst.arr0.getBit<A1>();
uint8_t l_temp_refresh_range = i_inst.arr0.getBit<A2>();
uint8_t l_temp_ref_mode = i_inst.arr0.getBit<A3>();
uint8_t l_vref_mon = i_inst.arr0.getBit<A4>();
fapi2::buffer<uint8_t> l_cs_cmd_latency_buffer;
mss::swizzle<5, 3, A8>(i_inst.arr0, l_cs_cmd_latency_buffer);
uint8_t l_ref_abort = i_inst.arr0.getBit<A9>();
uint8_t l_rd_pre_train_mode = i_inst.arr0.getBit<A10>();
uint8_t l_rd_preamble = i_inst.arr0.getBit<A11>();
uint8_t l_wr_preamble = i_inst.arr0.getBit<A12>();
uint8_t l_ppr = i_inst.arr0.getBit<A13>();
FAPI_INF("MR4 rank %d decode: MAX_PD: 0x%x, TEMP_REFRESH_RANGE: 0x%x, TEMP_REF_MODE: 0x%x "
"VREF_MON: 0x%x, CSL: 0x%x, REF_ABORT: 0x%x, RD_PTM: 0x%x, RD_PRE: 0x%x, "
"WR_PRE: 0x%x, PPR: 0x%x", i_rank,
l_max_pd_mode, l_temp_refresh_range, l_temp_ref_mode, l_vref_mon,
uint8_t(l_cs_cmd_latency_buffer), l_ref_abort,
l_rd_pre_train_mode, l_rd_preamble, l_wr_preamble, l_ppr);
return FAPI2_RC_SUCCESS;
}
fapi2::ReturnCode (*mrs04_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs04_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank) = &mrs04;
fapi2::ReturnCode (*mrs04_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank) = &mrs04_decode;
} // ns ddr4
} // ns mss
<commit_msg>Fixed eff_config attr generation<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs04.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mrs04.C
/// @brief Run and manage the DDR4 MRS04 loading
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
namespace ddr4
{
///
/// @brief mrs04_data ctor
/// @param[in] a fapi2::TARGET_TYPE_DIMM target
/// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
mrs04_data::mrs04_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ):
iv_max_pd_mode(0),
iv_temp_refresh_range(0),
iv_temp_ref_mode(0),
iv_vref_mon(0),
iv_cs_cmd_latency(0),
iv_ref_abort(0),
iv_rd_pre_train_mode(fapi2::ENUM_ATTR_EFF_RD_PREAMBLE_TRAIN_DISABLE),
iv_rd_preamble(0),
iv_wr_preamble(0),
iv_ppr(0)
{
FAPI_TRY( mss::eff_max_powerdown_mode(i_target, iv_max_pd_mode) );
FAPI_TRY( mss::mrw_temp_refresh_range(iv_temp_refresh_range) );
FAPI_TRY( mss::eff_temp_refresh_mode(i_target, iv_temp_ref_mode) );
FAPI_TRY( mss::eff_internal_vref_monitor(i_target, iv_vref_mon) );
FAPI_TRY( mss::eff_cs_cmd_latency(i_target, iv_cs_cmd_latency) );
FAPI_TRY( mss::eff_self_ref_abort(i_target, iv_ref_abort) );
FAPI_TRY( mss::eff_rd_preamble_train(i_target, iv_rd_pre_train_mode) );
FAPI_TRY( mss::eff_rd_preamble(i_target, iv_rd_preamble) );
FAPI_TRY( mss::eff_wr_preamble(i_target, iv_wr_preamble) );
FAPI_TRY( mss::eff_dram_ppr(i_target, iv_ppr) );
FAPI_INF("MR4 attributes: MAX_PD: 0x%x, TEMP_REFRESH_RANGE: 0x%x, TEMP_REF_MODE: 0x%x "
"VREF_MON: 0x%x, CSL: 0x%x, REF_ABORT: 0x%x, RD_PTM: 0x%x, RD_PRE: 0x%x, "
"WR_PRE: 0x%x, PPR: 0x%x",
iv_max_pd_mode, iv_temp_refresh_range, iv_temp_ref_mode, iv_vref_mon,
iv_cs_cmd_latency, iv_ref_abort,
iv_rd_pre_train_mode, iv_rd_preamble, iv_wr_preamble, iv_ppr);
o_rc = fapi2::FAPI2_RC_SUCCESS;
return;
fapi_try_exit:
o_rc = fapi2::current_err;
FAPI_ERR("unable to get attributes for mrs0");
return;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs04
/// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank thes rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs04(const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
// Check to make sure our ctor worked ok
mrs04_data l_data( i_target, fapi2::current_err );
FAPI_TRY( fapi2::current_err, "Unable to construct MRS04 data from attributes");
FAPI_TRY( mrs04(i_target, l_data, io_inst, i_rank) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs04, data object as input
/// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM>
/// @param[in] i_data an mrs04_data object, filled in
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs04(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs04_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
constexpr uint64_t CS_CMD_COUNT = 9;
// 0 3 4 5 6 8
constexpr uint8_t cs_cmd_latency_map[CS_CMD_COUNT] = { 0b000, 0, 0, 0b001, 0b010, 0b011, 0b100, 0, 0b101 };
fapi2::buffer<uint8_t> l_cs_cmd_latency_buffer;
FAPI_ASSERT( (i_data.iv_cs_cmd_latency < CS_CMD_COUNT),
fapi2::MSS_BAD_MR_PARAMETER()
.set_MR_NUMBER(4)
.set_PARAMETER(CS_CMD_LATENCY)
.set_PARAMETER_VALUE(i_data.iv_cs_cmd_latency)
.set_DIMM_IN_ERROR(i_target),
"Bad value for CS to CMD/ADDR Latency: %d (%s)", i_data.iv_cs_cmd_latency, mss::c_str(i_target));
l_cs_cmd_latency_buffer = cs_cmd_latency_map[i_data.iv_cs_cmd_latency];
io_inst.arr0.writeBit<A1>(i_data.iv_max_pd_mode);
io_inst.arr0.writeBit<A2>(i_data.iv_temp_refresh_range);
io_inst.arr0.writeBit<A3>(i_data.iv_temp_ref_mode);
io_inst.arr0.writeBit<A4>(i_data.iv_vref_mon);
mss::swizzle<A6, 3, 7>(l_cs_cmd_latency_buffer, io_inst.arr0);
io_inst.arr0.writeBit<A9>(i_data.iv_ref_abort);
io_inst.arr0.writeBit<A10>(i_data.iv_rd_pre_train_mode);
io_inst.arr0.writeBit<A11>(i_data.iv_rd_preamble);
io_inst.arr0.writeBit<A12>(i_data.iv_wr_preamble);
io_inst.arr0.writeBit<A13>(i_data.iv_ppr);
FAPI_INF("MR4: 0x%016llx", uint64_t(io_inst.arr0));
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Given a CCS instruction which contains address bits with an encoded MRS4,
/// decode and trace the contents
/// @param[in] i_inst the CCS instruction
/// @param[in] i_rank ths rank in question
/// @return void
///
fapi2::ReturnCode mrs04_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank)
{
uint8_t l_max_pd_mode = i_inst.arr0.getBit<A1>();
uint8_t l_temp_refresh_range = i_inst.arr0.getBit<A2>();
uint8_t l_temp_ref_mode = i_inst.arr0.getBit<A3>();
uint8_t l_vref_mon = i_inst.arr0.getBit<A4>();
fapi2::buffer<uint8_t> l_cs_cmd_latency_buffer;
mss::swizzle<5, 3, A8>(i_inst.arr0, l_cs_cmd_latency_buffer);
uint8_t l_ref_abort = i_inst.arr0.getBit<A9>();
uint8_t l_rd_pre_train_mode = i_inst.arr0.getBit<A10>();
uint8_t l_rd_preamble = i_inst.arr0.getBit<A11>();
uint8_t l_wr_preamble = i_inst.arr0.getBit<A12>();
uint8_t l_ppr = i_inst.arr0.getBit<A13>();
FAPI_INF("MR4 rank %d decode: MAX_PD: 0x%x, TEMP_REFRESH_RANGE: 0x%x, TEMP_REF_MODE: 0x%x "
"VREF_MON: 0x%x, CSL: 0x%x, REF_ABORT: 0x%x, RD_PTM: 0x%x, RD_PRE: 0x%x, "
"WR_PRE: 0x%x, PPR: 0x%x", i_rank,
l_max_pd_mode, l_temp_refresh_range, l_temp_ref_mode, l_vref_mon,
uint8_t(l_cs_cmd_latency_buffer), l_ref_abort,
l_rd_pre_train_mode, l_rd_preamble, l_wr_preamble, l_ppr);
return FAPI2_RC_SUCCESS;
}
fapi2::ReturnCode (*mrs04_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs04_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank) = &mrs04;
fapi2::ReturnCode (*mrs04_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank) = &mrs04_decode;
} // ns ddr4
} // ns mss
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_occ.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __PM_RECOVERY_FFDC_OCC_
#define __PM_RECOVERY_FFDC_OCC_
///
/// @file p9_pm_recovery_ffdc_occ.H
/// @brief Models OCC platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner: Amit Tendolkar <amit.tendolkar@in.ibm.com>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <fapi2.H>
#include <stdint.h>
#include <p9_pm_recovery_ffdc_base.H>
namespace p9_stop_recov_ffdc
{
class PlatOcc : public PlatPmComplex
{
public:
/// @brief constructor
PlatOcc ( const fapi2::Target <fapi2::TARGET_TYPE_PROC_CHIP>
i_procChipTgt );
/// @brief destructor
virtual ~PlatOcc() { };
/// @brief Initializes the OCC FFDC Sub-Sections in HOMER with default header
/// @param[in] i_pHomerBuf points to base of P9 HOMER.
/// @return fapi2 return code
fapi2::ReturnCode init ( void* i_pHomerBuf );
/// @brief collects FFDC of the OCC 405, GPE0 and GPE1.
/// @param[in] i_pHomerBuf points to base of P9 HOMER.
/// @param[in] i_ffdcType indicates the content type to collect
/// @return fapi2 return code.
fapi2::ReturnCode collectFfdc ( void* i_pHomerBuf,
uint8_t i_ffdcType = ALL );
private:
/// @brief collects trace info from a known region OCC SRAM
/// @param[in] i_pHomerBuf location in HOMER to write at
/// @param[in] i_occSramRegion See OccFfdcValidStatus,
/// Indicates OCC SRAM Region to read
/// @return fapi2 return code.
fapi2::ReturnCode collectTrace( uint8_t* i_pHomerBuf,
uint8_t i_occSramRegion );
/// @brief reads OCC SRAM to find out the region extent and
/// then collects info from that region
/// @param[in] i_pHomerBuf location in HOMER to write at
/// @param[in] i_occSramRegion See OccFfdcValidStatus.
/// Indicates OCC SRAM Region to read
/// @return fapi2 return code.
fapi2::ReturnCode readSramRegion ( uint8_t* i_pHomerBuf,
uint8_t i_occSramRegion );
/// @brief updates the OCC FFDC Header
/// @param[in] i_pHomerBuf points to a location in HOMER meant for
/// OCC FFDC Header
///@param[in] i_ffdcValid Indicates what fields in OCC FFDC are
/// valid. See OccFfdcValidStatus
///@return fapi2 return code.
fapi2::ReturnCode updateOccFfdcHeader ( uint8_t* i_pHomerBuf,
uint16_t i_ffdcValid );
/// @brief collects register info for a given OCC
/// @param[in] i_pHomerBuf points to location of HOMER meant for OCC internal register.
///@return fapi2 return code.
fapi2::ReturnCode collectOccReg( uint8_t * i_pHomerBuf);
};
extern "C"
{
typedef fapi2::ReturnCode( *p9_pm_recovery_ffdc_occ_FP_t )
( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_procChipTgt,
void* i_occFfdcBuf );
}
} //namespace p9_stop_recov_ffdc ends
#endif //__PM_RECOVERY_FFDC_OCC_
<commit_msg>PM: Generation of summarized version of STOP Recovery FFDC.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_occ.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __PM_RECOVERY_FFDC_OCC_
#define __PM_RECOVERY_FFDC_OCC_
///
/// @file p9_pm_recovery_ffdc_occ.H
/// @brief Models OCC platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner: Amit Tendolkar <amit.tendolkar@in.ibm.com>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <fapi2.H>
#include <stdint.h>
#include <p9_pm_recovery_ffdc_base.H>
namespace p9_stop_recov_ffdc
{
class PlatOcc : public PlatPmComplex
{
public:
/// @brief constructor
PlatOcc ( const fapi2::Target <fapi2::TARGET_TYPE_PROC_CHIP>
i_procChipTgt );
/// @brief destructor
virtual ~PlatOcc() { };
/// @brief Initializes the OCC FFDC Sub-Sections in HOMER with default header
/// @param[in] i_pHomerBuf points to base of P9 HOMER.
/// @return fapi2 return code
fapi2::ReturnCode init ( void* i_pHomerBuf );
/// @brief collects FFDC of the OCC 405, GPE0 and GPE1.
/// @param[in] i_pHomerBuf points to base of P9 HOMER.
/// @param[in] i_ffdcType indicates the content type to collect
/// @return fapi2 return code.
fapi2::ReturnCode collectFfdc ( void* i_pHomerBuf,
uint8_t i_ffdcType = ALL );
/// @brief generates summary of FFDC pertaining to a given platform.
/// @param[in] i_pHomer points to Homer base.
/// @return fapi2 return code
fapi2::ReturnCode generateSummary( void * i_pHomer );
private:
/// @brief collects trace info from a known region OCC SRAM
/// @param[in] i_pHomerBuf location in HOMER to write at
/// @param[in] i_occSramRegion See OccFfdcValidStatus,
/// Indicates OCC SRAM Region to read
/// @return fapi2 return code.
fapi2::ReturnCode collectTrace( uint8_t* i_pHomerBuf,
uint8_t i_occSramRegion );
/// @brief reads OCC SRAM to find out the region extent and
/// then collects info from that region
/// @param[in] i_pHomerBuf location in HOMER to write at
/// @param[in] i_occSramRegion See OccFfdcValidStatus.
/// Indicates OCC SRAM Region to read
/// @return fapi2 return code.
fapi2::ReturnCode readSramRegion ( uint8_t* i_pHomerBuf,
uint8_t i_occSramRegion );
/// @brief updates the OCC FFDC Header
/// @param[in] i_pHomerBuf points to a location in HOMER meant for
/// OCC FFDC Header
///@param[in] i_ffdcValid Indicates what fields in OCC FFDC are
/// valid. See OccFfdcValidStatus
///@return fapi2 return code.
fapi2::ReturnCode updateOccFfdcHeader ( uint8_t* i_pHomerBuf,
uint16_t i_ffdcValid );
/// @brief collects register info for a given OCC
/// @param[in] i_pHomerBuf points to location of HOMER meant for OCC internal register.
///@return fapi2 return code.
fapi2::ReturnCode collectOccReg( uint8_t * i_pHomerBuf);
///@brief initializes a list of register for generation of FFDC summary.
void initRegList();
private:
std::vector<uint32_t> iv_occSummaryReg;
};
//---------------------------------------------------------------------------------------------
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode( *p9_pm_recovery_ffdc_occ_FP_t )
( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_procChipTgt,
void* i_occFfdcBuf );
extern "C"
{
// -----------------------------------------------------------------------------
// Function prototypes
// -----------------------------------------------------------------------------
///
/// @brief Populates the OCC FFDC section with FFDC collected from OCC GPE0 and GPE1.
///
/// @param[in] i_procChipTarget Proc Chip target
/// @param[in] i_pHomerImage Pointer to the base of the chip HOMER region
///
/// @return FAPI2_RC_SUCCESS on success or error return code
///
fapi2::ReturnCode p9_pm_recovery_ffdc_occ
( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_procChipTarget,
void* i_pHomerImage );
}
} //namespace p9_stop_recov_ffdc ends
#endif //__PM_RECOVERY_FFDC_OCC_
<|endoftext|> |
<commit_before>/*
* copyright: (c) RDO-Team, 2011
* filename : array.cpp
* author :
* date : 02.05.11
* bref :
* indent : 4T
*/
// ====================================================================== PCH
#include "rdo_lib/rdo_runtime/pch.h"
// ====================================================================== INCLUDES
// ====================================================================== SYNOPSIS
#include "rdo_lib/rdo_runtime/calc/array.h"
// ===============================================================================
OPEN_RDO_RUNTIME_NAMESPACE
// ----------------------------------------------------------------------------
// ---------- RDOCalcArraySize
// ----------------------------------------------------------------------------
RDOCalcArraySize::RDOCalcArraySize(CREF(LPRDOCalc) pArray)
: m_pArray(pArray)
{}
REF(RDOValue) RDOCalcArraySize::doCalc(PTR(RDORuntime) pRuntime)
{
RDOValue m_value = m_pArray->calcValue(pRuntime);
RDOArrayValue arrayValue = m_value.getArray();
rsint aSize = arrayValue.arraySize();
m_value = RDOValue(aSize);
return m_value;
}
// ----------------------------------------------------------------------------
// ---------- RDOCalcArrayItem
// ----------------------------------------------------------------------------
RDOCalcArrayItem::RDOCalcArrayItem(CREF(LPRDOCalc) pArray, CREF(LPRDOCalc) pArrayInd)
: m_pArray (pArray ),
m_pArrayInd(pArrayInd)
{}
REF(RDOValue) RDOCalcArrayItem::doCalc(PTR(RDORuntime) pRuntime)
{
RDOValue m_value = m_pArray->calcValue(pRuntime);
RDOArrayValue arrayValue = m_value.getArray();
RDOValue arrayInd = m_pArrayInd->calcValue(pRuntime);
m_value = arrayValue[arrayInd];
return m_value;
}
CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - исправлено возващение локальной переменной - ручная оптимизация скорости<commit_after>/*
* copyright: (c) RDO-Team, 2011
* filename : array.cpp
* author :
* date : 02.05.11
* bref :
* indent : 4T
*/
// ====================================================================== PCH
#include "rdo_lib/rdo_runtime/pch.h"
// ====================================================================== INCLUDES
// ====================================================================== SYNOPSIS
#include "rdo_lib/rdo_runtime/calc/array.h"
// ===============================================================================
OPEN_RDO_RUNTIME_NAMESPACE
// ----------------------------------------------------------------------------
// ---------- RDOCalcArraySize
// ----------------------------------------------------------------------------
RDOCalcArraySize::RDOCalcArraySize(CREF(LPRDOCalc) pArray)
: m_pArray(pArray)
{}
REF(RDOValue) RDOCalcArraySize::doCalc(PTR(RDORuntime) pRuntime)
{
m_value = m_pArray->calcValue(pRuntime);
RDOArrayValue arrayValue = m_value.getArray();
rsint aSize = arrayValue.arraySize();
m_value = RDOValue(aSize);
return m_value;
}
// ----------------------------------------------------------------------------
// ---------- RDOCalcArrayItem
// ----------------------------------------------------------------------------
RDOCalcArrayItem::RDOCalcArrayItem(CREF(LPRDOCalc) pArray, CREF(LPRDOCalc) pArrayInd)
: m_pArray (pArray )
, m_pArrayInd(pArrayInd)
{}
REF(RDOValue) RDOCalcArrayItem::doCalc(PTR(RDORuntime) pRuntime)
{
CREF(RDOArrayValue) arrayValue = m_pArray->calcValue(pRuntime).getArray();
m_value = arrayValue[m_pArrayInd->calcValue(pRuntime)];
return m_value;
}
CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|> |
<commit_before>/*
* A auto-growing buffer you can write to.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "growing_buffer.hxx"
#include "pool.hxx"
#include "util/ConstBuffer.hxx"
#include "util/WritableBuffer.hxx"
#include <assert.h>
#include <string.h>
GrowingBuffer::Buffer *
GrowingBuffer::Buffer::New(struct pool &pool, size_t size)
{
Buffer *buffer;
void *p = p_malloc(&pool, sizeof(*buffer) - sizeof(buffer->data) + size);
return new(p) Buffer();
}
GrowingBuffer::GrowingBuffer(struct pool &_pool, size_t _initial_size)
:pool(_pool),
#ifndef NDEBUG
initial_size(_initial_size),
#endif
size(_initial_size)
{
}
GrowingBuffer *gcc_malloc
growing_buffer_new(struct pool *pool, size_t initial_size)
{
return NewFromPool<GrowingBuffer>(*pool, *pool, initial_size);
}
void
GrowingBuffer::AppendBuffer(Buffer &buffer)
{
assert(buffer.next == nullptr);
if (tail != nullptr) {
tail->next = &buffer;
tail = &buffer;
} else {
head = tail = &buffer;
}
}
void *
GrowingBuffer::Write(size_t length)
{
void *ret;
assert(size > 0);
auto *buffer = tail;
if (buffer == nullptr || buffer->length + length > size) {
if (size < length)
size = length; /* XXX round up? */
buffer = Buffer::New(pool, size);
AppendBuffer(*buffer);
}
assert(buffer->length + length <= size);
ret = buffer->data + buffer->length;
buffer->length += length;
return ret;
}
void
GrowingBuffer::Write(const void *p, size_t length)
{
memcpy(Write(length), p, length);
}
void
GrowingBuffer::Write(const char *p)
{
Write(p, strlen(p));
}
void
GrowingBuffer::AppendMoveFrom(GrowingBuffer &&src)
{
tail->next = src.head;
tail = src.tail;
size = src.size;
}
size_t
GrowingBuffer::GetSize() const
{
size_t result = 0;
for (const auto *buffer = head;
buffer != nullptr; buffer = buffer->next)
result += buffer->length;
return result;
}
GrowingBufferReader::GrowingBufferReader(const GrowingBuffer &gb)
#ifndef NDEBUG
:growing_buffer(&gb)
#endif
{
assert(gb.head == nullptr ||
gb.head->length > 0 || gb.head->next == nullptr ||
(gb.head->next != nullptr &&
gb.size > gb.initial_size &&
gb.head->next->length > gb.initial_size));
buffer = gb.head;
assert(buffer == nullptr || buffer->length > 0);
position = 0;
}
void
GrowingBufferReader::Update(const GrowingBuffer &gb)
{
assert(position == 0 || position <= buffer->length);
if (buffer == nullptr)
buffer = gb.head;
else if (position == buffer->length &&
buffer->next != nullptr) {
/* the reader was at the end of all buffers, but then a new
buffer was appended */
buffer = buffer->next;
position = 0;
}
}
bool
GrowingBufferReader::IsEOF() const
{
assert(buffer == nullptr || position <= buffer->length);
return buffer == nullptr || position == buffer->length;
}
size_t
GrowingBufferReader::Available() const
{
if (buffer == nullptr)
return 0;
assert(position <= buffer->length);
size_t available = buffer->length - position;
for (const auto *b = buffer->next; b != nullptr; b = b->next) {
assert(b->length > 0);
available += b->length;
}
return available;
}
ConstBuffer<void>
GrowingBufferReader::Read() const
{
if (buffer == nullptr)
return nullptr;
assert(buffer != nullptr);
const auto *b = buffer;
if (position >= b->length) {
assert(position == b->length);
assert(buffer->next == nullptr);
return nullptr;
}
return { b->data + position, b->length - position };
}
void
GrowingBufferReader::Consume(size_t length)
{
assert(buffer != nullptr);
if (length == 0)
return;
position += length;
assert(position <= buffer->length);
if (position >= buffer->length) {
if (buffer->next == nullptr)
return;
buffer = buffer->next;
position = 0;
}
}
ConstBuffer<void>
GrowingBufferReader::PeekNext() const
{
const auto *b = buffer;
if (b == nullptr)
return nullptr;
assert(b->length > 0);
b = b->next;
if (b == nullptr)
return nullptr;
assert(b->length > 0);
return { b->data, b->length };
}
void
GrowingBufferReader::Skip(size_t length)
{
while (length > 0) {
assert(buffer != nullptr);
size_t remaining = buffer->length - position;
if (length < remaining ||
(length == remaining && buffer->next == nullptr)) {
position += length;
return;
}
length -= remaining;
if (buffer->next == nullptr) {
assert(position + remaining == length);
position = length;
return;
}
assert(buffer->next != nullptr);
buffer = buffer->next;
position = 0;
}
}
void
GrowingBuffer::CopyTo(void *dest) const
{
for (const auto *buffer = head; buffer != nullptr;
buffer = buffer->next)
dest = mempcpy(dest, buffer->data, buffer->length);
}
WritableBuffer<void>
GrowingBuffer::Dup(struct pool &_pool) const
{
size_t length = GetSize();
if (length == 0)
return nullptr;
void *dest = p_malloc(&_pool, length);
CopyTo(dest);
return { dest, length };
}
<commit_msg>growing_buffer: remove obsolete assert() condition<commit_after>/*
* A auto-growing buffer you can write to.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "growing_buffer.hxx"
#include "pool.hxx"
#include "util/ConstBuffer.hxx"
#include "util/WritableBuffer.hxx"
#include <assert.h>
#include <string.h>
GrowingBuffer::Buffer *
GrowingBuffer::Buffer::New(struct pool &pool, size_t size)
{
Buffer *buffer;
void *p = p_malloc(&pool, sizeof(*buffer) - sizeof(buffer->data) + size);
return new(p) Buffer();
}
GrowingBuffer::GrowingBuffer(struct pool &_pool, size_t _initial_size)
:pool(_pool),
#ifndef NDEBUG
initial_size(_initial_size),
#endif
size(_initial_size)
{
}
GrowingBuffer *gcc_malloc
growing_buffer_new(struct pool *pool, size_t initial_size)
{
return NewFromPool<GrowingBuffer>(*pool, *pool, initial_size);
}
void
GrowingBuffer::AppendBuffer(Buffer &buffer)
{
assert(buffer.next == nullptr);
if (tail != nullptr) {
tail->next = &buffer;
tail = &buffer;
} else {
head = tail = &buffer;
}
}
void *
GrowingBuffer::Write(size_t length)
{
void *ret;
assert(size > 0);
auto *buffer = tail;
if (buffer == nullptr || buffer->length + length > size) {
if (size < length)
size = length; /* XXX round up? */
buffer = Buffer::New(pool, size);
AppendBuffer(*buffer);
}
assert(buffer->length + length <= size);
ret = buffer->data + buffer->length;
buffer->length += length;
return ret;
}
void
GrowingBuffer::Write(const void *p, size_t length)
{
memcpy(Write(length), p, length);
}
void
GrowingBuffer::Write(const char *p)
{
Write(p, strlen(p));
}
void
GrowingBuffer::AppendMoveFrom(GrowingBuffer &&src)
{
tail->next = src.head;
tail = src.tail;
size = src.size;
}
size_t
GrowingBuffer::GetSize() const
{
size_t result = 0;
for (const auto *buffer = head;
buffer != nullptr; buffer = buffer->next)
result += buffer->length;
return result;
}
GrowingBufferReader::GrowingBufferReader(const GrowingBuffer &gb)
#ifndef NDEBUG
:growing_buffer(&gb)
#endif
{
assert(gb.head == nullptr || gb.head->length > 0);
buffer = gb.head;
assert(buffer == nullptr || buffer->length > 0);
position = 0;
}
void
GrowingBufferReader::Update(const GrowingBuffer &gb)
{
assert(position == 0 || position <= buffer->length);
if (buffer == nullptr)
buffer = gb.head;
else if (position == buffer->length &&
buffer->next != nullptr) {
/* the reader was at the end of all buffers, but then a new
buffer was appended */
buffer = buffer->next;
position = 0;
}
}
bool
GrowingBufferReader::IsEOF() const
{
assert(buffer == nullptr || position <= buffer->length);
return buffer == nullptr || position == buffer->length;
}
size_t
GrowingBufferReader::Available() const
{
if (buffer == nullptr)
return 0;
assert(position <= buffer->length);
size_t available = buffer->length - position;
for (const auto *b = buffer->next; b != nullptr; b = b->next) {
assert(b->length > 0);
available += b->length;
}
return available;
}
ConstBuffer<void>
GrowingBufferReader::Read() const
{
if (buffer == nullptr)
return nullptr;
assert(buffer != nullptr);
const auto *b = buffer;
if (position >= b->length) {
assert(position == b->length);
assert(buffer->next == nullptr);
return nullptr;
}
return { b->data + position, b->length - position };
}
void
GrowingBufferReader::Consume(size_t length)
{
assert(buffer != nullptr);
if (length == 0)
return;
position += length;
assert(position <= buffer->length);
if (position >= buffer->length) {
if (buffer->next == nullptr)
return;
buffer = buffer->next;
position = 0;
}
}
ConstBuffer<void>
GrowingBufferReader::PeekNext() const
{
const auto *b = buffer;
if (b == nullptr)
return nullptr;
assert(b->length > 0);
b = b->next;
if (b == nullptr)
return nullptr;
assert(b->length > 0);
return { b->data, b->length };
}
void
GrowingBufferReader::Skip(size_t length)
{
while (length > 0) {
assert(buffer != nullptr);
size_t remaining = buffer->length - position;
if (length < remaining ||
(length == remaining && buffer->next == nullptr)) {
position += length;
return;
}
length -= remaining;
if (buffer->next == nullptr) {
assert(position + remaining == length);
position = length;
return;
}
assert(buffer->next != nullptr);
buffer = buffer->next;
position = 0;
}
}
void
GrowingBuffer::CopyTo(void *dest) const
{
for (const auto *buffer = head; buffer != nullptr;
buffer = buffer->next)
dest = mempcpy(dest, buffer->data, buffer->length);
}
WritableBuffer<void>
GrowingBuffer::Dup(struct pool &_pool) const
{
size_t length = GetSize();
if (length == 0)
return nullptr;
void *dest = p_malloc(&_pool, length);
CopyTo(dest);
return { dest, length };
}
<|endoftext|> |
<commit_before>/*******************************************************************
* Driver-Programm für den Nelder-Mead Optimierungsalgorithmus. *
* Autor: Sonja Biedermann, a1402891 OPS WS15 7/4 *
* *
* Führt die Optimierung durch und stellt das Ergebnis einer jeden *
* Iteration grafisch dar. Verwendet dazu POSIX-Pipes und Gnuplot. *
* Verfügt weiters über ein kleines Info-Feature, dass auf Wunsch *
* des Benutzers Daten (wie etwa die Tiefpunkte der Funktion, die *
* zur Überprüfung der Ergebnisse nützlich sein können) über eine *
* bestimmte unterstützte Funktion anzeigen. *
*******************************************************************/
#include <iostream>
#include <unordered_map>
#include <sstream>
#include <string>
#include <cmath>
#include <fstream>
#include "Funktion.h"
#include "nelder_mead_optimizer.hpp"
// PIPE {{{
class pipe {
private:
FILE* handle;
public:
pipe(std::string const& cmd) : handle{ popen(cmd.c_str(), "w") } {}
pipe(pipe&& other) : handle{ std::move(other.handle) } { std::cout << "move"; other.handle = NULL; }
~pipe() { fflush(handle); if(handle) { fclose(handle); } }
pipe& flush() { fflush(handle); return *this; }
pipe& operator<<(std::string input) {
fputs(input.c_str(), handle);
return *this;
}
};
// }}}
// GNUPLOTTER {{{
class gnuplotter {
private:
pipe pipehandle;
std::string plot_cmd;
public:
gnuplotter(std::string const& plot_cmd = "")
: pipehandle{ pipe("gnuplot -p 2> /dev/null") }, plot_cmd{ plot_cmd } {}
gnuplotter(pipe&& p) : pipehandle{ std::move(p) } {}
gnuplotter& push_settings(std::string settings) {
pipehandle << settings;
pipehandle.flush();
return *this;
}
std::string& plot_command() { return plot_cmd; }
gnuplotter& replot() {
pipehandle << plot_cmd;
pipehandle.flush();
return *this;
}
};
// }}}
std::string read_all_about(std::string const& topic) {
std::ifstream file("info.txt");
std::string result;
std::string buffer;
while(getline(file, buffer) && buffer != topic);
while(getline(file, buffer) && buffer != "----") result += buffer + '\n';
return result;
}
int main(int argc, char const** argv) {
// {{{ GNUPLOT SETTINGS
char const* settings =
"set palette rgbformulae 33,13,10\n"
"set border 15 front linetype -1 linewidth 1.000\n"
"set logscale z 10\n"
"set view map\n"
"set isosamples 60, 60\n"
"set contour base\n"
"set xlabel 'x'\n"
"set xrange [*:*] noreverse nowriteback\n"
"set ylabel 'y'\n"
"set zlabel ''\n"
"set yrange [*:*] noreverse nowriteback\n"
"set zrange [*:*] noreverse nowriteback\n"
"set cntrparam levels 10\n"
"set surface\n";
// }}}
// FUNCTION STRUCTS {{{
struct : Funktion {
double value(double x, double y) { return 3*x*x + y*y - 3*x*y - 3*x; }
} example1;
struct : Funktion {
double value(double x, double y) { return y*y*y*y + 2*x*x - 3*x*y + 1; }
} example2;
struct : Funktion {
double value(double x, double y) { return (x*x + y - 11)*(x*x + y - 11) + (x + y*y - 7)*(x + y*y -7); }
} himmelblau;
struct : Funktion {
double value(double x, double y) { return 100*(y - x*x)*(y - x*x) + (x - 1)*(x - 1); }
} banana;
struct : Funktion {
double value(double x, double y) { return (x + 2*y - 7)*(x + 2*y - 7) + (2*x + y - 5)*(2*x + y - 5); }
} booth;
struct : Funktion {
double value(double x, double y) { return 0.26*(x*x + y*y) - 0.48*x*y; }
} matyas;
struct : Funktion {
double value(double x, double y) { return (1.5 - x + x*y)*(1.5 - x + x*y) + (2.25 - x + x*y*y)*(2.25 - x + x*y*y) + (2.625 - x + x*y*y*y)*(2.625 - x + x*y*y*y); }
} beale;
struct : Funktion {
double value(double x, double y) { return 2*x*x - 1.05*x*x*x*x + (x*x*x*x*x*x)/6 + x*y + y*y; }
} camel;
// }}}
// HASHMAP {{{
std::unordered_map<std::string, std::pair<std::string, Funktion*>> plot_functions = {
{"example1", std::make_pair("3*x**2 + y**2 - 3*x*y - 3*x", &example1)},
{"example2", std::make_pair("y**4 + 2*x**2 - 3*x*y + 1", &example2)},
{"himmelblau", std::make_pair("(x**2 + y - 11)**2 + (x + y**2 - 7)**2", &himmelblau)},
{"banana", std::make_pair("100*(y - x**2)**2 + (x - 1)**2", &banana)},
{"matyas", std::make_pair("0.26*(x**2 + y**2) - 0.48*x*y", &matyas)},
{"booth", std::make_pair("(x + 2*y - 7)**2 + (2*x + y - 5)**2", &booth)},
{"beale", std::make_pair("(1.5 - x + x*y)**2 + (2.25 - x + x*y**2)**2 + (2.625 - x + x*y**3)**2", &beale)},
{"camel", std::make_pair("2*x**2 - 1.05*x**4 + (x**6)/6 + x*y + y**2", &camel)}
};
// }}}
if(argc < 2) {
std::cerr << "No function specified.\n"
<< "Try one of these:\n"
<< "\thimmelblau – minimizes the Himmelblau function\n"
<< "\tbanana – minimizes Rosenbrock's Banana function\n"
<< "\tmatyas – minimizes the Matyas function\n"
<< "\tcamel – minimizes the three-hump camel function\n"
<< "\tbooth – minimizes Booth's function\n"
<< "\tbeale – minimizes Beale's function\n"
<< "\texample1 – minimizes the function 3*x**2 + y**2 - 3*x*y - 3*x\n"
<< "\texample2 – minimizes the function y**4 + 2*x**2 - 3*x*y + 1\n";
return 1;
}
if(std::string("info").compare(argv[1]) == 0) {
if(argc < 3) {
std::cerr << "Please specify the function you want to know more about.\n";
return 1;
}
std::string info = read_all_about(argv[2]);
std::cout << info;
return 0;
}
std::cout << "\tN E L D E R - M E A D\n"
<< "\tDEMOTOOL\n"
<< "\tMinimizes one of 8 given functions.\n"
<< "\tDisplays progress via gnuplot.\n"
<< "\t***********************************\n\n";
Funktion* user_choice;
try {
user_choice = plot_functions.at(argv[1]).second;
} catch(std::out_of_range const& ex) {
std::cerr << "No such function. (\"" << argv[1] << "\")\n";
return 1;
}
gnuplotter gnu(pipe("gnuplot -p"));
gnu.push_settings(settings);
gnu.push_settings(std::string("set title '") + argv[1] + "'\n");
std::ostringstream oss;
oss << "splot [-10.5:10.5] [-10.5:10.5] \\\n" << plot_functions[argv[1]].first
<< " with lines palette notitle nosurface, \\\n"
<< "'-' with lines lc rgb 'red' notitle\n";
std::string base_cmd = oss.str();
nelder_mead_optimizer nmo(*user_choice, 0.000005, {-1, -5}, {8, 8}, {3, -8});
int n = 0;
while(!nmo.done()) {
std::cout << "#" << n++ << '\n';
auto points = nmo.retrieve_current_simplex();
std::cout << "B = " << std::get<0>(points).format() << '\n'
<< "G = " << std::get<1>(points).format() << '\n'
<< "W = " << std::get<2>(points).format() << '\n';
oss.str("");
oss << base_cmd;
oss << std::get<0>(points).raw()<< " 1\n"
<< std::get<1>(points).raw() << " 1\n"
<< std::get<2>(points).raw() << " 1\n"
<< std::get<0>(points).raw() << " 1\n"
<< "e\n";
gnu.plot_command() = oss.str();
gnu.replot();
nmo.step();
std::cin.get();
if(std::cin.eof()) { return 0; }
}
}
/* vim: set ts=4 sw=4 tw=0 et :*/
<commit_msg>remove weird print statement<commit_after>/*******************************************************************
* Driver-Programm für den Nelder-Mead Optimierungsalgorithmus. *
* Autor: Sonja Biedermann, a1402891 OPS WS15 7/4 *
* *
* Führt die Optimierung durch und stellt das Ergebnis einer jeden *
* Iteration grafisch dar. Verwendet dazu POSIX-Pipes und Gnuplot. *
* Verfügt weiters über ein kleines Info-Feature, dass auf Wunsch *
* des Benutzers Daten (wie etwa die Tiefpunkte der Funktion, die *
* zur Überprüfung der Ergebnisse nützlich sein können) über eine *
* bestimmte unterstützte Funktion anzeigen. *
*******************************************************************/
#include <iostream>
#include <unordered_map>
#include <sstream>
#include <string>
#include <cmath>
#include <fstream>
#include "Funktion.h"
#include "nelder_mead_optimizer.hpp"
// PIPE {{{
class pipe {
private:
FILE* handle;
public:
pipe(std::string const& cmd) : handle{ popen(cmd.c_str(), "w") } {}
pipe(pipe&& other) : handle{ std::move(other.handle) } { other.handle = NULL; }
~pipe() { fflush(handle); if(handle) { fclose(handle); } }
pipe& flush() { fflush(handle); return *this; }
pipe& operator<<(std::string input) {
fputs(input.c_str(), handle);
return *this;
}
};
// }}}
// GNUPLOTTER {{{
class gnuplotter {
private:
pipe pipehandle;
std::string plot_cmd;
public:
gnuplotter(std::string const& plot_cmd = "")
: pipehandle{ pipe("gnuplot -p 2> /dev/null") }, plot_cmd{ plot_cmd } {}
gnuplotter(pipe&& p) : pipehandle{ std::move(p) } {}
gnuplotter& push_settings(std::string settings) {
pipehandle << settings;
pipehandle.flush();
return *this;
}
std::string& plot_command() { return plot_cmd; }
gnuplotter& replot() {
pipehandle << plot_cmd;
pipehandle.flush();
return *this;
}
};
// }}}
std::string read_all_about(std::string const& topic) {
std::ifstream file("info.txt");
std::string result;
std::string buffer;
while(getline(file, buffer) && buffer != topic);
while(getline(file, buffer) && buffer != "----") result += buffer + '\n';
return result;
}
int main(int argc, char const** argv) {
// {{{ GNUPLOT SETTINGS
char const* settings =
"set palette rgbformulae 33,13,10\n"
"set border 15 front linetype -1 linewidth 1.000\n"
"set logscale z 10\n"
"set view map\n"
"set isosamples 60, 60\n"
"set contour base\n"
"set xlabel 'x'\n"
"set xrange [*:*] noreverse nowriteback\n"
"set ylabel 'y'\n"
"set zlabel ''\n"
"set yrange [*:*] noreverse nowriteback\n"
"set zrange [*:*] noreverse nowriteback\n"
"set cntrparam levels 10\n"
"set surface\n";
// }}}
// FUNCTION STRUCTS {{{
struct : Funktion {
double value(double x, double y) { return 3*x*x + y*y - 3*x*y - 3*x; }
} example1;
struct : Funktion {
double value(double x, double y) { return y*y*y*y + 2*x*x - 3*x*y + 1; }
} example2;
struct : Funktion {
double value(double x, double y) { return (x*x + y - 11)*(x*x + y - 11) + (x + y*y - 7)*(x + y*y -7); }
} himmelblau;
struct : Funktion {
double value(double x, double y) { return 100*(y - x*x)*(y - x*x) + (x - 1)*(x - 1); }
} banana;
struct : Funktion {
double value(double x, double y) { return (x + 2*y - 7)*(x + 2*y - 7) + (2*x + y - 5)*(2*x + y - 5); }
} booth;
struct : Funktion {
double value(double x, double y) { return 0.26*(x*x + y*y) - 0.48*x*y; }
} matyas;
struct : Funktion {
double value(double x, double y) { return (1.5 - x + x*y)*(1.5 - x + x*y) + (2.25 - x + x*y*y)*(2.25 - x + x*y*y) + (2.625 - x + x*y*y*y)*(2.625 - x + x*y*y*y); }
} beale;
struct : Funktion {
double value(double x, double y) { return 2*x*x - 1.05*x*x*x*x + (x*x*x*x*x*x)/6 + x*y + y*y; }
} camel;
// }}}
// HASHMAP {{{
std::unordered_map<std::string, std::pair<std::string, Funktion*>> plot_functions = {
{"example1", std::make_pair("3*x**2 + y**2 - 3*x*y - 3*x", &example1)},
{"example2", std::make_pair("y**4 + 2*x**2 - 3*x*y + 1", &example2)},
{"himmelblau", std::make_pair("(x**2 + y - 11)**2 + (x + y**2 - 7)**2", &himmelblau)},
{"banana", std::make_pair("100*(y - x**2)**2 + (x - 1)**2", &banana)},
{"matyas", std::make_pair("0.26*(x**2 + y**2) - 0.48*x*y", &matyas)},
{"booth", std::make_pair("(x + 2*y - 7)**2 + (2*x + y - 5)**2", &booth)},
{"beale", std::make_pair("(1.5 - x + x*y)**2 + (2.25 - x + x*y**2)**2 + (2.625 - x + x*y**3)**2", &beale)},
{"camel", std::make_pair("2*x**2 - 1.05*x**4 + (x**6)/6 + x*y + y**2", &camel)}
};
// }}}
if(argc < 2) {
std::cerr << "No function specified.\n"
<< "Try one of these:\n"
<< "\thimmelblau – minimizes the Himmelblau function\n"
<< "\tbanana – minimizes Rosenbrock's Banana function\n"
<< "\tmatyas – minimizes the Matyas function\n"
<< "\tcamel – minimizes the three-hump camel function\n"
<< "\tbooth – minimizes Booth's function\n"
<< "\tbeale – minimizes Beale's function\n"
<< "\texample1 – minimizes the function 3*x**2 + y**2 - 3*x*y - 3*x\n"
<< "\texample2 – minimizes the function y**4 + 2*x**2 - 3*x*y + 1\n";
return 1;
}
if(std::string("info").compare(argv[1]) == 0) {
if(argc < 3) {
std::cerr << "Please specify the function you want to know more about.\n";
return 1;
}
std::string info = read_all_about(argv[2]);
std::cout << info;
return 0;
}
std::cout << "\tN E L D E R - M E A D\n"
<< "\tDEMOTOOL\n"
<< "\tMinimizes one of 8 given functions.\n"
<< "\tDisplays progress via gnuplot.\n"
<< "\t***********************************\n\n";
Funktion* user_choice;
try {
user_choice = plot_functions.at(argv[1]).second;
} catch(std::out_of_range const& ex) {
std::cerr << "No such function. (\"" << argv[1] << "\")\n";
return 1;
}
gnuplotter gnu(pipe("gnuplot -p 2> /dev/null"));
gnu.push_settings(settings);
gnu.push_settings(std::string("set title '") + argv[1] + "'\n");
std::ostringstream oss;
oss << "splot [-10.5:10.5] [-10.5:10.5] \\\n" << plot_functions[argv[1]].first
<< " with lines palette notitle nosurface, \\\n"
<< "'-' with lines lc rgb 'red' notitle\n";
std::string base_cmd = oss.str();
nelder_mead_optimizer nmo(*user_choice, 0.000005, {-1, -5}, {8, 8}, {3, -8});
int n = 0;
while(!nmo.done()) {
std::cout << "#" << n++ << '\n';
auto points = nmo.retrieve_current_simplex();
std::cout << "B = " << std::get<0>(points).format() << '\n'
<< "G = " << std::get<1>(points).format() << '\n'
<< "W = " << std::get<2>(points).format() << '\n';
oss.str("");
oss << base_cmd;
oss << std::get<0>(points).raw()<< " 1\n"
<< std::get<1>(points).raw() << " 1\n"
<< std::get<2>(points).raw() << " 1\n"
<< std::get<0>(points).raw() << " 1\n"
<< "e\n";
gnu.plot_command() = oss.str();
gnu.replot();
nmo.step();
std::cin.get();
if(std::cin.eof()) { return 0; }
}
}
/* vim: set ts=4 sw=4 tw=0 et :*/
<|endoftext|> |
<commit_before>#include "CmdSession.h"
#ifdef ARGP_FOUND
#include <string>
#include <memory>
#include <cstdlib>
#include <SmurffCpp/Version.h>
#include <SmurffCpp/Configs/Config.h>
#include <SmurffCpp/Configs/NoiseConfig.h>
// !!! DO NOT CHANGE ORDER OF INCLUDES (<algorithm>, <argp.h>)!!!
// https://stackoverflow.com/questions/19043109/gcc-4-8-1-combining-c-code-with-c11-code
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/IO/MatrixIO.h>
#include <argp.h>
using namespace Eigen;
using namespace smurff;
using namespace generic_io;
using namespace matrix_io;
enum OPT_ENUM
{
ROW_PRIOR = 1024, COL_PRIOR, ROW_FEATURES, COL_FEATURES, FNAME_ROW_MODEL, FNAME_COL_MODEL, FNAME_TEST, FNAME_TRAIN,
BURNIN, NSAMPLES, NUM_LATENT, PRECISION, ADAPTIVE, LAMBDA_BETA, TOL, DIRECT,
RESTORE_PREFIX, RESTORE_SUFFIX, SAVE_PREFIX, SAVE_SUFFIX, SAVE_FREQ, THRESHOLD, VERBOSE, QUIET, VERSION, SEED,
INIT_MODEL, CENTER, STATUS_FILE
};
void set_noise_model(Config& config, std::string noiseName, std::string optarg)
{
NoiseConfig nc;
nc.setNoiseType(smurff::stringToNoiseType(noiseName));
if (nc.getNoiseType() == NoiseTypes::adaptive)
{
char *token, *str = strdup(optarg.c_str());
if(str && (token = strsep(&str, ",")))
nc.sn_init = strtod(token, NULL);
if(str && (token = strsep(&str, ",")))
nc.sn_max = strtod(token, NULL);
}
else if (nc.getNoiseType() == NoiseTypes::fixed)
{
nc.precision = strtod(optarg.c_str(), NULL);
}
if(!config.m_train)
THROWERROR("train data is not provided");
// set global noise model
if (config.m_train->getNoiseConfig().getNoiseType() == NoiseTypes::noiseless)
config.m_train->setNoiseConfig(nc);
//set for row/col feautres
for(auto m: config.m_row_features)
if (m->getNoiseConfig().getNoiseType() == NoiseTypes::noiseless)
m->setNoiseConfig(nc);
for(auto m: config.m_col_features)
if (m->getNoiseConfig().getNoiseType() == NoiseTypes::noiseless)
m->setNoiseConfig(nc);
}
static int parse_opts(int key, char *optarg, struct argp_state *state)
{
Config &c = *(Config *)(state->input);
switch (key)
{
case ROW_PRIOR: c.row_prior_type = stringToPriorType(optarg); break;
case COL_PRIOR: c.col_prior_type = stringToPriorType(optarg); break;
case ROW_FEATURES: c.m_row_features.push_back(read_matrix(optarg, false)); break;
case COL_FEATURES: c.m_col_features.push_back(read_matrix(optarg, false)); break;
case CENTER: break;
case FNAME_TRAIN: c.m_train = read_data_config(optarg, true); break;
case LAMBDA_BETA: c.lambda_beta = strtod(optarg, NULL); break;
case BURNIN: c.burnin = strtol(optarg, NULL, 10); break;
case TOL: c.tol = atof(optarg); break;
case DIRECT: c.direct = true; break;
case FNAME_TEST: c.m_test = read_data_config(optarg, true); break;
case NUM_LATENT: c.num_latent = strtol(optarg, NULL, 10); break;
case NSAMPLES: c.nsamples = strtol(optarg, NULL, 10); break;
case SEED: c.random_seed_set = true;
c.random_seed = strtol(optarg, NULL, 10);
break;
case RESTORE_PREFIX: c.restore_prefix = std::string(optarg); break;
case RESTORE_SUFFIX: c.restore_suffix = std::string(optarg); break;
case SAVE_PREFIX: c.setSavePrefix(std::string(optarg)); break;
case SAVE_SUFFIX: c.save_suffix = std::string(optarg); break;
case SAVE_FREQ: c.save_freq = strtol(optarg, NULL, 10); break;
case PRECISION: set_noise_model(c, NOISE_NAME_FIXED, optarg); break;
case ADAPTIVE: set_noise_model(c, NOISE_NAME_ADAPTIVE, optarg); break;
case THRESHOLD: c.threshold = strtod(optarg, 0); c.classify = true; break;
case INIT_MODEL: c.model_init_type = stringToModelInitType(optarg); break;
case VERBOSE: c.verbose = optarg ? strtol(optarg, NULL, 0) : 1; break;
case QUIET: c.verbose = 0; break;
case VERSION: std::cout << "SMURFF " << smurff::SMURFF_VERSION << std::endl; exit(0);
case STATUS_FILE: c.csv_status = optarg; break;
default: return ARGP_ERR_UNKNOWN;
}
return 0;
}
#endif
void CmdSession::setFromArgs(int argc, char** argv)
{
#ifdef ARGP_FOUND
// Program documentation.
char doc[] = "SMURFF: Scalable Matrix Factorization Framework\n\thttp://github.com/ExaScience/smurff";
struct argp_option options[] =
{
{0,0,0,0,"Priors and side Info:",1},
{"row-prior", ROW_PRIOR , "PRIOR", 0, "One of <normal|spikeandslab|macau|macauone>"},
{"col-prior", COL_PRIOR , "PRIOR", 0, "One of <normal|spikeandslab|macau|macauone>"},
{"row-features", ROW_FEATURES , "FILE", 0, "side info for rows"},
{"col-features", COL_FEATURES , "FILE", 0, "side info for cols"},
{"row-model", FNAME_ROW_MODEL , "FILE", 0, "initialization matrix for row model"},
{"col-model", FNAME_COL_MODEL , "FILE", 0, "initialization matrix for col model"},
{"center", CENTER , "MODE", 0, "center <global|rows|cols|none>"},
{0,0,0,0,"Test and train matrices:",2},
{"test", FNAME_TEST , "FILE", 0, "test data (for computing RMSE)"},
{"train", FNAME_TRAIN , "FILE", 0, "train data file"},
{0,0,0,0,"General parameters:",3},
{"burnin", BURNIN , "NUM", 0, "200 number of samples to discard"},
{"nsamples", NSAMPLES , "NUM", 0, "800 number of samples to collect"},
{"num-latent", NUM_LATENT , "NUM", 0, "96 number of latent dimensions"},
{"restore-prefix", RESTORE_PREFIX , "PATH", 0, "prefix for file to initialize state"},
{"restore-suffix", RESTORE_SUFFIX , "EXT", 0, "suffix for initialization files (.csv or .ddm)"},
{"init-model", INIT_MODEL , "NAME", 0, "One of <random|zero>"},
{"save-prefix", SAVE_PREFIX , "PATH", 0, "prefix for result files"},
{"save-suffix", SAVE_SUFFIX , "EXT", 0, "suffix for result files (.csv or .ddm)"},
{"save-freq", SAVE_FREQ , "NUM", 0, "save every n iterations (0 == never, -1 == final model)"},
{"threshold", THRESHOLD , "NUM", 0, "threshold for binary classification"},
{"verbose", VERBOSE , "NUM", OPTION_ARG_OPTIONAL, "verbose output (default = 1)"},
{"quiet", QUIET , 0, 0, "no output"},
{"version", VERSION , 0, 0, "print version info"},
{"status", STATUS_FILE, "FILE", 0, "output progress to csv file"},
{"seed", SEED, "NUM", 0, "random number generator seed"},
{0,0,0,0,"Noise model:",4},
{"precision", PRECISION , "NUM", 0, "5.0 precision of observations"},
{"adaptive", ADAPTIVE , "NUM,NUM", 0, "1.0,10.0 adaptive precision of observations"},
{0,0,0,0,"For the macau prior:",5},
{"lambda-beta", LAMBDA_BETA , "NUM", 0, "10.0 initial value of lambda beta"},
{"tol", TOL , "NUM", 0, "1e-6 tolerance for CG"},
{"direct", DIRECT , 0, 0, "false Use Cholesky decomposition i.o. CG Solver"},
{0,0,0,0,"General Options:",0},
{0}
};
Config cfg;
struct argp argp = { options, parse_opts, 0, doc };
if(argp_parse (&argp, argc, argv, 0, 0, &cfg) != 0)
THROWERROR("Failed to parse command line arguments");
setFromConfig(cfg);
#else
THROWERROR("argp library is not available");
#endif
}<commit_msg>temporarely disable argp dependent code.<commit_after>#include "CmdSession.h"
#ifdef ARGP_FOUND
#include <string>
#include <memory>
#include <cstdlib>
#include <SmurffCpp/Version.h>
#include <SmurffCpp/Configs/Config.h>
#include <SmurffCpp/Configs/NoiseConfig.h>
// !!! DO NOT CHANGE ORDER OF INCLUDES (<algorithm>, <argp.h>)!!!
// https://stackoverflow.com/questions/19043109/gcc-4-8-1-combining-c-code-with-c11-code
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/IO/MatrixIO.h>
#include <argp.h>
using namespace Eigen;
using namespace generic_io;
using namespace matrix_io;
#endif
using namespace smurff;
#ifdef ARGP_FOUND
enum OPT_ENUM
{
ROW_PRIOR = 1024, COL_PRIOR, ROW_FEATURES, COL_FEATURES, FNAME_ROW_MODEL, FNAME_COL_MODEL, FNAME_TEST, FNAME_TRAIN,
BURNIN, NSAMPLES, NUM_LATENT, PRECISION, ADAPTIVE, LAMBDA_BETA, TOL, DIRECT,
RESTORE_PREFIX, RESTORE_SUFFIX, SAVE_PREFIX, SAVE_SUFFIX, SAVE_FREQ, THRESHOLD, VERBOSE, QUIET, VERSION, SEED,
INIT_MODEL, CENTER, STATUS_FILE
};
void set_noise_model(Config& config, std::string noiseName, std::string optarg)
{
NoiseConfig nc;
nc.setNoiseType(smurff::stringToNoiseType(noiseName));
if (nc.getNoiseType() == NoiseTypes::adaptive)
{
char *token, *str = strdup(optarg.c_str());
if(str && (token = strsep(&str, ",")))
nc.sn_init = strtod(token, NULL);
if(str && (token = strsep(&str, ",")))
nc.sn_max = strtod(token, NULL);
}
else if (nc.getNoiseType() == NoiseTypes::fixed)
{
nc.precision = strtod(optarg.c_str(), NULL);
}
if(!config.m_train)
THROWERROR("train data is not provided");
// set global noise model
if (config.m_train->getNoiseConfig().getNoiseType() == NoiseTypes::noiseless)
config.m_train->setNoiseConfig(nc);
//set for row/col feautres
for(auto m: config.m_row_features)
if (m->getNoiseConfig().getNoiseType() == NoiseTypes::noiseless)
m->setNoiseConfig(nc);
for(auto m: config.m_col_features)
if (m->getNoiseConfig().getNoiseType() == NoiseTypes::noiseless)
m->setNoiseConfig(nc);
}
static int parse_opts(int key, char *optarg, struct argp_state *state)
{
Config &c = *(Config *)(state->input);
switch (key)
{
case ROW_PRIOR: c.row_prior_type = stringToPriorType(optarg); break;
case COL_PRIOR: c.col_prior_type = stringToPriorType(optarg); break;
case ROW_FEATURES: c.m_row_features.push_back(read_matrix(optarg, false)); break;
case COL_FEATURES: c.m_col_features.push_back(read_matrix(optarg, false)); break;
case CENTER: break;
case FNAME_TRAIN: c.m_train = read_data_config(optarg, true); break;
case LAMBDA_BETA: c.lambda_beta = strtod(optarg, NULL); break;
case BURNIN: c.burnin = strtol(optarg, NULL, 10); break;
case TOL: c.tol = atof(optarg); break;
case DIRECT: c.direct = true; break;
case FNAME_TEST: c.m_test = read_data_config(optarg, true); break;
case NUM_LATENT: c.num_latent = strtol(optarg, NULL, 10); break;
case NSAMPLES: c.nsamples = strtol(optarg, NULL, 10); break;
case SEED: c.random_seed_set = true;
c.random_seed = strtol(optarg, NULL, 10);
break;
case RESTORE_PREFIX: c.restore_prefix = std::string(optarg); break;
case RESTORE_SUFFIX: c.restore_suffix = std::string(optarg); break;
case SAVE_PREFIX: c.setSavePrefix(std::string(optarg)); break;
case SAVE_SUFFIX: c.save_suffix = std::string(optarg); break;
case SAVE_FREQ: c.save_freq = strtol(optarg, NULL, 10); break;
case PRECISION: set_noise_model(c, NOISE_NAME_FIXED, optarg); break;
case ADAPTIVE: set_noise_model(c, NOISE_NAME_ADAPTIVE, optarg); break;
case THRESHOLD: c.threshold = strtod(optarg, 0); c.classify = true; break;
case INIT_MODEL: c.model_init_type = stringToModelInitType(optarg); break;
case VERBOSE: c.verbose = optarg ? strtol(optarg, NULL, 0) : 1; break;
case QUIET: c.verbose = 0; break;
case VERSION: std::cout << "SMURFF " << smurff::SMURFF_VERSION << std::endl; exit(0);
case STATUS_FILE: c.csv_status = optarg; break;
default: return ARGP_ERR_UNKNOWN;
}
return 0;
}
#endif
void CmdSession::setFromArgs(int argc, char** argv)
{
#ifdef ARGP_FOUND
// Program documentation.
char doc[] = "SMURFF: Scalable Matrix Factorization Framework\n\thttp://github.com/ExaScience/smurff";
struct argp_option options[] =
{
{0,0,0,0,"Priors and side Info:",1},
{"row-prior", ROW_PRIOR , "PRIOR", 0, "One of <normal|spikeandslab|macau|macauone>"},
{"col-prior", COL_PRIOR , "PRIOR", 0, "One of <normal|spikeandslab|macau|macauone>"},
{"row-features", ROW_FEATURES , "FILE", 0, "side info for rows"},
{"col-features", COL_FEATURES , "FILE", 0, "side info for cols"},
{"row-model", FNAME_ROW_MODEL , "FILE", 0, "initialization matrix for row model"},
{"col-model", FNAME_COL_MODEL , "FILE", 0, "initialization matrix for col model"},
{"center", CENTER , "MODE", 0, "center <global|rows|cols|none>"},
{0,0,0,0,"Test and train matrices:",2},
{"test", FNAME_TEST , "FILE", 0, "test data (for computing RMSE)"},
{"train", FNAME_TRAIN , "FILE", 0, "train data file"},
{0,0,0,0,"General parameters:",3},
{"burnin", BURNIN , "NUM", 0, "200 number of samples to discard"},
{"nsamples", NSAMPLES , "NUM", 0, "800 number of samples to collect"},
{"num-latent", NUM_LATENT , "NUM", 0, "96 number of latent dimensions"},
{"restore-prefix", RESTORE_PREFIX , "PATH", 0, "prefix for file to initialize state"},
{"restore-suffix", RESTORE_SUFFIX , "EXT", 0, "suffix for initialization files (.csv or .ddm)"},
{"init-model", INIT_MODEL , "NAME", 0, "One of <random|zero>"},
{"save-prefix", SAVE_PREFIX , "PATH", 0, "prefix for result files"},
{"save-suffix", SAVE_SUFFIX , "EXT", 0, "suffix for result files (.csv or .ddm)"},
{"save-freq", SAVE_FREQ , "NUM", 0, "save every n iterations (0 == never, -1 == final model)"},
{"threshold", THRESHOLD , "NUM", 0, "threshold for binary classification"},
{"verbose", VERBOSE , "NUM", OPTION_ARG_OPTIONAL, "verbose output (default = 1)"},
{"quiet", QUIET , 0, 0, "no output"},
{"version", VERSION , 0, 0, "print version info"},
{"status", STATUS_FILE, "FILE", 0, "output progress to csv file"},
{"seed", SEED, "NUM", 0, "random number generator seed"},
{0,0,0,0,"Noise model:",4},
{"precision", PRECISION , "NUM", 0, "5.0 precision of observations"},
{"adaptive", ADAPTIVE , "NUM,NUM", 0, "1.0,10.0 adaptive precision of observations"},
{0,0,0,0,"For the macau prior:",5},
{"lambda-beta", LAMBDA_BETA , "NUM", 0, "10.0 initial value of lambda beta"},
{"tol", TOL , "NUM", 0, "1e-6 tolerance for CG"},
{"direct", DIRECT , 0, 0, "false Use Cholesky decomposition i.o. CG Solver"},
{0,0,0,0,"General Options:",0},
{0}
};
Config cfg;
struct argp argp = { options, parse_opts, 0, doc };
if(argp_parse (&argp, argc, argv, 0, 0, &cfg) != 0)
THROWERROR("Failed to parse command line arguments");
setFromConfig(cfg);
#else
THROWERROR("argp library is not available");
#endif
}<|endoftext|> |
<commit_before>#include "Library.h"
#include "ui_Library.h"
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QDebug>
#include <QDirIterator>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <cctype>
#if defined(_WIN32) || defined(_WIN64)
#include <QSettings>
#endif
namespace pt = boost::property_tree;
Library::Library(Database db)
: QWidget(0),
db(db),
ui(new Ui::Library),
runningProcess(new QProcess(this))
{
ui->setupUi(this);
this->setObjectName("libraryUI");
connect(runningProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this,
SLOT(finished(int, QProcess::ExitStatus)));
connect(runningProcess, SIGNAL(error(QProcess::ProcessError)), this,
SLOT(onLaunchError(QProcess::ProcessError)));
QList<Game> games = db.getGames();
for (auto game : games)
{
qDebug() << game.id << game.gameName << game.gameDirectory
<< game.executablePath;
}
refreshGames();
QDir originRoot(qgetenv("APPDATA").append("/Origin"));
if (originRoot.exists())
{
findOriginGames(originRoot);
}
else
{
qDebug() << "Origin not found. Possibly not installed.";
}
bool steamFound = true;
QDir steamRoot;
steamRoot.setPath("");
#if defined(_WIN32) || defined(_WIN64)
QSettings settings("HKEY_CURRENT_USER\\Software\\Valve\\Steam",
QSettings::NativeFormat);
QString steamPath = settings.value("SteamPath").toString();
steamRoot = QDir(steamPath);
steamFound = steamRoot != QDir::currentPath();
#elif defined(__APPLE__)
// TODO: however OS X handles steam
return;
#elif defined(__linux__)
steamRoot = QDir(QDir::home().filePath(".steam/steam"));
#else
QMessageBox(QMessageBox::Critical, "Error",
"Platform doesn't support steam.");
return;
#endif
if (steamRoot.exists() && steamFound)
{
findSteamGames(steamRoot);
}
else
{
qDebug("Steam was not found, probably not installed.");
steamFound = false;
}
}
Library::~Library()
{
delete ui;
delete runningProcess;
}
void Library::on_testLaunch_clicked()
{
if (!isProcessRunning())
{
auto selection = ui->gameListWidget->currentItem();
if (selection != nullptr)
{
Game game = db.getGameByName(selection->text());
runProcess(game.executablePath, game.gameDirectory);
}
}
else
{
QMessageBox messageBox;
messageBox.setText("Error: an application is already running.");
messageBox.exec();
}
}
void Library::on_addGame_clicked()
{
QString name = QInputDialog::getText(0, "Game Name", "Game Name:");
if (name.trimmed() == "")
{
QMessageBox::critical(0, "Error", "You must specify a game name!");
return;
}
QFileDialog exeDialog;
exeDialog.setWindowTitle("Select Executable");
exeDialog.setFileMode(QFileDialog::ExistingFile);
#if defined(__unix__)
exeDialog.setDirectory(QDir::home());
#elif defined(_WIN32) || defined(_WIN64)
exeDialog.setDirectory("C:");
#endif
if (exeDialog.exec())
{
QStringList files = exeDialog.selectedFiles();
QString exe = files.at(0);
#ifdef Q_WS_MACX
// Get the binary from the app bundle
QDir dir(file + "/Contents/MacOS");
// TODO: Change to dir.entryList(QDir::NoDotAndDotDot) to be safe
QStringList fileList = dir.entryList();
file = dir.absoluteFilePath(
fileList.at(2)); // USUALLY this is the executable (after ., ..)
#endif
QFileDialog wdDialog; // Working Directory
wdDialog.setWindowTitle("Select Working Directory");
wdDialog.setFileMode(QFileDialog::DirectoryOnly);
wdDialog.setDirectory(exeDialog.directory().absolutePath());
if (wdDialog.exec())
{
QStringList dirs = wdDialog.selectedFiles();
QString dir = dirs.at(0);
qDebug() << "Adding game:" << name << exe << dir;
db.addGame(name, dir, exe);
refreshGames();
}
}
}
void Library::on_removeGame_clicked()
{
auto selection = ui->gameListWidget->currentItem();
if (selection != nullptr)
{
db.removeGameByName(selection->text());
refreshGames();
}
}
void Library::runProcess(QString file, QString workingDirectory)
{
// TODO: Implement some threading
if (!isProcessRunning())
{
qDebug() << "Launching:" << file << ", at" << workingDirectory;
runningProcess->setWorkingDirectory(workingDirectory);
runningProcess->setStandardErrorFile("error.txt");
runningProcess->setStandardOutputFile("log.txt");
runningProcess->start(file, QStringList());
runningProcess->waitForStarted();
}
}
void Library::refreshGames()
{
ui->gameListWidget->clear();
QList<Game> gameList = db.getGames();
for (auto game : gameList)
{
ui->gameListWidget->addItem(game.gameName);
}
}
void Library::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
if (exitCode != 0)
{
QMessageBox(
QMessageBox::Warning, "Warning",
"The game finished, but it claims to have encountered an error")
.exec();
}
}
void Library::onLaunchError(QProcess::ProcessError error)
{
switch (error)
{
case QProcess::FailedToStart:
QMessageBox(
QMessageBox::Critical, "Error",
"Could not start the game. Please double check that you are "
"using the correct file to launch it.")
.exec();
break;
case QProcess::Crashed:
QMessageBox(QMessageBox::Warning, "Crash!",
"The launched game has crashed")
.exec();
break;
default:
// Other cases are errors unrelated to startup, so let's not handle
// them
break;
}
}
bool Library::isProcessRunning() const
{
// We shall consider "Starting" to be running here too
return runningProcess->state() != QProcess::NotRunning;
}
void Library::findSteamGames(QDir steamRoot)
{
pt::ptree libraryFolders;
pt::read_info(steamRoot.filePath("steamapps/libraryfolders.vdf")
.toLocal8Bit()
.constData(),
libraryFolders);
steamDirectoryList.append(steamRoot.filePath(""));
QString pathString = "" + steamDirectoryList.at(0) + "\n";
for (auto kv : libraryFolders.get_child("LibraryFolders"))
{
if (std::isdigit(static_cast<int>(*kv.first.data())))
{
std::string path = kv.second.data();
QDir dir(QString::fromStdString(path));
if (dir.exists())
{
steamDirectoryList.append(dir.filePath(""));
pathString += dir.filePath("");
pathString += "\n";
}
}
}
// TODO: Make this prompting better/less obtrusive
bool directoryPlural = (steamDirectoryList.size() > 1);
int ret =
QMessageBox(QMessageBox::Question,
"Found " + QString::number(steamDirectoryList.size()) +
" director" + (directoryPlural ? "ies" : "y"),
QString::number(steamDirectoryList.size()) +
" directories have been found.\n\n" + pathString +
"Proceed?",
QMessageBox::Yes | QMessageBox::No)
.exec();
switch (ret)
{
case QMessageBox::Yes:
parseAcf();
break;
case QMessageBox::No:
break;
default:
break;
}
}
void Library::findOriginGames(QDir originRoot)
{
QDir originFolder;
pt::ptree originTree;
read_xml(originRoot.filePath("local.xml").toLocal8Bit().constData(),
originTree);
for (auto& xmlIter : originTree.get_child("Settings"))
{
if (xmlIter.second.get<std::string>("<xmlattr>.key") ==
"DownloadInPlaceDir")
{
originFolder = QString::fromStdString(
xmlIter.second.get<std::string>("<xmlattr>.value"));
qDebug() << originFolder;
break;
}
}
QStringList ignoreList;
ignoreList << "Cleanup.exe"
<< "Touchup.exe"
<< "DXSETUP.exe"
<< "vcredist_x86.exe"
<< "vcredist_x64.exe"
<< "ActivationUI.exe"
<< "PatchProgress.exe"
<< "activation.exe"
<< "EACoreServer.exe"
<< "EAProxyInstaller.exe"
<< "D3D11Install.exe";
originFolder.setFilter(QDir::Dirs | QDir::NoDotAndDotDot |
QDir::NoSymLinks);
QStringList folderList = originFolder.entryList();
QHash<QString, QStringList> masterList;
for (auto i : folderList)
{
// TODO: Populate a widget with this info
QDir dir(originFolder.absoluteFilePath(i));
dir.setNameFilters(QStringList("*.exe"));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
qDebug() << "Looking in: " << dir.filePath("");
QStringList test = recursiveFindFiles(dir, ignoreList);
masterList.insert(dir.filePath(""), test);
}
QHashIterator<QString, QStringList> masterIter(masterList);
while (masterIter.hasNext())
{
masterIter.next();
qDebug() << "Found in: " << masterIter.key();
for (auto fileIter : masterIter.value())
{
qDebug() << fileIter;
}
}
}
QStringList Library::recursiveFindFiles(QDir dir, QStringList ignoreList)
{
QStringList dirList;
QDirIterator it(dir, QDirIterator::Subdirectories);
while (it.hasNext())
{
QDir cur = it.next();
if (!ignoreList.contains(cur.dirName()))
{
bool found = false;
for (auto foundIter : dirList)
{
if (QDir(foundIter).dirName() == cur.dirName())
{
found = true;
break;
}
}
if (!found)
{
dirList.append(cur.filePath(""));
}
}
}
return dirList;
}
void Library::parseAcf()
{
// TODO: This stuff needs its own thread
for (QString iter : steamDirectoryList)
{
QDir steamAppsDir(iter);
steamAppsDir = steamAppsDir.filePath("steamapps");
QStringList fileList = steamAppsDir.entryList(
QStringList("*.acf"), QDir::Files | QDir::NoSymLinks);
for (auto fileIter : fileList)
{
pt::ptree fileTree;
std::string acfDir =
steamAppsDir.filePath(fileIter).toLocal8Bit().constData();
pt::read_info(acfDir, fileTree);
QString name = QString::fromStdString(
fileTree.get<std::string>("AppState.name"));
// TODO: Either add SteamID to db, or add getGameByPath
if (!std::get<0>(db.isExistant(name)))
{
QString path = steamAppsDir.filePath("common/" + QString::fromStdString(fileTree.get<std::string>("AppState.installdir")));
QString exe;
QStringList exeList = QDir(path).entryList(QDir::Files | QDir::NoSymLinks | QDir::Executable);
QFileDialog exeDialog;
exeDialog.setWindowTitle("Select Executable");
exeDialog.setFileMode(QFileDialog::ExistingFile);
exeDialog.setDirectory(path);
if (exeDialog.exec())
{
exe = exeDialog.selectedFiles().at(0);
}
db.addGame(name, path, exe);
refreshGames();
}
}
}
}
<commit_msg>Fix case for SteamApps directory<commit_after>#include "Library.h"
#include "ui_Library.h"
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QDebug>
#include <QDirIterator>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <cctype>
#if defined(_WIN32) || defined(_WIN64)
#include <QSettings>
#endif
namespace pt = boost::property_tree;
Library::Library(Database db)
: QWidget(0),
db(db),
ui(new Ui::Library),
runningProcess(new QProcess(this))
{
ui->setupUi(this);
this->setObjectName("libraryUI");
connect(runningProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this,
SLOT(finished(int, QProcess::ExitStatus)));
connect(runningProcess, SIGNAL(error(QProcess::ProcessError)), this,
SLOT(onLaunchError(QProcess::ProcessError)));
QList<Game> games = db.getGames();
for (auto game : games)
{
qDebug() << game.id << game.gameName << game.gameDirectory
<< game.executablePath;
}
refreshGames();
QDir originRoot(qgetenv("APPDATA").append("/Origin"));
if (originRoot.exists())
{
findOriginGames(originRoot);
}
else
{
qDebug() << "Origin not found. Possibly not installed.";
}
bool steamFound = true;
QDir steamRoot;
steamRoot.setPath("");
#if defined(_WIN32) || defined(_WIN64)
QSettings settings("HKEY_CURRENT_USER\\Software\\Valve\\Steam",
QSettings::NativeFormat);
QString steamPath = settings.value("SteamPath").toString();
steamRoot = QDir(steamPath);
steamFound = steamRoot != QDir::currentPath();
#elif defined(__APPLE__)
// TODO: however OS X handles steam
return;
#elif defined(__linux__)
steamRoot = QDir(QDir::home().filePath(".steam/steam"));
#else
QMessageBox(QMessageBox::Critical, "Error",
"Platform doesn't support steam.");
return;
#endif
if (steamRoot.exists() && steamFound)
{
findSteamGames(steamRoot);
}
else
{
qDebug("Steam was not found, probably not installed.");
steamFound = false;
}
}
Library::~Library()
{
delete ui;
delete runningProcess;
}
void Library::on_testLaunch_clicked()
{
if (!isProcessRunning())
{
auto selection = ui->gameListWidget->currentItem();
if (selection != nullptr)
{
Game game = db.getGameByName(selection->text());
runProcess(game.executablePath, game.gameDirectory);
}
}
else
{
QMessageBox messageBox;
messageBox.setText("Error: an application is already running.");
messageBox.exec();
}
}
void Library::on_addGame_clicked()
{
QString name = QInputDialog::getText(0, "Game Name", "Game Name:");
if (name.trimmed() == "")
{
QMessageBox::critical(0, "Error", "You must specify a game name!");
return;
}
QFileDialog exeDialog;
exeDialog.setWindowTitle("Select Executable");
exeDialog.setFileMode(QFileDialog::ExistingFile);
#if defined(__unix__)
exeDialog.setDirectory(QDir::home());
#elif defined(_WIN32) || defined(_WIN64)
exeDialog.setDirectory("C:");
#endif
if (exeDialog.exec())
{
QStringList files = exeDialog.selectedFiles();
QString exe = files.at(0);
#ifdef Q_WS_MACX
// Get the binary from the app bundle
QDir dir(file + "/Contents/MacOS");
// TODO: Change to dir.entryList(QDir::NoDotAndDotDot) to be safe
QStringList fileList = dir.entryList();
file = dir.absoluteFilePath(
fileList.at(2)); // USUALLY this is the executable (after ., ..)
#endif
QFileDialog wdDialog; // Working Directory
wdDialog.setWindowTitle("Select Working Directory");
wdDialog.setFileMode(QFileDialog::DirectoryOnly);
wdDialog.setDirectory(exeDialog.directory().absolutePath());
if (wdDialog.exec())
{
QStringList dirs = wdDialog.selectedFiles();
QString dir = dirs.at(0);
qDebug() << "Adding game:" << name << exe << dir;
db.addGame(name, dir, exe);
refreshGames();
}
}
}
void Library::on_removeGame_clicked()
{
auto selection = ui->gameListWidget->currentItem();
if (selection != nullptr)
{
db.removeGameByName(selection->text());
refreshGames();
}
}
void Library::runProcess(QString file, QString workingDirectory)
{
// TODO: Implement some threading
if (!isProcessRunning())
{
qDebug() << "Launching:" << file << ", at" << workingDirectory;
runningProcess->setWorkingDirectory(workingDirectory);
runningProcess->setStandardErrorFile("error.txt");
runningProcess->setStandardOutputFile("log.txt");
runningProcess->start(file, QStringList());
runningProcess->waitForStarted();
}
}
void Library::refreshGames()
{
ui->gameListWidget->clear();
QList<Game> gameList = db.getGames();
for (auto game : gameList)
{
ui->gameListWidget->addItem(game.gameName);
}
}
void Library::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
if (exitCode != 0)
{
QMessageBox(
QMessageBox::Warning, "Warning",
"The game finished, but it claims to have encountered an error")
.exec();
}
}
void Library::onLaunchError(QProcess::ProcessError error)
{
switch (error)
{
case QProcess::FailedToStart:
QMessageBox(
QMessageBox::Critical, "Error",
"Could not start the game. Please double check that you are "
"using the correct file to launch it.")
.exec();
break;
case QProcess::Crashed:
QMessageBox(QMessageBox::Warning, "Crash!",
"The launched game has crashed")
.exec();
break;
default:
// Other cases are errors unrelated to startup, so let's not handle
// them
break;
}
}
bool Library::isProcessRunning() const
{
// We shall consider "Starting" to be running here too
return runningProcess->state() != QProcess::NotRunning;
}
void Library::findSteamGames(QDir steamRoot)
{
QDir steamAppsDir = steamRoot.filePath("steamapps");
if (!steamAppsDir.exists())
{
steamAppsDir = steamRoot.filePath("SteamApps");
}
pt::ptree libraryFolders;
pt::read_info(steamAppsDir.filePath("libraryfolders.vdf")
.toLocal8Bit()
.constData(),
libraryFolders);
steamDirectoryList.append(steamRoot.filePath(""));
QString pathString = "" + steamDirectoryList.at(0) + "\n";
for (auto kv : libraryFolders.get_child("LibraryFolders"))
{
if (std::isdigit(static_cast<int>(*kv.first.data())))
{
std::string path = kv.second.data();
QDir dir(QString::fromStdString(path));
if (dir.exists())
{
steamDirectoryList.append(dir.filePath(""));
pathString += dir.filePath("");
pathString += "\n";
}
}
}
// TODO: Make this prompting better/less obtrusive
bool directoryPlural = (steamDirectoryList.size() > 1);
int ret =
QMessageBox(QMessageBox::Question,
"Found " + QString::number(steamDirectoryList.size()) +
" director" + (directoryPlural ? "ies" : "y"),
QString::number(steamDirectoryList.size()) +
" directories have been found.\n\n" + pathString +
"Proceed?",
QMessageBox::Yes | QMessageBox::No)
.exec();
switch (ret)
{
case QMessageBox::Yes:
parseAcf();
break;
case QMessageBox::No:
break;
default:
break;
}
}
void Library::findOriginGames(QDir originRoot)
{
QDir originFolder;
pt::ptree originTree;
read_xml(originRoot.filePath("local.xml").toLocal8Bit().constData(),
originTree);
for (auto& xmlIter : originTree.get_child("Settings"))
{
if (xmlIter.second.get<std::string>("<xmlattr>.key") ==
"DownloadInPlaceDir")
{
originFolder = QString::fromStdString(
xmlIter.second.get<std::string>("<xmlattr>.value"));
qDebug() << originFolder;
break;
}
}
QStringList ignoreList;
ignoreList << "Cleanup.exe"
<< "Touchup.exe"
<< "DXSETUP.exe"
<< "vcredist_x86.exe"
<< "vcredist_x64.exe"
<< "ActivationUI.exe"
<< "PatchProgress.exe"
<< "activation.exe"
<< "EACoreServer.exe"
<< "EAProxyInstaller.exe"
<< "D3D11Install.exe";
originFolder.setFilter(QDir::Dirs | QDir::NoDotAndDotDot |
QDir::NoSymLinks);
QStringList folderList = originFolder.entryList();
QHash<QString, QStringList> masterList;
for (auto i : folderList)
{
// TODO: Populate a widget with this info
QDir dir(originFolder.absoluteFilePath(i));
dir.setNameFilters(QStringList("*.exe"));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
qDebug() << "Looking in: " << dir.filePath("");
QStringList test = recursiveFindFiles(dir, ignoreList);
masterList.insert(dir.filePath(""), test);
}
QHashIterator<QString, QStringList> masterIter(masterList);
while (masterIter.hasNext())
{
masterIter.next();
qDebug() << "Found in: " << masterIter.key();
for (auto fileIter : masterIter.value())
{
qDebug() << fileIter;
}
}
}
QStringList Library::recursiveFindFiles(QDir dir, QStringList ignoreList)
{
QStringList dirList;
QDirIterator it(dir, QDirIterator::Subdirectories);
while (it.hasNext())
{
QDir cur = it.next();
if (!ignoreList.contains(cur.dirName()))
{
bool found = false;
for (auto foundIter : dirList)
{
if (QDir(foundIter).dirName() == cur.dirName())
{
found = true;
break;
}
}
if (!found)
{
dirList.append(cur.filePath(""));
}
}
}
return dirList;
}
void Library::parseAcf()
{
// TODO: This stuff needs its own thread
for (QString iter : steamDirectoryList)
{
QDir steamAppsDir(iter);
if (steamAppsDir.exists("SteamApps"))
{
steamAppsDir = steamAppsDir.filePath("SteamApps");
}
else
{
steamAppsDir = steamAppsDir.filePath("steamapps");
}
QStringList fileList = steamAppsDir.entryList(
QStringList("*.acf"), QDir::Files | QDir::NoSymLinks);
for (auto fileIter : fileList)
{
pt::ptree fileTree;
std::string acfDir =
steamAppsDir.filePath(fileIter).toLocal8Bit().constData();
pt::read_info(acfDir, fileTree);
QString name = QString::fromStdString(
fileTree.get<std::string>("AppState.name"));
// TODO: Either add SteamID to db, or add getGameByPath
if (!std::get<0>(db.isExistant(name)))
{
QString path = steamAppsDir.filePath("common/" + QString::fromStdString(fileTree.get<std::string>("AppState.installdir")));
QString exe;
QStringList exeList = QDir(path).entryList(QDir::Files | QDir::NoSymLinks | QDir::Executable);
QFileDialog exeDialog;
exeDialog.setWindowTitle("Select Executable");
exeDialog.setFileMode(QFileDialog::ExistingFile);
exeDialog.setDirectory(path);
if (exeDialog.exec())
{
exe = exeDialog.selectedFiles().at(0);
}
db.addGame(name, path, exe);
refreshGames();
}
}
}
}
<|endoftext|> |
<commit_before>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "cPacket_NamedEntitySpawn.h"
void cPacket_NamedEntitySpawn::Serialize(AString & a_Data) const
{
short CurrentItem = m_CurrentItem;
assert(CurrentItem > 0);
if (CurrentItem <= 0)
{
CurrentItem = 0;
// Fix, to make sure no invalid values are sent.
// WARNING: HERE ITS 0, BUT IN EQUIP PACKET ITS -1 !!
}
AppendByte (a_Data, m_PacketID);
AppendInteger (a_Data, m_UniqueID);
AppendString16(a_Data, m_PlayerName);
AppendInteger (a_Data, m_PosX);
AppendInteger (a_Data, m_PosY);
AppendInteger (a_Data, m_PosZ);
AppendByte (a_Data, m_Rotation);
AppendByte (a_Data, m_Pitch);
AppendShort (a_Data, CurrentItem);
}
<commit_msg>Fixed assertion bug in NamedEntitySpawn packet, it used to assert when item ID is 0, but now 0 is allowed<commit_after>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "cPacket_NamedEntitySpawn.h"
void cPacket_NamedEntitySpawn::Serialize(AString & a_Data) const
{
short CurrentItem = m_CurrentItem;
assert(CurrentItem >= 0);
if (CurrentItem <= 0)
{
CurrentItem = 0;
// Fix, to make sure no invalid values are sent.
// WARNING: HERE ITS 0, BUT IN EQUIP PACKET ITS -1 !!
}
AppendByte (a_Data, m_PacketID);
AppendInteger (a_Data, m_UniqueID);
AppendString16(a_Data, m_PlayerName);
AppendInteger (a_Data, m_PosX);
AppendInteger (a_Data, m_PosY);
AppendInteger (a_Data, m_PosZ);
AppendByte (a_Data, m_Rotation);
AppendByte (a_Data, m_Pitch);
AppendShort (a_Data, CurrentItem);
}
<|endoftext|> |
<commit_before>#include "RayCast.h"
#include "Application.h"
#include "ModuleCamera3D.h"
#include "ComponentMeshRenderer.h"
#include "ComponentTransform.h"
#include "moduleImGui.h"
RayCast::RayCast()
{
}
void RayCast::Update()
{
if (ImGui::IsMouseClicked(0) && App->input->IsMouseInWindow() == false)
{
int width = App->window->width;
int height = App->window->height;
int mouse_x = App->input->GetMouseX();
int mouse_y = App->input->GetMouseY();
float normalized_x = -(1.0f - (float(mouse_x) * 2.0f) / width);
float normalized_y = 1.0f - (float(mouse_y) * 2.0f) / height;
ray = App->camera->GetEditorCam()->frustum.UnProjectLineSegment(normalized_x, normalized_y);
GameObject* c = GetHit();
if (c != nullptr)
{
LOG("Object %s was hitted and returned succesfully", c->GetName());
}
}
DrawRay();
}
GameObject * RayCast::GetHit()
{
GameObject* ret;
// First we get the list of AABB's the ray is coliding with ordered by distance
GetObjectsByDistance(candidate_list);
// We check collisions for every triangle of the mesh of selected objects
ret = RayTest();
candidate_list.clear();
return ret;
}
void RayCast::GetObjectsByDistance(vector<GameObject*>& objects)
{
// This has to be improved with octree algorithm
for (int i = 0; i < App->scene_intro->GetList().size(); i++)
{
GameObject* curr_candidate = App->scene_intro->GetGameObject(i);
if (ray.Intersects(curr_candidate->GetBoundingBox()))
{
LOG("Candidate %d Hit", i);
objects.push_back(curr_candidate);
}
}
}
GameObject * RayCast::RayTest()
{
float best_distance = -1;
GameObject* ret = nullptr;
for (int i = 0; i < candidate_list.size(); i++)
{
ComponentMeshRenderer* tmp_mr = (ComponentMeshRenderer*)candidate_list[i]->GetComponent(COMPONENT_MESH_RENDERER); //For getting triangles points
ComponentTransform* tmp_trans = (ComponentTransform*)candidate_list[i]->GetComponent(COMPONENT_TRANSFORM); //For gettin triangle points transformation
for (int j = 0; j < tmp_mr->GetNumTriangles();)
{
float3 tri_point_1 = tmp_mr->vertices[tmp_mr->indices[j]];
j++;
float3 tri_point_2 = tmp_mr->vertices[tmp_mr->indices[j]];
j++;
float3 tri_point_3 = tmp_mr->vertices[tmp_mr->indices[j]];
j++;
Triangle tri(tri_point_1, tri_point_2, tri_point_3);
tri.Transform(tmp_trans->GetGlobalTransform());
float distance;
float3 hit_point;
if (ray.Intersects(tri, &distance, &hit_point))
{
if (best_distance > distance || best_distance == -1)
{
best_distance = distance;
ret = candidate_list[i];
}
}
}
}
return ret;
}
RayCast::~RayCast()
{
}
void RayCast::DrawRay()
{
DebugDraw(ray, Red);
}
<commit_msg>Log Corrected<commit_after>#include "RayCast.h"
#include "Application.h"
#include "ModuleCamera3D.h"
#include "ComponentMeshRenderer.h"
#include "ComponentTransform.h"
#include "moduleImGui.h"
RayCast::RayCast()
{
}
void RayCast::Update()
{
if (ImGui::IsMouseClicked(0) && App->input->IsMouseInWindow() == false)
{
int width = App->window->width;
int height = App->window->height;
int mouse_x = App->input->GetMouseX();
int mouse_y = App->input->GetMouseY();
float normalized_x = -(1.0f - (float(mouse_x) * 2.0f) / width);
float normalized_y = 1.0f - (float(mouse_y) * 2.0f) / height;
ray = App->camera->GetEditorCam()->frustum.UnProjectLineSegment(normalized_x, normalized_y);
GameObject* c = GetHit();
if (c != nullptr)
{
LOG("Object %s was hitted and returned succesfully", c->GetName());
}
}
DrawRay();
}
GameObject * RayCast::GetHit()
{
GameObject* ret;
// First we get the list of AABB's the ray is coliding with ordered by distance
GetObjectsByDistance(candidate_list);
// We check collisions for every triangle of the mesh of selected objects
ret = RayTest();
candidate_list.clear();
return ret;
}
void RayCast::GetObjectsByDistance(vector<GameObject*>& objects)
{
// This has to be improved with octree algorithm
for (int i = 0; i < App->scene_intro->GetList().size(); i++)
{
GameObject* curr_candidate = App->scene_intro->GetGameObject(i);
if (ray.Intersects(curr_candidate->GetBoundingBox()))
{
LOG("Bounding Box %d Hit", i);
objects.push_back(curr_candidate);
}
}
}
GameObject * RayCast::RayTest()
{
float best_distance = -1;
GameObject* ret = nullptr;
for (int i = 0; i < candidate_list.size(); i++)
{
ComponentMeshRenderer* tmp_mr = (ComponentMeshRenderer*)candidate_list[i]->GetComponent(COMPONENT_MESH_RENDERER); //For getting triangles points
ComponentTransform* tmp_trans = (ComponentTransform*)candidate_list[i]->GetComponent(COMPONENT_TRANSFORM); //For gettin triangle points transformation
for (int j = 0; j < tmp_mr->GetNumTriangles();)
{
float3 tri_point_1 = tmp_mr->vertices[tmp_mr->indices[j]];
j++;
float3 tri_point_2 = tmp_mr->vertices[tmp_mr->indices[j]];
j++;
float3 tri_point_3 = tmp_mr->vertices[tmp_mr->indices[j]];
j++;
Triangle tri(tri_point_1, tri_point_2, tri_point_3);
tri.Transform(tmp_trans->GetGlobalTransform());
float distance;
float3 hit_point;
if (ray.Intersects(tri, &distance, &hit_point))
{
if (best_distance > distance || best_distance == -1)
{
best_distance = distance;
ret = candidate_list[i];
}
}
}
}
return ret;
}
RayCast::~RayCast()
{
}
void RayCast::DrawRay()
{
DebugDraw(ray, Red);
}
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
Copyright (C) 2017-2018 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tiff/CiffIFD.h"
#include "common/Common.h" // for uint32, ushort16, isIn
#include "common/NORangesSet.h" // for NORangesSet
#include "common/RawspeedException.h" // for RawspeedException
#include "io/ByteStream.h" // for ByteStream
#include "io/IOException.h" // for IOException
#include "parsers/CiffParserException.h" // for ThrowCPE, CiffParserException
#include "tiff/CiffEntry.h" // for CiffEntry, CiffDataType::CI...
#include <cassert> // for assert
#include <map> // for map, _Rb_tree_iterator
#include <memory> // for unique_ptr
#include <string> // for allocator, operator==, string
#include <utility> // for pair
#include <vector> // for vector
using std::string;
using std::vector;
using std::unique_ptr;
namespace rawspeed {
void CiffIFD::parseIFDEntry(NORangesSet<Buffer>* valueDatas,
const ByteStream* valueData,
ByteStream* dirEntries) {
assert(valueDatas);
assert(valueData);
assert(dirEntries);
ByteStream dirEntry = dirEntries->getStream(10); // Entry is 10 bytes.
auto t = std::make_unique<CiffEntry>(valueDatas, valueData, dirEntry);
switch (t->type) {
case CIFF_SUB1:
case CIFF_SUB2: {
add(std::make_unique<CiffIFD>(this, t->data));
break;
}
default:
// Will we ever look for this entry?
if (!isIn(t->tag, CiffTagsWeCareAbout))
return;
add(move(t));
}
}
CiffIFD::CiffIFD(CiffIFD* const parent_) : parent(parent_) {
recursivelyCheckSubIFDs(1);
// If we are good (can add this IFD without violating the limits),
// we are still here. However, due to the way we add parsed sub-IFD's (lazy),
// we need to count this IFD right *NOW*, not when adding it at the end.
recursivelyIncrementSubIFDCount();
}
CiffIFD::CiffIFD(CiffIFD* const parent_, ByteStream directory)
: CiffIFD(parent_) {
if (directory.getSize() < 4)
ThrowCPE("CIFF directory is too short.");
directory.setPosition(directory.getSize() - 4);
const uint32 valueDataSize = directory.getU32();
// The Recursion. Directory entries store data here. May contain IFDs.
directory.setPosition(0);
const ByteStream valueData(directory.getStream(valueDataSize));
// count of the Directory entries in this IFD
const ushort16 entryCount = directory.getU16();
// each entry is 10 bytes
ByteStream dirEntries(directory.getStream(entryCount, 10));
// IFDData might still contain OtherData until the valueDataSize at the end.
// But we do not care about that.
// Each IFD has it's own valueData area.
// In that area, no two entries may overlap.
NORangesSet<Buffer> valueDatas;
for (uint32 i = 0; i < entryCount; i++)
parseIFDEntry(&valueDatas, &valueData, &dirEntries);
}
void CiffIFD::recursivelyIncrementSubIFDCount() {
CiffIFD* p = this->parent;
if (!p)
return;
p->subIFDCount++;
for (; p != nullptr; p = p->parent)
p->subIFDCountRecursive++;
}
void CiffIFD::checkSubIFDs(int headroom) const {
int count = headroom + subIFDCount;
if (!headroom)
assert(count <= CiffIFD::Limits::SubIFDCount);
else if (count > CiffIFD::Limits::SubIFDCount)
ThrowCPE("TIFF IFD has %u SubIFDs", count);
count = headroom + subIFDCountRecursive;
if (!headroom)
assert(count <= CiffIFD::Limits::RecursiveSubIFDCount);
else if (count > CiffIFD::Limits::RecursiveSubIFDCount)
ThrowCPE("TIFF IFD file has %u SubIFDs (recursively)", count);
}
void CiffIFD::recursivelyCheckSubIFDs(int headroom) const {
int depth = 0;
for (const CiffIFD* p = this; p != nullptr;) {
if (!headroom)
assert(depth <= CiffIFD::Limits::Depth);
else if (depth > CiffIFD::Limits::Depth)
ThrowCPE("CiffIFD cascading overflow, found %u level IFD", depth);
p->checkSubIFDs(headroom);
// And step up
p = p->parent;
depth++;
}
}
void CiffIFD::add(std::unique_ptr<CiffIFD> subIFD) {
assert(subIFD->parent == this);
// We are good, and actually can add this sub-IFD, right?
subIFD->recursivelyCheckSubIFDs(0);
mSubIFD.push_back(move(subIFD));
}
void CiffIFD::add(std::unique_ptr<CiffEntry> entry) {
assert(isIn(entry->tag, CiffTagsWeCareAbout));
mEntry[entry->tag] = move(entry);
assert(mEntry.size() <= CiffTagsWeCareAbout.size());
}
template <typename Lambda>
std::vector<const CiffIFD*> CiffIFD::getIFDsWithTagIf(CiffTag tag,
const Lambda& f) const {
assert(isIn(tag, CiffTagsWeCareAbout));
std::vector<const CiffIFD*> matchingIFDs;
const auto found = mEntry.find(tag);
if (found != mEntry.end()) {
const auto entry = found->second.get();
if (f(entry))
matchingIFDs.push_back(this);
}
for (const auto& i : mSubIFD) {
const auto t = i->getIFDsWithTagIf(tag, f);
matchingIFDs.insert(matchingIFDs.end(), t.begin(), t.end());
}
return matchingIFDs;
}
template <typename Lambda>
const CiffEntry* CiffIFD::getEntryRecursiveIf(CiffTag tag,
const Lambda& f) const {
assert(isIn(tag, CiffTagsWeCareAbout));
const auto found = mEntry.find(tag);
if (found != mEntry.end()) {
const auto entry = found->second.get();
if (f(entry))
return entry;
}
for (const auto& i : mSubIFD) {
const CiffEntry* entry = i->getEntryRecursiveIf(tag, f);
if (entry)
return entry;
}
return nullptr;
}
vector<const CiffIFD*> CiffIFD::getIFDsWithTag(CiffTag tag) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getIFDsWithTagIf(tag, [](const CiffEntry*) { return true; });
}
vector<const CiffIFD*> CiffIFD::getIFDsWithTagWhere(CiffTag tag,
uint32 isValue) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getIFDsWithTagIf(tag, [&isValue](const CiffEntry* entry) {
return entry->isInt() && entry->getU32() == isValue;
});
}
vector<const CiffIFD*>
CiffIFD::getIFDsWithTagWhere(CiffTag tag, const string& isValue) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getIFDsWithTagIf(tag, [&isValue](const CiffEntry* entry) {
return entry->isString() && isValue == entry->getString();
});
}
bool __attribute__((pure)) CiffIFD::hasEntry(CiffTag tag) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return mEntry.count(tag) > 0;
}
bool __attribute__((pure)) CiffIFD::hasEntryRecursive(CiffTag tag) const {
assert(isIn(tag, CiffTagsWeCareAbout));
if (mEntry.count(tag) > 0)
return true;
for (const auto& i : mSubIFD) {
if (i->hasEntryRecursive(tag))
return true;
}
return false;
}
const CiffEntry* CiffIFD::getEntry(CiffTag tag) const {
assert(isIn(tag, CiffTagsWeCareAbout));
const auto found = mEntry.find(tag);
if (found != mEntry.end())
return found->second.get();
ThrowCPE("Entry 0x%x not found.", tag);
}
const CiffEntry* CiffIFD::getEntryRecursive(CiffTag tag) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getEntryRecursiveIf(tag, [](const CiffEntry*) { return true; });
}
const CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag,
uint32 isValue) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getEntryRecursiveIf(tag, [&isValue](const CiffEntry* entry) {
return entry->isInt() && entry->getU32() == isValue;
});
}
const CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag,
const string& isValue) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getEntryRecursiveIf(tag, [&isValue](const CiffEntry* entry) {
return entry->isString() && isValue == entry->getString();
});
}
} // namespace rawspeed
<commit_msg>CiffIFD::CiffIFD(): add a bit of sanity asserts at the end<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
Copyright (C) 2017-2018 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tiff/CiffIFD.h"
#include "common/Common.h" // for uint32, ushort16, isIn
#include "common/NORangesSet.h" // for NORangesSet
#include "common/RawspeedException.h" // for RawspeedException
#include "io/ByteStream.h" // for ByteStream
#include "io/IOException.h" // for IOException
#include "parsers/CiffParserException.h" // for ThrowCPE, CiffParserException
#include "tiff/CiffEntry.h" // for CiffEntry, CiffDataType::CI...
#include <cassert> // for assert
#include <map> // for map, _Rb_tree_iterator
#include <memory> // for unique_ptr
#include <string> // for allocator, operator==, string
#include <utility> // for pair
#include <vector> // for vector
using std::string;
using std::vector;
using std::unique_ptr;
namespace rawspeed {
void CiffIFD::parseIFDEntry(NORangesSet<Buffer>* valueDatas,
const ByteStream* valueData,
ByteStream* dirEntries) {
assert(valueDatas);
assert(valueData);
assert(dirEntries);
ByteStream dirEntry = dirEntries->getStream(10); // Entry is 10 bytes.
auto t = std::make_unique<CiffEntry>(valueDatas, valueData, dirEntry);
switch (t->type) {
case CIFF_SUB1:
case CIFF_SUB2: {
add(std::make_unique<CiffIFD>(this, t->data));
break;
}
default:
// Will we ever look for this entry?
if (!isIn(t->tag, CiffTagsWeCareAbout))
return;
add(move(t));
}
}
CiffIFD::CiffIFD(CiffIFD* const parent_) : parent(parent_) {
recursivelyCheckSubIFDs(1);
// If we are good (can add this IFD without violating the limits),
// we are still here. However, due to the way we add parsed sub-IFD's (lazy),
// we need to count this IFD right *NOW*, not when adding it at the end.
recursivelyIncrementSubIFDCount();
}
CiffIFD::CiffIFD(CiffIFD* const parent_, ByteStream directory)
: CiffIFD(parent_) {
if (directory.getSize() < 4)
ThrowCPE("CIFF directory is too short.");
directory.setPosition(directory.getSize() - 4);
const uint32 valueDataSize = directory.getU32();
// The Recursion. Directory entries store data here. May contain IFDs.
directory.setPosition(0);
const ByteStream valueData(directory.getStream(valueDataSize));
// count of the Directory entries in this IFD
const ushort16 entryCount = directory.getU16();
// each entry is 10 bytes
ByteStream dirEntries(directory.getStream(entryCount, 10));
// IFDData might still contain OtherData until the valueDataSize at the end.
// But we do not care about that.
// Each IFD has it's own valueData area.
// In that area, no two entries may overlap.
NORangesSet<Buffer> valueDatas;
for (uint32 i = 0; i < entryCount; i++)
parseIFDEntry(&valueDatas, &valueData, &dirEntries);
assert(valueDatas.size() <= entryCount);
assert(mEntry.size() <= CiffTagsWeCareAbout.size());
assert(mSubIFD.size() == decltype(mSubIFD)::size_type(subIFDCount));
assert(subIFDCount <= subIFDCountRecursive);
assert(mEntry.size() + mSubIFD.size() <= entryCount);
}
void CiffIFD::recursivelyIncrementSubIFDCount() {
CiffIFD* p = this->parent;
if (!p)
return;
p->subIFDCount++;
for (; p != nullptr; p = p->parent)
p->subIFDCountRecursive++;
}
void CiffIFD::checkSubIFDs(int headroom) const {
int count = headroom + subIFDCount;
if (!headroom)
assert(count <= CiffIFD::Limits::SubIFDCount);
else if (count > CiffIFD::Limits::SubIFDCount)
ThrowCPE("TIFF IFD has %u SubIFDs", count);
count = headroom + subIFDCountRecursive;
if (!headroom)
assert(count <= CiffIFD::Limits::RecursiveSubIFDCount);
else if (count > CiffIFD::Limits::RecursiveSubIFDCount)
ThrowCPE("TIFF IFD file has %u SubIFDs (recursively)", count);
}
void CiffIFD::recursivelyCheckSubIFDs(int headroom) const {
int depth = 0;
for (const CiffIFD* p = this; p != nullptr;) {
if (!headroom)
assert(depth <= CiffIFD::Limits::Depth);
else if (depth > CiffIFD::Limits::Depth)
ThrowCPE("CiffIFD cascading overflow, found %u level IFD", depth);
p->checkSubIFDs(headroom);
// And step up
p = p->parent;
depth++;
}
}
void CiffIFD::add(std::unique_ptr<CiffIFD> subIFD) {
assert(subIFD->parent == this);
// We are good, and actually can add this sub-IFD, right?
subIFD->recursivelyCheckSubIFDs(0);
mSubIFD.push_back(move(subIFD));
}
void CiffIFD::add(std::unique_ptr<CiffEntry> entry) {
assert(isIn(entry->tag, CiffTagsWeCareAbout));
mEntry[entry->tag] = move(entry);
assert(mEntry.size() <= CiffTagsWeCareAbout.size());
}
template <typename Lambda>
std::vector<const CiffIFD*> CiffIFD::getIFDsWithTagIf(CiffTag tag,
const Lambda& f) const {
assert(isIn(tag, CiffTagsWeCareAbout));
std::vector<const CiffIFD*> matchingIFDs;
const auto found = mEntry.find(tag);
if (found != mEntry.end()) {
const auto entry = found->second.get();
if (f(entry))
matchingIFDs.push_back(this);
}
for (const auto& i : mSubIFD) {
const auto t = i->getIFDsWithTagIf(tag, f);
matchingIFDs.insert(matchingIFDs.end(), t.begin(), t.end());
}
return matchingIFDs;
}
template <typename Lambda>
const CiffEntry* CiffIFD::getEntryRecursiveIf(CiffTag tag,
const Lambda& f) const {
assert(isIn(tag, CiffTagsWeCareAbout));
const auto found = mEntry.find(tag);
if (found != mEntry.end()) {
const auto entry = found->second.get();
if (f(entry))
return entry;
}
for (const auto& i : mSubIFD) {
const CiffEntry* entry = i->getEntryRecursiveIf(tag, f);
if (entry)
return entry;
}
return nullptr;
}
vector<const CiffIFD*> CiffIFD::getIFDsWithTag(CiffTag tag) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getIFDsWithTagIf(tag, [](const CiffEntry*) { return true; });
}
vector<const CiffIFD*> CiffIFD::getIFDsWithTagWhere(CiffTag tag,
uint32 isValue) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getIFDsWithTagIf(tag, [&isValue](const CiffEntry* entry) {
return entry->isInt() && entry->getU32() == isValue;
});
}
vector<const CiffIFD*>
CiffIFD::getIFDsWithTagWhere(CiffTag tag, const string& isValue) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getIFDsWithTagIf(tag, [&isValue](const CiffEntry* entry) {
return entry->isString() && isValue == entry->getString();
});
}
bool __attribute__((pure)) CiffIFD::hasEntry(CiffTag tag) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return mEntry.count(tag) > 0;
}
bool __attribute__((pure)) CiffIFD::hasEntryRecursive(CiffTag tag) const {
assert(isIn(tag, CiffTagsWeCareAbout));
if (mEntry.count(tag) > 0)
return true;
for (const auto& i : mSubIFD) {
if (i->hasEntryRecursive(tag))
return true;
}
return false;
}
const CiffEntry* CiffIFD::getEntry(CiffTag tag) const {
assert(isIn(tag, CiffTagsWeCareAbout));
const auto found = mEntry.find(tag);
if (found != mEntry.end())
return found->second.get();
ThrowCPE("Entry 0x%x not found.", tag);
}
const CiffEntry* CiffIFD::getEntryRecursive(CiffTag tag) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getEntryRecursiveIf(tag, [](const CiffEntry*) { return true; });
}
const CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag,
uint32 isValue) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getEntryRecursiveIf(tag, [&isValue](const CiffEntry* entry) {
return entry->isInt() && entry->getU32() == isValue;
});
}
const CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag,
const string& isValue) const {
assert(isIn(tag, CiffTagsWeCareAbout));
return getEntryRecursiveIf(tag, [&isValue](const CiffEntry* entry) {
return entry->isString() && isValue == entry->getString();
});
}
} // namespace rawspeed
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/eval/onnx/onnx_wrapper.h>
#include <vespa/eval/eval/tensor_spec.h>
#include <vespa/eval/eval/value_codec.h>
#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/test/test_io.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/vespalib/util/require.h>
#include <vespa/vespalib/util/guard.h>
#include <vespa/vespalib/util/stringfmt.h>
using vespalib::make_string_short::fmt;
using vespalib::Slime;
using vespalib::slime::JsonFormat;
using vespalib::slime::Inspector;
using vespalib::slime::Cursor;
using vespalib::FilePointer;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
struct MyError {
vespalib::string msg;
};
bool read_line(FilePointer &file, vespalib::string &line) {
char line_buffer[1024];
char *res = fgets(line_buffer, sizeof(line_buffer), file.fp());
if (res == nullptr) {
line.clear();
return false;
}
line = line_buffer;
while (!line.empty() && isspace(line[line.size() - 1])) {
line.pop_back();
}
return true;
}
void extract(const vespalib::string &str, const vespalib::string &prefix, vespalib::string &dst) {
if (starts_with(str, prefix)) {
size_t pos = prefix.size();
while ((str.size() > pos) && isspace(str[pos])) {
++pos;
}
dst = str.substr(pos);
}
}
void report_memory_usage(const vespalib::string &desc) {
vespalib::string vm_size = "unknown";
vespalib::string vm_rss = "unknown";
vespalib::string line;
FilePointer file(fopen("/proc/self/status", "r"));
while (read_line(file, line)) {
extract(line, "VmSize:", vm_size);
extract(line, "VmRSS:", vm_rss);
}
fprintf(stderr, "vm_size: %s, vm_rss: %s (%s)\n", vm_size.c_str(), vm_rss.c_str(), desc.c_str());
}
struct Options {
size_t pos = 0;
std::vector<vespalib::string> opt_list;
void add_option(const vespalib::string &opt) {
opt_list.push_back(opt);
}
vespalib::string get_option(const vespalib::string &desc, const vespalib::string &fallback) {
vespalib::string opt;
if (pos < opt_list.size()) {
opt = opt_list[pos];
fprintf(stderr, "option[%zu](%s): %s\n",
pos, desc.c_str(), opt.c_str());
} else {
opt = fallback;
fprintf(stderr, "unspecified option[%zu](%s), fallback: %s\n",
pos, desc.c_str(), fallback.c_str());
}
++pos;
return opt;
}
bool get_bool_opt(const vespalib::string &desc, const vespalib::string &fallback) {
auto opt = get_option(desc, fallback);
REQUIRE((opt == "true") || (opt == "false"));
return (opt == "true");
}
size_t get_size_opt(const vespalib::string &desc, const vespalib::string &fallback) {
auto opt = get_option(desc, fallback);
size_t value = atoi(opt.c_str());
REQUIRE(value > 0);
return value;
}
};
void dump_model_info(const Onnx &model) {
fprintf(stderr, "model meta-data:\n");
for (size_t i = 0; i < model.inputs().size(); ++i) {
fprintf(stderr, " input[%zu]: '%s' %s\n", i, model.inputs()[i].name.c_str(), model.inputs()[i].type_as_string().c_str());
}
for (size_t i = 0; i < model.outputs().size(); ++i) {
fprintf(stderr, " output[%zu]: '%s' %s\n", i, model.outputs()[i].name.c_str(), model.outputs()[i].type_as_string().c_str());
}
}
void dump_wire_info(const Onnx::WireInfo &wire) {
fprintf(stderr, "test setup:\n");
REQUIRE_EQ(wire.vespa_inputs.size(), wire.onnx_inputs.size());
for (size_t i = 0; i < wire.vespa_inputs.size(); ++i) {
fprintf(stderr, " input[%zu]: %s -> %s\n", i, wire.vespa_inputs[i].to_spec().c_str(), wire.onnx_inputs[i].type_as_string().c_str());
}
REQUIRE_EQ(wire.onnx_outputs.size(), wire.vespa_outputs.size());
for (size_t i = 0; i < wire.onnx_outputs.size(); ++i) {
fprintf(stderr, " output[%zu]: %s -> %s\n", i, wire.onnx_outputs[i].type_as_string().c_str(), wire.vespa_outputs[i].to_spec().c_str());
}
}
struct MakeInputType {
Options &opts;
std::map<vespalib::string,int> symbolic_sizes;
MakeInputType(Options &opts_in) : opts(opts_in), symbolic_sizes() {}
ValueType operator()(const Onnx::TensorInfo &info) {
int d = 0;
std::vector<ValueType::Dimension> dim_list;
for (const auto &dim: info.dimensions) {
REQUIRE(d <= 9);
size_t size = 0;
if (dim.is_known()) {
size = dim.value;
} else if (dim.is_symbolic()) {
size = symbolic_sizes[dim.name];
if (size == 0) {
size = opts.get_size_opt(fmt("symbolic size '%s'", dim.name.c_str()), "1");
symbolic_sizes[dim.name] = size;
}
} else {
size = opts.get_size_opt(fmt("size of input '%s' dimension %d", info.name.c_str(), d), "1");
}
dim_list.emplace_back(fmt("d%d", d), size);
++d;
}
return ValueType::make_type(Onnx::WirePlanner::best_cell_type(info.elements), std::move(dim_list));
}
};
vespalib::string make_bound_str(const std::map<vespalib::string,size_t> &bound) {
vespalib::string result;
if (!bound.empty()) {
for (const auto &[name, size]: bound) {
if (result.empty()) {
result.append(" (");
} else {
result.append(",");
}
result.append(fmt("%s=%zu", name.c_str(), size));
}
result.append(")");
}
return result;
}
void bind_input(Onnx::WirePlanner &planner, const Onnx::TensorInfo &input, const ValueType &type) {
auto bound = planner.get_bound_sizes(input);
if (!planner.bind_input_type(type, input)) {
auto bound_str = make_bound_str(bound);
throw MyError{fmt("incompatible type for input '%s': %s -> %s%s",
input.name.c_str(), type.to_spec().c_str(), input.type_as_string().c_str(), bound_str.c_str())};
}
}
ValueType make_output(const Onnx::WirePlanner &planner, const Onnx::TensorInfo &output) {
auto type = planner.make_output_type(output);
if (type.is_error()) {
throw MyError{fmt("unable to make compatible type for output '%s': %s -> error",
output.name.c_str(), output.type_as_string().c_str())};
}
return type;
}
Onnx::WireInfo make_plan(Options &opts, const Onnx &model) {
Onnx::WirePlanner planner;
MakeInputType make_input_type(opts);
for (const auto &input: model.inputs()) {
auto type = make_input_type(input);
bind_input(planner, input, type);
}
planner.prepare_output_types(model);
for (const auto &output: model.outputs()) {
make_output(planner, output);
}
return planner.get_wire_info(model);
}
struct MyEval {
Onnx::EvalContext context;
std::vector<Value::UP> inputs;
MyEval(const Onnx &model, const Onnx::WireInfo &wire) : context(model, wire), inputs() {
for (const auto &input_type: wire.vespa_inputs) {
TensorSpec spec(input_type.to_spec());
inputs.push_back(value_from_spec(spec, FastValueBuilderFactory::get()));
}
}
void eval() {
for (size_t i = 0; i < inputs.size(); ++i) {
context.bind_param(i, *inputs[i]);
}
context.eval();
}
};
int usage(const char *self) {
fprintf(stderr, "usage: %s <onnx-model> [options...]\n", self);
fprintf(stderr, " load onnx model and report memory usage\n");
fprintf(stderr, " options are used to specify unknown values, like dimension sizes\n");
fprintf(stderr, " options are accepted in the order in which they are needed\n");
fprintf(stderr, " tip: run without options first, to see which you need\n\n");
fprintf(stderr, "usage: %s --probe-types\n", self);
fprintf(stderr, " use onnx model to infer/probe output types based on input types\n");
fprintf(stderr, " parameters are read from stdin and results are written to stdout\n");
fprintf(stderr, " input format (json): {model:<filename>, inputs:{<name>:vespa-type-string}}\n");
fprintf(stderr, " output format (json): {outputs:{<name>:vespa-type-string}}\n");
return 1;
}
int probe_types() {
StdIn std_in;
StdOut std_out;
Slime params;
if (!JsonFormat::decode(std_in, params)) {
throw MyError{"invalid json"};
}
Slime result;
auto &root = result.setObject();
auto &types = root.setObject("outputs");
Onnx model(params["model"].asString().make_string(), Onnx::Optimize::DISABLE);
Onnx::WirePlanner planner;
for (size_t i = 0; i < model.inputs().size(); ++i) {
auto spec = params["inputs"][model.inputs()[i].name].asString().make_string();
auto input_type = ValueType::from_spec(spec);
if (input_type.is_error()) {
if (!params["inputs"][model.inputs()[i].name].valid()) {
throw MyError{fmt("missing type for model input '%s'",
model.inputs()[i].name.c_str())};
} else {
throw MyError{fmt("invalid type for model input '%s': '%s'",
model.inputs()[i].name.c_str(), spec.c_str())};
}
}
bind_input(planner, model.inputs()[i], input_type);
}
planner.prepare_output_types(model);
for (const auto &output: model.outputs()) {
auto output_type = make_output(planner, output);
types.setString(output.name, output_type.to_spec());
}
write_compact(result, std_out);
return 0;
}
int my_main(int argc, char **argv) {
if (argc < 2) {
return usage(argv[0]);
}
if ((argc == 2) && (vespalib::string(argv[1]) == "--probe-types")) {
return probe_types();
}
Options opts;
for (int i = 2; i < argc; ++i) {
opts.add_option(argv[i]);
}
Onnx::Optimize optimize = opts.get_bool_opt("optimize model", "true")
? Onnx::Optimize::ENABLE : Onnx::Optimize::DISABLE;
report_memory_usage("before loading model");
Onnx model(argv[1], optimize);
report_memory_usage("after loading model");
dump_model_info(model);
auto wire_info = make_plan(opts, model);
dump_wire_info(wire_info);
std::vector<std::unique_ptr<MyEval>> eval_list;
size_t max_concurrent = opts.get_size_opt("max concurrent evaluations", "1");
report_memory_usage("no evaluations yet");
for (size_t i = 1; i <= max_concurrent; ++i) {
eval_list.push_back(std::make_unique<MyEval>(model, wire_info));
eval_list.back()->eval();
if ((i % 8) == 0) {
report_memory_usage(fmt("concurrent evaluations: %zu", i));
}
}
if ((max_concurrent % 8) != 0) {
report_memory_usage(fmt("concurrent evaluations: %zu", max_concurrent));
}
eval_list.resize(1);
double min_time_s = vespalib::BenchmarkTimer::benchmark([&e = *eval_list.back()](){ e.eval(); }, 10.0);
fprintf(stderr, "estimated model evaluation time: %g ms\n", min_time_s * 1000.0);
return 0;
}
int main(int argc, char **argv) {
try {
return my_main(argc, argv);
} catch (const MyError &err) {
fprintf(stderr, "error: %s\n", err.msg.c_str());
return 3;
} catch (const std::exception &ex) {
fprintf(stderr, "got exception: %s\n", ex.what());
return 2;
}
}
<commit_msg>use stdout for 'error' result<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/eval/onnx/onnx_wrapper.h>
#include <vespa/eval/eval/tensor_spec.h>
#include <vespa/eval/eval/value_codec.h>
#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/test/test_io.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/vespalib/util/require.h>
#include <vespa/vespalib/util/guard.h>
#include <vespa/vespalib/util/stringfmt.h>
using vespalib::make_string_short::fmt;
using vespalib::Slime;
using vespalib::slime::JsonFormat;
using vespalib::slime::Inspector;
using vespalib::slime::Cursor;
using vespalib::FilePointer;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
struct MyError {
vespalib::string msg;
};
bool read_line(FilePointer &file, vespalib::string &line) {
char line_buffer[1024];
char *res = fgets(line_buffer, sizeof(line_buffer), file.fp());
if (res == nullptr) {
line.clear();
return false;
}
line = line_buffer;
while (!line.empty() && isspace(line[line.size() - 1])) {
line.pop_back();
}
return true;
}
void extract(const vespalib::string &str, const vespalib::string &prefix, vespalib::string &dst) {
if (starts_with(str, prefix)) {
size_t pos = prefix.size();
while ((str.size() > pos) && isspace(str[pos])) {
++pos;
}
dst = str.substr(pos);
}
}
void report_memory_usage(const vespalib::string &desc) {
vespalib::string vm_size = "unknown";
vespalib::string vm_rss = "unknown";
vespalib::string line;
FilePointer file(fopen("/proc/self/status", "r"));
while (read_line(file, line)) {
extract(line, "VmSize:", vm_size);
extract(line, "VmRSS:", vm_rss);
}
fprintf(stderr, "vm_size: %s, vm_rss: %s (%s)\n", vm_size.c_str(), vm_rss.c_str(), desc.c_str());
}
struct Options {
size_t pos = 0;
std::vector<vespalib::string> opt_list;
void add_option(const vespalib::string &opt) {
opt_list.push_back(opt);
}
vespalib::string get_option(const vespalib::string &desc, const vespalib::string &fallback) {
vespalib::string opt;
if (pos < opt_list.size()) {
opt = opt_list[pos];
fprintf(stderr, "option[%zu](%s): %s\n",
pos, desc.c_str(), opt.c_str());
} else {
opt = fallback;
fprintf(stderr, "unspecified option[%zu](%s), fallback: %s\n",
pos, desc.c_str(), fallback.c_str());
}
++pos;
return opt;
}
bool get_bool_opt(const vespalib::string &desc, const vespalib::string &fallback) {
auto opt = get_option(desc, fallback);
REQUIRE((opt == "true") || (opt == "false"));
return (opt == "true");
}
size_t get_size_opt(const vespalib::string &desc, const vespalib::string &fallback) {
auto opt = get_option(desc, fallback);
size_t value = atoi(opt.c_str());
REQUIRE(value > 0);
return value;
}
};
void dump_model_info(const Onnx &model) {
fprintf(stderr, "model meta-data:\n");
for (size_t i = 0; i < model.inputs().size(); ++i) {
fprintf(stderr, " input[%zu]: '%s' %s\n", i, model.inputs()[i].name.c_str(), model.inputs()[i].type_as_string().c_str());
}
for (size_t i = 0; i < model.outputs().size(); ++i) {
fprintf(stderr, " output[%zu]: '%s' %s\n", i, model.outputs()[i].name.c_str(), model.outputs()[i].type_as_string().c_str());
}
}
void dump_wire_info(const Onnx::WireInfo &wire) {
fprintf(stderr, "test setup:\n");
REQUIRE_EQ(wire.vespa_inputs.size(), wire.onnx_inputs.size());
for (size_t i = 0; i < wire.vespa_inputs.size(); ++i) {
fprintf(stderr, " input[%zu]: %s -> %s\n", i, wire.vespa_inputs[i].to_spec().c_str(), wire.onnx_inputs[i].type_as_string().c_str());
}
REQUIRE_EQ(wire.onnx_outputs.size(), wire.vespa_outputs.size());
for (size_t i = 0; i < wire.onnx_outputs.size(); ++i) {
fprintf(stderr, " output[%zu]: %s -> %s\n", i, wire.onnx_outputs[i].type_as_string().c_str(), wire.vespa_outputs[i].to_spec().c_str());
}
}
struct MakeInputType {
Options &opts;
std::map<vespalib::string,int> symbolic_sizes;
MakeInputType(Options &opts_in) : opts(opts_in), symbolic_sizes() {}
ValueType operator()(const Onnx::TensorInfo &info) {
int d = 0;
std::vector<ValueType::Dimension> dim_list;
for (const auto &dim: info.dimensions) {
REQUIRE(d <= 9);
size_t size = 0;
if (dim.is_known()) {
size = dim.value;
} else if (dim.is_symbolic()) {
size = symbolic_sizes[dim.name];
if (size == 0) {
size = opts.get_size_opt(fmt("symbolic size '%s'", dim.name.c_str()), "1");
symbolic_sizes[dim.name] = size;
}
} else {
size = opts.get_size_opt(fmt("size of input '%s' dimension %d", info.name.c_str(), d), "1");
}
dim_list.emplace_back(fmt("d%d", d), size);
++d;
}
return ValueType::make_type(Onnx::WirePlanner::best_cell_type(info.elements), std::move(dim_list));
}
};
vespalib::string make_bound_str(const std::map<vespalib::string,size_t> &bound) {
vespalib::string result;
if (!bound.empty()) {
for (const auto &[name, size]: bound) {
if (result.empty()) {
result.append(" (");
} else {
result.append(",");
}
result.append(fmt("%s=%zu", name.c_str(), size));
}
result.append(")");
}
return result;
}
void bind_input(Onnx::WirePlanner &planner, const Onnx::TensorInfo &input, const ValueType &type) {
auto bound = planner.get_bound_sizes(input);
if (!planner.bind_input_type(type, input)) {
auto bound_str = make_bound_str(bound);
throw MyError{fmt("incompatible type for input '%s': %s -> %s%s",
input.name.c_str(), type.to_spec().c_str(), input.type_as_string().c_str(), bound_str.c_str())};
}
}
ValueType make_output(const Onnx::WirePlanner &planner, const Onnx::TensorInfo &output) {
auto type = planner.make_output_type(output);
if (type.is_error()) {
throw MyError{fmt("unable to make compatible type for output '%s': %s -> error",
output.name.c_str(), output.type_as_string().c_str())};
}
return type;
}
Onnx::WireInfo make_plan(Options &opts, const Onnx &model) {
Onnx::WirePlanner planner;
MakeInputType make_input_type(opts);
for (const auto &input: model.inputs()) {
auto type = make_input_type(input);
bind_input(planner, input, type);
}
planner.prepare_output_types(model);
for (const auto &output: model.outputs()) {
make_output(planner, output);
}
return planner.get_wire_info(model);
}
struct MyEval {
Onnx::EvalContext context;
std::vector<Value::UP> inputs;
MyEval(const Onnx &model, const Onnx::WireInfo &wire) : context(model, wire), inputs() {
for (const auto &input_type: wire.vespa_inputs) {
TensorSpec spec(input_type.to_spec());
inputs.push_back(value_from_spec(spec, FastValueBuilderFactory::get()));
}
}
void eval() {
for (size_t i = 0; i < inputs.size(); ++i) {
context.bind_param(i, *inputs[i]);
}
context.eval();
}
};
int usage(const char *self) {
fprintf(stderr, "usage: %s <onnx-model> [options...]\n", self);
fprintf(stderr, " load onnx model and report memory usage\n");
fprintf(stderr, " options are used to specify unknown values, like dimension sizes\n");
fprintf(stderr, " options are accepted in the order in which they are needed\n");
fprintf(stderr, " tip: run without options first, to see which you need\n\n");
fprintf(stderr, "usage: %s --probe-types\n", self);
fprintf(stderr, " use onnx model to infer/probe output types based on input types\n");
fprintf(stderr, " parameters are read from stdin and results are written to stdout\n");
fprintf(stderr, " input format (json): {model:<filename>, inputs:{<name>:vespa-type-string}}\n");
fprintf(stderr, " output format (json): {outputs:{<name>:vespa-type-string}}\n");
return 1;
}
int probe_types() {
StdIn std_in;
StdOut std_out;
Slime params;
if (!JsonFormat::decode(std_in, params)) {
throw MyError{"invalid json"};
}
Slime result;
auto &root = result.setObject();
auto &types = root.setObject("outputs");
Onnx model(params["model"].asString().make_string(), Onnx::Optimize::DISABLE);
Onnx::WirePlanner planner;
for (size_t i = 0; i < model.inputs().size(); ++i) {
auto spec = params["inputs"][model.inputs()[i].name].asString().make_string();
auto input_type = ValueType::from_spec(spec);
if (input_type.is_error()) {
if (!params["inputs"][model.inputs()[i].name].valid()) {
throw MyError{fmt("missing type for model input '%s'",
model.inputs()[i].name.c_str())};
} else {
throw MyError{fmt("invalid type for model input '%s': '%s'",
model.inputs()[i].name.c_str(), spec.c_str())};
}
}
bind_input(planner, model.inputs()[i], input_type);
}
planner.prepare_output_types(model);
for (const auto &output: model.outputs()) {
auto output_type = make_output(planner, output);
types.setString(output.name, output_type.to_spec());
}
write_compact(result, std_out);
return 0;
}
int my_main(int argc, char **argv) {
if (argc < 2) {
return usage(argv[0]);
}
if ((argc == 2) && (vespalib::string(argv[1]) == "--probe-types")) {
return probe_types();
}
Options opts;
for (int i = 2; i < argc; ++i) {
opts.add_option(argv[i]);
}
Onnx::Optimize optimize = opts.get_bool_opt("optimize model", "true")
? Onnx::Optimize::ENABLE : Onnx::Optimize::DISABLE;
report_memory_usage("before loading model");
Onnx model(argv[1], optimize);
report_memory_usage("after loading model");
dump_model_info(model);
auto wire_info = make_plan(opts, model);
dump_wire_info(wire_info);
std::vector<std::unique_ptr<MyEval>> eval_list;
size_t max_concurrent = opts.get_size_opt("max concurrent evaluations", "1");
report_memory_usage("no evaluations yet");
for (size_t i = 1; i <= max_concurrent; ++i) {
eval_list.push_back(std::make_unique<MyEval>(model, wire_info));
eval_list.back()->eval();
if ((i % 8) == 0) {
report_memory_usage(fmt("concurrent evaluations: %zu", i));
}
}
if ((max_concurrent % 8) != 0) {
report_memory_usage(fmt("concurrent evaluations: %zu", max_concurrent));
}
eval_list.resize(1);
double min_time_s = vespalib::BenchmarkTimer::benchmark([&e = *eval_list.back()](){ e.eval(); }, 10.0);
fprintf(stderr, "estimated model evaluation time: %g ms\n", min_time_s * 1000.0);
return 0;
}
int main(int argc, char **argv) {
try {
return my_main(argc, argv);
} catch (const MyError &err) {
fprintf(stdout, "error: %s\n", err.msg.c_str());
return 3;
} catch (const std::exception &ex) {
fprintf(stdout, "got exception: %s\n", ex.what());
return 2;
}
}
<|endoftext|> |
<commit_before>#include <sl.h>
#include <push.h>
#include "NvidiaGpu.h"
#include <hwinfo.h>
#include "NvThermalDiode\NvThermalDiode.h"
#include "nvapi.h"
BYTE GfCoreFamily = 0;
LONG m_dwDiodeGainMul;
LONG GetDiodeGainMul( DWORD coreFamily );
INT32 *displayHandles;
BOOLEAN GfInitialized;
BOOLEAN
InitGeForce()
{
if (GfInitialized)
return TRUE;
GfCoreFamily = (ReadGpuRegister(0) >> 20) & 0xff;
//m_dwDiodeGainMul = GetDiodeGainMul(GfCoreFamily);
GfInitialized = TRUE;
NvtdInitialize();
return TRUE;
}
/*//////////////////////////////////////////////////////////////////////
// Get default thermal diode gain mul calibration parameter for
// thermal diode capable GPUs
//////////////////////////////////////////////////////////////////////
LONG
GetDiodeGainMul( DWORD coreFamily )
{
switch (coreFamily)
{
case 0x43:
//NV43
return 792;
break;
case 0x44:
case 0x4A:
case 0x47:
//NV44 and G70
return 780;
break;
case 0x46:
case 0x49:
case 0x4B:
//G71, G72 and G73
return 450;
break;
case 0x50:
//G80
return 430;
break;
case 0x84:
case 0x86:
case 0x94:
//G84, G86 and G94
return 1;
break;
case 0x92:
//G92
return 10;
break;
default:
//return 0 if GPU has no on-die thermal diode
return 0;
}
}*/
static int CalcSpeed_nv50(int base_freq, int m1, int m2, int n1, int n2, int p)
{
return (int)((float)(n1*n2) / (m1*m2) * base_freq) >> p;
}
float GetClock_nv50(int base_freq, unsigned int pll, unsigned int pll2)
{
int m1, m2, n1, n2, p;
p = (pll >> 16) & 0x03;
m1 = pll2 & 0xFF;
n1 = (pll2 >> 8) & 0xFF;
/* This is always 1 for NV5x? */
m2 = 1;
n2 = 1;
/*if (nv_card->debug)
printf("m1=%d m2=%d n1=%d n2=%d p=%d\n", m1, m2, n1, n2, p);*/
/* The clocks need to be multiplied by 4 for some reason. Is this 4 stored in 0x4000/0x4004? */
return (float)4 * CalcSpeed_nv50(base_freq, m1, m2, n1, n2, p) / 1000;
}
static float nv50_get_gpu_speed()
{
int pll = ReadGpuRegister(0x4024);
int pll2 = ReadGpuRegister(0x402c);
int base_freq = 27000;
return (float)GetClock_nv50(base_freq, pll, pll2);
}
NvidiaGpu::NvidiaGpu()
{
Nvapi_Initialize();
}
UINT16
NvidiaGpu::GetEngineClock()
{
return nv50_get_gpu_speed();
}
UINT16
NvidiaGpu::GetMemoryClock()
{
return Nvapi_GetMemoryClock();
}
UINT64 NvidiaGpu::GetTotalMemory()
{
return Nvapi_GetTotalMemory();
}
UINT64 NvidiaGpu::GetFreeMemory()
{
return Nvapi_GetFreeMemory();
}
UINT8
NvidiaGpu::GetTemperature()
{
if (!InitGeForce())
return 0;
return NvtdGetTemperature();
}
UINT8
NvidiaGpu::GetLoad()
{
return Nvapi_GetActivity();
}
UINT16
NvidiaGpu::GetMaximumEngineClock()
{
return Nvapi_GetMaxEngineClock();
}
UINT16
NvidiaGpu::GetMaximumMemoryClock()
{
return Nvapi_GetMaxMemoryClock();
}
VOID
NvidiaGpu::ForceMaximumClocks()
{
}<commit_msg>implemented clocks<commit_after>#include <sl.h>
#include <push.h>
#include "NvidiaGpu.h"
#include <hwinfo.h>
#include "NvThermalDiode\NvThermalDiode.h"
#include "nvapi.h"
BYTE GfCoreFamily = 0;
LONG m_dwDiodeGainMul;
LONG GetDiodeGainMul( DWORD coreFamily );
INT32 *displayHandles;
BOOLEAN GfInitialized;
BOOLEAN
InitGeForce()
{
if (GfInitialized)
return TRUE;
GfCoreFamily = (ReadGpuRegister(0) >> 20) & 0xff;
//m_dwDiodeGainMul = GetDiodeGainMul(GfCoreFamily);
GfInitialized = TRUE;
NvtdInitialize();
return TRUE;
}
static int CalcSpeed_nv50(int base_freq, int m1, int m2, int n1, int n2, int p)
{
return (int)((float)(n1*n2) / (m1*m2) * base_freq) >> p;
}
float GetClock_nv50(int base_freq, unsigned int pll, unsigned int pll2)
{
int m1, m2, n1, n2, p;
p = (pll >> 16) & 0x03;
m1 = pll2 & 0xFF;
n1 = (pll2 >> 8) & 0xFF;
/* This is always 1 for NV5x? */
m2 = 1;
n2 = 1;
/* The clocks need to be multiplied by 4 for some reason. Is this 4 stored in 0x4000/0x4004? */
return (float)4 * CalcSpeed_nv50(base_freq, m1, m2, n1, n2, p) / 1000;
}
float nv50_get_gpu_speed()
{
int pll = ReadGpuRegister(0x4028);
int pll2 = ReadGpuRegister(0x402c);
int base_freq = 25000;
return (float)GetClock_nv50(base_freq, pll, pll2);
}
float nv50_get_memory_speed()
{
int pll = ReadGpuRegister(0x4008);
int pll2 = ReadGpuRegister(0x400c);
int base_freq = 27000;
return (float)GetClock_nv50(base_freq, pll, pll2);
}
NvidiaGpu::NvidiaGpu()
{
Nvapi_Initialize();
}
UINT16 NvidiaGpu::GetEngineClock()
{
return nv50_get_gpu_speed();
}
UINT16 NvidiaGpu::GetMemoryClock()
{
return nv50_get_memory_speed();
}
UINT64 NvidiaGpu::GetTotalMemory()
{
return Nvapi_GetTotalMemory();
}
UINT64 NvidiaGpu::GetFreeMemory()
{
return Nvapi_GetFreeMemory();
}
UINT8
NvidiaGpu::GetTemperature()
{
if (!InitGeForce())
return 0;
return NvtdGetTemperature();
}
UINT8
NvidiaGpu::GetLoad()
{
return Nvapi_GetActivity();
}
UINT16
NvidiaGpu::GetMaximumEngineClock()
{
return Nvapi_GetMaxEngineClock();
}
UINT16
NvidiaGpu::GetMaximumMemoryClock()
{
return Nvapi_GetMaxMemoryClock();
}
VOID
NvidiaGpu::ForceMaximumClocks()
{
}<|endoftext|> |
<commit_before>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* Raphael Hiesgen <raphael.hiesgen@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License *
* or (at your option) any later version. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef CPPA_OPENCL_COMMAND_DISPATCHER_HPP
#define CPPA_OPENCL_COMMAND_DISPATCHER_HPP
#include <atomic>
#include <vector>
#include <algorithm>
#include <functional>
#include "cppa/option.hpp"
#include "cppa/channel.hpp"
#include "cppa/cow_tuple.hpp"
#include "cppa/logging.hpp"
#include "cppa/opencl/global.hpp"
#include "cppa/opencl/command.hpp"
#include "cppa/opencl/program.hpp"
#include "cppa/opencl/smart_ptr.hpp"
#include "cppa/opencl/actor_facade.hpp"
#include "cppa/detail/singleton_mixin.hpp"
#include "cppa/detail/singleton_manager.hpp"
#include "cppa/intrusive/blocking_single_reader_queue.hpp"
namespace cppa { namespace opencl {
struct dereferencer {
inline void operator()(ref_counted* ptr) { ptr->deref(); }
};
template<typename... Ts>
option<cow_tuple<Ts...>> default_map_args(any_tuple msg) {
return tuple_cast<Ts...>(msg);
}
#ifdef CPPA_OPENCL
class command_dispatcher {
struct worker;
friend struct worker;
friend class detail::singleton_manager;
friend class program;
friend void enqueue_to_dispatcher(command_dispatcher* dispatcher,
command_ptr cmd);
public:
void enqueue();
template<typename Ret, typename... Args>
actor_ptr spawn(const program& prog,
const char* kernel_name,
std::vector<size_t> global_dims,
std::vector<size_t> local_dims,
std::function<option<cow_tuple<typename util::rm_ref<Args>::type...>>(any_tuple)> map_args,
std::function<any_tuple(Ret&)> map_result)
{
auto i = std::find(local_dims.begin(), local_dims.end(), 0);
if (i != local_dims.end()) local_dims.clear();
return new actor_facade<Ret (Args...)>(this,
prog,
kernel_name,
global_dims,
local_dims,
map_args,
map_result);
}
template<typename Ret, typename... Args>
actor_ptr spawn(const program& prog,
const char* kernel_name,
std::vector<size_t> global_dims = {1,1,1},
std::vector<size_t> local_dims = {0,0,0})
{
std::function<option<cow_tuple<typename util::rm_ref<Args>::type...>>(any_tuple)> f0 = [] (any_tuple msg) {
return tuple_cast<typename util::rm_ref<Args>::type...>(msg);
};
std::function<any_tuple(Ret&)> f1 = [] (Ret& result) {
return make_any_tuple(std::move(result));
};
return this->spawn<Ret,Args...>(prog,
kernel_name,
global_dims,
local_dims,
std::move(f0),
std::move(f1));
}
private:
struct device_info {
unsigned id;
command_queue_ptr cmd_queue;
device_ptr dev_id;
size_t max_itms_per_grp;
cl_uint max_dim;
std::vector<size_t> max_itms_per_dim;
device_info(unsigned id,
command_queue_ptr queue,
device_ptr device_id,
size_t max_itms_per_grp,
cl_uint max_dim,
std::vector<size_t> max_itms_per_dim)
: id(id)
, cmd_queue(queue)
, dev_id(device_id)
, max_itms_per_grp(max_itms_per_grp)
, max_dim(max_dim)
, max_itms_per_dim(std::move(max_itms_per_dim)) { }
};
typedef intrusive::blocking_single_reader_queue<command,dereferencer>
job_queue;
static inline command_dispatcher* create_singleton() {
return new command_dispatcher;
}
void initialize();
void dispose();
void destroy();
std::atomic<unsigned> dev_id_gen;
job_queue m_job_queue;
command_ptr m_dummy;
std::thread m_supervisor;
std::vector<device_info> m_devices;
context_ptr m_context;
static void worker_loop(worker*);
static void supervisor_loop(command_dispatcher *scheduler,
job_queue*,
command_ptr);
};
#else // CPPA_OPENCL
class command_dispatcher : public detail::singleton_mixin<command_dispatcher> { };
#endif // CPPA_OPENCL
command_dispatcher* get_command_dispatcher();
} } // namespace cppa::opencl
#endif // CPPA_OPENCL_COMMAND_DISPATCHER_HPP
<commit_msg>small code optimization<commit_after>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* Raphael Hiesgen <raphael.hiesgen@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License *
* or (at your option) any later version. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef CPPA_OPENCL_COMMAND_DISPATCHER_HPP
#define CPPA_OPENCL_COMMAND_DISPATCHER_HPP
#include <atomic>
#include <vector>
#include <algorithm>
#include <functional>
#include "cppa/option.hpp"
#include "cppa/channel.hpp"
#include "cppa/cow_tuple.hpp"
#include "cppa/logging.hpp"
#include "cppa/opencl/global.hpp"
#include "cppa/opencl/command.hpp"
#include "cppa/opencl/program.hpp"
#include "cppa/opencl/smart_ptr.hpp"
#include "cppa/opencl/actor_facade.hpp"
#include "cppa/detail/singleton_mixin.hpp"
#include "cppa/detail/singleton_manager.hpp"
#include "cppa/intrusive/blocking_single_reader_queue.hpp"
namespace cppa { namespace opencl {
struct dereferencer {
inline void operator()(ref_counted* ptr) { ptr->deref(); }
};
template<typename... Ts>
option<cow_tuple<Ts...>> default_map_args(any_tuple msg) {
return tuple_cast<Ts...>(msg);
}
#ifdef CPPA_OPENCL
class command_dispatcher {
struct worker;
friend struct worker;
friend class detail::singleton_manager;
friend class program;
friend void enqueue_to_dispatcher(command_dispatcher* dispatcher,
command_ptr cmd);
public:
void enqueue();
template<typename Ret, typename... Args>
actor_ptr spawn(const program& prog,
const char* kernel_name,
std::vector<size_t> global_dims,
std::vector<size_t> local_dims,
std::function<option<cow_tuple<typename util::rm_ref<Args>::type...>>(any_tuple)> map_args,
std::function<any_tuple(Ret&)> map_result)
{
return new actor_facade<Ret (Args...)>(this,
prog,
kernel_name,
std::move(global_dims),
std::move(local_dims),
std::move(map_args),
std::move(map_result));
}
template<typename Ret, typename... Args>
actor_ptr spawn(const program& prog,
const char* kernel_name,
std::vector<size_t> global_dims = {1,1,1},
std::vector<size_t> local_dims = {})
{
std::function<option<cow_tuple<typename util::rm_ref<Args>::type...>>(any_tuple)> f0 = [] (any_tuple msg) {
return tuple_cast<typename util::rm_ref<Args>::type...>(msg);
};
std::function<any_tuple(Ret&)> f1 = [] (Ret& result) {
return make_any_tuple(std::move(result));
};
return this->spawn<Ret,Args...>(prog,
kernel_name,
std::move(global_dims),
std::move(local_dims),
std::move(f0),
std::move(f1));
}
private:
struct device_info {
unsigned id;
command_queue_ptr cmd_queue;
device_ptr dev_id;
size_t max_itms_per_grp;
cl_uint max_dim;
std::vector<size_t> max_itms_per_dim;
device_info(unsigned id,
command_queue_ptr queue,
device_ptr device_id,
size_t max_itms_per_grp,
cl_uint max_dim,
std::vector<size_t> max_itms_per_dim)
: id(id)
, cmd_queue(queue)
, dev_id(device_id)
, max_itms_per_grp(max_itms_per_grp)
, max_dim(max_dim)
, max_itms_per_dim(std::move(max_itms_per_dim)) { }
};
typedef intrusive::blocking_single_reader_queue<command,dereferencer>
job_queue;
static inline command_dispatcher* create_singleton() {
return new command_dispatcher;
}
void initialize();
void dispose();
void destroy();
std::atomic<unsigned> dev_id_gen;
job_queue m_job_queue;
command_ptr m_dummy;
std::thread m_supervisor;
std::vector<device_info> m_devices;
context_ptr m_context;
static void worker_loop(worker*);
static void supervisor_loop(command_dispatcher *scheduler,
job_queue*,
command_ptr);
};
#else // CPPA_OPENCL
class command_dispatcher : public detail::singleton_mixin<command_dispatcher> { };
#endif // CPPA_OPENCL
command_dispatcher* get_command_dispatcher();
} } // namespace cppa::opencl
#endif // CPPA_OPENCL_COMMAND_DISPATCHER_HPP
<|endoftext|> |
<commit_before>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 2013-2015 Richard Hughes <richard@hughsie.com>
*
* Most of this code was taken from Zif, libzif/zif-transaction.c
*
* Licensed under the GNU Lesser General Public License Version 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or(at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* SECTION:dnf-goal
* @short_description: Helper methods for dealing with hawkey goals.
* @include: libdnf.h
* @stability: Unstable
*
* These methods make it easier to deal with hawkey goals.
*/
#include <glib.h>
#include "hy-util.h"
#include "hy-goal-private.hpp"
#include "dnf-goal.h"
#include "dnf-package.h"
#include "hy-packageset-private.hpp"
#include "hy-iutil-private.hpp"
#include "dnf-sack-private.hpp"
#include "dnf-utils.h"
/**
* dnf_goal_depsolve:
* @goal: a #HyGoal.
* @flags: some #DnfGoalActions to enable.
* @error: a #GError or %NULL
*
* Returns: %TRUE if depsolve is successful.
*
* Since: 0.7.0
*/
gboolean
dnf_goal_depsolve(HyGoal goal, DnfGoalActions flags, GError **error)
{
gint cnt;
gint j;
gint rc;
g_autoptr(GString) string = NULL;
rc = hy_goal_run_flags(goal, flags);
if (rc) {
string = g_string_new("Could not depsolve transaction; ");
cnt = hy_goal_count_problems(goal);
if (cnt == 1)
g_string_append_printf(string, "%i problem detected:\n", cnt);
else
g_string_append_printf(string, "%i problems detected:\n", cnt);
for (j = 0; j < cnt; j++) {
auto tmp = hy_goal_describe_problem_rules(goal, j);
for (auto iter = tmp; *iter; ++iter) {
if (tmp == iter) {
if (cnt != 1) {
g_string_append_printf(string, " Problem %i: %s\n", j + 1, *iter);
} else {
g_string_append_printf(string, " Problem: %s\n", *iter);
}
} else {
g_string_append_printf(string, " - %s\n", *iter);
}
g_free(*iter);
}
g_free(tmp);
}
g_string_truncate(string, string->len - 1);
g_set_error_literal(error,
DNF_ERROR,
DNF_ERROR_PACKAGE_CONFLICTS,
string->str);
return FALSE;
}
/* anything to do? */
if (hy_goal_req_length(goal) == 0) {
g_set_error_literal(error,
DNF_ERROR,
DNF_ERROR_NO_PACKAGES_TO_UPDATE,
"The transaction was empty");
return FALSE;
}
return TRUE;
}
/**
* dnf_goal_get_packages:
*/
GPtrArray *
dnf_goal_get_packages(HyGoal goal, ...)
{
GPtrArray *array;
DnfPackage *pkg;
gint info_tmp;
guint i;
guint j;
va_list args;
/* process the valist */
va_start(args, goal);
array = g_ptr_array_new_with_free_func((GDestroyNotify) g_object_unref);
for (j = 0;; j++) {
GPtrArray *pkglist = NULL;
info_tmp = va_arg(args, gint);
if (info_tmp == -1)
break;
switch(info_tmp) {
case DNF_PACKAGE_INFO_REMOVE:
pkglist = hy_goal_list_erasures(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_REMOVE);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
case DNF_PACKAGE_INFO_INSTALL:
pkglist = hy_goal_list_installs(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_INSTALL);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
case DNF_PACKAGE_INFO_OBSOLETE:
pkglist = hy_goal_list_obsoleted(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_OBSOLETE);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
case DNF_PACKAGE_INFO_REINSTALL:
pkglist = hy_goal_list_reinstalls(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_REINSTALL);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
case DNF_PACKAGE_INFO_UPDATE:
pkglist = hy_goal_list_upgrades(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_UPDATE);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
case DNF_PACKAGE_INFO_DOWNGRADE:
pkglist = hy_goal_list_downgrades(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_DOWNGRADE);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
default:
g_assert_not_reached();
}
g_ptr_array_unref(pkglist);
}
va_end(args);
return array;
}
/**
* dnf_goal_add_protected:
* @goal: a #HyGoal.
* @pset: a #DnfPackageSet that would be added to the protected packages.
*
* Since: 0.7.0
*/
void
dnf_goal_add_protected(HyGoal goal, DnfPackageSet *pset)
{
Pool *pool = dnf_sack_get_pool(goal->sack);
Map *protected_pkgs = goal->protected_pkgs;
Map *nprotected = dnf_packageset_get_map(pset);
if (protected_pkgs == NULL) {
protected_pkgs = (Map*)g_malloc0(sizeof(Map));
map_init(protected_pkgs, pool->nsolvables);
goal->protected_pkgs = protected_pkgs;
} else
map_grow(protected_pkgs, pool->nsolvables);
map_or(protected_pkgs, nprotected);
}
/**
* dnf_goal_set_protected:
* @goal: a #HyGoal.
* @pset: a #DnfPackageSet of protected packages (the previous setup will be overridden).
*
* Since: 0.7.0
*/
void
dnf_goal_set_protected(HyGoal goal, DnfPackageSet *pset)
{
goal->protected_pkgs = free_map_fully(goal->protected_pkgs);
if (pset) {
Map *nprotected = dnf_packageset_get_map(pset);
goal->protected_pkgs = (Map*)g_malloc0(sizeof(Map));
map_init_clone(goal->protected_pkgs, nprotected);
}
}
<commit_msg>Add translation for problem reports<commit_after>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 2013-2015 Richard Hughes <richard@hughsie.com>
*
* Most of this code was taken from Zif, libzif/zif-transaction.c
*
* Licensed under the GNU Lesser General Public License Version 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or(at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* SECTION:dnf-goal
* @short_description: Helper methods for dealing with hawkey goals.
* @include: libdnf.h
* @stability: Unstable
*
* These methods make it easier to deal with hawkey goals.
*/
#include <glib.h>
#include "hy-util.h"
#include "hy-goal-private.hpp"
#include "dnf-goal.h"
#include "dnf-package.h"
#include "hy-packageset-private.hpp"
#include "hy-iutil-private.hpp"
#include "dnf-sack-private.hpp"
#include "dnf-utils.h"
#include "utils/bgettext/bgettext-lib.h"
/**
* dnf_goal_depsolve:
* @goal: a #HyGoal.
* @flags: some #DnfGoalActions to enable.
* @error: a #GError or %NULL
*
* Returns: %TRUE if depsolve is successful.
*
* Since: 0.7.0
*/
gboolean
dnf_goal_depsolve(HyGoal goal, DnfGoalActions flags, GError **error)
{
gint cnt;
gint j;
gint rc;
g_autoptr(GString) string = NULL;
rc = hy_goal_run_flags(goal, flags);
if (rc) {
string = g_string_new(_("Could not depsolve transaction; "));
cnt = hy_goal_count_problems(goal);
g_string_append_printf(string, P_("%i problem detected:\n", "%i problems detected:\n", cnt),
cnt);
for (j = 0; j < cnt; j++) {
auto tmp = hy_goal_describe_problem_rules(goal, j);
for (auto iter = tmp; *iter; ++iter) {
if (tmp == iter) {
if (cnt != 1) {
g_string_append_printf(string, _(" Problem %1$i: %2$s\n"), j + 1, *iter);
} else {
g_string_append_printf(string, _(" Problem: %s\n"), *iter);
}
} else {
g_string_append_printf(string, " - %s\n", *iter);
}
g_free(*iter);
}
g_free(tmp);
}
g_string_truncate(string, string->len - 1);
g_set_error_literal(error,
DNF_ERROR,
DNF_ERROR_PACKAGE_CONFLICTS,
string->str);
return FALSE;
}
/* anything to do? */
if (hy_goal_req_length(goal) == 0) {
g_set_error_literal(error,
DNF_ERROR,
DNF_ERROR_NO_PACKAGES_TO_UPDATE,
"The transaction was empty");
return FALSE;
}
return TRUE;
}
/**
* dnf_goal_get_packages:
*/
GPtrArray *
dnf_goal_get_packages(HyGoal goal, ...)
{
GPtrArray *array;
DnfPackage *pkg;
gint info_tmp;
guint i;
guint j;
va_list args;
/* process the valist */
va_start(args, goal);
array = g_ptr_array_new_with_free_func((GDestroyNotify) g_object_unref);
for (j = 0;; j++) {
GPtrArray *pkglist = NULL;
info_tmp = va_arg(args, gint);
if (info_tmp == -1)
break;
switch(info_tmp) {
case DNF_PACKAGE_INFO_REMOVE:
pkglist = hy_goal_list_erasures(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_REMOVE);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
case DNF_PACKAGE_INFO_INSTALL:
pkglist = hy_goal_list_installs(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_INSTALL);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
case DNF_PACKAGE_INFO_OBSOLETE:
pkglist = hy_goal_list_obsoleted(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_OBSOLETE);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
case DNF_PACKAGE_INFO_REINSTALL:
pkglist = hy_goal_list_reinstalls(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_REINSTALL);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
case DNF_PACKAGE_INFO_UPDATE:
pkglist = hy_goal_list_upgrades(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_UPDATE);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
case DNF_PACKAGE_INFO_DOWNGRADE:
pkglist = hy_goal_list_downgrades(goal, NULL);
for (i = 0; i < pkglist->len; i++) {
pkg = (DnfPackage*)g_ptr_array_index (pkglist, i);
dnf_package_set_action(pkg, DNF_STATE_ACTION_DOWNGRADE);
g_ptr_array_add(array, g_object_ref(pkg));
}
break;
default:
g_assert_not_reached();
}
g_ptr_array_unref(pkglist);
}
va_end(args);
return array;
}
/**
* dnf_goal_add_protected:
* @goal: a #HyGoal.
* @pset: a #DnfPackageSet that would be added to the protected packages.
*
* Since: 0.7.0
*/
void
dnf_goal_add_protected(HyGoal goal, DnfPackageSet *pset)
{
Pool *pool = dnf_sack_get_pool(goal->sack);
Map *protected_pkgs = goal->protected_pkgs;
Map *nprotected = dnf_packageset_get_map(pset);
if (protected_pkgs == NULL) {
protected_pkgs = (Map*)g_malloc0(sizeof(Map));
map_init(protected_pkgs, pool->nsolvables);
goal->protected_pkgs = protected_pkgs;
} else
map_grow(protected_pkgs, pool->nsolvables);
map_or(protected_pkgs, nprotected);
}
/**
* dnf_goal_set_protected:
* @goal: a #HyGoal.
* @pset: a #DnfPackageSet of protected packages (the previous setup will be overridden).
*
* Since: 0.7.0
*/
void
dnf_goal_set_protected(HyGoal goal, DnfPackageSet *pset)
{
goal->protected_pkgs = free_map_fully(goal->protected_pkgs);
if (pset) {
Map *nprotected = dnf_packageset_get_map(pset);
goal->protected_pkgs = (Map*)g_malloc0(sizeof(Map));
map_init_clone(goal->protected_pkgs, nprotected);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/user/tray_user.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_item_view.h"
#include "ash/system/tray/tray_views.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_strings.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkShader.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/size.h"
#include "ui/gfx/skia_util.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace {
const int kUserInfoVerticalPadding = 10;
const int kUserIconSize = 27;
} // namespace
namespace ash {
namespace internal {
namespace tray {
// A custom image view with rounded edges.
class RoundedImageView : public views::View {
public:
// Constructs a new rounded image view with rounded corners of radius
// |corner_radius|.
explicit RoundedImageView(int corner_radius) : corner_radius_(corner_radius) {
}
virtual ~RoundedImageView() {
}
// Set the image that should be displayed from a pointer. The pointer
// contents is copied in the receiver's image.
void SetImage(const gfx::ImageSkia& img, const gfx::Size& size) {
image_ = img;
image_size_ = size;
// Try to get the best image quality for the avatar.
resized_ = skia::ImageOperations::Resize(image_,
skia::ImageOperations::RESIZE_BEST, size.width(), size.height());
if (GetWidget() && visible()) {
PreferredSizeChanged();
SchedulePaint();
}
}
// Overridden from views::View.
virtual gfx::Size GetPreferredSize() OVERRIDE {
return gfx::Size(image_size_.width() + GetInsets().width(),
image_size_.height() + GetInsets().height());
}
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
View::OnPaint(canvas);
gfx::Rect image_bounds(GetPreferredSize());
image_bounds = gfx::Rect(size()).Center(image_bounds.size());
image_bounds.Inset(GetInsets());
const SkScalar kRadius = SkIntToScalar(corner_radius_);
SkPath path;
path.addRoundRect(gfx::RectToSkRect(image_bounds), kRadius, kRadius);
SkPaint paint;
SkShader* shader = SkShader::CreateBitmapShader(resized_,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
SkMatrix shader_matrix;
shader_matrix.setTranslate(SkIntToScalar(image_bounds.x()),
SkIntToScalar(image_bounds.y()));
shader->setLocalMatrix(shader_matrix);
paint.setShader(shader);
paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
shader->unref();
canvas->DrawPath(path, paint);
}
private:
gfx::ImageSkia image_;
gfx::ImageSkia resized_;
gfx::Size image_size_;
int corner_radius_;
DISALLOW_COPY_AND_ASSIGN(RoundedImageView);
};
class UserView : public views::View,
public views::ButtonListener {
public:
explicit UserView(ash::user::LoginStatus login)
: login_(login),
container_(NULL),
user_info_(NULL),
username_(NULL),
email_(NULL),
signout_(NULL) {
CHECK(login_ != ash::user::LOGGED_IN_NONE);
set_background(views::Background::CreateSolidBackground(kBackgroundColor));
bool guest = login_ == ash::user::LOGGED_IN_GUEST;
bool kiosk = login_ == ash::user::LOGGED_IN_KIOSK;
bool locked = login_ == ash::user::LOGGED_IN_LOCKED;
container_ = new TrayPopupTextButtonContainer;
container_->layout()->set_spread_blank_space(false);
AddChildView(container_);
if (!guest && !kiosk)
AddUserInfo();
// A user should not be able to modify logged in state when screen is
// locked.
if (!locked)
AddButtonContainer();
}
virtual ~UserView() {}
// Create container for buttons.
void AddButtonContainer() {
bool guest = login_ == ash::user::LOGGED_IN_GUEST;
bool kiosk = login_ == ash::user::LOGGED_IN_KIOSK;
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
if (kiosk) {
views::Label* label = new views::Label;
label->SetText(
bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_KIOSK_LABEL));
label->set_border(views::Border::CreateEmptyBorder(
0, kTrayPopupPaddingHorizontal, 0, 1));
label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
container_->AddChildView(label);
}
TrayPopupTextButton* button =
new TrayPopupTextButton(this, bundle.GetLocalizedString(
guest ? IDS_ASH_STATUS_TRAY_EXIT_GUEST :
kiosk ? IDS_ASH_STATUS_TRAY_EXIT_KIOSK :
IDS_ASH_STATUS_TRAY_SIGN_OUT));
container_->AddTextButton(button);
signout_ = button;
}
private:
void AddUserInfo() {
user_info_ = new views::View;
user_info_->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kHorizontal, kTrayPopupPaddingHorizontal,
kUserInfoVerticalPadding, kTrayPopupPaddingBetweenItems));
RoundedImageView* image = new RoundedImageView(kTrayRoundedBorderRadius);
image->SetImage(ash::Shell::GetInstance()->tray_delegate()->GetUserImage(),
gfx::Size(kUserIconSize, kUserIconSize));
user_info_->AddChildView(image);
views::View* user = new views::View;
user->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kVertical, 0, 5, 0));
ash::SystemTrayDelegate* tray =
ash::Shell::GetInstance()->tray_delegate();
username_ = new views::Label(tray->GetUserDisplayName());
username_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
user->AddChildView(username_);
email_ = new views::Label(UTF8ToUTF16(tray->GetUserEmail()));
email_->SetFont(username_->font().DeriveFont(-1));
email_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
email_->SetEnabled(false);
user->AddChildView(email_);
user_info_->AddChildView(user);
container_->AddChildView(user_info_);
}
// Overridden from views::ButtonListener.
virtual void ButtonPressed(views::Button* sender,
const views::Event& event) OVERRIDE {
CHECK(sender == signout_);
ash::SystemTrayDelegate* tray = ash::Shell::GetInstance()->tray_delegate();
tray->SignOut();
}
// Overridden from views::View.
virtual gfx::Size GetPreferredSize() OVERRIDE {
gfx::Size size;
if (user_info_)
size = user_info_->GetPreferredSize();
if (signout_) {
gfx::Size signout_size = signout_->GetPreferredSize();
size.set_height(std::max(size.height(), signout_size.height()));
size.set_width(size.width() + signout_size.width() +
kTrayPopupPaddingHorizontal * 2 + kTrayPopupPaddingBetweenItems);
}
return size;
}
virtual void Layout() OVERRIDE {
views::View::Layout();
if (bounds().IsEmpty())
return;
container_->SetBoundsRect(gfx::Rect(size()));
if (signout_ && user_info_) {
gfx::Rect signout_bounds(signout_->GetPreferredSize());
signout_bounds = bounds().Center(signout_bounds.size());
signout_bounds.set_x(width() - signout_bounds.width() -
kTrayPopupPaddingHorizontal);
signout_->SetBoundsRect(signout_bounds);
gfx::Rect usercard_bounds(user_info_->GetPreferredSize());
usercard_bounds.set_width(signout_bounds.x());
user_info_->SetBoundsRect(usercard_bounds);
} else if (signout_) {
signout_->SetBoundsRect(gfx::Rect(size()));
} else if (user_info_) {
user_info_->SetBoundsRect(gfx::Rect(size()));
}
}
user::LoginStatus login_;
TrayPopupTextButtonContainer* container_;
views::View* user_info_;
views::Label* username_;
views::Label* email_;
views::Button* signout_;
DISALLOW_COPY_AND_ASSIGN(UserView);
};
} // namespace tray
TrayUser::TrayUser()
: user_(NULL),
avatar_(NULL) {
}
TrayUser::~TrayUser() {
}
views::View* TrayUser::CreateTrayView(user::LoginStatus status) {
CHECK(avatar_ == NULL);
avatar_ = new tray::RoundedImageView(kTrayRoundedBorderRadius);
avatar_->set_border(views::Border::CreateEmptyBorder(0, 6, 0, 0));
UpdateAfterLoginStatusChange(status);
return avatar_;
}
views::View* TrayUser::CreateDefaultView(user::LoginStatus status) {
if (status == user::LOGGED_IN_NONE)
return NULL;
CHECK(user_ == NULL);
user_ = new tray::UserView(status);
return user_;
}
views::View* TrayUser::CreateDetailedView(user::LoginStatus status) {
return NULL;
}
void TrayUser::DestroyTrayView() {
avatar_ = NULL;
}
void TrayUser::DestroyDefaultView() {
user_ = NULL;
}
void TrayUser::DestroyDetailedView() {
}
void TrayUser::UpdateAfterLoginStatusChange(user::LoginStatus status) {
if (status != user::LOGGED_IN_NONE && status != user::LOGGED_IN_KIOSK &&
status != user::LOGGED_IN_GUEST) {
avatar_->SetImage(
ash::Shell::GetInstance()->tray_delegate()->GetUserImage(),
gfx::Size(kUserIconSize, kUserIconSize));
avatar_->SetVisible(true);
} else {
avatar_->SetVisible(false);
}
}
void TrayUser::OnUserUpdate() {
avatar_->SetImage(
ash::Shell::GetInstance()->tray_delegate()->GetUserImage(),
gfx::Size(kUserIconSize, kUserIconSize));
}
} // namespace internal
} // namespace ash
<commit_msg>ash: Fix uber-tray popup exit-session button in demo mode.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/user/tray_user.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_item_view.h"
#include "ash/system/tray/tray_views.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_strings.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkShader.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/size.h"
#include "ui/gfx/skia_util.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace {
const int kUserInfoVerticalPadding = 10;
const int kUserIconSize = 27;
} // namespace
namespace ash {
namespace internal {
namespace tray {
// A custom image view with rounded edges.
class RoundedImageView : public views::View {
public:
// Constructs a new rounded image view with rounded corners of radius
// |corner_radius|.
explicit RoundedImageView(int corner_radius) : corner_radius_(corner_radius) {
}
virtual ~RoundedImageView() {
}
// Set the image that should be displayed from a pointer. The pointer
// contents is copied in the receiver's image.
void SetImage(const gfx::ImageSkia& img, const gfx::Size& size) {
image_ = img;
image_size_ = size;
// Try to get the best image quality for the avatar.
resized_ = skia::ImageOperations::Resize(image_,
skia::ImageOperations::RESIZE_BEST, size.width(), size.height());
if (GetWidget() && visible()) {
PreferredSizeChanged();
SchedulePaint();
}
}
// Overridden from views::View.
virtual gfx::Size GetPreferredSize() OVERRIDE {
return gfx::Size(image_size_.width() + GetInsets().width(),
image_size_.height() + GetInsets().height());
}
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
View::OnPaint(canvas);
gfx::Rect image_bounds(GetPreferredSize());
image_bounds = gfx::Rect(size()).Center(image_bounds.size());
image_bounds.Inset(GetInsets());
const SkScalar kRadius = SkIntToScalar(corner_radius_);
SkPath path;
path.addRoundRect(gfx::RectToSkRect(image_bounds), kRadius, kRadius);
SkPaint paint;
SkShader* shader = SkShader::CreateBitmapShader(resized_,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
SkMatrix shader_matrix;
shader_matrix.setTranslate(SkIntToScalar(image_bounds.x()),
SkIntToScalar(image_bounds.y()));
shader->setLocalMatrix(shader_matrix);
paint.setShader(shader);
paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
shader->unref();
canvas->DrawPath(path, paint);
}
private:
gfx::ImageSkia image_;
gfx::ImageSkia resized_;
gfx::Size image_size_;
int corner_radius_;
DISALLOW_COPY_AND_ASSIGN(RoundedImageView);
};
class UserView : public views::View,
public views::ButtonListener {
public:
explicit UserView(ash::user::LoginStatus login)
: login_(login),
container_(NULL),
user_info_(NULL),
username_(NULL),
email_(NULL),
signout_(NULL) {
CHECK(login_ != ash::user::LOGGED_IN_NONE);
set_background(views::Background::CreateSolidBackground(kBackgroundColor));
bool guest = login_ == ash::user::LOGGED_IN_GUEST;
bool locked = login_ == ash::user::LOGGED_IN_LOCKED;
container_ = new TrayPopupTextButtonContainer;
container_->layout()->set_spread_blank_space(false);
AddChildView(container_);
if (!guest)
AddUserInfo();
// A user should not be able to modify logged in state when screen is
// locked.
if (!locked)
AddButtonContainer();
}
virtual ~UserView() {}
// Create container for buttons.
void AddButtonContainer() {
bool guest = login_ == ash::user::LOGGED_IN_GUEST;
bool kiosk = login_ == ash::user::LOGGED_IN_KIOSK;
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
TrayPopupTextButton* button =
new TrayPopupTextButton(this, bundle.GetLocalizedString(
guest ? IDS_ASH_STATUS_TRAY_EXIT_GUEST :
kiosk ? IDS_ASH_STATUS_TRAY_EXIT_KIOSK :
IDS_ASH_STATUS_TRAY_SIGN_OUT));
container_->AddTextButton(button);
signout_ = button;
}
private:
void AddUserInfo() {
user_info_ = new views::View;
user_info_->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kHorizontal, kTrayPopupPaddingHorizontal,
kUserInfoVerticalPadding, kTrayPopupPaddingBetweenItems));
container_->AddChildView(user_info_);
if (login_ == ash::user::LOGGED_IN_KIOSK) {
views::Label* label = new views::Label;
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
label->SetText(
bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_KIOSK_LABEL));
label->set_border(views::Border::CreateEmptyBorder(
0, 4, 0, 1));
label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
user_info_->AddChildView(label);
return;
}
RoundedImageView* image = new RoundedImageView(kTrayRoundedBorderRadius);
image->SetImage(ash::Shell::GetInstance()->tray_delegate()->GetUserImage(),
gfx::Size(kUserIconSize, kUserIconSize));
user_info_->AddChildView(image);
views::View* user = new views::View;
user->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kVertical, 0, 5, 0));
ash::SystemTrayDelegate* tray =
ash::Shell::GetInstance()->tray_delegate();
username_ = new views::Label(tray->GetUserDisplayName());
username_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
user->AddChildView(username_);
email_ = new views::Label(UTF8ToUTF16(tray->GetUserEmail()));
email_->SetFont(username_->font().DeriveFont(-1));
email_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
email_->SetEnabled(false);
user->AddChildView(email_);
user_info_->AddChildView(user);
}
// Overridden from views::ButtonListener.
virtual void ButtonPressed(views::Button* sender,
const views::Event& event) OVERRIDE {
CHECK(sender == signout_);
ash::SystemTrayDelegate* tray = ash::Shell::GetInstance()->tray_delegate();
tray->SignOut();
}
// Overridden from views::View.
virtual gfx::Size GetPreferredSize() OVERRIDE {
gfx::Size size;
if (user_info_)
size = user_info_->GetPreferredSize();
if (signout_) {
gfx::Size signout_size = signout_->GetPreferredSize();
size.set_height(std::max(size.height(), signout_size.height()));
size.set_width(size.width() + signout_size.width() +
kTrayPopupPaddingHorizontal * 2 + kTrayPopupPaddingBetweenItems);
}
return size;
}
virtual void Layout() OVERRIDE {
views::View::Layout();
if (bounds().IsEmpty())
return;
container_->SetBoundsRect(gfx::Rect(size()));
if (signout_ && user_info_) {
gfx::Rect signout_bounds(signout_->GetPreferredSize());
signout_bounds = bounds().Center(signout_bounds.size());
signout_bounds.set_x(width() - signout_bounds.width() -
kTrayPopupPaddingHorizontal);
signout_->SetBoundsRect(signout_bounds);
gfx::Rect usercard_bounds(user_info_->GetPreferredSize());
usercard_bounds.set_width(signout_bounds.x());
user_info_->SetBoundsRect(usercard_bounds);
} else if (signout_) {
signout_->SetBoundsRect(gfx::Rect(size()));
} else if (user_info_) {
user_info_->SetBoundsRect(gfx::Rect(size()));
}
}
user::LoginStatus login_;
TrayPopupTextButtonContainer* container_;
views::View* user_info_;
views::Label* username_;
views::Label* email_;
views::Button* signout_;
DISALLOW_COPY_AND_ASSIGN(UserView);
};
} // namespace tray
TrayUser::TrayUser()
: user_(NULL),
avatar_(NULL) {
}
TrayUser::~TrayUser() {
}
views::View* TrayUser::CreateTrayView(user::LoginStatus status) {
CHECK(avatar_ == NULL);
avatar_ = new tray::RoundedImageView(kTrayRoundedBorderRadius);
avatar_->set_border(views::Border::CreateEmptyBorder(0, 6, 0, 0));
UpdateAfterLoginStatusChange(status);
return avatar_;
}
views::View* TrayUser::CreateDefaultView(user::LoginStatus status) {
if (status == user::LOGGED_IN_NONE)
return NULL;
CHECK(user_ == NULL);
user_ = new tray::UserView(status);
return user_;
}
views::View* TrayUser::CreateDetailedView(user::LoginStatus status) {
return NULL;
}
void TrayUser::DestroyTrayView() {
avatar_ = NULL;
}
void TrayUser::DestroyDefaultView() {
user_ = NULL;
}
void TrayUser::DestroyDetailedView() {
}
void TrayUser::UpdateAfterLoginStatusChange(user::LoginStatus status) {
if (status != user::LOGGED_IN_NONE && status != user::LOGGED_IN_KIOSK &&
status != user::LOGGED_IN_GUEST) {
avatar_->SetImage(
ash::Shell::GetInstance()->tray_delegate()->GetUserImage(),
gfx::Size(kUserIconSize, kUserIconSize));
avatar_->SetVisible(true);
} else {
avatar_->SetVisible(false);
}
}
void TrayUser::OnUserUpdate() {
avatar_->SetImage(
ash::Shell::GetInstance()->tray_delegate()->GetUserImage(),
gfx::Size(kUserIconSize, kUserIconSize));
}
} // namespace internal
} // namespace ash
<|endoftext|> |
<commit_before>#include "Slider.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace MinimalUI;
int Slider::DEFAULT_HEIGHT = UIElement::DEFAULT_HEIGHT;
int Slider::DEFAULT_WIDTH = UIController::DEFAULT_PANEL_WIDTH - UIController::DEFAULT_MARGIN_LARGE * 2;
int Slider::DEFAULT_HANDLE_HALFWIDTH = 8;
int ButtonSlider::DEFAULT_HEIGHT = UIElement::DEFAULT_HEIGHT;
int ButtonSlider::DEFAULT_WIDTH = UIElement::DEFAULT_HEIGHT;
int ButtonSlider::DEFAULT_HANDLE_HALFHEIGHT = 8;
int Slider2D::DEFAULT_HEIGHT = 96;
int Slider2D::DEFAULT_WIDTH = 96;
int Slider2D::DEFAULT_HANDLE_HALFWIDTH = 4;
Slider::Slider( UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString )
: UIElement( aUIController, aName, aParamString )
{
// initialize unique variables
mLinkedValue = aValueToLink;
mMin = hasParam( "min" ) ? getParam<float>( "min" ) : 0.0f;
mMax = hasParam( "max" ) ? getParam<float>( "max" ) : 1.0f;
// set colors
std::stringstream str;
string strValue;
uint32_t hexValue;
strValue = hasParam( "foregroundColor" ) ? getParam<string>( "foregroundColor" ) : "0xFF12424A"; // should be same as DEFAULT_STROKE_COLOR
str << strValue;
str >> std::hex >> hexValue;
setForegroundColor( ColorA::hexA( hexValue ) );
strValue = hasParam( "backgroundColor" ) ? getParam<string>( "backgroundColor" ) : "0xFF000000"; // should be same as DEFAULT_BACKGROUND_COLOR
str.clear();
str << strValue;
str >> std::hex >> hexValue;
setBackgroundColor( ColorA::hexA( hexValue ) );
// set size and render name texture
int x = hasParam( "width" ) ? getParam<int>( "width" ) : Slider::DEFAULT_WIDTH;
int y = Slider::DEFAULT_HEIGHT;
setSize( Vec2i( x, y ) );
renderNameTexture();
// set position and bounds
setPositionAndBounds();
// set screen min and max
mScreenMin = getPosition().x + Slider::DEFAULT_HANDLE_HALFWIDTH;
mScreenMax = getBounds().getX2() - Slider::DEFAULT_HANDLE_HALFWIDTH;
// set screen value
update();
}
UIElementRef Slider::create( UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString )
{
return shared_ptr<Slider>( new Slider( aUIController, aName, aValueToLink, aParamString ) );
}
void Slider::draw()
{
// draw the solid rect
if ( isLocked() ) {
gl::color( UIController::DEFAULT_STROKE_COLOR );
} else {
gl::color( getBackgroundColor() );//Color::black() );
}
gl::drawSolidRect( getBounds() );
// draw the outer rect
if ( isActive() ) {
gl::color( UIController::ACTIVE_STROKE_COLOR );
} else {
gl::color( UIController::DEFAULT_STROKE_COLOR );
}
gl::drawStrokedRect( getBounds() );
// draw the handle
if ( isLocked() ) {
gl::color( Color::black() );
} else if ( isActive() ) {
gl::color( UIController::ACTIVE_STROKE_COLOR );
} else {
gl::color( UIController::DEFAULT_STROKE_COLOR );
}
Vec2f handleStart = Vec2f( mValue - Slider::DEFAULT_HANDLE_HALFWIDTH, getBounds().getY1() );
Vec2f handleEnd = Vec2f( mValue + Slider::DEFAULT_HANDLE_HALFWIDTH, getBounds().getY2() );
gl::drawStrokedRect( Rectf( handleStart, handleEnd ) );
gl::drawSolidRect( Rectf( handleStart, handleEnd ) );
// draw the label
drawLabel();
}
void Slider::update()
{
mValue = lmap<float>(*mLinkedValue, mMin, mMax, getPosition().x + Slider::DEFAULT_HANDLE_HALFWIDTH, getBounds().getX2() - Slider::DEFAULT_HANDLE_HALFWIDTH );
}
void Slider::handleMouseDown( const Vec2i &aMousePos )
{
updatePosition( aMousePos.x );
}
void Slider::handleMouseDrag( const Vec2i &aMousePos )
{
updatePosition( math<int>::clamp( aMousePos.x, mScreenMin, mScreenMax ) );
}
void Slider::updatePosition( const int &aPos )
{
mValue = aPos;
*mLinkedValue = lmap<float>(mValue, mScreenMin, mScreenMax, mMin, mMax );
}
// ButtonSlider
ButtonSlider::ButtonSlider( UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString )
: UIElement( aUIController, aName, aParamString )
{
// initialize unique variables
mLinkedValue = aValueToLink;
mMin = hasParam( "min" ) ? getParam<float>( "min" ) : 0.0f;
mMax = hasParam( "max" ) ? getParam<float>( "max" ) : 1.0f;
// set colors
std::stringstream str;
string strValue;
uint32_t hexValue;
strValue = hasParam( "foregroundColor" ) ? getParam<string>( "foregroundColor" ) : "0xFF12424A"; // should be same as DEFAULT_STROKE_COLOR
str << strValue;
str >> std::hex >> hexValue;
setForegroundColor( ColorA::hexA( hexValue ) );
strValue = hasParam( "backgroundColor" ) ? getParam<string>( "backgroundColor" ) : "0xFF000000"; // should be same as DEFAULT_BACKGROUND_COLOR
str.clear();
str << strValue;
str >> std::hex >> hexValue;
setBackgroundColor( ColorA::hexA( hexValue ) );
// set size and render name texture
int x = ButtonSlider::DEFAULT_WIDTH;
int y = ButtonSlider::DEFAULT_HEIGHT;
setSize( Vec2i( x, y ) );
renderNameTexture();
// set position and bounds
setPositionAndBounds();
// set screen min and max
mScreenMin = getPosition().y + ButtonSlider::DEFAULT_HANDLE_HALFHEIGHT;
mScreenMax = getBounds().getY2() - ButtonSlider::DEFAULT_HANDLE_HALFHEIGHT;
// set screen value
update();
}
UIElementRef ButtonSlider::create( UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString )
{
return shared_ptr<ButtonSlider>( new ButtonSlider( aUIController, aName, aValueToLink, aParamString ) );
}
void ButtonSlider::draw()
{
// draw the solid rect
if ( isLocked() ) {
gl::color( UIController::DEFAULT_STROKE_COLOR );
} else {
gl::color( getBackgroundColor() );//Color::black() );
}
gl::drawSolidRect( getBounds() );
// draw the outer rect
if ( isActive() ) {
gl::color( UIController::ACTIVE_STROKE_COLOR );
} else {
gl::color( UIController::DEFAULT_STROKE_COLOR );//getForegroundColor() );//UIController::DEFAULT_STROKE_COLOR );
}
gl::drawStrokedRect( getBounds() );
// draw the handle
if ( isLocked() ) {
gl::color( Color::black() );
} else if ( isActive() ) {
gl::color( UIController::ACTIVE_STROKE_COLOR );
} else {
gl::color( UIController::DEFAULT_STROKE_COLOR );//getForegroundColor() );//UIController::DEFAULT_STROKE_COLOR );
}
/*Vec2f handleStart = Vec2f( mValue - SliderV::DEFAULT_HANDLE_HALFHEIGHT, getBounds().getX1() );
Vec2f handleEnd = Vec2f( mValue + SliderV::DEFAULT_HANDLE_HALFHEIGHT, getBounds().getX2() );
gl::drawStrokedRect( Rectf( handleStart, handleEnd ) );
gl::drawSolidRect( Rectf( handleStart, handleEnd ) );*/
// draw the label
drawLabel();
}
void ButtonSlider::update()
{
mValue = lmap<float>(*mLinkedValue, mMin, mMax, getBounds().getY1() - ButtonSlider::DEFAULT_HANDLE_HALFHEIGHT, getPosition().y + ButtonSlider::DEFAULT_HANDLE_HALFHEIGHT );
}
void ButtonSlider::handleMouseDown( const Vec2i &aMousePos )
{
updatePosition( aMousePos.y );
}
void ButtonSlider::handleMouseDrag( const Vec2i &aMousePos )
{
updatePosition( math<int>::clamp( aMousePos.y, mScreenMin, mScreenMax ) );
}
void ButtonSlider::updatePosition( const int &aPos )
{
mValue = aPos;
*mLinkedValue = lmap<float>(mValue, mScreenMax, mScreenMin, mMin, mMax );
}
// Slider2D
Slider2D::Slider2D( UIController *aUIController, const string &aName, Vec2f *aValueToLink, const string &aParamString )
: UIElement( aUIController, aName, aParamString )
{
// initialize unique variables
mLinkedValue = aValueToLink;
float minX = hasParam( "minX" ) ? getParam<float>( "minX" ) : 0.0f;
float maxX = hasParam( "maxX" ) ? getParam<float>( "maxX" ) : 1.0f;
float minY = hasParam( "minY" ) ? getParam<float>( "minY" ) : 0.0f;
float maxY = hasParam( "maxY" ) ? getParam<float>( "maxY" ) : 1.0f;
mMin = Vec2f( minX, minY );
mMax = Vec2f( maxX, maxY );
// set size and render name texture
int x = hasParam( "width" ) ? getParam<int>( "width" ) : Slider2D::DEFAULT_WIDTH;
int y = Slider2D::DEFAULT_HEIGHT;
setSize( Vec2i( x, y ) );
renderNameTexture();
// set position and bounds
setPositionAndBounds();
// set screen min and max
Vec2i offset = Vec2i( Slider2D::DEFAULT_HANDLE_HALFWIDTH, Slider2D::DEFAULT_HANDLE_HALFWIDTH );
mScreenMin = getPosition() + offset;
mScreenMax = getBounds().getLR() - offset;
// set screen value
update();
}
UIElementRef Slider2D::create( UIController *aUIController, const string &aName, Vec2f *aValueToLink, const string &aParamString )
{
return shared_ptr<Slider2D>( new Slider2D( aUIController, aName, aValueToLink, aParamString ) );
}
void Slider2D::draw()
{
// draw the outer rect
gl::color( UIController::DEFAULT_STROKE_COLOR );
gl::drawStrokedRect( getBounds() );
gl::drawSolidRect( getBounds() );
// draw the indicator lines
gl::color( UIController::ACTIVE_STROKE_COLOR );
gl::drawLine( Vec2f( getBounds().getX1(), mValue.y ), Vec2f( getBounds().getX2(), mValue.y ) );
gl::drawLine( Vec2f( mValue.x, getBounds().getY1() ), Vec2f( mValue.x, getBounds().getY2() ) );
// draw the handle
Vec2f offset = Vec2i( Slider2D::DEFAULT_HANDLE_HALFWIDTH, Slider2D::DEFAULT_HANDLE_HALFWIDTH );
Vec2f handleStart = mValue - offset;
Vec2f handleEnd = mValue + offset;
gl::drawStrokedRect( Rectf( handleStart, handleEnd ) );
gl::drawSolidRect( Rectf( handleStart, handleEnd ) );
}
void Slider2D::update()
{
Vec2i offset = Vec2i( Slider2D::DEFAULT_HANDLE_HALFWIDTH, Slider2D::DEFAULT_HANDLE_HALFWIDTH );
mValue.x = lmap<float>((*mLinkedValue).x, mMin.x, mMax.x, getPosition().x + offset.x, getBounds().getX2() - offset.x );
mValue.y = lmap<float>((*mLinkedValue).y, mMin.y, mMax.y, getBounds().getY2() - offset.y, getPosition().y + offset.y );
}
void Slider2D::handleMouseDown( const Vec2i &aMousePos )
{
updatePosition( aMousePos );
}
void Slider2D::handleMouseDrag( const Vec2i &aMousePos )
{
Vec2i newPos;
newPos.x = math<int>::clamp( aMousePos.x, mScreenMin.x, mScreenMax.x );
newPos.y = math<int>::clamp( aMousePos.y, mScreenMin.y, mScreenMax.y );
updatePosition( newPos );
}
void Slider2D::updatePosition( const Vec2i &aPos )
{
mValue = aPos;
(*mLinkedValue).x = lmap<float>(mValue.x, mScreenMin.x, mScreenMax.x, mMin.x, mMax.x );
(*mLinkedValue).y = lmap<float>(mValue.y, mScreenMin.y, mScreenMax.y, mMax.y, mMin.y );
}
<commit_msg>removed comments<commit_after>#include "Slider.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace MinimalUI;
int Slider::DEFAULT_HEIGHT = UIElement::DEFAULT_HEIGHT;
int Slider::DEFAULT_WIDTH = UIController::DEFAULT_PANEL_WIDTH - UIController::DEFAULT_MARGIN_LARGE * 2;
int Slider::DEFAULT_HANDLE_HALFWIDTH = 8;
int ButtonSlider::DEFAULT_HEIGHT = UIElement::DEFAULT_HEIGHT;
int ButtonSlider::DEFAULT_WIDTH = UIElement::DEFAULT_HEIGHT;
int ButtonSlider::DEFAULT_HANDLE_HALFHEIGHT = 8;
int Slider2D::DEFAULT_HEIGHT = 96;
int Slider2D::DEFAULT_WIDTH = 96;
int Slider2D::DEFAULT_HANDLE_HALFWIDTH = 4;
Slider::Slider( UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString )
: UIElement( aUIController, aName, aParamString )
{
// initialize unique variables
mLinkedValue = aValueToLink;
mMin = hasParam( "min" ) ? getParam<float>( "min" ) : 0.0f;
mMax = hasParam( "max" ) ? getParam<float>( "max" ) : 1.0f;
// set colors
std::stringstream str;
string strValue;
uint32_t hexValue;
strValue = hasParam( "foregroundColor" ) ? getParam<string>( "foregroundColor" ) : "0xFF12424A"; // should be same as DEFAULT_STROKE_COLOR
str << strValue;
str >> std::hex >> hexValue;
setForegroundColor( ColorA::hexA( hexValue ) );
strValue = hasParam( "backgroundColor" ) ? getParam<string>( "backgroundColor" ) : "0xFF000000"; // should be same as DEFAULT_BACKGROUND_COLOR
str.clear();
str << strValue;
str >> std::hex >> hexValue;
setBackgroundColor( ColorA::hexA( hexValue ) );
// set size and render name texture
int x = hasParam( "width" ) ? getParam<int>( "width" ) : Slider::DEFAULT_WIDTH;
int y = Slider::DEFAULT_HEIGHT;
setSize( Vec2i( x, y ) );
renderNameTexture();
// set position and bounds
setPositionAndBounds();
// set screen min and max
mScreenMin = getPosition().x + Slider::DEFAULT_HANDLE_HALFWIDTH;
mScreenMax = getBounds().getX2() - Slider::DEFAULT_HANDLE_HALFWIDTH;
// set screen value
update();
}
UIElementRef Slider::create( UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString )
{
return shared_ptr<Slider>( new Slider( aUIController, aName, aValueToLink, aParamString ) );
}
void Slider::draw()
{
// draw the solid rect
if ( isLocked() ) {
gl::color( UIController::DEFAULT_STROKE_COLOR );
} else {
gl::color( getBackgroundColor() );//Color::black() );
}
gl::drawSolidRect( getBounds() );
// draw the outer rect
if ( isActive() ) {
gl::color( UIController::ACTIVE_STROKE_COLOR );
} else {
gl::color( UIController::DEFAULT_STROKE_COLOR );
}
gl::drawStrokedRect( getBounds() );
// draw the handle
if ( isLocked() ) {
gl::color( Color::black() );
} else if ( isActive() ) {
gl::color( UIController::ACTIVE_STROKE_COLOR );
} else {
gl::color( UIController::DEFAULT_STROKE_COLOR );
}
Vec2f handleStart = Vec2f( mValue - Slider::DEFAULT_HANDLE_HALFWIDTH, getBounds().getY1() );
Vec2f handleEnd = Vec2f( mValue + Slider::DEFAULT_HANDLE_HALFWIDTH, getBounds().getY2() );
gl::drawStrokedRect( Rectf( handleStart, handleEnd ) );
gl::drawSolidRect( Rectf( handleStart, handleEnd ) );
// draw the label
drawLabel();
}
void Slider::update()
{
mValue = lmap<float>(*mLinkedValue, mMin, mMax, getPosition().x + Slider::DEFAULT_HANDLE_HALFWIDTH, getBounds().getX2() - Slider::DEFAULT_HANDLE_HALFWIDTH );
}
void Slider::handleMouseDown( const Vec2i &aMousePos )
{
updatePosition( aMousePos.x );
}
void Slider::handleMouseDrag( const Vec2i &aMousePos )
{
updatePosition( math<int>::clamp( aMousePos.x, mScreenMin, mScreenMax ) );
}
void Slider::updatePosition( const int &aPos )
{
mValue = aPos;
*mLinkedValue = lmap<float>(mValue, mScreenMin, mScreenMax, mMin, mMax );
}
// ButtonSlider
ButtonSlider::ButtonSlider( UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString )
: UIElement( aUIController, aName, aParamString )
{
// initialize unique variables
mLinkedValue = aValueToLink;
mMin = hasParam( "min" ) ? getParam<float>( "min" ) : 0.0f;
mMax = hasParam( "max" ) ? getParam<float>( "max" ) : 1.0f;
// set colors
std::stringstream str;
string strValue;
uint32_t hexValue;
strValue = hasParam( "foregroundColor" ) ? getParam<string>( "foregroundColor" ) : "0xFF12424A"; // should be same as DEFAULT_STROKE_COLOR
str << strValue;
str >> std::hex >> hexValue;
setForegroundColor( ColorA::hexA( hexValue ) );
strValue = hasParam( "backgroundColor" ) ? getParam<string>( "backgroundColor" ) : "0xFF000000"; // should be same as DEFAULT_BACKGROUND_COLOR
str.clear();
str << strValue;
str >> std::hex >> hexValue;
setBackgroundColor( ColorA::hexA( hexValue ) );
// set size and render name texture
int x = ButtonSlider::DEFAULT_WIDTH;
int y = ButtonSlider::DEFAULT_HEIGHT;
setSize( Vec2i( x, y ) );
renderNameTexture();
// set position and bounds
setPositionAndBounds();
// set screen min and max
mScreenMin = getPosition().y + ButtonSlider::DEFAULT_HANDLE_HALFHEIGHT;
mScreenMax = getBounds().getY2() - ButtonSlider::DEFAULT_HANDLE_HALFHEIGHT;
// set screen value
update();
}
UIElementRef ButtonSlider::create( UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString )
{
return shared_ptr<ButtonSlider>( new ButtonSlider( aUIController, aName, aValueToLink, aParamString ) );
}
void ButtonSlider::draw()
{
// draw the solid rect
if ( isLocked() ) {
gl::color( UIController::DEFAULT_STROKE_COLOR );
} else {
gl::color( getBackgroundColor() );//Color::black() );
}
gl::drawSolidRect( getBounds() );
// draw the outer rect
if ( isActive() ) {
gl::color( UIController::ACTIVE_STROKE_COLOR );
} else {
gl::color( UIController::DEFAULT_STROKE_COLOR );
}
gl::drawStrokedRect( getBounds() );
// draw the handle
if ( isLocked() ) {
gl::color( Color::black() );
} else if ( isActive() ) {
gl::color( UIController::ACTIVE_STROKE_COLOR );
} else {
gl::color( UIController::DEFAULT_STROKE_COLOR );
}
// draw the label
drawLabel();
}
void ButtonSlider::update()
{
mValue = lmap<float>(*mLinkedValue, mMin, mMax, getBounds().getY1() - ButtonSlider::DEFAULT_HANDLE_HALFHEIGHT, getPosition().y + ButtonSlider::DEFAULT_HANDLE_HALFHEIGHT );
}
void ButtonSlider::handleMouseDown( const Vec2i &aMousePos )
{
updatePosition( aMousePos.y );
}
void ButtonSlider::handleMouseDrag( const Vec2i &aMousePos )
{
updatePosition( math<int>::clamp( aMousePos.y, mScreenMin, mScreenMax ) );
}
void ButtonSlider::updatePosition( const int &aPos )
{
mValue = aPos;
*mLinkedValue = lmap<float>(mValue, mScreenMax, mScreenMin, mMin, mMax );
}
// Slider2D
Slider2D::Slider2D( UIController *aUIController, const string &aName, Vec2f *aValueToLink, const string &aParamString )
: UIElement( aUIController, aName, aParamString )
{
// initialize unique variables
mLinkedValue = aValueToLink;
float minX = hasParam( "minX" ) ? getParam<float>( "minX" ) : 0.0f;
float maxX = hasParam( "maxX" ) ? getParam<float>( "maxX" ) : 1.0f;
float minY = hasParam( "minY" ) ? getParam<float>( "minY" ) : 0.0f;
float maxY = hasParam( "maxY" ) ? getParam<float>( "maxY" ) : 1.0f;
mMin = Vec2f( minX, minY );
mMax = Vec2f( maxX, maxY );
// set size and render name texture
int x = hasParam( "width" ) ? getParam<int>( "width" ) : Slider2D::DEFAULT_WIDTH;
int y = Slider2D::DEFAULT_HEIGHT;
setSize( Vec2i( x, y ) );
renderNameTexture();
// set position and bounds
setPositionAndBounds();
// set screen min and max
Vec2i offset = Vec2i( Slider2D::DEFAULT_HANDLE_HALFWIDTH, Slider2D::DEFAULT_HANDLE_HALFWIDTH );
mScreenMin = getPosition() + offset;
mScreenMax = getBounds().getLR() - offset;
// set screen value
update();
}
UIElementRef Slider2D::create( UIController *aUIController, const string &aName, Vec2f *aValueToLink, const string &aParamString )
{
return shared_ptr<Slider2D>( new Slider2D( aUIController, aName, aValueToLink, aParamString ) );
}
void Slider2D::draw()
{
// draw the outer rect
gl::color( UIController::DEFAULT_STROKE_COLOR );
gl::drawStrokedRect( getBounds() );
gl::drawSolidRect( getBounds() );
// draw the indicator lines
gl::color( UIController::ACTIVE_STROKE_COLOR );
gl::drawLine( Vec2f( getBounds().getX1(), mValue.y ), Vec2f( getBounds().getX2(), mValue.y ) );
gl::drawLine( Vec2f( mValue.x, getBounds().getY1() ), Vec2f( mValue.x, getBounds().getY2() ) );
// draw the handle
Vec2f offset = Vec2i( Slider2D::DEFAULT_HANDLE_HALFWIDTH, Slider2D::DEFAULT_HANDLE_HALFWIDTH );
Vec2f handleStart = mValue - offset;
Vec2f handleEnd = mValue + offset;
gl::drawStrokedRect( Rectf( handleStart, handleEnd ) );
gl::drawSolidRect( Rectf( handleStart, handleEnd ) );
}
void Slider2D::update()
{
Vec2i offset = Vec2i( Slider2D::DEFAULT_HANDLE_HALFWIDTH, Slider2D::DEFAULT_HANDLE_HALFWIDTH );
mValue.x = lmap<float>((*mLinkedValue).x, mMin.x, mMax.x, getPosition().x + offset.x, getBounds().getX2() - offset.x );
mValue.y = lmap<float>((*mLinkedValue).y, mMin.y, mMax.y, getBounds().getY2() - offset.y, getPosition().y + offset.y );
}
void Slider2D::handleMouseDown( const Vec2i &aMousePos )
{
updatePosition( aMousePos );
}
void Slider2D::handleMouseDrag( const Vec2i &aMousePos )
{
Vec2i newPos;
newPos.x = math<int>::clamp( aMousePos.x, mScreenMin.x, mScreenMax.x );
newPos.y = math<int>::clamp( aMousePos.y, mScreenMin.y, mScreenMax.y );
updatePosition( newPos );
}
void Slider2D::updatePosition( const Vec2i &aPos )
{
mValue = aPos;
(*mLinkedValue).x = lmap<float>(mValue.x, mScreenMin.x, mScreenMax.x, mMin.x, mMax.x );
(*mLinkedValue).y = lmap<float>(mValue.y, mScreenMin.y, mScreenMax.y, mMax.y, mMin.y );
}
<|endoftext|> |
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "open_spiel/abseil-cpp/absl/flags/flag.h"
#include "open_spiel/abseil-cpp/absl/flags/usage.h"
#include "open_spiel/abseil-cpp/absl/flags/parse.h"
#include "open_spiel/higc/referee.h"
ABSL_FLAG(std::string, game, "kuhn_poker", "What game should be played.");
ABSL_FLAG(int, num_matches, 1, "Number of matches to play.");
ABSL_FLAG(std::vector<std::string>, executables, {},
"Comma-separated list of paths to bot executable files.");
ABSL_FLAG(int, seed, 42, "Seed of the referee.");
int main(int argc, char** argv) {
absl::ParseCommandLine(argc, argv);
open_spiel::higc::Referee ref(
absl::GetFlag(FLAGS_game),
absl::GetFlag(FLAGS_executables),
absl::GetFlag(FLAGS_seed),
open_spiel::higc::TournamentSettings{
.timeout_ready = 200,
.timeout_start = 5000,
.timeout_act = 5000,
.timeout_ponder = 200,
.timeout_match_over = 1000,
.time_tournament_over = 60000,
.max_invalid_behaviors = 3,
.disqualification_rate = 0.1,
});
ref.PlayTournament(absl::GetFlag(FLAGS_num_matches));
}
<commit_msg>Update start/ready timing.<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "open_spiel/abseil-cpp/absl/flags/flag.h"
#include "open_spiel/abseil-cpp/absl/flags/usage.h"
#include "open_spiel/abseil-cpp/absl/flags/parse.h"
#include "open_spiel/higc/referee.h"
ABSL_FLAG(std::string, game, "kuhn_poker", "What game should be played.");
ABSL_FLAG(int, num_matches, 1, "Number of matches to play.");
ABSL_FLAG(std::vector<std::string>, executables, {},
"Comma-separated list of paths to bot executable files.");
ABSL_FLAG(int, seed, 42, "Seed of the referee.");
int main(int argc, char** argv) {
absl::ParseCommandLine(argc, argv);
open_spiel::higc::Referee ref(
absl::GetFlag(FLAGS_game),
absl::GetFlag(FLAGS_executables),
absl::GetFlag(FLAGS_seed),
open_spiel::higc::TournamentSettings{
.timeout_ready = 5000,
.timeout_start = 200,
.timeout_act = 5000,
.timeout_ponder = 200,
.timeout_match_over = 1000,
.time_tournament_over = 60000,
.max_invalid_behaviors = 3,
.disqualification_rate = 0.1,
});
ref.PlayTournament(absl::GetFlag(FLAGS_num_matches));
}
<|endoftext|> |
<commit_before>/*
* SchemeSmobAV.c
*
* Scheme small objects (SMOBS) for attention values.
*
* Copyright (c) 2008,2009 Linas Vepstas <linas@linas.org>
*/
#ifdef HAVE_GUILE
#include <libguile.h>
#include <opencog/atomspace/AttentionValue.h>
#include <opencog/guile/SchemeSmob.h>
using namespace opencog;
/* ============================================================== */
/**
* Search for an attention value in a list of values.
* Return the attention value if found, else return null.
* Throw errors if the list is not stictly just key-value pairs
*/
AttentionValue * SchemeSmob::get_av_from_list(SCM slist)
{
while (scm_is_pair(slist))
{
SCM sval = SCM_CAR(slist);
if (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, sval))
{
scm_t_bits misctype = SCM_SMOB_FLAGS(sval);
switch (misctype)
{
case COG_AV:
return (AttentionValue *) SCM_SMOB_DATA(sval);
default:
break;
}
}
slist = SCM_CDR(slist);
}
return NULL;
}
/* ============================================================== */
std::string SchemeSmob::av_to_string(const AttentionValue *av)
{
#define BUFLEN 120
char buff[BUFLEN];
snprintf(buff, BUFLEN, "(av %d %d %d)",
av->getSTI(), av->getLTI(), av->getVLTI());
std::string ret = buff;
return ret;
}
/* ============================================================== */
/**
* Take over memory management of an attention value
*/
SCM SchemeSmob::take_av (AttentionValue *av)
{
scm_gc_register_collectable_memory (av,
sizeof(*av), "opencog av");
SCM smob;
SCM_NEWSMOB (smob, cog_misc_tag, av);
SCM_SET_SMOB_FLAGS(smob, COG_AV);
return smob;
}
/* ============================================================== */
/**
* Create a new attention value, with indicated sti/lti/vlti
*/
SCM SchemeSmob::ss_new_av (SCM ssti, SCM slti, SCM svlti)
{
AttentionValue::sti_t sti = scm_to_short(ssti);
AttentionValue::lti_t lti = scm_to_short(slti);
AttentionValue::vlti_t vlti = scm_to_short(svlti);
AttentionValue *av = new AttentionValue(sti, lti, vlti);
return take_av(av);
}
/* ============================================================== */
/**
* Return true if the scm is an attention value
*/
SCM SchemeSmob::ss_av_p (SCM s)
{
if (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, s))
{
scm_t_bits misctype = SCM_SMOB_FLAGS(s);
switch (misctype)
{
case COG_AV:
return SCM_BOOL_T;
default:
return SCM_BOOL_F;
}
}
return SCM_BOOL_F;
}
/* ============================================================== */
AttentionValue * SchemeSmob::verify_av(SCM sav, const char *subrname)
{
if (!SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, sav))
scm_wrong_type_arg_msg(subrname, 2, sav, "opencog attention value");
scm_t_bits misctype = SCM_SMOB_FLAGS(sav);
if (COG_AV != misctype)
scm_wrong_type_arg_msg(subrname, 2, sav, "opencog attention value");
AttentionValue *av = (AttentionValue *) SCM_SMOB_DATA(sav);
return av;
}
/**
* Return association list holding contents of an attention value
*/
SCM SchemeSmob::ss_av_get_value (SCM s)
{
AttentionValue *av = verify_av(s, "cog-av->alist");
SCM sti = scm_from_short(av->getSTI());
SCM lti = scm_from_short(av->getLTI());
SCM vlti = scm_from_short(av->getVLTI());
SCM ssti = scm_from_locale_symbol("sti");
SCM slti = scm_from_locale_symbol("lti");
SCM svlti = scm_from_locale_symbol("vlti");
SCM rc = SCM_EOL;
rc = scm_acons(svlti, vlti, rc);
rc = scm_acons(slti, lti, rc);
rc = scm_acons(ssti, sti, rc);
return rc;
}
#endif /* HAVE_GUILE */
/* ===================== END OF FILE ============================ */
<commit_msg>Change VLTI to a SCM bool rather than an int<commit_after>/*
* SchemeSmobAV.c
*
* Scheme small objects (SMOBS) for attention values.
*
* Copyright (c) 2008,2009 Linas Vepstas <linas@linas.org>
*/
#ifdef HAVE_GUILE
#include <libguile.h>
#include <opencog/atomspace/AttentionValue.h>
#include <opencog/guile/SchemeSmob.h>
using namespace opencog;
/* ============================================================== */
/**
* Search for an attention value in a list of values.
* Return the attention value if found, else return null.
* Throw errors if the list is not stictly just key-value pairs
*/
AttentionValue * SchemeSmob::get_av_from_list(SCM slist)
{
while (scm_is_pair(slist))
{
SCM sval = SCM_CAR(slist);
if (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, sval))
{
scm_t_bits misctype = SCM_SMOB_FLAGS(sval);
switch (misctype)
{
case COG_AV:
return (AttentionValue *) SCM_SMOB_DATA(sval);
default:
break;
}
}
slist = SCM_CDR(slist);
}
return NULL;
}
/* ============================================================== */
std::string SchemeSmob::av_to_string(const AttentionValue *av)
{
#define BUFLEN 120
char buff[BUFLEN];
if (av->getVLTI() == 0) {
snprintf(buff, BUFLEN, "(av %d %d #f)",
av->getSTI(), av->getLTI());
} else {
snprintf(buff, BUFLEN, "(av %d %d #t)",
av->getSTI(), av->getLTI());
}
std::string ret = buff;
return ret;
}
/* ============================================================== */
/**
* Take over memory management of an attention value
*/
SCM SchemeSmob::take_av (AttentionValue *av)
{
scm_gc_register_collectable_memory (av,
sizeof(*av), "opencog av");
SCM smob;
SCM_NEWSMOB (smob, cog_misc_tag, av);
SCM_SET_SMOB_FLAGS(smob, COG_AV);
return smob;
}
/* ============================================================== */
/**
* Create a new attention value, with indicated sti/lti/vlti
*/
SCM SchemeSmob::ss_new_av (SCM ssti, SCM slti, SCM svlti)
{
AttentionValue::sti_t sti = scm_to_short(ssti);
AttentionValue::lti_t lti = scm_to_short(slti);
AttentionValue::vlti_t vlti = false;
if (!scm_is_bool(svlti)) {
scm_wrong_type_arg_msg("cog-new-tv", 4, svlti, "boolean value");
}
if (scm_is_true(svlti)) {
vlti = true;
}
AttentionValue *av = new AttentionValue(sti, lti, vlti);
return take_av(av);
}
/* ============================================================== */
/**
* Return true if the scm is an attention value
*/
SCM SchemeSmob::ss_av_p (SCM s)
{
if (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, s))
{
scm_t_bits misctype = SCM_SMOB_FLAGS(s);
switch (misctype)
{
case COG_AV:
return SCM_BOOL_T;
default:
return SCM_BOOL_F;
}
}
return SCM_BOOL_F;
}
/* ============================================================== */
AttentionValue * SchemeSmob::verify_av(SCM sav, const char *subrname)
{
if (!SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, sav))
scm_wrong_type_arg_msg(subrname, 2, sav, "opencog attention value");
scm_t_bits misctype = SCM_SMOB_FLAGS(sav);
if (COG_AV != misctype)
scm_wrong_type_arg_msg(subrname, 2, sav, "opencog attention value");
AttentionValue *av = (AttentionValue *) SCM_SMOB_DATA(sav);
return av;
}
/**
* Return association list holding contents of an attention value
*/
SCM SchemeSmob::ss_av_get_value (SCM s)
{
AttentionValue *av = verify_av(s, "cog-av->alist");
SCM sti = scm_from_short(av->getSTI());
SCM lti = scm_from_short(av->getLTI());
SCM vlti = scm_from_bool((int)av->getVLTI());
SCM ssti = scm_from_locale_symbol("sti");
SCM slti = scm_from_locale_symbol("lti");
SCM svlti = scm_from_locale_symbol("vlti");
SCM rc = SCM_EOL;
rc = scm_acons(svlti, vlti, rc);
rc = scm_acons(slti, lti, rc);
rc = scm_acons(ssti, sti, rc);
return rc;
}
#endif /* HAVE_GUILE */
/* ===================== END OF FILE ============================ */
<|endoftext|> |
<commit_before>#include "apfMesh.h"
#include "apf.h"
#include <PCU.h>
#include <gmi.h>
namespace apf {
static void intersect(
std::set<int>& a,
std::set<int> const& b)
{
for (std::set<int>::iterator it = a.begin();
it != a.end();)
{
if ( ! b.count(*it))
a.erase(*(it++));
else
++it;
}
}
static Parts getCandidateParts(Mesh* m, MeshEntity* e)
{
Downward d;
int nd = m->getDownward(e, getDimension(m, e) - 1, d);
Parts c;
m->getResidence(d[0], c);
for (int i = 1; i < nd; ++i)
{
Parts dr;
m->getResidence(d[i], dr);
intersect(c, dr);
}
return c;
}
static bool isSubset(Parts const& a, Parts const& b)
{
APF_ITERATE(Parts, a, it)
if (!b.count(*it))
return false;
return true;
}
static void verifyDown(Mesh* m, MeshEntity* e, int gd, int ed)
{
Downward d;
int nd = m->getDownward(e, ed - 1, d);
for (int i = 0; i < nd; ++i)
{
int dgd = m->getModelType(m->toModel(d[i]));
assert(dgd <= gd);
}
Parts r;
m->getResidence(e, r);
assert(isSubset(r, getCandidateParts(m, e)));
}
typedef std::map<ModelEntity*, int> UpwardCounts;
typedef std::map<ModelEntity*, bool> SideManifoldness;
static void getUpwardCounts(gmi_model* gm, int meshDimension, UpwardCounts& uc)
{
gmi_iter* it = gmi_begin(gm, meshDimension - 1);
gmi_ent* ge;
while ((ge = gmi_next(gm, it))) {
gmi_set* up = gmi_adjacent(gm, ge, meshDimension);
uc[(ModelEntity*)ge] = up->n;
gmi_free_set(up);
}
gmi_end(gm, it);
}
static void verifyUp(Mesh* m, UpwardCounts& guc,
MeshEntity* e)
{
apf::Up up;
m->getUp(e, up);
int upwardCount = up.n;
int meshDimension = m->getDimension();
int entityDimension = getDimension(m, e);
int difference = meshDimension - entityDimension;
if (!difference) { //element
assert(upwardCount == 0);
return;
}
ModelEntity* ge = m->toModel(e);
int modelDimension = m->getModelType(ge);
/* minimum number of upward adjacencies if
everything is manifold: */
int manifoldMin;
/* test for boundary exposure in the manifold case */
if ((modelDimension < meshDimension) || m->isShared(e))
manifoldMin = difference;
else
manifoldMin = difference + 1;
assert(upwardCount >= manifoldMin);
/* mesh faces must have exactly the right number of
adjacent elements, other entities can have fans
of any size above the minimum */
if (difference == 1) {
int expected = manifoldMin;
/* account for classification on non-manifold model faces that have 2
adjacent regions as well as model faces with no topology
that have "0" adjacent regions */
if (modelDimension == entityDimension)
expected = std::max( guc[ge], expected );
assert(upwardCount == expected);
}
}
static void verifyResidence(Mesh* m, MeshEntity* e)
{
Parts p;
m->getResidence(e, p);
assert(p.count(m->getOwner(e)));
Copies r;
m->getRemotes(e, r);
assert(r.size() + 1 == p.size());
APF_ITERATE(Copies, r, it)
assert(p.count(it->first));
}
static void verifyEntity(Mesh* m, UpwardCounts& guc, MeshEntity* e)
{
int ed = getDimension(m, e);
int md = m->getDimension();
assert(md >= ed);
int gd = m->getModelType(m->toModel(e));
assert(gd >= ed);
if (ed)
verifyDown(m, e, gd, ed);
if (ed < md)
verifyUp(m, guc, e);
verifyResidence(m, e);
}
static Copies getAllCopies(Mesh* m, MeshEntity* e)
{
Copies c;
m->getRemotes(e, c);
c[PCU_Comm_Self()] = e;
return c;
}
static void verifyAllCopies(Copies& a)
{
APF_ITERATE(Copies, a, it)
{
assert(it->first >= 0);
assert(it->first < PCU_Comm_Peers());
}
}
static void packCopies(
int to,
Copies& copies)
{
int n = copies.size();
PCU_COMM_PACK(to,n);
APF_ITERATE(Copies,copies,it)
{
PCU_COMM_PACK(to,it->first);
PCU_COMM_PACK(to,it->second);
}
}
static void unpackCopies(
Copies& copies)
{
int n;
PCU_COMM_UNPACK(n);
for (int i=0; i < n; ++i)
{
int part;
PCU_COMM_UNPACK(part);
MeshEntity* remote;
PCU_COMM_UNPACK(remote);
assert(remote);
copies[part]=remote;
}
}
static void sendAllCopies(Mesh* m, MeshEntity* e)
{
Copies a;
Copies r;
a = getAllCopies(m, e);
verifyAllCopies(a);
m->getRemotes(e, r);
assert(!r.count(PCU_Comm_Self()));
APF_ITERATE(Copies, r, it)
{
PCU_COMM_PACK(it->first, it->second);
packCopies(it->first, a);
}
}
static void receiveAllCopies(Mesh* m)
{
MeshEntity* e;
PCU_COMM_UNPACK(e);
Copies a;
unpackCopies(a);
Copies b = getAllCopies(m, e);
assert(a == b);
}
static void verifyConnectivity(Mesh* m)
{
PCU_Comm_Begin();
for (int d = 0; d <= m->getDimension(); ++d)
{
MeshIterator* it = m->begin(d);
MeshEntity* e;
while ((e = m->iterate(it)))
if (m->isShared(e))
sendAllCopies(m, e);
m->end(it);
}
PCU_Comm_Send();
while (PCU_Comm_Receive())
receiveAllCopies(m);
}
static void sendCoords(Mesh* m, MeshEntity* e)
{
Vector3 x;
m->getPoint(e, 0, x);
Vector3 p(0,0,0);
m->getParam(e, p);
Copies r;
m->getRemotes(e, r);
APF_ITERATE(Copies, r, it)
{
PCU_COMM_PACK(it->first, it->second);
PCU_COMM_PACK(it->first, x);
PCU_COMM_PACK(it->first, p);
}
}
static bool receiveCoords(Mesh* m)
{
MeshEntity* e;
Vector3 ox;
Vector3 op;
PCU_COMM_UNPACK(e);
PCU_COMM_UNPACK(ox);
PCU_COMM_UNPACK(op);
Vector3 x;
Vector3 p(0,0,0);
m->getPoint(e, 0, x);
m->getParam(e, p);
return (x == ox) && (p == op);
}
static long verifyCoords(Mesh* m)
{
PCU_Comm_Begin();
MeshIterator* it = m->begin(0);
MeshEntity* e;
while ((e = m->iterate(it)))
if (m->isShared(e))
sendCoords(m, e);
m->end(it);
PCU_Comm_Send();
long n = 0;
while (PCU_Comm_Receive())
if (!receiveCoords(m))
++n;
PCU_Add_Longs(&n, 1);
return n;
}
static long verifyVolumes(Mesh* m)
{
MeshIterator* it = m->begin(m->getDimension());
MeshEntity* e;
long n = 0;
while ((e = m->iterate(it)))
{
if (!isSimplex(m->getType(e)))
continue;
MeshElement* me = createMeshElement(m, e);
if (measure(me) < 0)
++n;
destroyMeshElement(me);
}
m->end(it);
PCU_Add_Longs(&n, 1);
return n;
}
static void packOrder(Mesh* m, MeshEntity* e, MeshEntity* r, int to)
{
PCU_COMM_PACK(to,r);
int d = getDimension(m, e);
Downward down;
int nd = m->getDownward(e, d - 1, down);
for (int i = 0; i < nd; ++i) {
Copies remotes;
m->getRemotes(down[i], remotes);
MeshEntity* dr = remotes[to];
PCU_COMM_PACK(to,dr);
}
}
static void sendOrder(Mesh* m, MeshEntity* e)
{
Copies remotes;
m->getRemotes(e, remotes);
APF_ITERATE(Copies, remotes, it)
packOrder(m, e, it->second, it->first);
}
static void receiveOrder(Mesh* m)
{
MeshEntity* e;
PCU_COMM_UNPACK(e);
int d = getDimension(m, e);
Downward down;
int nd = m->getDownward(e, d - 1, down);
for (int i = 0; i < nd; ++i) {
PCU_COMM_UNPACK(e);
assert(down[i] == e);
}
}
static void verifyOrder(Mesh* m)
{
PCU_Comm_Begin();
for (int d = 1; d <= m->getDimension(); ++d)
{
MeshIterator* it = m->begin(d);
MeshEntity* e;
while ((e = m->iterate(it)))
if (m->isShared(e))
sendOrder(m, e);
m->end(it);
}
PCU_Comm_Send();
while (PCU_Comm_Receive())
receiveOrder(m);
}
void verify(Mesh* m)
{
double t0 = MPI_Wtime();
UpwardCounts guc;
getUpwardCounts(m->getModel(), m->getDimension(), guc);
/* got to 3 on purpose, so we can verify if
m->getDimension is lying */
for (int d = 0; d <= 3; ++d)
{
MeshIterator* it = m->begin(d);
MeshEntity* e;
size_t n = 0;
while ((e = m->iterate(it)))
{
verifyEntity(m, guc, e);
++n;
}
m->end(it);
assert(n == m->count(d));
if (d <= m->getDimension())
assert(n);
else
assert(!n);
}
guc.clear();
verifyConnectivity(m);
verifyOrder(m);
long n = verifyCoords(m);
if (n && (!PCU_Comm_Self()))
fprintf(stderr,"apf::verify warning: %ld coordinate mismatches\n", n);
n = verifyVolumes(m);
if (n && (!PCU_Comm_Self()))
fprintf(stderr,"apf::verify warning: %ld negative simplex elements\n", n);
double t1 = MPI_Wtime();
if (!PCU_Comm_Self())
printf("mesh verified in %f seconds\n", t1 - t0);
}
}
<commit_msg>another iteration on apf::verify<commit_after>#include "apfMesh.h"
#include "apf.h"
#include <PCU.h>
#include <gmi.h>
namespace apf {
static void intersect(
std::set<int>& a,
std::set<int> const& b)
{
for (std::set<int>::iterator it = a.begin();
it != a.end();)
{
if ( ! b.count(*it))
a.erase(*(it++));
else
++it;
}
}
static Parts getCandidateParts(Mesh* m, MeshEntity* e)
{
Downward d;
int nd = m->getDownward(e, getDimension(m, e) - 1, d);
Parts c;
m->getResidence(d[0], c);
for (int i = 1; i < nd; ++i)
{
Parts dr;
m->getResidence(d[i], dr);
intersect(c, dr);
}
return c;
}
static bool isSubset(Parts const& a, Parts const& b)
{
APF_ITERATE(Parts, a, it)
if (!b.count(*it))
return false;
return true;
}
static void verifyDown(Mesh* m, MeshEntity* e, int gd, int ed)
{
Downward d;
int nd = m->getDownward(e, ed - 1, d);
for (int i = 0; i < nd; ++i)
{
int dgd = m->getModelType(m->toModel(d[i]));
assert(dgd <= gd);
}
Parts r;
m->getResidence(e, r);
assert(isSubset(r, getCandidateParts(m, e)));
}
typedef std::map<ModelEntity*, int> UpwardCounts;
typedef std::map<ModelEntity*, bool> SideManifoldness;
static void getUpwardCounts(gmi_model* gm, int meshDimension, UpwardCounts& uc)
{
for (int d = 0; d < meshDimension; ++d) {
gmi_iter* it = gmi_begin(gm, d);
gmi_ent* ge;
while ((ge = gmi_next(gm, it))) {
gmi_set* up = gmi_adjacent(gm, ge, d + 1);
uc[(ModelEntity*)ge] = up->n;
gmi_free_set(up);
}
gmi_end(gm, it);
}
}
static void verifyUp(Mesh* m, UpwardCounts& guc,
MeshEntity* e)
{
apf::Up up;
m->getUp(e, up);
int upwardCount = up.n;
int meshDimension = m->getDimension();
int entityDimension = getDimension(m, e);
int difference = meshDimension - entityDimension;
if (!difference) { //element
assert(upwardCount == 0);
return;
}
ModelEntity* ge = m->toModel(e);
int modelDimension = m->getModelType(ge);
int modelUpwardCount = guc[ge];
bool isOnNonManifoldFace = (modelDimension == meshDimension - 1) &&
(modelUpwardCount > 1);
bool isOnManifoldBoundary = ( ! isOnNonManifoldFace) &&
(modelDimension < meshDimension);
bool isExposed = m->isShared(e) || isOnManifoldBoundary;
bool isOnEqualOrder = (modelDimension == entityDimension);
int expected;
if (isExposed) {
expected = difference;
} else {
expected = difference + 1;
if (isOnEqualOrder)
expected = std::max(expected, modelUpwardCount);
}
assert(upwardCount >= expected);
if (difference == 1)
assert(upwardCount == expected);
}
static void verifyResidence(Mesh* m, MeshEntity* e)
{
Parts p;
m->getResidence(e, p);
assert(p.count(m->getOwner(e)));
Copies r;
m->getRemotes(e, r);
assert(r.size() + 1 == p.size());
APF_ITERATE(Copies, r, it)
assert(p.count(it->first));
}
static void verifyEntity(Mesh* m, UpwardCounts& guc, MeshEntity* e)
{
int ed = getDimension(m, e);
int md = m->getDimension();
assert(md >= ed);
int gd = m->getModelType(m->toModel(e));
assert(gd >= ed);
if (ed)
verifyDown(m, e, gd, ed);
if (ed < md)
verifyUp(m, guc, e);
verifyResidence(m, e);
}
static Copies getAllCopies(Mesh* m, MeshEntity* e)
{
Copies c;
m->getRemotes(e, c);
c[PCU_Comm_Self()] = e;
return c;
}
static void verifyAllCopies(Copies& a)
{
APF_ITERATE(Copies, a, it)
{
assert(it->first >= 0);
assert(it->first < PCU_Comm_Peers());
}
}
static void packCopies(
int to,
Copies& copies)
{
int n = copies.size();
PCU_COMM_PACK(to,n);
APF_ITERATE(Copies,copies,it)
{
PCU_COMM_PACK(to,it->first);
PCU_COMM_PACK(to,it->second);
}
}
static void unpackCopies(
Copies& copies)
{
int n;
PCU_COMM_UNPACK(n);
for (int i=0; i < n; ++i)
{
int part;
PCU_COMM_UNPACK(part);
MeshEntity* remote;
PCU_COMM_UNPACK(remote);
assert(remote);
copies[part]=remote;
}
}
static void sendAllCopies(Mesh* m, MeshEntity* e)
{
Copies a;
Copies r;
a = getAllCopies(m, e);
verifyAllCopies(a);
m->getRemotes(e, r);
assert(!r.count(PCU_Comm_Self()));
APF_ITERATE(Copies, r, it)
{
PCU_COMM_PACK(it->first, it->second);
packCopies(it->first, a);
}
}
static void receiveAllCopies(Mesh* m)
{
MeshEntity* e;
PCU_COMM_UNPACK(e);
Copies a;
unpackCopies(a);
Copies b = getAllCopies(m, e);
assert(a == b);
}
static void verifyConnectivity(Mesh* m)
{
PCU_Comm_Begin();
for (int d = 0; d <= m->getDimension(); ++d)
{
MeshIterator* it = m->begin(d);
MeshEntity* e;
while ((e = m->iterate(it)))
if (m->isShared(e))
sendAllCopies(m, e);
m->end(it);
}
PCU_Comm_Send();
while (PCU_Comm_Receive())
receiveAllCopies(m);
}
static void sendCoords(Mesh* m, MeshEntity* e)
{
Vector3 x;
m->getPoint(e, 0, x);
Vector3 p(0,0,0);
m->getParam(e, p);
Copies r;
m->getRemotes(e, r);
APF_ITERATE(Copies, r, it)
{
PCU_COMM_PACK(it->first, it->second);
PCU_COMM_PACK(it->first, x);
PCU_COMM_PACK(it->first, p);
}
}
static bool receiveCoords(Mesh* m)
{
MeshEntity* e;
Vector3 ox;
Vector3 op;
PCU_COMM_UNPACK(e);
PCU_COMM_UNPACK(ox);
PCU_COMM_UNPACK(op);
Vector3 x;
Vector3 p(0,0,0);
m->getPoint(e, 0, x);
m->getParam(e, p);
return (x == ox) && (p == op);
}
static long verifyCoords(Mesh* m)
{
PCU_Comm_Begin();
MeshIterator* it = m->begin(0);
MeshEntity* e;
while ((e = m->iterate(it)))
if (m->isShared(e))
sendCoords(m, e);
m->end(it);
PCU_Comm_Send();
long n = 0;
while (PCU_Comm_Receive())
if (!receiveCoords(m))
++n;
PCU_Add_Longs(&n, 1);
return n;
}
static long verifyVolumes(Mesh* m)
{
MeshIterator* it = m->begin(m->getDimension());
MeshEntity* e;
long n = 0;
while ((e = m->iterate(it)))
{
if (!isSimplex(m->getType(e)))
continue;
MeshElement* me = createMeshElement(m, e);
if (measure(me) < 0)
++n;
destroyMeshElement(me);
}
m->end(it);
PCU_Add_Longs(&n, 1);
return n;
}
static void packOrder(Mesh* m, MeshEntity* e, MeshEntity* r, int to)
{
PCU_COMM_PACK(to,r);
int d = getDimension(m, e);
Downward down;
int nd = m->getDownward(e, d - 1, down);
for (int i = 0; i < nd; ++i) {
Copies remotes;
m->getRemotes(down[i], remotes);
MeshEntity* dr = remotes[to];
PCU_COMM_PACK(to,dr);
}
}
static void sendOrder(Mesh* m, MeshEntity* e)
{
Copies remotes;
m->getRemotes(e, remotes);
APF_ITERATE(Copies, remotes, it)
packOrder(m, e, it->second, it->first);
}
static void receiveOrder(Mesh* m)
{
MeshEntity* e;
PCU_COMM_UNPACK(e);
int d = getDimension(m, e);
Downward down;
int nd = m->getDownward(e, d - 1, down);
for (int i = 0; i < nd; ++i) {
PCU_COMM_UNPACK(e);
assert(down[i] == e);
}
}
static void verifyOrder(Mesh* m)
{
PCU_Comm_Begin();
for (int d = 1; d <= m->getDimension(); ++d)
{
MeshIterator* it = m->begin(d);
MeshEntity* e;
while ((e = m->iterate(it)))
if (m->isShared(e))
sendOrder(m, e);
m->end(it);
}
PCU_Comm_Send();
while (PCU_Comm_Receive())
receiveOrder(m);
}
void verify(Mesh* m)
{
double t0 = MPI_Wtime();
UpwardCounts guc;
getUpwardCounts(m->getModel(), m->getDimension(), guc);
/* got to 3 on purpose, so we can verify if
m->getDimension is lying */
for (int d = 0; d <= 3; ++d)
{
MeshIterator* it = m->begin(d);
MeshEntity* e;
size_t n = 0;
while ((e = m->iterate(it)))
{
verifyEntity(m, guc, e);
++n;
}
m->end(it);
assert(n == m->count(d));
if (d <= m->getDimension())
assert(n);
else
assert(!n);
}
guc.clear();
verifyConnectivity(m);
verifyOrder(m);
long n = verifyCoords(m);
if (n && (!PCU_Comm_Self()))
fprintf(stderr,"apf::verify warning: %ld coordinate mismatches\n", n);
n = verifyVolumes(m);
if (n && (!PCU_Comm_Self()))
fprintf(stderr,"apf::verify warning: %ld negative simplex elements\n", n);
double t1 = MPI_Wtime();
if (!PCU_Comm_Self())
printf("mesh verified in %f seconds\n", t1 - t0);
}
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "fnord-logtable/LogTableServlet.h"
#include "fnord-json/json.h"
#include "fnord-msg/MessageEncoder.h"
namespace fnord {
namespace logtable {
LogTableServlet::LogTableServlet(TableRepository* tables) : tables_(tables) {}
void LogTableServlet::handleHTTPRequest(
fnord::http::HTTPRequest* req,
fnord::http::HTTPResponse* res) {
URI uri(req->uri());
res->addHeader("Access-Control-Allow-Origin", "*");
try {
if (StringUtil::endsWith(uri.path(), "/insert")) {
return insertRecord(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/fetch")) {
return fetchRecords(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/commit")) {
return commitTable(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/merge")) {
return mergeTable(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/gc")) {
return gcTable(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/info")) {
return tableInfo(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/snapshot")) {
return tableSnapshot(req, res, &uri);
}
res->setStatus(fnord::http::kStatusNotFound);
res->addBody("not found");
} catch (const Exception& e) {
res->setStatus(http::kStatusInternalServerError);
res->addBody(StringUtil::format("error: $0", e.getMessage()));
}
}
void LogTableServlet::insertRecord(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto tbl = tables_->findTableWriter(table);
if (tbl->arenaSize() > 50000) {
res->setStatus(http::kStatusServiceUnavailable);
res->addBody("too many uncommitted records, retry in a few seconds");
} else {
tbl->addRecords(req->body());
res->setStatus(http::kStatusCreated);
}
}
void LogTableServlet::commitTable(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto tbl = tables_->findTableWriter(table);
auto n = tbl->commit();
res->setStatus(http::kStatusOK);
res->addBody(StringUtil::toString(n));
}
void LogTableServlet::mergeTable(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto tbl = tables_->findTableWriter(table);
tbl->merge();
res->setStatus(http::kStatusOK);
}
void LogTableServlet::gcTable(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto tbl = tables_->findTableWriter(table);
tbl->gc();
res->setStatus(http::kStatusOK);
}
void LogTableServlet::tableInfo(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto tbl = tables_->findTableWriter(table);
auto snap = tables_->getSnapshot(table);
HashMap<String, uint64_t> per_replica_head;
HashMap<String, uint64_t> artifacts;
HashMap<String, HashMap<String, String>> per_replica;
uint64_t num_recs_commited = 0;
uint64_t num_recs_arena = 0;
for (const auto& c : snap->head->chunks) {
auto chunkname = table + "." + c.replica_id + "." + c.chunk_id;
num_recs_commited += c.num_records;
artifacts[chunkname] = c.num_records;
auto seq = (c.start_sequence + c.num_records) - 1;
if (seq > per_replica_head[c.replica_id]) {
per_replica_head[c.replica_id] = seq;
per_replica[c.replica_id]["head_sequence"] = StringUtil::toString(seq);
}
}
auto my_head = per_replica_head[tables_->replicaID()];
for (const auto& a : snap->arenas) {
if (a->startSequence() > my_head) {
num_recs_arena += a->size();
}
}
Vector<String> missing_chunks;
uint64_t bytes_total = 0;
uint64_t bytes_present = 0;
uint64_t bytes_downloading = 0;
uint64_t bytes_missing = 0;
uint64_t num_chunks_present = 0;
uint64_t num_chunks_downloading = 0;
uint64_t num_chunks_missing = 0;
uint64_t num_recs_present = 0;
uint64_t num_recs_downloading = 0;
uint64_t num_recs_missing = 0;
auto artifactlist = tbl->artifactIndex()->listArtifacts();
for (const auto& a : artifactlist) {
if (artifacts.count(a.name) > 0) {
bytes_total += a.totalSize();
switch (a.status) {
case ArtifactStatus::PRESENT:
bytes_present += a.totalSize();
++num_chunks_present;
num_recs_present += artifacts[a.name];
break;
case ArtifactStatus::DOWNLOAD:
bytes_downloading += a.totalSize();
++num_chunks_downloading;
num_recs_downloading += artifacts[a.name];
break;
default:
case ArtifactStatus::MISSING:
missing_chunks.emplace_back(a.name);
bytes_missing += a.totalSize();
++num_chunks_missing;
num_recs_missing += artifacts[a.name];
break;
}
}
}
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream j(res->getBodyOutputStream());
j.beginObject();
j.addObjectEntry("table");
j.addString(table);
j.addComma();
j.addObjectEntry("num_records_total");
j.addInteger(num_recs_commited + num_recs_arena);
j.addComma();
j.addObjectEntry("num_records_commited");
j.addInteger(num_recs_commited);
j.addComma();
j.addObjectEntry("num_records_present");
j.addInteger(num_recs_present);
j.addComma();
j.addObjectEntry("num_records_downloading");
j.addInteger(num_recs_downloading);
j.addComma();
j.addObjectEntry("num_records_stage");
j.addInteger(num_recs_arena);
j.addComma();
j.addObjectEntry("num_records_missing");
j.addInteger(num_recs_missing);
j.addComma();
j.addObjectEntry("bytes_total");
j.addInteger(bytes_total);
j.addComma();
j.addObjectEntry("bytes_present");
j.addInteger(bytes_present);
j.addComma();
j.addObjectEntry("bytes_downloading");
j.addInteger(bytes_downloading);
j.addComma();
j.addObjectEntry("bytes_missing");
j.addInteger(bytes_missing);
j.addComma();
j.addObjectEntry("num_chunks");
j.addInteger(snap->head->chunks.size());
j.addComma();
j.addObjectEntry("num_chunks_present");
j.addInteger(num_chunks_present);
j.addComma();
j.addObjectEntry("num_chunks_downloading");
j.addInteger(num_chunks_downloading);
j.addComma();
j.addObjectEntry("num_chunks_missing");
j.addInteger(num_chunks_missing);
j.addComma();
j.addObjectEntry("replicas");
json::toJSON(per_replica, &j);
j.addComma();
j.addObjectEntry("missing_chunks");
json::toJSON(missing_chunks, &j);
j.endObject();
}
void LogTableServlet::tableSnapshot(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto snap = tables_->getSnapshot(table);
Buffer buf;
snap->head->encode(&buf);
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res->addBody(buf);
}
void LogTableServlet::fetchRecords(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
String replica;
if (!URI::getParam(params, "replica", &replica)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?replica=... parameter");
return;
}
String seq_str;
uint64_t seq;
if (URI::getParam(params, "seq", &seq_str)) {
seq = std::stoull(seq_str);
} else {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?seq=... parameter");
return;
}
String limit_str;
uint64_t limit;
if (URI::getParam(params, "limit", &limit_str)) {
limit = std::stoull(limit_str);
} else {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?limit=... parameter");
return;
}
auto tbl = tables_->findTableReader(table);
const auto& schema = tbl->schema();
Buffer body;
auto on_record = [&body, &schema] (const msg::MessageObject& rec) -> bool {
msg::MessageEncoder::encode(rec, schema, &body);
return true;
};
tbl->fetchRecords(replica, seq, limit, on_record);
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res->addBody(body);
}
}
}
<commit_msg>return records in human readable format<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "fnord-logtable/LogTableServlet.h"
#include "fnord-json/json.h"
#include "fnord-msg/MessageEncoder.h"
#include "fnord-msg/MessagePrinter.h"
namespace fnord {
namespace logtable {
LogTableServlet::LogTableServlet(TableRepository* tables) : tables_(tables) {}
void LogTableServlet::handleHTTPRequest(
fnord::http::HTTPRequest* req,
fnord::http::HTTPResponse* res) {
URI uri(req->uri());
res->addHeader("Access-Control-Allow-Origin", "*");
try {
if (StringUtil::endsWith(uri.path(), "/insert")) {
return insertRecord(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/fetch")) {
return fetchRecords(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/commit")) {
return commitTable(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/merge")) {
return mergeTable(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/gc")) {
return gcTable(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/info")) {
return tableInfo(req, res, &uri);
}
if (StringUtil::endsWith(uri.path(), "/snapshot")) {
return tableSnapshot(req, res, &uri);
}
res->setStatus(fnord::http::kStatusNotFound);
res->addBody("not found");
} catch (const Exception& e) {
res->setStatus(http::kStatusInternalServerError);
res->addBody(StringUtil::format("error: $0", e.getMessage()));
}
}
void LogTableServlet::insertRecord(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto tbl = tables_->findTableWriter(table);
if (tbl->arenaSize() > 50000) {
res->setStatus(http::kStatusServiceUnavailable);
res->addBody("too many uncommitted records, retry in a few seconds");
} else {
tbl->addRecords(req->body());
res->setStatus(http::kStatusCreated);
}
}
void LogTableServlet::commitTable(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto tbl = tables_->findTableWriter(table);
auto n = tbl->commit();
res->setStatus(http::kStatusOK);
res->addBody(StringUtil::toString(n));
}
void LogTableServlet::mergeTable(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto tbl = tables_->findTableWriter(table);
tbl->merge();
res->setStatus(http::kStatusOK);
}
void LogTableServlet::gcTable(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto tbl = tables_->findTableWriter(table);
tbl->gc();
res->setStatus(http::kStatusOK);
}
void LogTableServlet::tableInfo(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto tbl = tables_->findTableWriter(table);
auto snap = tables_->getSnapshot(table);
HashMap<String, uint64_t> per_replica_head;
HashMap<String, uint64_t> artifacts;
HashMap<String, HashMap<String, String>> per_replica;
uint64_t num_recs_commited = 0;
uint64_t num_recs_arena = 0;
for (const auto& c : snap->head->chunks) {
auto chunkname = table + "." + c.replica_id + "." + c.chunk_id;
num_recs_commited += c.num_records;
artifacts[chunkname] = c.num_records;
auto seq = (c.start_sequence + c.num_records) - 1;
if (seq > per_replica_head[c.replica_id]) {
per_replica_head[c.replica_id] = seq;
per_replica[c.replica_id]["head_sequence"] = StringUtil::toString(seq);
}
}
auto my_head = per_replica_head[tables_->replicaID()];
for (const auto& a : snap->arenas) {
if (a->startSequence() > my_head) {
num_recs_arena += a->size();
}
}
Vector<String> missing_chunks;
uint64_t bytes_total = 0;
uint64_t bytes_present = 0;
uint64_t bytes_downloading = 0;
uint64_t bytes_missing = 0;
uint64_t num_chunks_present = 0;
uint64_t num_chunks_downloading = 0;
uint64_t num_chunks_missing = 0;
uint64_t num_recs_present = 0;
uint64_t num_recs_downloading = 0;
uint64_t num_recs_missing = 0;
auto artifactlist = tbl->artifactIndex()->listArtifacts();
for (const auto& a : artifactlist) {
if (artifacts.count(a.name) > 0) {
bytes_total += a.totalSize();
switch (a.status) {
case ArtifactStatus::PRESENT:
bytes_present += a.totalSize();
++num_chunks_present;
num_recs_present += artifacts[a.name];
break;
case ArtifactStatus::DOWNLOAD:
bytes_downloading += a.totalSize();
++num_chunks_downloading;
num_recs_downloading += artifacts[a.name];
break;
default:
case ArtifactStatus::MISSING:
missing_chunks.emplace_back(a.name);
bytes_missing += a.totalSize();
++num_chunks_missing;
num_recs_missing += artifacts[a.name];
break;
}
}
}
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream j(res->getBodyOutputStream());
j.beginObject();
j.addObjectEntry("table");
j.addString(table);
j.addComma();
j.addObjectEntry("num_records_total");
j.addInteger(num_recs_commited + num_recs_arena);
j.addComma();
j.addObjectEntry("num_records_commited");
j.addInteger(num_recs_commited);
j.addComma();
j.addObjectEntry("num_records_present");
j.addInteger(num_recs_present);
j.addComma();
j.addObjectEntry("num_records_downloading");
j.addInteger(num_recs_downloading);
j.addComma();
j.addObjectEntry("num_records_stage");
j.addInteger(num_recs_arena);
j.addComma();
j.addObjectEntry("num_records_missing");
j.addInteger(num_recs_missing);
j.addComma();
j.addObjectEntry("bytes_total");
j.addInteger(bytes_total);
j.addComma();
j.addObjectEntry("bytes_present");
j.addInteger(bytes_present);
j.addComma();
j.addObjectEntry("bytes_downloading");
j.addInteger(bytes_downloading);
j.addComma();
j.addObjectEntry("bytes_missing");
j.addInteger(bytes_missing);
j.addComma();
j.addObjectEntry("num_chunks");
j.addInteger(snap->head->chunks.size());
j.addComma();
j.addObjectEntry("num_chunks_present");
j.addInteger(num_chunks_present);
j.addComma();
j.addObjectEntry("num_chunks_downloading");
j.addInteger(num_chunks_downloading);
j.addComma();
j.addObjectEntry("num_chunks_missing");
j.addInteger(num_chunks_missing);
j.addComma();
j.addObjectEntry("replicas");
json::toJSON(per_replica, &j);
j.addComma();
j.addObjectEntry("missing_chunks");
json::toJSON(missing_chunks, &j);
j.endObject();
}
void LogTableServlet::tableSnapshot(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
auto snap = tables_->getSnapshot(table);
Buffer buf;
snap->head->encode(&buf);
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/octet-stream");
res->addBody(buf);
}
void LogTableServlet::fetchRecords(
http::HTTPRequest* req,
http::HTTPResponse* res,
URI* uri) {
const auto& params = uri->queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?table=... parameter");
return;
}
String replica;
if (!URI::getParam(params, "replica", &replica)) {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?replica=... parameter");
return;
}
String seq_str;
uint64_t seq;
if (URI::getParam(params, "seq", &seq_str)) {
seq = std::stoull(seq_str);
} else {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?seq=... parameter");
return;
}
String limit_str;
uint64_t limit;
if (URI::getParam(params, "limit", &limit_str)) {
limit = std::stoull(limit_str);
} else {
res->setStatus(fnord::http::kStatusBadRequest);
res->addBody("missing ?limit=... parameter");
return;
}
String format = "binary";
URI::getParam(params, "format", &format);
auto tbl = tables_->findTableReader(table);
const auto& schema = tbl->schema();
Buffer body;
if (format == "human") {
tbl->fetchRecords(
replica,
seq,
limit,
[&body, &schema] (const msg::MessageObject& rec) -> bool {
body.append(msg::MessagePrinter::print(rec, schema));
return true;
});
res->addHeader("Content-Type", "text/plain");
} else {
tbl->fetchRecords(
replica,
seq,
limit,
[&body, &schema] (const msg::MessageObject& rec) -> bool {
msg::MessageEncoder::encode(rec, schema, &body);
return true;
});
res->addHeader("Content-Type", "application/octet-stream");
}
res->setStatus(http::kStatusOK);
res->addBody(body);
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: Filter.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2003-03-25 18:01:15 $
*
* 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 FORMS_COMPONENT_FILTER_HXX
#define FORMS_COMPONENT_FILTER_HXX
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XBOUNDCOMPONENT_HPP_
#include <com/sun/star/form/XBoundComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XTEXTCOMPONENT_HPP_
#include <com/sun/star/awt/XTextComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef _TOOLKIT_CONTROLS_UNOCONTROL_HXX_
#include <toolkit/controls/unocontrol.hxx>
#endif
#ifndef _TOOLKIT_AWT_LISTENERMULTIPLEXER_HXX_
#include <toolkit/helper/listenermultiplexer.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#include <connectivity/sqlparse.hxx>
#endif
#ifndef SVX_QUERYDESIGNCONTEXT_HXX
#include <svx/ParseContext.hxx>
#endif
class Window;
//.........................................................................
namespace frm
{
//.........................................................................
//=====================================================================
// OFilterControl
//=====================================================================
typedef ::cppu::ImplHelper5 < ::com::sun::star::awt::XTextComponent
, ::com::sun::star::awt::XFocusListener
, ::com::sun::star::awt::XItemListener
, ::com::sun::star::form::XBoundComponent
, ::com::sun::star::lang::XInitialization
> OFilterControl_BASE;
class OFilterControl :public UnoControl
,public OFilterControl_BASE
,public ::svxform::OParseContextClient
{
TextListenerMultiplexer m_aTextListeners;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xField;
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > m_xMessageParent;
::rtl::OUString m_aText;
::connectivity::OSQLParser m_aParser;
sal_Int16 m_nControlClass; // which kind of control do we use?
sal_Bool m_bFilterList : 1;
sal_Bool m_bMultiLine : 1;
sal_Bool m_bFilterListFilled : 1;
private:
// OFilterControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
void implInitFilterList();
public:
OFilterControl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB );
DECLARE_UNO3_AGG_DEFAULTS(OFilterControl,OWeakAggObject);
::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId();
sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 > & rId );
virtual ::rtl::OUString GetComponentServiceName();
virtual void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit > & rxToolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > & rParentPeer ) throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::lang::XComponent
virtual void SAL_CALL dispose(void) throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::awt::XTextComponent
virtual void SAL_CALL addTextListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextListener > & l ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL removeTextListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextListener > & l ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setText( const ::rtl::OUString& aText ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL insertText( const ::com::sun::star::awt::Selection& rSel, const ::rtl::OUString& aText ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getText() throw( ::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getSelectedText() throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setSelection( const ::com::sun::star::awt::Selection& aSelection ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::awt::Selection SAL_CALL getSelection() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL isEditable() throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setEditable( sal_Bool bEditable ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setMaxTextLen( sal_Int16 nLength ) throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Int16 SAL_CALL getMaxTextLen() throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::form::XBoundComponent
virtual void SAL_CALL addUpdateListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XUpdateListener > & l) throw( ::com::sun::star::uno::RuntimeException ) {}
virtual void SAL_CALL removeUpdateListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XUpdateListener > & l) throw( ::com::sun::star::uno::RuntimeException ) {}
virtual sal_Bool SAL_CALL commit() throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::lang::XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::awt::XFocusListener
virtual void SAL_CALL focusGained(const ::com::sun::star::awt::FocusEvent& e) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL focusLost(const ::com::sun::star::awt::FocusEvent& e) throw( ::com::sun::star::uno::RuntimeException ){}
// ::com::sun::star::awt::XItemListener
virtual void SAL_CALL itemStateChanged(const ::com::sun::star::awt::ItemEvent& rEvent) throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::util::XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);
// com::sun::star::lang::XServiceInfo - static version
static ::rtl::OUString SAL_CALL getImplementationName_Static();
static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_Static();
static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getCurrentServiceNames_Static();
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory );
protected:
virtual void PrepareWindowDescriptor( ::com::sun::star::awt::WindowDescriptor& rDesc );
virtual void ImplSetPeerProperty( const ::rtl::OUString& rPropName, const ::com::sun::star::uno::Any& rVal );
sal_Bool ensureInitialized( );
void displayException( const ::com::sun::star::sdb::SQLContext& _rExcept );
};
//.........................................................................
} // namespace frm
//.........................................................................
#endif // FORMS_COMPONENT_FILTER_HXX
<commit_msg>INTEGRATION: CWS frmcontrols01 (1.2.46); FILE MERGED 2003/10/22 13:06:04 fs 1.2.46.1: removed obsolete getCurrentServiceNames_Static (stumbled upon this during #21277#)<commit_after>/*************************************************************************
*
* $RCSfile: Filter.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2003-12-11 12:28:37 $
*
* 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 FORMS_COMPONENT_FILTER_HXX
#define FORMS_COMPONENT_FILTER_HXX
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XBOUNDCOMPONENT_HPP_
#include <com/sun/star/form/XBoundComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XTEXTCOMPONENT_HPP_
#include <com/sun/star/awt/XTextComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef _TOOLKIT_CONTROLS_UNOCONTROL_HXX_
#include <toolkit/controls/unocontrol.hxx>
#endif
#ifndef _TOOLKIT_AWT_LISTENERMULTIPLEXER_HXX_
#include <toolkit/helper/listenermultiplexer.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#include <connectivity/sqlparse.hxx>
#endif
#ifndef SVX_QUERYDESIGNCONTEXT_HXX
#include <svx/ParseContext.hxx>
#endif
class Window;
//.........................................................................
namespace frm
{
//.........................................................................
//=====================================================================
// OFilterControl
//=====================================================================
typedef ::cppu::ImplHelper5 < ::com::sun::star::awt::XTextComponent
, ::com::sun::star::awt::XFocusListener
, ::com::sun::star::awt::XItemListener
, ::com::sun::star::form::XBoundComponent
, ::com::sun::star::lang::XInitialization
> OFilterControl_BASE;
class OFilterControl :public UnoControl
,public OFilterControl_BASE
,public ::svxform::OParseContextClient
{
TextListenerMultiplexer m_aTextListeners;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xField;
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > m_xMessageParent;
::rtl::OUString m_aText;
::connectivity::OSQLParser m_aParser;
sal_Int16 m_nControlClass; // which kind of control do we use?
sal_Bool m_bFilterList : 1;
sal_Bool m_bMultiLine : 1;
sal_Bool m_bFilterListFilled : 1;
private:
// OFilterControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
void implInitFilterList();
public:
OFilterControl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB );
DECLARE_UNO3_AGG_DEFAULTS(OFilterControl,OWeakAggObject);
::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId();
sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 > & rId );
virtual ::rtl::OUString GetComponentServiceName();
virtual void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit > & rxToolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > & rParentPeer ) throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::lang::XComponent
virtual void SAL_CALL dispose(void) throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::awt::XTextComponent
virtual void SAL_CALL addTextListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextListener > & l ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL removeTextListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextListener > & l ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setText( const ::rtl::OUString& aText ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL insertText( const ::com::sun::star::awt::Selection& rSel, const ::rtl::OUString& aText ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getText() throw( ::com::sun::star::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getSelectedText() throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setSelection( const ::com::sun::star::awt::Selection& aSelection ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::awt::Selection SAL_CALL getSelection() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL isEditable() throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setEditable( sal_Bool bEditable ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setMaxTextLen( sal_Int16 nLength ) throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Int16 SAL_CALL getMaxTextLen() throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::form::XBoundComponent
virtual void SAL_CALL addUpdateListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XUpdateListener > & l) throw( ::com::sun::star::uno::RuntimeException ) {}
virtual void SAL_CALL removeUpdateListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XUpdateListener > & l) throw( ::com::sun::star::uno::RuntimeException ) {}
virtual sal_Bool SAL_CALL commit() throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::lang::XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::awt::XFocusListener
virtual void SAL_CALL focusGained(const ::com::sun::star::awt::FocusEvent& e) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL focusLost(const ::com::sun::star::awt::FocusEvent& e) throw( ::com::sun::star::uno::RuntimeException ){}
// ::com::sun::star::awt::XItemListener
virtual void SAL_CALL itemStateChanged(const ::com::sun::star::awt::ItemEvent& rEvent) throw( ::com::sun::star::uno::RuntimeException );
// ::com::sun::star::util::XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);
// com::sun::star::lang::XServiceInfo - static version
static ::rtl::OUString SAL_CALL getImplementationName_Static();
static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_Static();
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory );
protected:
virtual void PrepareWindowDescriptor( ::com::sun::star::awt::WindowDescriptor& rDesc );
virtual void ImplSetPeerProperty( const ::rtl::OUString& rPropName, const ::com::sun::star::uno::Any& rVal );
sal_Bool ensureInitialized( );
void displayException( const ::com::sun::star::sdb::SQLContext& _rExcept );
};
//.........................................................................
} // namespace frm
//.........................................................................
#endif // FORMS_COMPONENT_FILTER_HXX
<|endoftext|> |
<commit_before><commit_msg>FIX: forgot ;<commit_after><|endoftext|> |
<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
//
// Simple example of use of Producer::RenderSurface + KeyboardMouseCallback + SceneView
// example that provides the user with control over view position with support for
// enabling the osgDB::DatabasePager as required by the PagedLOD and TXP databases.
#include <Producer/RenderSurface>
#include <Producer/KeyboardMouse>
#include <Producer/Trackball>
#include <osg/Timer>
#include <osgUtil/SceneView>
#include <osgUtil/IntersectVisitor>
#include <osgDB/ReadFile>
#include <osgFX/Scribe>
class MyKeyboardMouseCallback : public Producer::KeyboardMouseCallback
{
public:
MyKeyboardMouseCallback(osgUtil::SceneView* sceneView) :
Producer::KeyboardMouseCallback(),
_mx(0.0f),_my(0.0f),_mbutton(0),
_done(false),
_trackBall(new Producer::Trackball),
_sceneView(sceneView)
{
resetTrackball();
}
virtual void specialKeyPress( Producer::KeyCharacter key )
{
if (key==Producer::KeyChar_Escape)
shutdown();
}
virtual void shutdown()
{
_done = true;
}
virtual void keyPress( Producer::KeyCharacter key)
{
if (key==' ') resetTrackball();
}
virtual void mouseMotion( float mx, float my )
{
_mx = mx;
_my = my;
}
virtual void buttonPress( float mx, float my, unsigned int mbutton )
{
_mx = mx;
_my = my;
_mbutton |= (1<<(mbutton-1));
_mx_buttonPress = _mx;
_my_buttonPress = _my;
}
virtual void buttonRelease( float mx, float my, unsigned int mbutton )
{
_mx = mx;
_my = my;
_mbutton &= ~(1<<(mbutton-1));
}
bool done() { return _done; }
float mx() { return _mx; }
float my() { return _my; }
unsigned int mbutton() { return _mbutton; }
void resetTrackball()
{
osg::Node* scene = _sceneView->getSceneData();
if (scene)
{
const osg::BoundingSphere& bs = scene->getBound();
if (bs.valid())
{
_trackBall->reset();
_trackBall->setOrientation( Producer::Trackball::Z_UP );
_trackBall->setDistance(bs.radius()*2.0f);
_trackBall->translate(-bs.center().x(),-bs.center().y(),-bs.center().z());
}
}
}
osg::Matrixd getViewMatrix()
{
_trackBall->input( mx(), my(), mbutton() );
return osg::Matrixd(_trackBall->getMatrix().ptr());
}
private:
float _mx, _my;
float _mx_buttonPress, _my_buttonPress;
unsigned int _mbutton;
bool _done;
osg::ref_ptr<Producer::Trackball> _trackBall;
osg::ref_ptr<osgUtil::SceneView> _sceneView;
};
int main( int argc, char **argv )
{
if (argc<2)
{
std::cout << argv[0] <<": requires filename argument." << std::endl;
return 1;
}
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
if (!loadedModel)
{
std::cout << argv[0] <<": No data loaded." << std::endl;
return 1;
}
// When numTimesToRun>1 allow the user to test opening and closing graphics contexts whilst
// still keep scene graph around.
unsigned int numTimesToRun = 1;
if (argc>2)
{
numTimesToRun = atoi(argv[2]);
}
// do the set up of the DatabasePager...
// create the database pager via the osgDB::Registry
osgDB::DatabasePager* databasePager = osgDB::Registry::instance()->getOrCreateDatabasePager();
// set wether the DatabasePager thread should be blocked while the scene graph is being used to render a frame
// setting frame block to true can help achieve constant frame rates on single CPU systems.
databasePager->setUseFrameBlock(false);
// set whether to pre compile GL objects before merging new subgraphs with main scene graph
// databasePager->setCompileGLObjectsForContextID(sceneView->getState()->getContextID(),true);
// register any PagedLOD that need to be tracked in the scene graph
databasePager->registerPagedLODs(loadedModel.get());
// record the timer tick at the start of rendering.
osg::Timer_t start_tick = osg::Timer::instance()->tick();
// set the frame number count. Note, this is outside the window loop, so that
// frame numbers increment even a graphics context is closed down and another opened
// this is to ensure the record of the frame numbers in the scene graph are kept valid.
unsigned int frameNum = 0;
if (numTimesToRun>1)
{
// make sure the database pager doesn't unref images as otherwise they won't be around the next time
// they are needed when the a new graphics context comes up.
databasePager->setUnrefImageDataAfterApplyPolicy(true,false);
}
for(unsigned int i=0;i<numTimesToRun;++i)
{
// create the view of the scene.
osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
sceneView->setDefaults();
sceneView->setSceneData(loadedModel.get());
sceneView->setLightingMode(osgUtil::SceneView::SKY_LIGHT);
// need to register the DatabasePager with the SceneView's CullVisitor so it can pass on request
// for files to be loaded.
sceneView->getCullVisitor()->setDatabaseRequestHandler(databasePager);
// create the window to draw to.
osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface;
renderSurface->setWindowName("osgsimplepager");
renderSurface->setWindowRectangle(100,100,800,600);
renderSurface->useBorder(true);
renderSurface->realize();
// set up a KeyboardMouse to manage the events comming in from the RenderSurface
osg::ref_ptr<Producer::KeyboardMouse> kbm = new Producer::KeyboardMouse(renderSurface.get());
// create a KeyboardMouseCallback to handle the mouse events within this applications
osg::ref_ptr<MyKeyboardMouseCallback> kbmcb = new MyKeyboardMouseCallback(sceneView.get());
// main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
while( renderSurface->isRealized() && !kbmcb->done())
{
// set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
osg::FrameStamp* frameStamp = new osg::FrameStamp;
frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick()));
frameStamp->setFrameNumber(frameNum++);
// pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp
sceneView->setFrameStamp(frameStamp);
// pass any keyboard mouse events onto the local keyboard mouse callback.
kbm->update( *kbmcb );
// set the view
sceneView->setViewMatrix(kbmcb->getViewMatrix());
// update the viewport dimensions, incase the window has been resized.
sceneView->setViewport(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight());
// tell the DatabasePager the frame number of that the scene graph is being actively used to render a frame
databasePager->signalBeginFrame(frameStamp);
// syncronize changes required by the DatabasePager thread to the scene graph
databasePager->updateSceneGraph(frameStamp->getReferenceTime());
// do the update traversal the scene graph - such as updating animations
sceneView->update();
// do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins
sceneView->cull();
// draw the rendering bins.
sceneView->draw();
// tell the DatabasePager that the frame is complete and that scene graph is no longer be activity traversed.
databasePager->signalEndFrame();
// Swap Buffers
renderSurface->swapBuffers();
// clean up and compile gl objects with a specified limit
double availableTime = 0.0025; // 2.5 ms
// compile any GL objects that are required.
databasePager->compileGLObjects(*(sceneView->getState()),availableTime);
// flush deleted GL objects.
sceneView->flushDeletedGLObjects(availableTime);
}
// clear the database pager so its starts a fresh on the next update/cull/draw traversals
databasePager->clear();
// release the GL objects stored in the scene graph.
sceneView->releaseAllGLObjects();
// do a flush to delete all the OpenGL objects that have been deleted or released from the scene graph.
sceneView->flushAllDeletedGLObjects();
// reset the osg::State so that next time its used its in a cleaned state.
// sceneView->getState()->reset();
}
// switch off the database pager by unreferencing it.
osgDB::Registry::instance()->setDatabasePager(0);
return 0;
}
<commit_msg>Added extra comment explaining where state reset() should be called.<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
//
// Simple example of use of Producer::RenderSurface + KeyboardMouseCallback + SceneView
// example that provides the user with control over view position with support for
// enabling the osgDB::DatabasePager as required by the PagedLOD and TXP databases.
#include <Producer/RenderSurface>
#include <Producer/KeyboardMouse>
#include <Producer/Trackball>
#include <osg/Timer>
#include <osgUtil/SceneView>
#include <osgUtil/IntersectVisitor>
#include <osgDB/ReadFile>
#include <osgFX/Scribe>
class MyKeyboardMouseCallback : public Producer::KeyboardMouseCallback
{
public:
MyKeyboardMouseCallback(osgUtil::SceneView* sceneView) :
Producer::KeyboardMouseCallback(),
_mx(0.0f),_my(0.0f),_mbutton(0),
_done(false),
_trackBall(new Producer::Trackball),
_sceneView(sceneView)
{
resetTrackball();
}
virtual void specialKeyPress( Producer::KeyCharacter key )
{
if (key==Producer::KeyChar_Escape)
shutdown();
}
virtual void shutdown()
{
_done = true;
}
virtual void keyPress( Producer::KeyCharacter key)
{
if (key==' ') resetTrackball();
}
virtual void mouseMotion( float mx, float my )
{
_mx = mx;
_my = my;
}
virtual void buttonPress( float mx, float my, unsigned int mbutton )
{
_mx = mx;
_my = my;
_mbutton |= (1<<(mbutton-1));
_mx_buttonPress = _mx;
_my_buttonPress = _my;
}
virtual void buttonRelease( float mx, float my, unsigned int mbutton )
{
_mx = mx;
_my = my;
_mbutton &= ~(1<<(mbutton-1));
}
bool done() { return _done; }
float mx() { return _mx; }
float my() { return _my; }
unsigned int mbutton() { return _mbutton; }
void resetTrackball()
{
osg::Node* scene = _sceneView->getSceneData();
if (scene)
{
const osg::BoundingSphere& bs = scene->getBound();
if (bs.valid())
{
_trackBall->reset();
_trackBall->setOrientation( Producer::Trackball::Z_UP );
_trackBall->setDistance(bs.radius()*2.0f);
_trackBall->translate(-bs.center().x(),-bs.center().y(),-bs.center().z());
}
}
}
osg::Matrixd getViewMatrix()
{
_trackBall->input( mx(), my(), mbutton() );
return osg::Matrixd(_trackBall->getMatrix().ptr());
}
private:
float _mx, _my;
float _mx_buttonPress, _my_buttonPress;
unsigned int _mbutton;
bool _done;
osg::ref_ptr<Producer::Trackball> _trackBall;
osg::ref_ptr<osgUtil::SceneView> _sceneView;
};
int main( int argc, char **argv )
{
if (argc<2)
{
std::cout << argv[0] <<": requires filename argument." << std::endl;
return 1;
}
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
if (!loadedModel)
{
std::cout << argv[0] <<": No data loaded." << std::endl;
return 1;
}
// When numTimesToRun>1 allow the user to test opening and closing graphics contexts whilst
// still keep scene graph around.
unsigned int numTimesToRun = 1;
if (argc>2)
{
numTimesToRun = atoi(argv[2]);
}
// do the set up of the DatabasePager...
// create the database pager via the osgDB::Registry
osgDB::DatabasePager* databasePager = osgDB::Registry::instance()->getOrCreateDatabasePager();
// set wether the DatabasePager thread should be blocked while the scene graph is being used to render a frame
// setting frame block to true can help achieve constant frame rates on single CPU systems.
databasePager->setUseFrameBlock(false);
// set whether to pre compile GL objects before merging new subgraphs with main scene graph
// databasePager->setCompileGLObjectsForContextID(sceneView->getState()->getContextID(),true);
// register any PagedLOD that need to be tracked in the scene graph
databasePager->registerPagedLODs(loadedModel.get());
// record the timer tick at the start of rendering.
osg::Timer_t start_tick = osg::Timer::instance()->tick();
// set the frame number count. Note, this is outside the window loop, so that
// frame numbers increment even a graphics context is closed down and another opened
// this is to ensure the record of the frame numbers in the scene graph are kept valid.
unsigned int frameNum = 0;
if (numTimesToRun>1)
{
// make sure the database pager doesn't unref images as otherwise they won't be around the next time
// they are needed when the a new graphics context comes up.
databasePager->setUnrefImageDataAfterApplyPolicy(true,false);
}
for(unsigned int i=0;i<numTimesToRun;++i)
{
// create the view of the scene.
osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
sceneView->setDefaults();
sceneView->setSceneData(loadedModel.get());
sceneView->setLightingMode(osgUtil::SceneView::SKY_LIGHT);
// need to register the DatabasePager with the SceneView's CullVisitor so it can pass on request
// for files to be loaded.
sceneView->getCullVisitor()->setDatabaseRequestHandler(databasePager);
// create the window to draw to.
osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface;
renderSurface->setWindowName("osgsimplepager");
renderSurface->setWindowRectangle(100,100,800,600);
renderSurface->useBorder(true);
renderSurface->realize();
// set up a KeyboardMouse to manage the events comming in from the RenderSurface
osg::ref_ptr<Producer::KeyboardMouse> kbm = new Producer::KeyboardMouse(renderSurface.get());
// create a KeyboardMouseCallback to handle the mouse events within this applications
osg::ref_ptr<MyKeyboardMouseCallback> kbmcb = new MyKeyboardMouseCallback(sceneView.get());
// main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
while( renderSurface->isRealized() && !kbmcb->done())
{
// set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
osg::FrameStamp* frameStamp = new osg::FrameStamp;
frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick()));
frameStamp->setFrameNumber(frameNum++);
// pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp
sceneView->setFrameStamp(frameStamp);
// pass any keyboard mouse events onto the local keyboard mouse callback.
kbm->update( *kbmcb );
// set the view
sceneView->setViewMatrix(kbmcb->getViewMatrix());
// update the viewport dimensions, incase the window has been resized.
sceneView->setViewport(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight());
// tell the DatabasePager the frame number of that the scene graph is being actively used to render a frame
databasePager->signalBeginFrame(frameStamp);
// syncronize changes required by the DatabasePager thread to the scene graph
databasePager->updateSceneGraph(frameStamp->getReferenceTime());
// do the update traversal the scene graph - such as updating animations
sceneView->update();
// do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins
sceneView->cull();
// draw the rendering bins.
sceneView->draw();
// tell the DatabasePager that the frame is complete and that scene graph is no longer be activity traversed.
databasePager->signalEndFrame();
// Swap Buffers
renderSurface->swapBuffers();
// clean up and compile gl objects with a specified limit
double availableTime = 0.0025; // 2.5 ms
// compile any GL objects that are required.
databasePager->compileGLObjects(*(sceneView->getState()),availableTime);
// flush deleted GL objects.
sceneView->flushDeletedGLObjects(availableTime);
}
// clear the database pager so its starts a fresh on the next update/cull/draw traversals
databasePager->clear();
// release the GL objects stored in the scene graph.
sceneView->releaseAllGLObjects();
// do a flush to delete all the OpenGL objects that have been deleted or released from the scene graph.
sceneView->flushAllDeletedGLObjects();
// if you are reusing the same StateSet then you'll need to reset the osg::State as well so that next time its used its in a cleaned state.
// here we are uses a new SceneView for each new graphics context so we don't need the reset().
// sceneView->getState()->reset();
}
// switch off the database pager by unreferencing it.
osgDB::Registry::instance()->setDatabasePager(0);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/setting_level_bubble_view.h"
#include <string>
#include "base/logging.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/canvas.h"
#include "views/controls/progress_bar.h"
using views::Background;
using views::View;
using views::Widget;
namespace {
// Bubble metrics.
const int kWidth = 350, kHeight = 100;
const int kPadding = 20;
const int kProgressBarWidth = 211;
const int kProgressBarHeight = 17;
} // namespace
namespace chromeos {
SettingLevelBubbleView::SettingLevelBubbleView()
: progress_bar_(NULL),
icon_(NULL) {
}
void SettingLevelBubbleView::Init(SkBitmap* icon, int level_percent) {
DCHECK(icon);
DCHECK(level_percent >= 0 && level_percent <= 100);
icon_ = icon;
progress_bar_ = new views::ProgressBar();
AddChildView(progress_bar_);
Update(level_percent);
}
void SettingLevelBubbleView::SetIcon(SkBitmap* icon) {
DCHECK(icon);
icon_ = icon;
SchedulePaint();
}
void SettingLevelBubbleView::Update(int level_percent) {
DCHECK(level_percent >= 0 && level_percent <= 100);
progress_bar_->SetProgress(level_percent);
}
void SettingLevelBubbleView::OnPaint(gfx::Canvas* canvas) {
views::View::OnPaint(canvas);
canvas->DrawBitmapInt(*icon_, kPadding, (height() - icon_->height()) / 2);
}
void SettingLevelBubbleView::Layout() {
progress_bar_->SetBounds(width() - kPadding - kProgressBarWidth,
(height() - kProgressBarHeight) / 2,
kProgressBarWidth, kProgressBarHeight);
}
gfx::Size SettingLevelBubbleView::GetPreferredSize() {
return gfx::Size(kWidth, kHeight);
}
} // namespace chromeos
<commit_msg>Mirror the volume/brightness level bubble views for right-to-left UIs. Doing this also fixes the overlapping icon problem (see bug).<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/setting_level_bubble_view.h"
#include <string>
#include "base/logging.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/canvas.h"
#include "views/controls/progress_bar.h"
using views::Background;
using views::View;
using views::Widget;
namespace {
// Bubble metrics.
const int kWidth = 350, kHeight = 100;
const int kPadding = 20;
const int kProgressBarWidth = 211;
const int kProgressBarHeight = 17;
} // namespace
namespace chromeos {
SettingLevelBubbleView::SettingLevelBubbleView()
: progress_bar_(NULL),
icon_(NULL) {
}
void SettingLevelBubbleView::Init(SkBitmap* icon, int level_percent) {
DCHECK(icon);
DCHECK(level_percent >= 0 && level_percent <= 100);
icon_ = icon;
progress_bar_ = new views::ProgressBar();
AddChildView(progress_bar_);
Update(level_percent);
progress_bar_->EnableCanvasFlippingForRTLUI(true);
EnableCanvasFlippingForRTLUI(true);
}
void SettingLevelBubbleView::SetIcon(SkBitmap* icon) {
DCHECK(icon);
icon_ = icon;
SchedulePaint();
}
void SettingLevelBubbleView::Update(int level_percent) {
DCHECK(level_percent >= 0 && level_percent <= 100);
progress_bar_->SetProgress(level_percent);
}
void SettingLevelBubbleView::OnPaint(gfx::Canvas* canvas) {
views::View::OnPaint(canvas);
canvas->DrawBitmapInt(*icon_, kPadding, (height() - icon_->height()) / 2);
}
void SettingLevelBubbleView::Layout() {
progress_bar_->SetBounds(width() - kPadding - kProgressBarWidth,
(height() - kProgressBarHeight) / 2,
kProgressBarWidth, kProgressBarHeight);
}
gfx::Size SettingLevelBubbleView::GetPreferredSize() {
return gfx::Size(kWidth, kHeight);
}
} // namespace chromeos
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include "geojson_index_featureset.hpp"
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/json/feature_grammar.hpp>
#include <mapnik/util/utf_conv_win.hpp>
#include <mapnik/util/spatial_index.hpp>
#include <mapnik/geometry/is_empty.hpp>
// stl
#include <string>
#include <vector>
#include <fstream>
geojson_index_featureset::geojson_index_featureset(std::string const& filename, mapnik::filter_in_box const& filter)
:
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
//
#elif defined _WINDOWS
file_(_wfopen(mapnik::utf8_to_utf16(filename).c_str(), L"rb"), std::fclose),
#else
file_(std::fopen(filename.c_str(),"rb"), std::fclose),
#endif
ctx_(std::make_shared<mapnik::context_type>())
{
#if defined (MAPNIK_MEMORY_MAPPED_FILE)
boost::optional<mapnik::mapped_region_ptr> memory =
mapnik::mapped_memory_cache::instance().find(filename, true);
if (memory)
{
mapped_region_ = *memory;
}
else
{
throw std::runtime_error("could not create file mapping for " + filename);
}
#else
if (!file_) throw std::runtime_error("Can't open " + filename);
#endif
std::string indexname = filename + ".index";
std::ifstream index(indexname.c_str(), std::ios::binary);
if (!index) throw mapnik::datasource_exception("GeoJSON Plugin: can't open index file " + indexname);
mapnik::util::spatial_index<value_type,
mapnik::filter_in_box,
std::ifstream>::query(filter, index, positions_);
std::sort(positions_.begin(), positions_.end(),
[](value_type const& lhs, value_type const& rhs) { return lhs.first < rhs.first;});
itr_ = positions_.begin();
}
geojson_index_featureset::~geojson_index_featureset() {}
mapnik::feature_ptr geojson_index_featureset::next()
{
while( itr_ != positions_.end())
{
auto pos = *itr_++;
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
char const* start = (char const*)mapped_region_->get_address() + pos.first;
char const* end = start + pos.second;
#else
std::fseek(file_.get(), pos.first, SEEK_SET);
std::vector<char> record;
record.resize(pos.second);
std::fread(record.data(), pos.second, 1, file_.get());
auto const* start = record.data();
auto const* end = start + record.size();
#endif
static const mapnik::transcoder tr("utf8");
static const mapnik::json::feature_grammar<char const*, mapnik::feature_impl> grammar(tr);
using namespace boost::spirit;
standard::space_type space;
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx_, feature_id_++));
if (!qi::phrase_parse(start, end, (grammar)(boost::phoenix::ref(*feature)), space) || start != end)
{
throw std::runtime_error("Failed to parse GeoJSON feature");
}
// skip empty geometries
if (mapnik::geometry::is_empty(feature->get_geometry()))
continue;
return feature;
}
return mapnik::feature_ptr();
}
<commit_msg>use spirit::x3 based parser for disk-indexed GeoJSON access<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include "geojson_index_featureset.hpp"
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/util/utf_conv_win.hpp>
#include <mapnik/util/spatial_index.hpp>
#include <mapnik/geometry/is_empty.hpp>
#include <mapnik/json/unicode_string_grammar_x3_def.hpp>
#include <mapnik/json/positions_grammar_x3_def.hpp>
#include <mapnik/json/geojson_grammar_x3_def.hpp>
#include <mapnik/json/json_grammar_config.hpp>
#include <mapnik/json/create_feature.hpp>
// stl
#include <string>
#include <vector>
#include <fstream>
geojson_index_featureset::geojson_index_featureset(std::string const& filename, mapnik::filter_in_box const& filter)
:
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
//
#elif defined _WINDOWS
file_(_wfopen(mapnik::utf8_to_utf16(filename).c_str(), L"rb"), std::fclose),
#else
file_(std::fopen(filename.c_str(),"rb"), std::fclose),
#endif
ctx_(std::make_shared<mapnik::context_type>())
{
#if defined (MAPNIK_MEMORY_MAPPED_FILE)
boost::optional<mapnik::mapped_region_ptr> memory =
mapnik::mapped_memory_cache::instance().find(filename, true);
if (memory)
{
mapped_region_ = *memory;
}
else
{
throw std::runtime_error("could not create file mapping for " + filename);
}
#else
if (!file_) throw std::runtime_error("Can't open " + filename);
#endif
std::string indexname = filename + ".index";
std::ifstream index(indexname.c_str(), std::ios::binary);
if (!index) throw mapnik::datasource_exception("GeoJSON Plugin: can't open index file " + indexname);
mapnik::util::spatial_index<value_type,
mapnik::filter_in_box,
std::ifstream>::query(filter, index, positions_);
std::sort(positions_.begin(), positions_.end(),
[](value_type const& lhs, value_type const& rhs) { return lhs.first < rhs.first;});
itr_ = positions_.begin();
}
geojson_index_featureset::~geojson_index_featureset() {}
mapnik::feature_ptr geojson_index_featureset::next()
{
while( itr_ != positions_.end())
{
auto pos = *itr_++;
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
char const* start = (char const*)mapped_region_->get_address() + pos.first;
char const* end = start + pos.second;
#else
std::fseek(file_.get(), pos.first, SEEK_SET);
std::vector<char> record;
record.resize(pos.second);
std::fread(record.data(), pos.second, 1, file_.get());
auto const* start = record.data();
auto const* end = start + record.size();
#endif
static const mapnik::transcoder tr("utf8");
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx_, feature_id_++));
using namespace boost::spirit;
using space_type = mapnik::json::grammar::space_type;
using mapnik::json::grammar::iterator_type;
mapnik::json::geojson_value value;
auto keys = mapnik::json::get_keys();
auto grammar = x3::with<mapnik::json::keys_tag>(std::ref(keys))
[ mapnik::json::geojson_grammar() ];
try
{
bool result = x3::phrase_parse(start, end, grammar, space_type(), value);
if (!result) return mapnik::feature_ptr();
mapnik::json::create_feature(*feature, value, keys, tr);
}
catch (x3::expectation_failure<std::string::const_iterator> const& ex)
{
std::cerr << ex.what() << std::endl;
return mapnik::feature_ptr();
}
catch (std::runtime_error const& ex)
{
std::cerr << "Exception caught:" << ex.what() << std::endl;
return mapnik::feature_ptr();
}
// skip empty geometries
if (mapnik::geometry::is_empty(feature->get_geometry()))
continue;
return feature;
}
return mapnik::feature_ptr();
}
<|endoftext|> |
<commit_before>// Copyright 2013 Sean McKenna
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// object sub-classes (e.g. sphere, plane, triangular mesh OBJ)
// import triangular mesh class
#include "cyCodeBase/cyTriMesh.h"
// namespace
using namespace scene;
// Sphere definition
class Sphere: public Object{
public:
// constructor
Sphere(){
center.Set(0, 0, 0);
radius = 1.0;
}
// intsersect a ray against the unit sphere
// ray must be transformed into model space, first
bool intersectRay(Ray &r, HitInfo &h, int face=HIT_FRONT){
// pre-compute values for quadratic solution
Point pos = r.pos - center;
float A = r.dir % r.dir;
float B = 2.0 * pos % r.dir;
float C = pos % pos - radius * radius;
float det = (B * B) - (4 * A * C);
// if the ray intersects, compute the z-buffer value
if(det >= 0){
float z1 = (-B - sqrt(det)) / (2.0 * A);
float z2 = (-B + sqrt(det)) / (2.0 * A);
// determine if we have a back hit
if(z1 * z2 < 0.0)
h.front = false;
// if hit is too close, assume it is a back-face hit
else if(z1 <= getBias())
h.front = false;
// check closest z-buffer value, if positive (ahead of our ray)
if(z1 > getBias()){
h.z = z1;
// compute surface intersection and normal
h.p = r.pos + z1 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// check the next ray, if necessary
}else if(z2 > getBias()){
h.z = z2;
// compute surface intersection and normal
h.p = r.pos + z2 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// otherwise, all z-buffer values are negative, return false
}else
return false;
}
// otherwise, return false (no ray hit)
else
return false;
}
// get sphere bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0);
}
private:
// sphere center and its radius
Point center;
float radius;
};
// Plane definition (a "unit" plane)
class Plane: public Object{
public:
// intersect a ray against the "unit" plane
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// only compute for rays not parallel to the unit plane
if(r.dir.z > getBias() || r.dir.z < getBias()){
// compute distance along ray direction to plane
float t = -r.pos.z / r.dir.z;
// only accept hits in front of ray (with some bias)
if(t > getBias()){
// compute the hit point
Point hit = r.pos + t * r.dir;
// only allow a hit to occur if on the "unit" plane
if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){
// detect back face hits
if(r.pos.z < 0.0)
h.front = false;
// distance to hit
h.z = t;
// set hit point, normal, and return hit info
h.p = hit;
h.n = Point(0.0, 0.0, 1.0);
return true;
}
}
}
// when no ray hits the "unit" plane
return false;
}
// get plane bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0);
}
};
// Triangular Mesh Object definition (from an OBJ file)
class TriObj: public Object, private cyTriMesh{
public:
// intersect a ray against the triangular mesh
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// check each triangular face for ray intersection
for(int i = 0; i < NF(); i++){
bool triang = intersectTriangle(r, h, face, i);
if(triang)
return triang;
}
// no faces were hit
return false;
}
// get triangular mesh bounding box
BoundingBox getBoundBox(){
return BoundingBox(GetBoundMin(), GetBoundMax());
}
// when loading a triangular mesh, get its bounding box
bool load(const char *file){
if(!LoadFromFileObj(file))
return false;
if(!HasNormals())
ComputeNormals();
ComputeBoundingBox();
return true;
}
private:
// intersect a ray with a single triangle
bool intersectTriangle(Ray &r, HitInfo &h, int face, int faceID){
// ignore rays nearly parallel to surface
Point n = VN(faceID);
if(r.dir % n > getBias() || r.dir % n < -getBias()){
// compute distance along ray direction to plane
Point a = V(F(faceID).v[0]);
float t = -((r.pos - a) % n) / (r.dir % n);
// only accept hits in front of ray (with some bias) & closer hits
if(t > getBias() && t < h.z){
// compute hit point
Point hit = r.pos + t * r.dir;
// compute the area of the triangular face
Point b = V(F(faceID).v[1]);
Point c = V(F(faceID).v[2]);
float area = ((b - a) ^ (c - a)).Length() / 2.0;
// compute smaller areas of the face, relative to the full area
float alpha = ((b - a) ^ (hit - a)).Length() / 2.0 / area;
if(alpha > -getBias() && alpha < 1.0 + getBias()){
float beta = ((hit - a) ^ (c - a)).Length() / 2.0 / area;
if(beta > -getBias() && beta < 1.0 + getBias()){
if(alpha + beta < 1.0 + getBias()){
// detect back face hits
if(r.dir % n < 0.0)
h.front = false;
// we have a hit on the triangular face
h.z = t;
h.p = hit;
h.n = n;
return true;
}
}
}
}
}
// when no ray hits the triangular face
return false;
}
};
<commit_msg>partially working ray triangle intersecction, still some bug in there, though<commit_after>// Copyright 2013 Sean McKenna
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// object sub-classes (e.g. sphere, plane, triangular mesh OBJ)
// import triangular mesh class
#include "cyCodeBase/cyTriMesh.h"
// namespace
using namespace scene;
// Sphere definition
class Sphere: public Object{
public:
// constructor
Sphere(){
center.Set(0, 0, 0);
radius = 1.0;
}
// intsersect a ray against the unit sphere
// ray must be transformed into model space, first
bool intersectRay(Ray &r, HitInfo &h, int face=HIT_FRONT){
// pre-compute values for quadratic solution
Point pos = r.pos - center;
float A = r.dir % r.dir;
float B = 2.0 * pos % r.dir;
float C = pos % pos - radius * radius;
float det = (B * B) - (4 * A * C);
// if the ray intersects, compute the z-buffer value
if(det >= 0){
float z1 = (-B - sqrt(det)) / (2.0 * A);
float z2 = (-B + sqrt(det)) / (2.0 * A);
// determine if we have a back hit
if(z1 * z2 < 0.0)
h.front = false;
// if hit is too close, assume it is a back-face hit
else if(z1 <= getBias())
h.front = false;
// check closest z-buffer value, if positive (ahead of our ray)
if(z1 > getBias()){
h.z = z1;
// compute surface intersection and normal
h.p = r.pos + z1 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// check the next ray, if necessary
}else if(z2 > getBias()){
h.z = z2;
// compute surface intersection and normal
h.p = r.pos + z2 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// otherwise, all z-buffer values are negative, return false
}else
return false;
}
// otherwise, return false (no ray hit)
else
return false;
}
// get sphere bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0);
}
private:
// sphere center and its radius
Point center;
float radius;
};
// Plane definition (a "unit" plane)
class Plane: public Object{
public:
// intersect a ray against the "unit" plane
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// only compute for rays not parallel to the unit plane
if(r.dir.z > getBias() || r.dir.z < getBias()){
// compute distance along ray direction to plane
float t = -r.pos.z / r.dir.z;
// only accept hits in front of ray (with some bias)
if(t > getBias()){
// compute the hit point
Point hit = r.pos + t * r.dir;
// only allow a hit to occur if on the "unit" plane
if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){
// detect back face hits
if(r.pos.z < 0.0)
h.front = false;
// distance to hit
h.z = t;
// set hit point, normal, and return hit info
h.p = hit;
h.n = Point(0.0, 0.0, 1.0);
return true;
}
}
}
// when no ray hits the "unit" plane
return false;
}
// get plane bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0);
}
};
// Triangular Mesh Object definition (from an OBJ file)
class TriObj: public Object, private cyTriMesh{
public:
// intersect a ray against the triangular mesh
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// check each triangular face for ray intersection
for(int i = 0; i < NF(); i++){
bool triang = intersectTriangle(r, h, face, i);
if(triang)
return triang;
}
// no faces were hit
return false;
}
// get triangular mesh bounding box
BoundingBox getBoundBox(){
return BoundingBox(GetBoundMin(), GetBoundMax());
}
// when loading a triangular mesh, get its bounding box
bool load(const char *file){
if(!LoadFromFileObj(file))
return false;
if(!HasNormals())
ComputeNormals();
ComputeBoundingBox();
return true;
}
private:
// intersect a ray with a single triangle
bool intersectTriangle(Ray &r, HitInfo &h, int face, int faceID){
// ignore rays nearly parallel to surface
Point n = VN(faceID);
if(r.dir % n > getBias() || r.dir % n < -getBias()){
// compute distance along ray direction to plane
Point a = V(F(faceID).v[0]);
float t = -((r.pos - a) % n) / (r.dir % n);
// only accept hits in front of ray (with some bias) & closer hits
if(t > getBias() && t < h.z){
// compute hit point
Point hit = r.pos + t * r.dir;
// compute the area of the triangular face
Point b = V(F(faceID).v[1]);
Point c = V(F(faceID).v[2]);
float area = ((b - a) ^ (c - a)).Length() / 2.0;
// compute smaller areas of the face, relative to the full area
// aka, computation of the barycentric coordinates
float alpha = ((b - a) ^ (hit - a)).Length() / 2.0 / area;
if(alpha > -getBias()){
float beta = ((hit - a) ^ (c - a)).Length() / 2.0 / area;
if(beta > -getBias()){
if(alpha + beta < 1.0 + getBias()){
// interpolate the normal based on barycentric coordinates
Point bc = Point(1.0 - alpha - beta, beta, alpha);
// detect back face hits
if(r.dir % n < 0.0)
h.front = false;
// distance to hit
h.z = t;
// set hit point, normal, and return hit info
h.p = GetPoint(faceID, bc);
h.n = GetNormal(faceID, bc);
return true;
}
}
}
}
}
// when no ray hits the triangular face
return false;
}
};
<|endoftext|> |
<commit_before>#include "countdecimaldigit.h"
#include "digitslut.h"
#include "test.h"
// Additional count number of digit pass
// Use lookup table of two gDigitsLut
void u32toa_countlut(uint32_t value, char* buffer) {
unsigned digit = CountDecimalDigit32(value);
buffer += digit;
*buffer = '\0';
const uint16_t* gDigitsLut16 = reinterpret_cast<const uint16_t*>(gDigitsLut);
while (value >= 100) {
buffer -= 2;
reinterpret_cast<uint16_t*>(buffer)[0] = gDigitsLut16[value % 100];
value /= 100;
}
if (value < 10) {
--buffer;
buffer[0] = char(value) + '0';
}
else {
buffer -= 2;
reinterpret_cast<uint16_t*>(buffer)[0] = gDigitsLut16[value];
}
}
void i32toa_countlut(int32_t value, char* buffer) {
if (value < 0) {
*buffer++ = '-';
value = -value;
}
u32toa_countlut(static_cast<uint32_t>(value), buffer);
}
void u64toa_countlut(uint64_t value, char* buffer) {
unsigned digit = CountDecimalDigit64(value);
buffer += digit;
*buffer = '\0';
const uint16_t* gDigitsLut16 = reinterpret_cast<const uint16_t*>(gDigitsLut);
while (value >= 100000000) {
uint32_t a = static_cast<uint32_t>(value % 100000000);
value /= 100000000;
uint32_t b = a / 10000;
uint32_t c = a % 10000;
buffer -= 8;
reinterpret_cast<uint16_t*>(buffer)[0] = gDigitsLut16[b / 100];
reinterpret_cast<uint16_t*>(buffer)[1] = gDigitsLut16[b % 100];
reinterpret_cast<uint16_t*>(buffer)[2] = gDigitsLut16[c / 100];
reinterpret_cast<uint16_t*>(buffer)[3] = gDigitsLut16[c % 100];
}
uint32_t value32 = static_cast<uint32_t>(value);
while (value32 >= 100) {
buffer -= 2;
reinterpret_cast<uint16_t*>(buffer)[0] = gDigitsLut16[value32 % 100];
value32 /= 100;
}
if (value32 < 10) {
--buffer;
buffer[0] = char(value32) + '0';
} else {
buffer -= 2;
reinterpret_cast<uint16_t*>(buffer)[0] = gDigitsLut16[value32];
}
}
void i64toa_countlut(int64_t value, char* buffer) {
if (value < 0) {
*buffer++ = '-';
value = -value;
}
u64toa_countlut(static_cast<uint64_t>(value), buffer);
}
REGISTER_TEST(countlut);
<commit_msg>Revert "Optimize u64toa_countlut"<commit_after>#include "countdecimaldigit.h"
#include "digitslut.h"
#include "test.h"
// Additional count number of digit pass
// Use lookup table of two gDigitsLut
void u32toa_countlut(uint32_t value, char* buffer) {
unsigned digit = CountDecimalDigit32(value);
buffer += digit;
*buffer = '\0';
while (value >= 100) {
const unsigned i = (value % 100) << 1;
value /= 100;
*--buffer = gDigitsLut[i + 1];
*--buffer = gDigitsLut[i];
}
if (value < 10) {
*--buffer = char(value) + '0';
}
else {
const unsigned i = value << 1;
*--buffer = gDigitsLut[i + 1];
*--buffer = gDigitsLut[i];
}
}
void i32toa_countlut(int32_t value, char* buffer) {
if (value < 0) {
*buffer++ = '-';
value = -value;
}
u32toa_countlut(static_cast<uint32_t>(value), buffer);
}
void u64toa_countlut(uint64_t value, char* buffer) {
unsigned digit = CountDecimalDigit64(value);
buffer += digit;
*buffer = '\0';
while (value >= 100) {
const unsigned i = static_cast<unsigned>(value % 100) << 1;
value /= 100;
*--buffer = gDigitsLut[i + 1];
*--buffer = gDigitsLut[i];
}
if (value < 10) {
*--buffer = char(value) + '0';
}
else {
const unsigned i = static_cast<unsigned>(value) << 1;
*--buffer = gDigitsLut[i + 1];
*--buffer = gDigitsLut[i];
}
}
void i64toa_countlut(int64_t value, char* buffer) {
if (value < 0) {
*buffer++ = '-';
value = -value;
}
u64toa_countlut(static_cast<uint64_t>(value), buffer);
}
REGISTER_TEST(countlut);
<|endoftext|> |
<commit_before>/*
*
* Copyright 2017 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "asylo/grpc/auth/core/enclave_security_connector.h"
#include <stdbool.h>
#include <string.h>
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "asylo/util/logging.h"
#include "asylo/grpc/auth/core/enclave_credentials.h"
#include "asylo/grpc/auth/core/enclave_grpc_security_constants.h"
#include "asylo/grpc/auth/core/enclave_transport_security.h"
#include "include/grpc/support/alloc.h"
#include "include/grpc/support/log.h"
#include "include/grpc/support/string_util.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/security/context/security_context.h"
#include "src/core/lib/security/credentials/credentials.h"
#include "src/core/lib/security/transport/security_handshaker.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/tsi/transport_security.h"
#include "src/core/tsi/transport_security_interface.h"
namespace {
grpc_security_status grpc_enclave_auth_context_from_tsi_peer(
const tsi_peer *peer,
grpc_core::RefCountedPtr<grpc_auth_context> *auth_context) {
// Authenticated peers should have the following properties:
// * TSI_CERTIFICATE_TYPE_PEER_PROPERTY
// * TSI_SECURITY_LEVEL_PEER_PROPERTY
// * TSI_ENCLAVE_IDENTITIES_PROTO_PEER_PROPERTY
// * TSI_ENCLAVE_RECORD_PROTOCOL_PEER_PROPERTY
// They are translated into the following authentication context properties:
// * GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME
// * GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME
// * GRPC_ENCLAVE_IDENTITIES_PROTO_PROPERTY_NAME
// * GRPC_ENCLAVE_RECORD_PROTOCOL_PROPERTY_NAME
const tsi_peer_property *certificate_type_property =
tsi_peer_get_property_by_name(peer, TSI_CERTIFICATE_TYPE_PEER_PROPERTY);
// Check if all expected properties are present.
if (certificate_type_property == nullptr) {
gpr_log(GPR_ERROR, "Missing certificate type peer property");
return GRPC_SECURITY_ERROR;
}
if (strncmp(TSI_ENCLAVE_CERTIFICATE_TYPE,
certificate_type_property->value.data,
certificate_type_property->value.length) != 0) {
gpr_log(GPR_ERROR, "Invalid certificate type peer property");
return GRPC_SECURITY_ERROR;
}
const tsi_peer_property *security_level_property =
tsi_peer_get_property_by_name(peer, TSI_SECURITY_LEVEL_PEER_PROPERTY);
if (security_level_property == nullptr) {
gpr_log(GPR_ERROR, "Missing security level property.");
return GRPC_SECURITY_ERROR;
}
const tsi_peer_property *identity_property = tsi_peer_get_property_by_name(
peer, TSI_ENCLAVE_IDENTITIES_PROTO_PEER_PROPERTY);
if (identity_property == nullptr) {
gpr_log(GPR_ERROR, "Missing identity proto peer property");
return GRPC_SECURITY_ERROR;
}
const tsi_peer_property *record_protocol_property =
tsi_peer_get_property_by_name(peer,
TSI_ENCLAVE_RECORD_PROTOCOL_PEER_PROPERTY);
if (record_protocol_property == nullptr) {
gpr_log(GPR_ERROR, "Missing record protocol peer property");
return GRPC_SECURITY_ERROR;
}
// Create a new authentication context and set the properties.
*auth_context =
grpc_core::MakeRefCounted<grpc_auth_context>(/*chained=*/nullptr);
grpc_auth_context_add_cstring_property(
auth_context->get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME,
GRPC_ENCLAVE_TRANSPORT_SECURITY_TYPE);
grpc_auth_context_add_property(
auth_context->get(), GRPC_ENCLAVE_IDENTITIES_PROTO_PROPERTY_NAME,
identity_property->value.data, identity_property->value.length);
grpc_auth_context_add_property(auth_context->get(),
GRPC_ENCLAVE_RECORD_PROTOCOL_PROPERTY_NAME,
record_protocol_property->value.data,
record_protocol_property->value.length);
grpc_auth_context_add_property(auth_context->get(),
GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME,
security_level_property->value.data,
security_level_property->value.length);
// The EnclaveIdentities proto is the identity in the authentication context.
if (!grpc_auth_context_set_peer_identity_property_name(
auth_context->get(), GRPC_ENCLAVE_IDENTITIES_PROTO_PROPERTY_NAME)) {
gpr_log(GPR_ERROR, "Error setting peer identity property name");
return GRPC_SECURITY_ERROR;
}
return GRPC_SECURITY_OK;
}
void enclave_security_connector_check_peer(
grpc_security_connector *sc, tsi_peer peer,
grpc_core::RefCountedPtr<grpc_auth_context> *auth_context,
grpc_closure *on_peer_checked) {
grpc_error *error = GRPC_ERROR_NONE;
grpc_security_status status =
grpc_enclave_auth_context_from_tsi_peer(&peer, auth_context);
tsi_peer_destruct(&peer);
if (status != GRPC_SECURITY_OK) {
error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Failed to get enclave auth context from TSI peer");
}
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
}
/* -- Enclave security connector implementation. -- */
class grpc_enclave_channel_security_connector final
: public grpc_channel_security_connector {
public:
grpc_enclave_channel_security_connector(
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_credentials,
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
const char *target)
: grpc_channel_security_connector(/*url_scheme=*/nullptr,
std::move(channel_credentials),
std::move(request_metadata_creds)),
target_(gpr_strdup(target)) {}
~grpc_enclave_channel_security_connector() override {
gpr_free(target_);
}
void check_peer(tsi_peer peer, grpc_endpoint *ep,
grpc_core::RefCountedPtr<grpc_auth_context> *auth_context,
grpc_closure *on_peer_checked) override {
enclave_security_connector_check_peer(this, peer, auth_context,
on_peer_checked);
}
bool check_call_host(grpc_core::StringView host,
grpc_auth_context *auth_context,
grpc_closure *on_call_host_checked,
grpc_error **error) override {
return true;
}
void cancel_check_call_host(grpc_closure *on_call_host_checked,
grpc_error *error) override {
GRPC_ERROR_UNREF(error);
}
int cmp(const grpc_security_connector * /*other*/) const override {
return 1;
}
void add_handshakers(
const grpc_channel_args* args,
grpc_pollset_set *interested_parties,
grpc_handshake_manager *handshake_mgr) override {
tsi_handshaker *tsi_handshaker = nullptr;
grpc_enclave_channel_credentials *channel_creds =
CHECK_NOTNULL(dynamic_cast<grpc_enclave_channel_credentials *>(
this->mutable_channel_creds()));
tsi_result result = tsi_enclave_handshaker_create(
/*is_client=*/true, absl::MakeSpan(channel_creds->self_assertions),
absl::MakeSpan(channel_creds->accepted_peer_assertions),
channel_creds->additional_authenticated_data, channel_creds->peer_acl,
&tsi_handshaker);
if (result != TSI_OK) {
gpr_log(GPR_ERROR, "Enclave handshaker creation failed with error %s.",
tsi_result_to_string(result));
return;
}
grpc_handshake_manager_add(
handshake_mgr, grpc_security_handshaker_create(tsi_handshaker, this,
args));
}
private:
// The address of the server as a null-terminated string.
char *target_;
};
class grpc_enclave_server_security_connector final
: public grpc_server_security_connector {
public:
explicit grpc_enclave_server_security_connector(
grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials)
: grpc_server_security_connector(/*url_scheme=*/nullptr,
std::move(server_credentials)) {}
~grpc_enclave_server_security_connector() override = default;
void check_peer(tsi_peer peer, grpc_endpoint *ep,
grpc_core::RefCountedPtr<grpc_auth_context> *auth_context,
grpc_closure *on_peer_checked) override {
enclave_security_connector_check_peer(this, peer, auth_context,
on_peer_checked);
}
int cmp(const grpc_security_connector * /*other*/) const override {
return 1;
}
void add_handshakers(
const grpc_channel_args* args,
grpc_pollset_set *interested_parties,
grpc_handshake_manager *handshake_mgr) override {
tsi_handshaker *tsi_handshaker = nullptr;
grpc_enclave_server_credentials *server_creds =
CHECK_NOTNULL(dynamic_cast<grpc_enclave_server_credentials *>(
this->mutable_server_creds()));
tsi_result result = tsi_enclave_handshaker_create(
/*is_client=*/false, absl::MakeSpan(server_creds->self_assertions),
absl::MakeSpan(server_creds->accepted_peer_assertions),
server_creds->additional_authenticated_data, server_creds->peer_acl,
&tsi_handshaker);
if (result != TSI_OK) {
gpr_log(GPR_ERROR, "Enclave handshaker creation failed with error %s.",
tsi_result_to_string(result));
return;
}
grpc_handshake_manager_add(
handshake_mgr, grpc_security_handshaker_create(tsi_handshaker, this,
args));
}
};
} // namespace
grpc_core::RefCountedPtr<grpc_channel_security_connector>
grpc_enclave_channel_security_connector_create(
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_credentials,
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
const char *target) {
GRPC_API_TRACE(
"grpc_enclave_channel_security_connector_create("
"grpc_channel_credentials=%p, grpc_call_credentials=%p, target=%s)",
3, (channel_credentials.get(), request_metadata_creds.get(), target));
return grpc_core::MakeRefCounted<grpc_enclave_channel_security_connector>(
channel_credentials, request_metadata_creds, target);
}
grpc_core::RefCountedPtr<grpc_server_security_connector>
grpc_enclave_server_security_connector_create(
grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials) {
GRPC_API_TRACE(
"grpc_enclave_server_security_connector_create("
"grpc_server_credentials=%p)",
1, (server_credentials.get()));
return grpc_core::MakeRefCounted<grpc_enclave_server_security_connector>(
server_credentials);
}
<commit_msg>Switch from grpc_core::StringView to absl::string_view<commit_after>/*
*
* Copyright 2017 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "asylo/grpc/auth/core/enclave_security_connector.h"
#include <stdbool.h>
#include <string.h>
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "asylo/util/logging.h"
#include "asylo/grpc/auth/core/enclave_credentials.h"
#include "asylo/grpc/auth/core/enclave_grpc_security_constants.h"
#include "asylo/grpc/auth/core/enclave_transport_security.h"
#include "include/grpc/support/alloc.h"
#include "include/grpc/support/log.h"
#include "include/grpc/support/string_util.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/security/context/security_context.h"
#include "src/core/lib/security/credentials/credentials.h"
#include "src/core/lib/security/transport/security_handshaker.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/tsi/transport_security.h"
#include "src/core/tsi/transport_security_interface.h"
namespace {
grpc_security_status grpc_enclave_auth_context_from_tsi_peer(
const tsi_peer *peer,
grpc_core::RefCountedPtr<grpc_auth_context> *auth_context) {
// Authenticated peers should have the following properties:
// * TSI_CERTIFICATE_TYPE_PEER_PROPERTY
// * TSI_SECURITY_LEVEL_PEER_PROPERTY
// * TSI_ENCLAVE_IDENTITIES_PROTO_PEER_PROPERTY
// * TSI_ENCLAVE_RECORD_PROTOCOL_PEER_PROPERTY
// They are translated into the following authentication context properties:
// * GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME
// * GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME
// * GRPC_ENCLAVE_IDENTITIES_PROTO_PROPERTY_NAME
// * GRPC_ENCLAVE_RECORD_PROTOCOL_PROPERTY_NAME
const tsi_peer_property *certificate_type_property =
tsi_peer_get_property_by_name(peer, TSI_CERTIFICATE_TYPE_PEER_PROPERTY);
// Check if all expected properties are present.
if (certificate_type_property == nullptr) {
gpr_log(GPR_ERROR, "Missing certificate type peer property");
return GRPC_SECURITY_ERROR;
}
if (strncmp(TSI_ENCLAVE_CERTIFICATE_TYPE,
certificate_type_property->value.data,
certificate_type_property->value.length) != 0) {
gpr_log(GPR_ERROR, "Invalid certificate type peer property");
return GRPC_SECURITY_ERROR;
}
const tsi_peer_property *security_level_property =
tsi_peer_get_property_by_name(peer, TSI_SECURITY_LEVEL_PEER_PROPERTY);
if (security_level_property == nullptr) {
gpr_log(GPR_ERROR, "Missing security level property.");
return GRPC_SECURITY_ERROR;
}
const tsi_peer_property *identity_property = tsi_peer_get_property_by_name(
peer, TSI_ENCLAVE_IDENTITIES_PROTO_PEER_PROPERTY);
if (identity_property == nullptr) {
gpr_log(GPR_ERROR, "Missing identity proto peer property");
return GRPC_SECURITY_ERROR;
}
const tsi_peer_property *record_protocol_property =
tsi_peer_get_property_by_name(peer,
TSI_ENCLAVE_RECORD_PROTOCOL_PEER_PROPERTY);
if (record_protocol_property == nullptr) {
gpr_log(GPR_ERROR, "Missing record protocol peer property");
return GRPC_SECURITY_ERROR;
}
// Create a new authentication context and set the properties.
*auth_context =
grpc_core::MakeRefCounted<grpc_auth_context>(/*chained=*/nullptr);
grpc_auth_context_add_cstring_property(
auth_context->get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME,
GRPC_ENCLAVE_TRANSPORT_SECURITY_TYPE);
grpc_auth_context_add_property(
auth_context->get(), GRPC_ENCLAVE_IDENTITIES_PROTO_PROPERTY_NAME,
identity_property->value.data, identity_property->value.length);
grpc_auth_context_add_property(auth_context->get(),
GRPC_ENCLAVE_RECORD_PROTOCOL_PROPERTY_NAME,
record_protocol_property->value.data,
record_protocol_property->value.length);
grpc_auth_context_add_property(auth_context->get(),
GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME,
security_level_property->value.data,
security_level_property->value.length);
// The EnclaveIdentities proto is the identity in the authentication context.
if (!grpc_auth_context_set_peer_identity_property_name(
auth_context->get(), GRPC_ENCLAVE_IDENTITIES_PROTO_PROPERTY_NAME)) {
gpr_log(GPR_ERROR, "Error setting peer identity property name");
return GRPC_SECURITY_ERROR;
}
return GRPC_SECURITY_OK;
}
void enclave_security_connector_check_peer(
grpc_security_connector *sc, tsi_peer peer,
grpc_core::RefCountedPtr<grpc_auth_context> *auth_context,
grpc_closure *on_peer_checked) {
grpc_error *error = GRPC_ERROR_NONE;
grpc_security_status status =
grpc_enclave_auth_context_from_tsi_peer(&peer, auth_context);
tsi_peer_destruct(&peer);
if (status != GRPC_SECURITY_OK) {
error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Failed to get enclave auth context from TSI peer");
}
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
}
/* -- Enclave security connector implementation. -- */
class grpc_enclave_channel_security_connector final
: public grpc_channel_security_connector {
public:
grpc_enclave_channel_security_connector(
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_credentials,
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
const char *target)
: grpc_channel_security_connector(/*url_scheme=*/nullptr,
std::move(channel_credentials),
std::move(request_metadata_creds)),
target_(gpr_strdup(target)) {}
~grpc_enclave_channel_security_connector() override {
gpr_free(target_);
}
void check_peer(tsi_peer peer, grpc_endpoint *ep,
grpc_core::RefCountedPtr<grpc_auth_context> *auth_context,
grpc_closure *on_peer_checked) override {
enclave_security_connector_check_peer(this, peer, auth_context,
on_peer_checked);
}
bool check_call_host(absl::string_view host,
grpc_auth_context *auth_context,
grpc_closure *on_call_host_checked,
grpc_error **error) override {
return true;
}
void cancel_check_call_host(grpc_closure *on_call_host_checked,
grpc_error *error) override {
GRPC_ERROR_UNREF(error);
}
int cmp(const grpc_security_connector * /*other*/) const override {
return 1;
}
void add_handshakers(
const grpc_channel_args* args,
grpc_pollset_set *interested_parties,
grpc_handshake_manager *handshake_mgr) override {
tsi_handshaker *tsi_handshaker = nullptr;
grpc_enclave_channel_credentials *channel_creds =
CHECK_NOTNULL(dynamic_cast<grpc_enclave_channel_credentials *>(
this->mutable_channel_creds()));
tsi_result result = tsi_enclave_handshaker_create(
/*is_client=*/true, absl::MakeSpan(channel_creds->self_assertions),
absl::MakeSpan(channel_creds->accepted_peer_assertions),
channel_creds->additional_authenticated_data, channel_creds->peer_acl,
&tsi_handshaker);
if (result != TSI_OK) {
gpr_log(GPR_ERROR, "Enclave handshaker creation failed with error %s.",
tsi_result_to_string(result));
return;
}
grpc_handshake_manager_add(
handshake_mgr, grpc_security_handshaker_create(tsi_handshaker, this,
args));
}
private:
// The address of the server as a null-terminated string.
char *target_;
};
class grpc_enclave_server_security_connector final
: public grpc_server_security_connector {
public:
explicit grpc_enclave_server_security_connector(
grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials)
: grpc_server_security_connector(/*url_scheme=*/nullptr,
std::move(server_credentials)) {}
~grpc_enclave_server_security_connector() override = default;
void check_peer(tsi_peer peer, grpc_endpoint *ep,
grpc_core::RefCountedPtr<grpc_auth_context> *auth_context,
grpc_closure *on_peer_checked) override {
enclave_security_connector_check_peer(this, peer, auth_context,
on_peer_checked);
}
int cmp(const grpc_security_connector * /*other*/) const override {
return 1;
}
void add_handshakers(
const grpc_channel_args* args,
grpc_pollset_set *interested_parties,
grpc_handshake_manager *handshake_mgr) override {
tsi_handshaker *tsi_handshaker = nullptr;
grpc_enclave_server_credentials *server_creds =
CHECK_NOTNULL(dynamic_cast<grpc_enclave_server_credentials *>(
this->mutable_server_creds()));
tsi_result result = tsi_enclave_handshaker_create(
/*is_client=*/false, absl::MakeSpan(server_creds->self_assertions),
absl::MakeSpan(server_creds->accepted_peer_assertions),
server_creds->additional_authenticated_data, server_creds->peer_acl,
&tsi_handshaker);
if (result != TSI_OK) {
gpr_log(GPR_ERROR, "Enclave handshaker creation failed with error %s.",
tsi_result_to_string(result));
return;
}
grpc_handshake_manager_add(
handshake_mgr, grpc_security_handshaker_create(tsi_handshaker, this,
args));
}
};
} // namespace
grpc_core::RefCountedPtr<grpc_channel_security_connector>
grpc_enclave_channel_security_connector_create(
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_credentials,
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
const char *target) {
GRPC_API_TRACE(
"grpc_enclave_channel_security_connector_create("
"grpc_channel_credentials=%p, grpc_call_credentials=%p, target=%s)",
3, (channel_credentials.get(), request_metadata_creds.get(), target));
return grpc_core::MakeRefCounted<grpc_enclave_channel_security_connector>(
channel_credentials, request_metadata_creds, target);
}
grpc_core::RefCountedPtr<grpc_server_security_connector>
grpc_enclave_server_security_connector_create(
grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials) {
GRPC_API_TRACE(
"grpc_enclave_server_security_connector_create("
"grpc_server_credentials=%p)",
1, (server_credentials.get()));
return grpc_core::MakeRefCounted<grpc_enclave_server_security_connector>(
server_credentials);
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdio>
using namespace std;
class Point {
public:
double x,y;
Point() {
x = 0;
y = 0;
}
Point(double _x, double _y) {
x = _x;
y = _y;
}
};
inline int sgn(double x) {
return (x < 0) ? -1 : 1;
}
int intersectLineCircle(Point a, Point b, Point c, double r, Point& p1, Point& p2) {
// translate circle to (0|0)
double ax = a.x - c.x;
double ay = a.y - c.y;
double bx = b.x - c.x;
double by = b.y - c.y;
double dx = bx - ax; // Delta X
double dy = by - ay; // Delta Y
double dr = sqrt(dx*dx + dy*dy); // slope
double d = ax * by - bx * ay; // ?
double disc = (r*r) * (dr*dr) - (d*d); // discriminant
if (disc < 0) {
return 0; // no intersection
}
double discsq = sqrt(disc); // sqrt of discriminant
// calculate first intersection and translate back
p1.x = (d * dy + sgn(dy) * dx * discsq) / (dr*dr) + c.x;
p1.y = (-d * dx + abs(dy) * discsq) / (dr*dr) + c.y;
if (disc == 0) {
p2.x = p1.x;
p2.y = p1.y;
return 1;
}
// calculate second intersection and translate back
p2.x = (d * dy - sgn(dy) * dx * discsq) / (dr*dr) + c.x;
p2.y = (-d * dx - abs(dy) * discsq) / (dr*dr) + c.y;
return 2;
}
int main() {
/*Point a(-1, 0);
Point b(0, 1);
Point c(1, 1);
double r = 1.0;*/
Point a(0, -3);
Point b(1, 0);
Point c(-2, -4);
double r = 5.0;
Point p1, p2;
int intersections = intersectLineCircle(a, b, c, r, p1, p2);
printf("Intersections: %d\n", intersections);
if (intersections == 1) {
printf("(%f %f)\n", p1.x, p1.y);
} else if (intersections == 2) {
printf("(%f %f) (%f %f)\n", p1.x, p1.y, p2.x, p2.y);
}
return 0;
}<commit_msg>updated intersection algorithm<commit_after>#include <cmath>
#include <cstdio>
using namespace std;
#define EQ(a, b) (abs((a)-(b)) < 0.00001)
class Point {
public:
double x,y;
Point() {
x = 0;
y = 0;
}
Point(double _x, double _y) {
x = _x;
y = _y;
}
};
inline int sgn(double x) {
return (x < 0) ? -1 : 1;
}
int intersectLineCircle(Point a, Point b, Point c, double r, Point& p1, Point& p2) {
// translate circle to (0|0)
double ax = a.x - c.x;
double ay = a.y - c.y;
double bx = b.x - c.x;
double by = b.y - c.y;
double dx = bx - ax; // Delta X
double dy = by - ay; // Delta Y
double dr = sqrt(dx*dx + dy*dy); // slope
double d = ax * by - bx * ay; // ?
double disc = (r*r) * (dr*dr) - (d*d); // discriminant
if (disc < 0) {
return 0; // no intersection
}
double discsq = sqrt(disc); // sqrt of discriminant
// calculate first intersection and translate back
p1.x = (d * dy + sgn(dy) * dx * discsq) / (dr*dr) + c.x;
p1.y = (-d * dx + abs(dy) * discsq) / (dr*dr) + c.y;
if (disc == 0) {
p2.x = p1.x;
p2.y = p1.y;
return 1;
}
// calculate second intersection and translate back
p2.x = (d * dy - sgn(dy) * dx * discsq) / (dr*dr) + c.x;
p2.y = (-d * dx - abs(dy) * discsq) / (dr*dr) + c.y;
return 2;
}
bool inSegment(Point a, Point b, Point m) {
double d1 = (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y);
double e1 = (a.x-m.x)*(a.x-m.x) + (a.y-m.y)*(a.y-m.y);
double d2 = (b.x-a.x)*(b.x-a.x) + (b.y-a.y)*(b.y-a.y);
double e2 = (m.x-a.x)*(m.x-a.x) + (m.y-a.y)*(m.y-a.y);
return ((e1 <= d1) || EQ(e1, d1)) && ((e2 <= d2) || EQ(e2, d2));
}
bool intersectLineSegment(Point a, Point b, Point c, double r, Point& p1, Point& p2) {
int n = intersectLineCircle(a, b, c, r, p1, p2);
if (n == 0) {
return 0;
}
Point p1a, p2a;
n = 0;
if (inSegment(a, b, p1)) {
p1a = p1;
n++;
}
if (inSegment(a, b, p2)) {
if (n == 0) {
p1a = p1;
} else {
p2a = p2;
}
n++;
}
return n;
}
int main() {
Point a(-1, 0);
Point b(0, 1);
Point c(1, 1);
double r = 1.0;
/*Point a(0, -3);
Point b(1, 0);
Point c(-2, -4);
double r = 5.0;*/
Point p1, p2;
int intersections = intersectLineSegment(a, b, c, r, p1, p2);
printf("Intersections: %d\n", intersections);
if (intersections == 1) {
printf("(%f %f)\n", p1.x, p1.y);
printf("%s\n", (inSegment(a, b, p1) ? "y" : "n"));
} else if (intersections == 2) {
printf("(%f %f) (%f %f)\n", p1.x, p1.y, p2.x, p2.y);
printf("%s\n", (inSegment(a, b, p1) ? "y" : "n"));
printf("%s\n", (inSegment(a, b, p2) ? "y" : "n"));
}
return 0;
}<|endoftext|> |
<commit_before>#include "Lifter.h"
#include "../RobotMap.h"
#include "../Commands/ControlLifter.h"
Lifter::Lifter()
: Subsystem("Lifter")
{
m_cLiftMotor = new CANTalon(LIFTER);
m_cLiftMotor->ConfigLimitMode(CANTalon::kLimitMode_SwitchInputsOnly);
m_cLiftMotor->ConfigNeutralMode(CANTalon::kNeutralMode_Brake);
m_cLiftMotor->SetFeedbackDevice(CANTalon::QuadEncoder);
m_cLiftMotor->SetControlMode(CANSpeedController::kPercentVbus);
m_cLiftMotor->SetSensorDirection(false);
m_cLiftMotor->SetPID(0.05,0,0);
m_cLiftMotor->SetVoltageRampRate(300.0);
}
Lifter::~Lifter(){
delete m_cLiftMotor;
}
void Lifter::InitDefaultCommand()
{
// Set the default command for a subsystem here.
SetDefaultCommand(new ControlLifter());
}
void Lifter::toSetpoint(int goal)
{
double termP = Preferences::GetInstance()->GetInt("LifterPIDtermP", 5);
double termI = Preferences::GetInstance()->GetInt("LifterPIDtermI", 0);
double termD = Preferences::GetInstance()->GetInt("LifterPIDtermD", 0);
m_cLiftMotor->SetControlMode(CANSpeedController::kPosition);
m_cLiftMotor->SetPID(termP,termI,termD);
m_cLiftMotor->Set(goal);
m_cLiftMotor->EnableControl();
}
void Lifter::moveLifter(float goal)
{
if(goal > 0 and GetLimitSwitchTop()){
m_cLiftMotor->SetControlMode(CANSpeedController::kPercentVbus);
if(GetPosition() > Preferences::GetInstance()->GetInt("LifterSlowZoneTop", 4700)){ //Default number is 5450
m_cLiftMotor->Set(0.5*goal);
}else{
m_cLiftMotor->Set(goal);
}
}else if(goal < 0 and GetLimitSwitchBot()){
m_cLiftMotor->SetControlMode(CANSpeedController::kPercentVbus);
if(GetPosition() < Preferences::GetInstance()->GetInt("LifterSlowZoneBot", 600)){ //Default number is 400
m_cLiftMotor->Set(0.5*goal);
}else{
m_cLiftMotor->Set(goal);
}
}else if(m_cLiftMotor->GetControlMode() == CANSpeedController::kPercentVbus){
toSetpoint(GetPosition());
}
if(!GetLimitSwitchBot()){
m_cLiftMotor->SetPosition(0);
}
}
<commit_msg>Ramp Rate tuned<commit_after>#include "Lifter.h"
#include "../RobotMap.h"
#include "../Commands/ControlLifter.h"
Lifter::Lifter()
: Subsystem("Lifter")
{
m_cLiftMotor = new CANTalon(LIFTER);
m_cLiftMotor->ConfigLimitMode(CANTalon::kLimitMode_SwitchInputsOnly);
m_cLiftMotor->ConfigNeutralMode(CANTalon::kNeutralMode_Brake);
m_cLiftMotor->SetFeedbackDevice(CANTalon::QuadEncoder);
m_cLiftMotor->SetControlMode(CANSpeedController::kPercentVbus);
m_cLiftMotor->SetSensorDirection(false);
m_cLiftMotor->SetPID(0.05,0,0);
m_cLiftMotor->SetVoltageRampRate(125.0);
}
Lifter::~Lifter(){
delete m_cLiftMotor;
}
void Lifter::InitDefaultCommand()
{
// Set the default command for a subsystem here.
SetDefaultCommand(new ControlLifter());
}
void Lifter::toSetpoint(int goal)
{
m_cLiftMotor->SetVoltageRampRate(125.0);
double termP = Preferences::GetInstance()->GetInt("LifterPIDtermP", 5);
double termI = Preferences::GetInstance()->GetInt("LifterPIDtermI", 0);
double termD = Preferences::GetInstance()->GetInt("LifterPIDtermD", 0);
m_cLiftMotor->SetControlMode(CANSpeedController::kPosition);
m_cLiftMotor->SetPID(termP,termI,termD);
m_cLiftMotor->Set(goal);
m_cLiftMotor->EnableControl();
}
void Lifter::moveLifter(float goal)
{
m_cLiftMotor->SetVoltageRampRate(125.0);
if(goal > 0 and GetLimitSwitchTop()){
m_cLiftMotor->SetControlMode(CANSpeedController::kPercentVbus);
if(GetPosition() > Preferences::GetInstance()->GetInt("LifterSlowZoneTop", 4700)){ //Default number is 5450
m_cLiftMotor->Set(0.5*goal);
}else{
m_cLiftMotor->Set(goal);
}
}else if(goal < 0 and GetLimitSwitchBot()){
m_cLiftMotor->SetControlMode(CANSpeedController::kPercentVbus);
if(GetPosition() < Preferences::GetInstance()->GetInt("LifterSlowZoneBot", 600)){ //Default number is 400
m_cLiftMotor->Set(0.5*goal);
}else{
m_cLiftMotor->Set(goal);
}
}else if(m_cLiftMotor->GetControlMode() == CANSpeedController::kPercentVbus){
toSetpoint(GetPosition());
}
if(!GetLimitSwitchBot()){
m_cLiftMotor->SetPosition(0);
}
}
<|endoftext|> |
<commit_before>//
// ofx3DPro.cpp
//
// Copyright (c) 2013 Patricio Gonzalez Vivo <http://patriciogonzalezvivo.com>
//
//
#include "ofx3DPro.h"
ofx3DPro::ofx3DPro():
globalAmbientColor(0.25, 0.25, 0.25),
selectedLigth("NULL")
{
guiTemplate = new ofxUISuperCanvas(ofToUpper(getSystemName()));
guiTemplate->setName("TEMPLATE");
guiTemplate->setWidgetFontSize(OFX_UI_FONT_SMALL);
setupNumViewports(1);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, &globalAmbientColor.r);
};
ofx3DPro::~ofx3DPro(){
};
void ofx3DPro::play(){
if (!bPlaying){
if(camera->bEnable){
camera->enableMouseInput();
}
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->play();
}
ofx2DPro::play();
}
}
void ofx3DPro::stop(){
if(bPlaying){
camera->disableMouseInput();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->stop();
}
ofx2DPro::stop();
}
}
void ofx3DPro::draw(ofEventArgs & args){
if(bRenderSystem){
for(int i = 0; i<renderTargets.size();i++){
currentViewPort = i;
ofPushStyle();
#ifndef TARGET_RASPBERRY_PI
getRenderTarget(currentViewPort).begin();
#endif
// Background
//
background->draw();
// Start 3D scene
//
{
if(cameraEnabled){
getCameraRef().begin();
}
// Scene Setup
//
selfSceneTransformation(currentViewPort);
// Cached Values
//
glGetFloatv(GL_MODELVIEW_MATRIX, viewMatrix.getPtr());
glGetFloatv(GL_PROJECTION_MATRIX, projectionMatrix.getPtr());
glGetDoublev(GL_PROJECTION_MATRIX, matP);
glGetDoublev(GL_MODELVIEW_MATRIX, matM);
glGetIntegerv(GL_VIEWPORT, viewport);
ofEnableDepthTest();
if (bEdit&&bEnableLights){
lightsDraw();
}
// Draw Scene
//
{
if(bEnableLights){
lightsBegin();
}
if(bBackCull||bFrontCull){
glEnable(GL_CULL_FACE);
if(bBackCull){
glCullFace(GL_BACK);
ofPushStyle();
ofPushMatrix();
selfDraw();
ofPopMatrix();
ofPopStyle();
}
if(bFrontCull){
glCullFace(GL_FRONT);
ofPushStyle();
ofPushMatrix();
selfDraw();
ofPopMatrix();
ofPopStyle();
}
glDisable(GL_CULL_FACE);
} else {
ofPushStyle();
ofPushMatrix();
selfDraw();
ofPopMatrix();
ofPopStyle();
}
if(bEnableLights){
lightsEnd();
}
}
ofDisableDepthTest();
// Update Mouse
//
if (bUpdateCursor){
unprojectCursor(cursor, ofGetMouseX(), ofGetMouseY());
bUpdateCursor = false;
}
if(cameraEnabled){
getCameraRef().end();
}
}
// Draw Overlay
//
{
ofPushStyle();
ofPushMatrix();
selfDrawOverlay();
ofPopMatrix();
ofPopStyle();
}
#ifndef TARGET_RASPBERRY_PI
getRenderTarget(currentViewPort).end();
#endif
ofPopStyle();
}
#ifndef TARGET_RASPBERRY_PI
// Post-Draw ( shader time )
//
ofDisableLighting();
currentViewPort = 0;
selfPostDraw();
#endif
logGui.drawStatus();
}
}
void ofx3DPro::exit(ofEventArgs & args){
if(logGui.isRecording()){
logGui.record(false);
}
ofx3DPro::guiSave("Working");
materials.clear();
lights.clear();
guis.clear();
selfExit();
}
//-------------------- Mouse events + camera interaction
//
ofPoint ofx3DPro::unproject(ofPoint _screen){
float depth;
//read z value from depth buffer at mouse coords
getRenderTarget().getDepthTexture().bind();
glReadPixels(_screen.x, _screen.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
getRenderTarget().getDepthTexture().unbind();
if (depth == 1.0f) {
return ofPoint(0,0,0);
} else {
GLdouble c[3];
gluUnProject(_screen.x, _screen.y, depth, matM, matP, viewport, c, c+1, c+2);
return ofPoint(c[0], c[1],c[2]);
}
}
void ofx3DPro::unprojectCursor(MovingCursor &_cursor, float _x, float _y){
_cursor.lastFrame = _cursor;
//consider that these should be in viewport space
_cursor.screen.x = _x;
_cursor.screen.y = _y;
cursor.world = unproject(_cursor.screen);
if(cursor.world.z == 1.0f){
_cursor.worldValid = false;
} else {
_cursor.worldValid = true;
}
////
//worldViewFrameDifference
ofVec3f screenDiffNorm = _cursor.getScreenFrameDifference() / ofVec2f(viewport[2], -viewport[3]);
_cursor.worldViewFrameDifference = screenDiffNorm * viewMatrix.getInverse().getRotate();
float distance = (camera->getCameraPtn()->getPosition() - _cursor.world).length();
_cursor.worldViewFrameDifference *= distance * tan( camera->getCameraPtn()->getFov() * DEG_TO_RAD / 2.0f) * 2.0f * 2.0f;
_cursor.worldViewFrameDifference.x *= ofGetWidth() / ofGetHeight();
_cursor.lastUpdate = ofGetFrameNum();
}
void ofx3DPro::mouseMoved(ofMouseEventArgs & args){
if (bEdit){
bUpdateCursor = true;
}
ofx2DPro::mouseMoved(args);
};
void ofx3DPro::mousePressed(ofMouseEventArgs & args){
if( cursorIsOverGUI() ){
camera->disableMouseInput();
}
else if(bEdit && cursorIsOverLight() != "NULL"){
camera->disableMouseInput();
selectedLigth = cursorIsOverLight();
if(ofGetElapsedTimef()-lastClick<doublClickThreshold){
if(!bGui){
guiShow();
}
for (int i = 0; i<guis.size(); i++) {
if(guis[i]->getName()==selectedLigth){
guis[i]->setMinified(false);
guis[i]->getRect()->setX(1);
guis[i]->setPosition(args.x+25,
args.y-guis[i]->getRect()->getHalfHeight());
}
}
}
}
else {
if(ofGetElapsedTimef()-lastClick<doublClickThreshold)
selfMouseDoublePressed(args);
else
selfMousePressed(args);
}
}
void ofx3DPro::mouseDragged(ofMouseEventArgs & args){
if (bEdit){
bUpdateCursor = true;
}
if (cursorIsOverGUI()){
}
else if(bEdit && selectedLigth != "NULL"){
if(cursor.worldValid){
ofPoint pmouse(ofGetPreviousMouseX(),-ofGetPreviousMouseY());
ofPoint mouse(ofGetMouseX(),-ofGetMouseY());
ofPoint diff = getCameraRef().cameraToWorld(mouse)-getCameraRef().cameraToWorld(pmouse);
*lights[selectedLigth]+=diff*0.1;//diff.normalize()*cursor.getWorldFrameDifference().length();
}
}
else {
ofx2DPro::mouseDragged(args);
}
};
void ofx3DPro::mouseReleased(ofMouseEventArgs & args){
if(camera->bEnable){
camera->enableMouseInput();
}
selfMouseReleased(args);
selectedLigth = "NULL";
lastClick = ofGetElapsedTimef();
}
//------------------------------------------------------------ CORE SETUP
void ofx3DPro::setupCoreGuis(){
setupGui();
logGui.linkDataPath(getDataPath());
logGui.linkRenderTarget(&getRenderTarget());
guiAdd(logGui);
setupSystemGui();
setupRenderGui();
rdrGui->addSpacer();
rdrGui->addToggle("Back CULL", &bBackCull);
rdrGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
rdrGui->addToggle("Front CULL", &bFrontCull);
rdrGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
rdrGui->autoSizeToFitWidgets();
backgroundSet(new UIBackground);
cameraSet(new UIEasyCamera());
cameraEnable();
materialAdd( "MATERIAL" );
setupLightingGui();
lightAdd("POINT LIGHT 1", OF_LIGHT_POINT);
}
void ofx3DPro::cameraSet(UICamera *_cam){
if(camera != NULL){
for(int i = 0; i<guis.size(); i++){
if (guis[i]->getName() == "CAMERA"){
guis.erase(guis.begin()+i);
break;
}
}
}
camera = UICameraReference(_cam);
guiAdd(*_cam);
camera->loadLocations(getDataPath()+"cameras/");
}
void ofx3DPro::cameraEnable(bool enable){
cameraEnabled = enable;
}
//------------------------------------------------------------ 3D SPECIFIC SETUP
void ofx3DPro::setupLightingGui(){
bSmoothLighting = true;
bEnableLights = true;
UIReference tmp( new ofxUISuperCanvas("LIGHT", guiTemplate) );
lightsGui = tmp;
lightsGui->copyCanvasStyle(guiTemplate);
lightsGui->copyCanvasProperties(guiTemplate);
lightsGui->setName("LIGHT");
lightsGui->setPosition(guis[guis.size()-1]->getRect()->x+guis[guis.size()-1]->getRect()->getWidth()+1, 0);
lightsGui->setWidgetFontSize(OFX_UI_FONT_SMALL);
ofxUIToggle *toggle = lightsGui->addToggle("ENABLE", &bEnableLights);
toggle->setLabelPosition(OFX_UI_WIDGET_POSITION_LEFT);
lightsGui->resetPlacer();
lightsGui->addWidgetDown(toggle, OFX_UI_ALIGN_RIGHT, true);
lightsGui->addWidgetToHeader(toggle);
lightsGui->addSpacer();
lightsGui->addToggle("SMOOTH", &bSmoothLighting);
lightsGui->addSpacer();
float length = (lightsGui->getGlobalCanvasWidth()-lightsGui->getWidgetSpacing()*5)/3.;
float dim = lightsGui->getGlobalSliderHeight();
lightsGui->addLabel("GLOBAL AMBIENT COLOR", OFX_UI_FONT_SMALL);
lightsGui->addMinimalSlider("R", 0.0, 1.0, &(globalAmbientColor.r), length, dim)->setShowValue(false);
lightsGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
lightsGui->addMinimalSlider("G", 0.0, 1.0, &(globalAmbientColor.g), length, dim)->setShowValue(false);
lightsGui->addMinimalSlider("B", 0.0, 1.0, &(globalAmbientColor.b), length, dim)->setShowValue(false);
lightsGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
lightsGui->autoSizeToFitWidgets();
ofAddListener(lightsGui->newGUIEvent,this,&ofx3DPro::guiLightingEvent);
guis.push_back(lightsGui);
}
void ofx3DPro::guiLightingEvent(ofxUIEventArgs &e){
string name = e.widget->getName();
if(name == "R" || name == "G" || name == "B"){
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, &globalAmbientColor.r);
}
}
void ofx3DPro::lightAdd( string _name, ofLightType _type ){
UILightReference newLight(new UILight(_name, _type));
lights[_name] = newLight;
guis.push_back(newLight->getUIReference(guiTemplate));
}
string ofx3DPro::cursorIsOverLight(){
if(bEnableLights){
for( auto& it : lights ){
if ( it.second->distance(cursor.world) < 10 ){
return it.first;
}
}
}
return "NULL";
}
void ofx3DPro::lightsBegin(){
ofEnableLighting();
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, &globalAmbientColor.r);
ofSetSmoothLighting(bSmoothLighting);
for( auto& it : lights ){
it.second->enable();
}
}
void ofx3DPro::lightsEnd(){
for( auto& it : lights ){
it.second->disable();
}
ofDisableLighting();
}
void ofx3DPro::lightsDraw(){
if(bEnableLights){
ofPushStyle();
ofDisableLighting();
string overLight = cursorIsOverLight();
for( auto& it : lights ){
it.second->draw();
if( overLight == it.first){
ofPushMatrix();
ofPushStyle();
ofNoFill();
float pulse = abs(sin(ofGetElapsedTimef()));
ofColor color = it.second->getColor();
color.setBrightness(background->getUIBrightness()*255);
ofSetColor( color, pulse*255);
ofTranslate( it.second->getPosition() );
float size = it.second->getPosition().distance(getCameraRef().getPosition())*0.1;
camera->billboard();
ofSetLineWidth(2);
ofEllipse(0,0, size, size);
ofPopStyle();
ofPopMatrix();
}
}
ofPopStyle();
}
}
void ofx3DPro::materialAdd( string _name ){
UIMaterialReference newMaterial( new UIMaterial() );
if ( _name == "MATERIAL" ){
_name = "MATERIAL " + ofToString( materials.size() + 1);
}
newMaterial->setName(_name);
materials[ _name ] = newMaterial;
guis.push_back( newMaterial->getUIReference(guiTemplate) );
}
//------------------------------------------------------ Save & Load + CAMERA
void ofx3DPro::guiLoad(string _presetName){
ofx2DPro::guiLoad(_presetName);
camera->load(getDataPath()+"Presets/"+_presetName+"/"+"current.cam");
}
void ofx3DPro::guiLoadFromPath(string presetPath){
ofx2DPro::guiLoadFromPath(presetPath);
camera->load(presetPath+"/current.cam");
// ofx2DPro::guiLoadFromPath(presetPath);
}
void ofx3DPro::guiSave(string presetName){
ofx2DPro::guiSave(presetName);
camera->save(getDataPath()+"Presets/"+presetName+"/current.cam");
if(camera->bEnable){
camera->enableMouseInput();
}
}
ofCamera& ofx3DPro::getCameraRef(){
return (*camera->getCameraPtn());
}<commit_msg>mouse projectiong<commit_after>//
// ofx3DPro.cpp
//
// Copyright (c) 2013 Patricio Gonzalez Vivo <http://patriciogonzalezvivo.com>
//
//
#include "ofx3DPro.h"
ofx3DPro::ofx3DPro():
globalAmbientColor(0.25, 0.25, 0.25),
selectedLigth("NULL")
{
guiTemplate = new ofxUISuperCanvas(ofToUpper(getSystemName()));
guiTemplate->setName("TEMPLATE");
guiTemplate->setWidgetFontSize(OFX_UI_FONT_SMALL);
setupNumViewports(1);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, &globalAmbientColor.r);
};
ofx3DPro::~ofx3DPro(){
};
void ofx3DPro::play(){
if (!bPlaying){
if(camera->bEnable){
camera->enableMouseInput();
}
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->play();
}
ofx2DPro::play();
}
}
void ofx3DPro::stop(){
if(bPlaying){
camera->disableMouseInput();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->stop();
}
ofx2DPro::stop();
}
}
void ofx3DPro::draw(ofEventArgs & args){
if(bRenderSystem){
for(int i = 0; i<renderTargets.size();i++){
currentViewPort = i;
ofPushStyle();
#ifndef TARGET_RASPBERRY_PI
getRenderTarget(currentViewPort).begin();
#endif
// Background
//
background->draw();
// Start 3D scene
//
{
if(cameraEnabled){
getCameraRef().begin();
}
// Scene Setup
//
selfSceneTransformation(currentViewPort);
// Cached Values
//
glGetFloatv(GL_MODELVIEW_MATRIX, viewMatrix.getPtr());
glGetFloatv(GL_PROJECTION_MATRIX, projectionMatrix.getPtr());
glGetDoublev(GL_PROJECTION_MATRIX, matP);
glGetDoublev(GL_MODELVIEW_MATRIX, matM);
glGetIntegerv(GL_VIEWPORT, viewport);
ofEnableDepthTest();
if (bEdit&&bEnableLights){
lightsDraw();
}
// Draw Scene
//
{
if(bEnableLights){
lightsBegin();
}
if(bBackCull||bFrontCull){
glEnable(GL_CULL_FACE);
if(bBackCull){
glCullFace(GL_BACK);
ofPushStyle();
ofPushMatrix();
selfDraw();
ofPopMatrix();
ofPopStyle();
}
if(bFrontCull){
glCullFace(GL_FRONT);
ofPushStyle();
ofPushMatrix();
selfDraw();
ofPopMatrix();
ofPopStyle();
}
glDisable(GL_CULL_FACE);
} else {
ofPushStyle();
ofPushMatrix();
selfDraw();
ofPopMatrix();
ofPopStyle();
}
if(bEnableLights){
lightsEnd();
}
}
ofDisableDepthTest();
// Update Mouse
//
if (bUpdateCursor){
unprojectCursor(cursor, ofGetMouseX(), ofGetMouseY());
bUpdateCursor = false;
}
if(cameraEnabled){
getCameraRef().end();
}
}
// Draw Overlay
//
{
ofPushStyle();
ofPushMatrix();
selfDrawOverlay();
ofPopMatrix();
ofPopStyle();
}
#ifndef TARGET_RASPBERRY_PI
getRenderTarget(currentViewPort).end();
#endif
ofPopStyle();
}
#ifndef TARGET_RASPBERRY_PI
// Post-Draw ( shader time )
//
ofDisableLighting();
currentViewPort = 0;
selfPostDraw();
#endif
logGui.drawStatus();
}
}
void ofx3DPro::exit(ofEventArgs & args){
if(logGui.isRecording()){
logGui.record(false);
}
ofx3DPro::guiSave("Working");
materials.clear();
lights.clear();
guis.clear();
selfExit();
}
//-------------------- Mouse events + camera interaction
//
ofPoint ofx3DPro::unproject(ofPoint _screen){
float depth;
//read z value from depth buffer at mouse coords
getRenderTarget().getDepthTexture().bind();
glReadPixels(_screen.x, _screen.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
getRenderTarget().getDepthTexture().unbind();
if (depth == 1.0f || depth <= 0.0f) {
return ofPoint(0.,0.,0.);
} else {
GLdouble c[3];
gluUnProject(_screen.x, _screen.y, depth, matM, matP, viewport, c, c+1, c+2);
return ofPoint(c[0], c[1],c[2]);
}
}
void ofx3DPro::unprojectCursor(MovingCursor &_cursor, float _x, float _y){
_cursor.lastFrame = _cursor;
//consider that these should be in viewport space
_cursor.screen.x = _x;
_cursor.screen.y = _y;
cursor.world = unproject(_cursor.screen);
if(cursor.world.z == 1.0f){
_cursor.worldValid = false;
} else {
_cursor.worldValid = true;
}
////
//worldViewFrameDifference
ofVec3f screenDiffNorm = _cursor.getScreenFrameDifference() / ofVec2f(viewport[2], -viewport[3]);
_cursor.worldViewFrameDifference = screenDiffNorm * viewMatrix.getInverse().getRotate();
float distance = (camera->getCameraPtn()->getPosition() - _cursor.world).length();
_cursor.worldViewFrameDifference *= distance * tan( camera->getCameraPtn()->getFov() * DEG_TO_RAD / 2.0f) * 2.0f * 2.0f;
_cursor.worldViewFrameDifference.x *= ofGetWidth() / ofGetHeight();
_cursor.lastUpdate = ofGetFrameNum();
}
void ofx3DPro::mouseMoved(ofMouseEventArgs & args){
if (bEdit){
bUpdateCursor = true;
}
ofx2DPro::mouseMoved(args);
};
void ofx3DPro::mousePressed(ofMouseEventArgs & args){
if( cursorIsOverGUI() ){
camera->disableMouseInput();
}
else if(bEdit && cursorIsOverLight() != "NULL"){
camera->disableMouseInput();
selectedLigth = cursorIsOverLight();
if(ofGetElapsedTimef()-lastClick<doublClickThreshold){
if(!bGui){
guiShow();
}
for (int i = 0; i<guis.size(); i++) {
if(guis[i]->getName()==selectedLigth){
guis[i]->setMinified(false);
guis[i]->getRect()->setX(1);
guis[i]->setPosition(args.x+25,
args.y-guis[i]->getRect()->getHalfHeight());
}
}
}
}
else {
if(ofGetElapsedTimef()-lastClick<doublClickThreshold)
selfMouseDoublePressed(args);
else
selfMousePressed(args);
}
}
void ofx3DPro::mouseDragged(ofMouseEventArgs & args){
if (bEdit){
bUpdateCursor = true;
}
if (cursorIsOverGUI()){
}
else if(bEdit && selectedLigth != "NULL"){
if(cursor.worldValid){
ofPoint pmouse(ofGetPreviousMouseX(),-ofGetPreviousMouseY());
ofPoint mouse(ofGetMouseX(),-ofGetMouseY());
ofPoint diff = getCameraRef().cameraToWorld(mouse)-getCameraRef().cameraToWorld(pmouse);
*lights[selectedLigth]+=diff*0.1;//diff.normalize()*cursor.getWorldFrameDifference().length();
}
}
else {
ofx2DPro::mouseDragged(args);
}
};
void ofx3DPro::mouseReleased(ofMouseEventArgs & args){
if(camera->bEnable){
camera->enableMouseInput();
}
selfMouseReleased(args);
selectedLigth = "NULL";
lastClick = ofGetElapsedTimef();
}
//------------------------------------------------------------ CORE SETUP
void ofx3DPro::setupCoreGuis(){
setupGui();
logGui.linkDataPath(getDataPath());
logGui.linkRenderTarget(&getRenderTarget());
guiAdd(logGui);
setupSystemGui();
setupRenderGui();
rdrGui->addSpacer();
rdrGui->addToggle("Back CULL", &bBackCull);
rdrGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
rdrGui->addToggle("Front CULL", &bFrontCull);
rdrGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
rdrGui->autoSizeToFitWidgets();
backgroundSet(new UIBackground);
cameraSet(new UIEasyCamera());
cameraEnable();
materialAdd( "MATERIAL" );
setupLightingGui();
lightAdd("POINT LIGHT 1", OF_LIGHT_POINT);
}
void ofx3DPro::cameraSet(UICamera *_cam){
if(camera != NULL){
for(int i = 0; i<guis.size(); i++){
if (guis[i]->getName() == "CAMERA"){
guis.erase(guis.begin()+i);
break;
}
}
}
camera = UICameraReference(_cam);
guiAdd(*_cam);
camera->loadLocations(getDataPath()+"cameras/");
}
void ofx3DPro::cameraEnable(bool enable){
cameraEnabled = enable;
}
//------------------------------------------------------------ 3D SPECIFIC SETUP
void ofx3DPro::setupLightingGui(){
bSmoothLighting = true;
bEnableLights = true;
UIReference tmp( new ofxUISuperCanvas("LIGHT", guiTemplate) );
lightsGui = tmp;
lightsGui->copyCanvasStyle(guiTemplate);
lightsGui->copyCanvasProperties(guiTemplate);
lightsGui->setName("LIGHT");
lightsGui->setPosition(guis[guis.size()-1]->getRect()->x+guis[guis.size()-1]->getRect()->getWidth()+1, 0);
lightsGui->setWidgetFontSize(OFX_UI_FONT_SMALL);
ofxUIToggle *toggle = lightsGui->addToggle("ENABLE", &bEnableLights);
toggle->setLabelPosition(OFX_UI_WIDGET_POSITION_LEFT);
lightsGui->resetPlacer();
lightsGui->addWidgetDown(toggle, OFX_UI_ALIGN_RIGHT, true);
lightsGui->addWidgetToHeader(toggle);
lightsGui->addSpacer();
lightsGui->addToggle("SMOOTH", &bSmoothLighting);
lightsGui->addSpacer();
float length = (lightsGui->getGlobalCanvasWidth()-lightsGui->getWidgetSpacing()*5)/3.;
float dim = lightsGui->getGlobalSliderHeight();
lightsGui->addLabel("GLOBAL AMBIENT COLOR", OFX_UI_FONT_SMALL);
lightsGui->addMinimalSlider("R", 0.0, 1.0, &(globalAmbientColor.r), length, dim)->setShowValue(false);
lightsGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
lightsGui->addMinimalSlider("G", 0.0, 1.0, &(globalAmbientColor.g), length, dim)->setShowValue(false);
lightsGui->addMinimalSlider("B", 0.0, 1.0, &(globalAmbientColor.b), length, dim)->setShowValue(false);
lightsGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
lightsGui->autoSizeToFitWidgets();
ofAddListener(lightsGui->newGUIEvent,this,&ofx3DPro::guiLightingEvent);
guis.push_back(lightsGui);
}
void ofx3DPro::guiLightingEvent(ofxUIEventArgs &e){
string name = e.widget->getName();
if(name == "R" || name == "G" || name == "B"){
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, &globalAmbientColor.r);
}
}
void ofx3DPro::lightAdd( string _name, ofLightType _type ){
UILightReference newLight(new UILight(_name, _type));
lights[_name] = newLight;
guis.push_back(newLight->getUIReference(guiTemplate));
}
string ofx3DPro::cursorIsOverLight(){
if(bEnableLights){
for( auto& it : lights ){
if ( it.second->distance(cursor.world) < 10 ){
return it.first;
}
}
}
return "NULL";
}
void ofx3DPro::lightsBegin(){
ofEnableLighting();
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, &globalAmbientColor.r);
ofSetSmoothLighting(bSmoothLighting);
for( auto& it : lights ){
it.second->enable();
}
}
void ofx3DPro::lightsEnd(){
for( auto& it : lights ){
it.second->disable();
}
ofDisableLighting();
}
void ofx3DPro::lightsDraw(){
if(bEnableLights){
ofPushStyle();
ofDisableLighting();
string overLight = cursorIsOverLight();
for( auto& it : lights ){
it.second->draw();
if( overLight == it.first){
ofPushMatrix();
ofPushStyle();
ofNoFill();
float pulse = abs(sin(ofGetElapsedTimef()));
ofColor color = it.second->getColor();
color.setBrightness(background->getUIBrightness()*255);
ofSetColor( color, pulse*255);
ofTranslate( it.second->getPosition() );
float size = it.second->getPosition().distance(getCameraRef().getPosition())*0.1;
camera->billboard();
ofSetLineWidth(2);
ofEllipse(0,0, size, size);
ofPopStyle();
ofPopMatrix();
}
}
ofPopStyle();
}
}
void ofx3DPro::materialAdd( string _name ){
UIMaterialReference newMaterial( new UIMaterial() );
if ( _name == "MATERIAL" ){
_name = "MATERIAL " + ofToString( materials.size() + 1);
}
newMaterial->setName(_name);
materials[ _name ] = newMaterial;
guis.push_back( newMaterial->getUIReference(guiTemplate) );
}
//------------------------------------------------------ Save & Load + CAMERA
void ofx3DPro::guiLoad(string _presetName){
ofx2DPro::guiLoad(_presetName);
camera->load(getDataPath()+"Presets/"+_presetName+"/"+"current.cam");
}
void ofx3DPro::guiLoadFromPath(string presetPath){
ofx2DPro::guiLoadFromPath(presetPath);
camera->load(presetPath+"/current.cam");
// ofx2DPro::guiLoadFromPath(presetPath);
}
void ofx3DPro::guiSave(string presetName){
ofx2DPro::guiSave(presetName);
camera->save(getDataPath()+"Presets/"+presetName+"/current.cam");
if(camera->bEnable){
camera->enableMouseInput();
}
}
ofCamera& ofx3DPro::getCameraRef(){
return (*camera->getCameraPtn());
}<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/iat_patch.h"
#include "base/logging.h"
namespace iat_patch {
struct InterceptFunctionInformation {
bool finished_operation;
const char* imported_from_module;
const char* function_name;
void* new_function;
void** old_function;
IMAGE_THUNK_DATA** iat_thunk;
DWORD return_code;
};
static void* GetIATFunction(IMAGE_THUNK_DATA* iat_thunk) {
if (NULL == iat_thunk) {
NOTREACHED();
return NULL;
}
// Works around the 64 bit portability warning:
// The Function member inside IMAGE_THUNK_DATA is really a pointer
// to the IAT function. IMAGE_THUNK_DATA correctly maps to IMAGE_THUNK_DATA32
// or IMAGE_THUNK_DATA64 for correct pointer size.
union FunctionThunk {
IMAGE_THUNK_DATA thunk;
void* pointer;
} iat_function;
iat_function.thunk = *iat_thunk;
return iat_function.pointer;
}
static bool InterceptEnumCallback(const PEImage &image, const char* module,
DWORD ordinal, const char* name, DWORD hint,
IMAGE_THUNK_DATA* iat, void* cookie) {
InterceptFunctionInformation* intercept_information =
reinterpret_cast<InterceptFunctionInformation*>(cookie);
if (NULL == intercept_information) {
NOTREACHED();
return false;
}
DCHECK(module);
if ((0 == lstrcmpiA(module, intercept_information->imported_from_module)) &&
(NULL != name) &&
(0 == lstrcmpiA(name, intercept_information->function_name))) {
// Save the old pointer.
if (NULL != intercept_information->old_function) {
*(intercept_information->old_function) = GetIATFunction(iat);
}
if (NULL != intercept_information->iat_thunk) {
*(intercept_information->iat_thunk) = iat;
}
// portability check
COMPILE_ASSERT(sizeof(iat->u1.Function) ==
sizeof(intercept_information->new_function), unknown_IAT_thunk_format);
// Patch the function.
intercept_information->return_code =
ModifyCode(&(iat->u1.Function),
&(intercept_information->new_function),
sizeof(intercept_information->new_function));
// Terminate further enumeration.
intercept_information->finished_operation = true;
return false;
}
return true;
}
DWORD InterceptImportedFunction(HMODULE module_handle,
const char* imported_from_module,
const char* function_name, void* new_function,
void** old_function,
IMAGE_THUNK_DATA** iat_thunk) {
if ((NULL == module_handle) || (NULL == imported_from_module) ||
(NULL == function_name) || (NULL == new_function)) {
NOTREACHED();
return ERROR_INVALID_PARAMETER;
}
PEImage target_image(module_handle);
if (!target_image.VerifyMagic()) {
NOTREACHED();
return ERROR_INVALID_PARAMETER;
}
InterceptFunctionInformation intercept_information = {
false,
imported_from_module,
function_name,
new_function,
old_function,
iat_thunk,
ERROR_GEN_FAILURE};
// First go through the IAT. If we don't find the import we are looking
// for in IAT, search delay import table.
target_image.EnumAllImports(InterceptEnumCallback, &intercept_information);
if (!intercept_information.finished_operation) {
target_image.EnumAllDelayImports(InterceptEnumCallback,
&intercept_information);
}
return intercept_information.return_code;
}
DWORD RestoreImportedFunction(void* intercept_function,
void* original_function,
IMAGE_THUNK_DATA* iat_thunk) {
if ((NULL == intercept_function) || (NULL == original_function) ||
(NULL == iat_thunk)) {
NOTREACHED();
return ERROR_INVALID_PARAMETER;
}
if (GetIATFunction(iat_thunk) != intercept_function) {
// Check if someone else has intercepted on top of us.
// We cannot unpatch in this case, just raise a red flag.
NOTREACHED();
return ERROR_INVALID_FUNCTION;
}
return ModifyCode(&(iat_thunk->u1.Function),
&original_function,
sizeof(original_function));
}
DWORD ModifyCode(void* old_code, void* new_code, int length) {
if ((NULL == old_code) || (NULL == new_code) || (0 == length)) {
NOTREACHED();
return ERROR_INVALID_PARAMETER;
}
// Change the page protection so that we can write.
DWORD error = NO_ERROR;
DWORD old_page_protection = 0;
if (VirtualProtect(old_code,
length,
PAGE_READWRITE,
&old_page_protection)) {
// Write the data.
CopyMemory(old_code, new_code, length);
// Restore the old page protection.
error = ERROR_SUCCESS;
VirtualProtect(old_code,
length,
old_page_protection,
&old_page_protection);
} else {
error = GetLastError();
NOTREACHED();
}
return error;
}
IATPatchFunction::IATPatchFunction()
: original_function_(NULL),
iat_thunk_(NULL),
intercept_function_(NULL) {
}
IATPatchFunction::~IATPatchFunction() {
if (NULL != intercept_function_) {
DWORD error = Unpatch();
DCHECK_EQ(NO_ERROR, error);
}
}
DWORD IATPatchFunction::Patch(HMODULE module_handle,
const char* imported_from_module,
const char* function_name,
void* new_function) {
DCHECK_EQ(static_cast<void*>(NULL), original_function_);
DCHECK_EQ(static_cast<IMAGE_THUNK_DATA*>(NULL), iat_thunk_);
DCHECK_EQ(static_cast<void*>(NULL), intercept_function_);
DWORD error = InterceptImportedFunction(module_handle,
imported_from_module,
function_name,
new_function,
&original_function_,
&iat_thunk_);
if (NO_ERROR == error) {
DCHECK_NE(original_function_, intercept_function_);
intercept_function_ = new_function;
}
return error;
}
DWORD IATPatchFunction::Unpatch() {
DWORD error = RestoreImportedFunction(intercept_function_,
original_function_,
iat_thunk_);
if (NO_ERROR == error) {
intercept_function_ = NULL;
original_function_ = NULL;
iat_thunk_ = NULL;
}
return error;
}
} // namespace iat_patch
<commit_msg>Hands off the intercept if 'unpatch' fails<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/iat_patch.h"
#include "base/logging.h"
namespace iat_patch {
struct InterceptFunctionInformation {
bool finished_operation;
const char* imported_from_module;
const char* function_name;
void* new_function;
void** old_function;
IMAGE_THUNK_DATA** iat_thunk;
DWORD return_code;
};
static void* GetIATFunction(IMAGE_THUNK_DATA* iat_thunk) {
if (NULL == iat_thunk) {
NOTREACHED();
return NULL;
}
// Works around the 64 bit portability warning:
// The Function member inside IMAGE_THUNK_DATA is really a pointer
// to the IAT function. IMAGE_THUNK_DATA correctly maps to IMAGE_THUNK_DATA32
// or IMAGE_THUNK_DATA64 for correct pointer size.
union FunctionThunk {
IMAGE_THUNK_DATA thunk;
void* pointer;
} iat_function;
iat_function.thunk = *iat_thunk;
return iat_function.pointer;
}
static bool InterceptEnumCallback(const PEImage &image, const char* module,
DWORD ordinal, const char* name, DWORD hint,
IMAGE_THUNK_DATA* iat, void* cookie) {
InterceptFunctionInformation* intercept_information =
reinterpret_cast<InterceptFunctionInformation*>(cookie);
if (NULL == intercept_information) {
NOTREACHED();
return false;
}
DCHECK(module);
if ((0 == lstrcmpiA(module, intercept_information->imported_from_module)) &&
(NULL != name) &&
(0 == lstrcmpiA(name, intercept_information->function_name))) {
// Save the old pointer.
if (NULL != intercept_information->old_function) {
*(intercept_information->old_function) = GetIATFunction(iat);
}
if (NULL != intercept_information->iat_thunk) {
*(intercept_information->iat_thunk) = iat;
}
// portability check
COMPILE_ASSERT(sizeof(iat->u1.Function) ==
sizeof(intercept_information->new_function), unknown_IAT_thunk_format);
// Patch the function.
intercept_information->return_code =
ModifyCode(&(iat->u1.Function),
&(intercept_information->new_function),
sizeof(intercept_information->new_function));
// Terminate further enumeration.
intercept_information->finished_operation = true;
return false;
}
return true;
}
DWORD InterceptImportedFunction(HMODULE module_handle,
const char* imported_from_module,
const char* function_name, void* new_function,
void** old_function,
IMAGE_THUNK_DATA** iat_thunk) {
if ((NULL == module_handle) || (NULL == imported_from_module) ||
(NULL == function_name) || (NULL == new_function)) {
NOTREACHED();
return ERROR_INVALID_PARAMETER;
}
PEImage target_image(module_handle);
if (!target_image.VerifyMagic()) {
NOTREACHED();
return ERROR_INVALID_PARAMETER;
}
InterceptFunctionInformation intercept_information = {
false,
imported_from_module,
function_name,
new_function,
old_function,
iat_thunk,
ERROR_GEN_FAILURE};
// First go through the IAT. If we don't find the import we are looking
// for in IAT, search delay import table.
target_image.EnumAllImports(InterceptEnumCallback, &intercept_information);
if (!intercept_information.finished_operation) {
target_image.EnumAllDelayImports(InterceptEnumCallback,
&intercept_information);
}
return intercept_information.return_code;
}
DWORD RestoreImportedFunction(void* intercept_function,
void* original_function,
IMAGE_THUNK_DATA* iat_thunk) {
if ((NULL == intercept_function) || (NULL == original_function) ||
(NULL == iat_thunk)) {
NOTREACHED();
return ERROR_INVALID_PARAMETER;
}
if (GetIATFunction(iat_thunk) != intercept_function) {
// Check if someone else has intercepted on top of us.
// We cannot unpatch in this case, just raise a red flag.
NOTREACHED();
return ERROR_INVALID_FUNCTION;
}
return ModifyCode(&(iat_thunk->u1.Function),
&original_function,
sizeof(original_function));
}
DWORD ModifyCode(void* old_code, void* new_code, int length) {
if ((NULL == old_code) || (NULL == new_code) || (0 == length)) {
NOTREACHED();
return ERROR_INVALID_PARAMETER;
}
// Change the page protection so that we can write.
DWORD error = NO_ERROR;
DWORD old_page_protection = 0;
if (VirtualProtect(old_code,
length,
PAGE_READWRITE,
&old_page_protection)) {
// Write the data.
CopyMemory(old_code, new_code, length);
// Restore the old page protection.
error = ERROR_SUCCESS;
VirtualProtect(old_code,
length,
old_page_protection,
&old_page_protection);
} else {
error = GetLastError();
NOTREACHED();
}
return error;
}
IATPatchFunction::IATPatchFunction()
: original_function_(NULL),
iat_thunk_(NULL),
intercept_function_(NULL) {
}
IATPatchFunction::~IATPatchFunction() {
if (NULL != intercept_function_) {
DWORD error = Unpatch();
DCHECK_EQ(NO_ERROR, error);
}
}
DWORD IATPatchFunction::Patch(HMODULE module_handle,
const char* imported_from_module,
const char* function_name,
void* new_function) {
DCHECK_EQ(static_cast<void*>(NULL), original_function_);
DCHECK_EQ(static_cast<IMAGE_THUNK_DATA*>(NULL), iat_thunk_);
DCHECK_EQ(static_cast<void*>(NULL), intercept_function_);
DWORD error = InterceptImportedFunction(module_handle,
imported_from_module,
function_name,
new_function,
&original_function_,
&iat_thunk_);
if (NO_ERROR == error) {
DCHECK_NE(original_function_, intercept_function_);
intercept_function_ = new_function;
}
return error;
}
DWORD IATPatchFunction::Unpatch() {
DWORD error = RestoreImportedFunction(intercept_function_,
original_function_,
iat_thunk_);
DCHECK(NO_ERROR == error);
// Hands off the intercept if we fail to unpatch.
// If IATPatchFunction::Unpatch fails during RestoreImportedFunction
// it means that we cannot safely unpatch the import address table
// patch. In this case its better to be hands off the intercept as
// trying to unpatch again in the destructor of IATPatchFunction is
// not going to be any safer
intercept_function_ = NULL;
original_function_ = NULL;
iat_thunk_ = NULL;
return error;
}
} // namespace iat_patch
<|endoftext|> |
<commit_before>/*************************************************************************
> Author: Wayne Ho
> Purpose: TODO
> Created Time: Fri Apr 17 16:32:22 2015
> Mail: hewr2010@gmail.com
************************************************************************/
#include "argparse/macro-argparse-jquery.hh"
#include "solver/solver.h"
#include "eigen_triangle.h"
#include "triangle_brute_force.h"
#include "triangle_stream.h"
#include "storage/graph_builder.h"
#include "storage/mgraph.h"
#include "report/table_generator.h"
#include <iostream>
#include <cstdio>
#include <ctime>
#include <map>
#include <cstdlib>
using namespace std;
using namespace sae::io;
DEF_ARGUMENT_CLASS(
Argument,
string, content, "test", OPTIONAL, OPT_SLH(-c, --content, "what to say"),
//int, number, 1, REQUIRED, OPT_LH(-n, "what number is it? "),
bool, decorate, true, OPTIONAL, OPT_SLWH(-d, --decorate, true, "decoreate the output")
);
void makeFakeData(int numVertex=10) {
int numEdge = rand() % (numVertex * numVertex / 3) + numVertex;
GraphBuilder<int> graph;
for (int i = 0; i < numVertex; ++i) graph.AddVertex(i, 0);
map<pair<int, int>, bool> edges;
for (int i = 0; i < numEdge; ++i) {
pair<int, int> edge;
do {
int x = rand() % (numVertex - 1);
int y = rand() % (numVertex - x - 1) + x + 1;
edge = make_pair(x, y);
} while (edges.find(edge) != edges.end());
edges[edge] = true;
graph.AddEdge(edge.first, edge.second, 0);
//cout << edge.first << " " << edge.second << endl;
}
system("mkdir -p fake");
graph.Save("./fake/graph");
}
void testTriangle(char* prefix="./fake/graph") {
MappedGraph *graph;
graph = MappedGraph::Open(prefix);
// brute force
Triangle_Brute_Force bf(graph);
int bf_cnt = bf.solve();
// eigen
EigenTriangle et(graph);
double et_cnt = et.solve(graph -> VertexCount() * 0.1);
cout << "[brute force]\t" << bf_cnt << endl;
cout << "[eigen triangle]\t" << et_cnt << endl;
cout << "\terror " << (float(bf_cnt - et_cnt) / bf_cnt * 100) << "%" << endl;
// streaming
Triangle_Stream stm(50, 1000);
int stream_cnt(0);
for (auto itr = graph->Edges(); itr->Alive(); itr->Next()) {
vid_t x = itr->Source()->GlobalId(), y = itr->Target()->GlobalId();
auto res = stm.solve(x, y);
stream_cnt = res.second;
cout << "\r" << "[streaming]\t" << res.first << " " << res.second << flush;
}
cout << endl;
cout << "[streaming]\t" << stream_cnt << endl;
// evaluation
cout << "\terror " << (float(bf_cnt - stream_cnt) / bf_cnt * 100) << "%" << endl;
}
void testTable() {
TableGenerator table;
string title[] = {"z", "y", "x"};
table.setTitle(vector<string>(title, title + sizeof(title) / sizeof(title[0])));
for (int l = 0; l < rand() % 10 + 1; ++l) {
vector<string> content;
content.push_back(toString(l));
for (int i = 0; i < rand() % 10 + 1; ++i) content.push_back(toString(rand() % 1000));
table.addRow(content);
}
cout << table.report() << endl;
}
int main(int argc, char **argv) {
// parse arguments
Argument args;
if (!args.parse_args(argc, argv)) return 1;
//cout << args.content() << endl;
// main process
srand(time(NULL));
//testTable();
//makeFakeData(300);
testTriangle();
return 0;
}
<commit_msg>update<commit_after>/*************************************************************************
> Author: Wayne Ho
> Purpose: TODO
> Created Time: Fri Apr 17 16:32:22 2015
> Mail: hewr2010@gmail.com
************************************************************************/
#include "argparse/macro-argparse-jquery.hh"
#include "solver/solver.h"
#include "eigen_triangle.h"
#include "triangle_brute_force.h"
#include "triangle_stream.h"
#include "storage/graph_builder.h"
#include "storage/mgraph.h"
#include "report/table_generator.h"
#include <iostream>
#include <cstdio>
#include <ctime>
#include <map>
#include <cstdlib>
using namespace std;
using namespace sae::io;
DEF_ARGUMENT_CLASS(
Argument,
string, content, "test", OPTIONAL, OPT_SLH(-c, --content, "what to say"),
//int, number, 1, REQUIRED, OPT_LH(-n, "what number is it? "),
bool, decorate, true, OPTIONAL, OPT_SLWH(-d, --decorate, true, "decoreate the output")
);
void makeFakeData(int numVertex=10, double p = 0.1) {
//int numEdge = rand() % (numVertex * numVertex / 3) + numVertex;
int numEdge = (numVertex * (numVertex - 1)) / 2 * p;
GraphBuilder<int> graph;
for (int i = 0; i < numVertex; ++i) graph.AddVertex(i, 0);
map<pair<int, int>, bool> edges;
for (int i = 0; i < numEdge; ++i) {
pair<int, int> edge;
do {
int x = rand() % (numVertex - 1);
int y = rand() % (numVertex - x - 1) + x + 1;
edge = make_pair(x, y);
} while (edges.find(edge) != edges.end());
edges[edge] = true;
graph.AddEdge(edge.first, edge.second, 0);
//cout << edge.first << " " << edge.second << endl;
}
system("mkdir -p fake");
graph.Save("./fake/graph");
}
void testTriangle(char* prefix="./fake/graph") {
MappedGraph *graph;
graph = MappedGraph::Open(prefix);
// brute force
Triangle_Brute_Force bf(graph);
int bf_cnt = bf.solve();
// eigen
EigenTriangle et(graph);
double et_cnt = et.solve(graph -> VertexCount() * 0.1);
cout << "[brute force]\t" << bf_cnt << endl;
cout << "[eigen triangle]\t" << et_cnt << endl;
cout << "\terror " << (float(bf_cnt - et_cnt) / bf_cnt * 100) << "%" << endl;
// streaming
Triangle_Stream stm(50, 1000);
int stream_cnt(0);
for (auto itr = graph->Edges(); itr->Alive(); itr->Next()) {
vid_t x = itr->Source()->GlobalId(), y = itr->Target()->GlobalId();
auto res = stm.solve(x, y);
stream_cnt = res.second;
cout << "\r" << "[streaming]\t" << res.first << " " << res.second << flush;
}
cout << endl;
cout << "[streaming]\t" << stream_cnt << endl;
// evaluation
cout << "\terror " << (float(bf_cnt - stream_cnt) / bf_cnt * 100) << "%" << endl;
}
void testTable() {
TableGenerator table;
string title[] = {"z", "y", "x"};
table.setTitle(vector<string>(title, title + sizeof(title) / sizeof(title[0])));
for (int l = 0; l < rand() % 10 + 1; ++l) {
vector<string> content;
content.push_back(toString(l));
for (int i = 0; i < rand() % 10 + 1; ++i) content.push_back(toString(rand() % 1000));
table.addRow(content);
}
cout << table.report() << endl;
}
int main(int argc, char **argv) {
int vertexNum = 500;
double edgeProb = 0.7;
// parse arguments
Argument args;
if (!args.parse_args(argc, argv)) return 1;
//cout << args.content() << endl;
// main process
srand(time(NULL));
//testTable();
//makeFakeData(vertexNum, edgeProb);
testTriangle();
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <cstdio>
#include <fstream>
#include <set>
#include <cmath>
#include <chrono>
#include <iomanip>
#include <sstream>
#include "CUDA2HIP.h"
#include "CUDA2HIP_Scripting.h"
#include "LLVMCompat.h"
#include "HipifyAction.h"
#include "ArgParse.h"
#include "StringUtils.h"
#include "llvm/Support/Debug.h"
#if LLVM_VERSION_MAJOR < 8
#include "llvm/Support/Path.h"
#endif
constexpr auto DEBUG_TYPE = "cuda2hip";
namespace ct = clang::tooling;
int main(int argc, const char **argv) {
std::vector<const char*> new_argv(argv, argv + argc);
if (std::find(new_argv.begin(), new_argv.end(), std::string("--")) == new_argv.end()) {
new_argv.push_back("--");
new_argv.push_back(nullptr);
argv = new_argv.data();
argc++;
}
llcompat::PrintStackTraceOnErrorSignal();
ct::CommonOptionsParser OptionsParser(argc, argv, ToolTemplateCategory, llvm::cl::ZeroOrMore);
if (!llcompat::CheckCompatibility()) {
return 1;
}
std::vector<std::string> fileSources = OptionsParser.getSourcePathList();
if (fileSources.empty() && !GeneratePerl && !GeneratePython) {
llvm::errs() << "\n" << sHipify << sError << "Must specify at least 1 positional argument for source file" << "\n";
return 1;
}
if (!perl::generate(GeneratePerl)) {
llvm::errs() << "\n" << sHipify << sError << "hipify-perl generating failed" << "\n";
return 1;
}
bool bToRoc = TranslateToRoc;
TranslateToRoc = true;
bool bToPython = python::generate(GeneratePython);
TranslateToRoc = bToRoc;
if (!bToPython) {
llvm::errs() << "\n" << sHipify << sError << "hipify-python generating failed" << "\n";
return 1;
}
if (fileSources.empty()) {
return 0;
}
std::string dst = OutputFilename, dstDir = OutputDir;
std::error_code EC;
std::string sOutputDirAbsPath = getAbsoluteDirectoryPath(OutputDir, EC, "output");
if (EC) {
return 1;
}
if (!dst.empty()) {
if (fileSources.size() > 1) {
llvm::errs() << sHipify << sConflict << "-o and multiple source files are specified\n";
return 1;
}
if (Inplace) {
llvm::errs() << sHipify << sConflict << "both -o and -inplace options are specified\n";
return 1;
}
if (NoOutput) {
llvm::errs() << sHipify << sConflict << "both -no-output and -o options are specified\n";
return 1;
}
if (!dstDir.empty()) {
dst = sOutputDirAbsPath + "/" + dst;
}
}
if (NoOutput && Inplace) {
llvm::errs() << sHipify << sConflict << "both -no-output and -inplace options are specified\n";
return 1;
}
if (!dstDir.empty() && Inplace) {
llvm::errs() << sHipify << sConflict << "both -o-dir and -inplace options are specified\n";
return 1;
}
if (Examine) {
NoOutput = PrintStats = true;
}
int Result = 0;
SmallString<128> tmpFile;
StringRef sourceFileName, ext = "hip", csv_ext = "csv";
std::string sTmpFileName, sSourceAbsPath;
std::string sTmpDirAbsParh = getAbsoluteDirectoryPath(TemporaryDir, EC);
if (EC) {
return 1;
}
// Arguments for the Statistics print routines.
std::unique_ptr<std::ostream> csv = nullptr;
llvm::raw_ostream* statPrint = nullptr;
bool create_csv = false;
if (!OutputStatsFilename.empty()) {
PrintStatsCSV = true;
create_csv = true;
} else {
if (PrintStatsCSV && fileSources.size() > 1) {
OutputStatsFilename = "sum_stat.csv";
create_csv = true;
}
}
if (create_csv) {
if (!OutputDir.empty()) {
OutputStatsFilename = sOutputDirAbsPath + "/" + OutputStatsFilename;
}
csv = std::unique_ptr<std::ostream>(new std::ofstream(OutputStatsFilename, std::ios_base::trunc));
}
if (PrintStats) {
statPrint = &llvm::errs();
}
for (const auto & src : fileSources) {
// Create a copy of the file to work on. When we're done, we'll move this onto the
// output (which may mean overwriting the input, if we're in-place).
// Should we fail for some reason, we'll just leak this file and not corrupt the input.
sSourceAbsPath = getAbsoluteFilePath(src, EC);
if (EC) {
continue;
}
sourceFileName = sys::path::filename(sSourceAbsPath);
if (dst.empty()) {
if (Inplace) {
dst = src;
} else {
dst = src + "." + ext.str();
if (!dstDir.empty()) {
dst = sOutputDirAbsPath + "/" + sourceFileName.str() + "." + ext.str();
}
}
}
if (TemporaryDir.empty()) {
EC = sys::fs::createTemporaryFile(sourceFileName, ext, tmpFile);
if (EC) {
llvm::errs() << "\n" << sHipify << sError << EC.message() << ": " << tmpFile << "\n";
Result = 1;
continue;
}
} else {
sTmpFileName = sTmpDirAbsParh + "/" + sourceFileName.str() + "." + ext.str();
tmpFile = sTmpFileName;
}
EC = sys::fs::copy_file(src, tmpFile);
if (EC) {
llvm::errs() << "\n" << sHipify << sError << EC.message() << ": while copying " << src << " to " << tmpFile << "\n";
Result = 1;
continue;
}
if (PrintStatsCSV) {
if (OutputStatsFilename.empty()) {
OutputStatsFilename = sourceFileName.str() + "." + csv_ext.str();
if (!OutputDir.empty()) {
OutputStatsFilename = sOutputDirAbsPath + "/" + OutputStatsFilename;
}
}
if (!csv) {
csv = std::unique_ptr<std::ostream>(new std::ofstream(OutputStatsFilename, std::ios_base::trunc));
}
}
// Initialise the statistics counters for this file.
Statistics::setActive(src);
// RefactoringTool operates on the file in-place. Giving it the output path is no good,
// because that'll break relative includes, and we don't want to overwrite the input file.
// So what we do is operate on a copy, which we then move to the output.
ct::RefactoringTool Tool(OptionsParser.getCompilations(), std::string(tmpFile.c_str()));
ct::Replacements& replacementsToUse = llcompat::getReplacements(Tool, tmpFile.c_str());
ReplacementsFrontendActionFactory<HipifyAction> actionFactory(&replacementsToUse);
if (!IncludeDirs.empty()) {
for (std::string s : IncludeDirs) {
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(s.c_str(), ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-I", ct::ArgumentInsertPosition::BEGIN));
}
}
if (!MacroNames.empty()) {
for (std::string s : MacroNames) {
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(s.c_str(), ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-D", ct::ArgumentInsertPosition::BEGIN));
}
}
// Includes for clang's CUDA wrappers for using by packaged hipify-clang
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("./include", ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-isystem", ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("./include/cuda_wrappers", ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-isystem", ct::ArgumentInsertPosition::BEGIN));
// Ensure at least c++11 is used.
std::string stdCpp = "-std=c++11";
#if defined(_MSC_VER)
stdCpp = "-std=c++14";
#endif
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(stdCpp.c_str(), ct::ArgumentInsertPosition::BEGIN));
std::string sInclude = "-I" + sys::path::parent_path(sSourceAbsPath).str();
#if defined(HIPIFY_CLANG_RES)
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-resource-dir=" HIPIFY_CLANG_RES, ct::ArgumentInsertPosition::BEGIN));
#endif
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(sInclude.c_str(), ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-fno-delayed-template-parsing", ct::ArgumentInsertPosition::BEGIN));
if (llcompat::pragma_once_outside_header()) {
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-Wno-pragma-once-outside-header", ct::ArgumentInsertPosition::BEGIN));
}
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("--cuda-host-only", ct::ArgumentInsertPosition::BEGIN));
if (!CudaGpuArch.empty()) {
std::string sCudaGpuArch = "--cuda-gpu-arch=" + CudaGpuArch;
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(sCudaGpuArch.c_str(), ct::ArgumentInsertPosition::BEGIN));
}
if (!CudaPath.empty()) {
std::string sCudaPath = "--cuda-path=" + CudaPath;
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(sCudaPath.c_str(), ct::ArgumentInsertPosition::BEGIN));
}
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("cuda", ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-x", ct::ArgumentInsertPosition::BEGIN));
if (Verbose) {
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-v", ct::ArgumentInsertPosition::END));
}
Tool.appendArgumentsAdjuster(ct::getClangSyntaxOnlyAdjuster());
Statistics& currentStat = Statistics::current();
// Hipify _all_ the things!
if (Tool.runAndSave(&actionFactory)) {
currentStat.hasErrors = true;
Result = 1;
LLVM_DEBUG(llvm::dbgs() << "Skipped some replacements.\n");
}
// Copy the tmpfile to the output
if (!NoOutput && !currentStat.hasErrors) {
EC = sys::fs::copy_file(tmpFile, dst);
if (EC) {
llvm::errs() << "\n" << sHipify << sError << EC.message() << ": while copying " << tmpFile << " to " << dst << "\n";
Result = 1;
continue;
}
}
// Remove the tmp file without error check
if (!SaveTemps) {
sys::fs::remove(tmpFile);
}
Statistics::current().markCompletion();
Statistics::current().print(csv.get(), statPrint);
dst.clear();
}
if (fileSources.size() > 1) {
Statistics::printAggregate(csv.get(), statPrint);
}
return Result;
}
<commit_msg>[HIPIFY][fix][#1246][#1655] Sort input files based on their dependency graph<commit_after>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <cstdio>
#include <fstream>
#include <set>
#include <cmath>
#include <chrono>
#include <iomanip>
#include <sstream>
#include "CUDA2HIP.h"
#include "CUDA2HIP_Scripting.h"
#include "LLVMCompat.h"
#include "HipifyAction.h"
#include "ArgParse.h"
#include "StringUtils.h"
#include "llvm/Support/Debug.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticIDs.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#if LLVM_VERSION_MAJOR < 8
#include "llvm/Support/Path.h"
#endif
constexpr auto DEBUG_TYPE = "cuda2hip";
namespace ct = clang::tooling;
int main(int argc, const char **argv) {
std::vector<const char*> new_argv(argv, argv + argc);
if (std::find(new_argv.begin(), new_argv.end(), std::string("--")) == new_argv.end()) {
new_argv.push_back("--");
new_argv.push_back(nullptr);
argv = new_argv.data();
argc++;
}
llcompat::PrintStackTraceOnErrorSignal();
ct::CommonOptionsParser OptionsParser(argc, argv, ToolTemplateCategory, llvm::cl::ZeroOrMore);
if (!llcompat::CheckCompatibility()) {
return 1;
}
std::vector<std::string> fileSources = OptionsParser.getSourcePathList();
if (fileSources.empty() && !GeneratePerl && !GeneratePython) {
llvm::errs() << "\n" << sHipify << sError << "Must specify at least 1 positional argument for source file" << "\n";
return 1;
}
if (!perl::generate(GeneratePerl)) {
llvm::errs() << "\n" << sHipify << sError << "hipify-perl generating failed" << "\n";
return 1;
}
bool bToRoc = TranslateToRoc;
TranslateToRoc = true;
bool bToPython = python::generate(GeneratePython);
TranslateToRoc = bToRoc;
if (!bToPython) {
llvm::errs() << "\n" << sHipify << sError << "hipify-python generating failed" << "\n";
return 1;
}
if (fileSources.empty()) {
return 0;
}
std::string dst = OutputFilename, dstDir = OutputDir;
std::error_code EC;
std::string sOutputDirAbsPath = getAbsoluteDirectoryPath(OutputDir, EC, "output");
if (EC) {
return 1;
}
if (!dst.empty()) {
if (fileSources.size() > 1) {
llvm::errs() << sHipify << sConflict << "-o and multiple source files are specified\n";
return 1;
}
if (Inplace) {
llvm::errs() << sHipify << sConflict << "both -o and -inplace options are specified\n";
return 1;
}
if (NoOutput) {
llvm::errs() << sHipify << sConflict << "both -no-output and -o options are specified\n";
return 1;
}
if (!dstDir.empty()) {
dst = sOutputDirAbsPath + "/" + dst;
}
}
if (NoOutput && Inplace) {
llvm::errs() << sHipify << sConflict << "both -no-output and -inplace options are specified\n";
return 1;
}
if (!dstDir.empty() && Inplace) {
llvm::errs() << sHipify << sConflict << "both -o-dir and -inplace options are specified\n";
return 1;
}
if (Examine) {
NoOutput = PrintStats = true;
}
int Result = 0;
SmallString<128> tmpFile;
StringRef sourceFileName, ext = "hip", csv_ext = "csv";
std::string sTmpFileName, sSourceAbsPath;
std::string sTmpDirAbsParh = getAbsoluteDirectoryPath(TemporaryDir, EC);
if (EC) {
return 1;
}
// Arguments for the Statistics print routines.
std::unique_ptr<std::ostream> csv = nullptr;
llvm::raw_ostream* statPrint = nullptr;
bool create_csv = false;
if (!OutputStatsFilename.empty()) {
PrintStatsCSV = true;
create_csv = true;
} else {
if (PrintStatsCSV && fileSources.size() > 1) {
OutputStatsFilename = "sum_stat.csv";
create_csv = true;
}
}
if (create_csv) {
if (!OutputDir.empty()) {
OutputStatsFilename = sOutputDirAbsPath + "/" + OutputStatsFilename;
}
csv = std::unique_ptr<std::ostream>(new std::ofstream(OutputStatsFilename, std::ios_base::trunc));
}
if (PrintStats) {
statPrint = &llvm::errs();
}
if (fileSources.size() > 1) {
IntrusiveRefCntPtr<clang::DiagnosticOptions> diagOpts(new clang::DiagnosticOptions());
clang::TextDiagnosticPrinter diagClient(llvm::errs(), &*diagOpts);
clang::DiagnosticsEngine Diagnostics(IntrusiveRefCntPtr<clang::DiagnosticIDs>(new clang::DiagnosticIDs()), &*diagOpts, &diagClient, false);
std::unique_ptr<clang::driver::Driver> driver(new clang::driver::Driver("", "nvptx64-nvidia-cuda", Diagnostics));
SmallVector<const char*, 16> Args(argv, argv + argc);
std::unique_ptr<clang::driver::Compilation> C(driver->BuildCompilation(Args));
std::vector<std::string> fileSourcesOrdered;
for (const auto &J : C->getJobs()) {
if (std::string(J.getCreator().getName()) != "clang") continue;
const auto &JA = J.getArguments();
for (size_t i = 0; i < JA.size(); ++i) {
const auto &A = std::string(JA[i]);
if (std::find(fileSources.begin(), fileSources.end(), A) != fileSources.end() &&
i > 0 && std::string(JA[i-1]) == "-main-file-name") {
fileSourcesOrdered.push_back(A);
}
}
}
if (!fileSourcesOrdered.empty()) {
std::reverse(fileSourcesOrdered.begin(), fileSourcesOrdered.end());
fileSources = fileSourcesOrdered;
}
}
for (const auto & src : fileSources) {
// Create a copy of the file to work on. When we're done, we'll move this onto the
// output (which may mean overwriting the input, if we're in-place).
// Should we fail for some reason, we'll just leak this file and not corrupt the input.
sSourceAbsPath = getAbsoluteFilePath(src, EC);
if (EC) {
continue;
}
sourceFileName = sys::path::filename(sSourceAbsPath);
if (dst.empty()) {
if (Inplace) {
dst = src;
} else {
dst = src + "." + ext.str();
if (!dstDir.empty()) {
dst = sOutputDirAbsPath + "/" + sourceFileName.str() + "." + ext.str();
}
}
}
if (TemporaryDir.empty()) {
EC = sys::fs::createTemporaryFile(sourceFileName, ext, tmpFile);
if (EC) {
llvm::errs() << "\n" << sHipify << sError << EC.message() << ": " << tmpFile << "\n";
Result = 1;
continue;
}
} else {
sTmpFileName = sTmpDirAbsParh + "/" + sourceFileName.str() + "." + ext.str();
tmpFile = sTmpFileName;
}
EC = sys::fs::copy_file(src, tmpFile);
if (EC) {
llvm::errs() << "\n" << sHipify << sError << EC.message() << ": while copying " << src << " to " << tmpFile << "\n";
Result = 1;
continue;
}
if (PrintStatsCSV) {
if (OutputStatsFilename.empty()) {
OutputStatsFilename = sourceFileName.str() + "." + csv_ext.str();
if (!OutputDir.empty()) {
OutputStatsFilename = sOutputDirAbsPath + "/" + OutputStatsFilename;
}
}
if (!csv) {
csv = std::unique_ptr<std::ostream>(new std::ofstream(OutputStatsFilename, std::ios_base::trunc));
}
}
// Initialise the statistics counters for this file.
Statistics::setActive(src);
// RefactoringTool operates on the file in-place. Giving it the output path is no good,
// because that'll break relative includes, and we don't want to overwrite the input file.
// So what we do is operate on a copy, which we then move to the output.
ct::RefactoringTool Tool(OptionsParser.getCompilations(), std::string(tmpFile.c_str()));
ct::Replacements& replacementsToUse = llcompat::getReplacements(Tool, tmpFile.c_str());
ReplacementsFrontendActionFactory<HipifyAction> actionFactory(&replacementsToUse);
if (!IncludeDirs.empty()) {
for (std::string s : IncludeDirs) {
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(s.c_str(), ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-I", ct::ArgumentInsertPosition::BEGIN));
}
}
if (!MacroNames.empty()) {
for (std::string s : MacroNames) {
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(s.c_str(), ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-D", ct::ArgumentInsertPosition::BEGIN));
}
}
// Includes for clang's CUDA wrappers for using by packaged hipify-clang
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("./include", ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-isystem", ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("./include/cuda_wrappers", ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-isystem", ct::ArgumentInsertPosition::BEGIN));
// Ensure at least c++11 is used.
std::string stdCpp = "-std=c++11";
#if defined(_MSC_VER)
stdCpp = "-std=c++14";
#endif
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(stdCpp.c_str(), ct::ArgumentInsertPosition::BEGIN));
std::string sInclude = "-I" + sys::path::parent_path(sSourceAbsPath).str();
#if defined(HIPIFY_CLANG_RES)
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-resource-dir=" HIPIFY_CLANG_RES, ct::ArgumentInsertPosition::BEGIN));
#endif
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(sInclude.c_str(), ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-fno-delayed-template-parsing", ct::ArgumentInsertPosition::BEGIN));
if (llcompat::pragma_once_outside_header()) {
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-Wno-pragma-once-outside-header", ct::ArgumentInsertPosition::BEGIN));
}
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("--cuda-host-only", ct::ArgumentInsertPosition::BEGIN));
if (!CudaGpuArch.empty()) {
std::string sCudaGpuArch = "--cuda-gpu-arch=" + CudaGpuArch;
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(sCudaGpuArch.c_str(), ct::ArgumentInsertPosition::BEGIN));
}
if (!CudaPath.empty()) {
std::string sCudaPath = "--cuda-path=" + CudaPath;
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(sCudaPath.c_str(), ct::ArgumentInsertPosition::BEGIN));
}
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("cuda", ct::ArgumentInsertPosition::BEGIN));
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-x", ct::ArgumentInsertPosition::BEGIN));
if (Verbose) {
Tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster("-v", ct::ArgumentInsertPosition::END));
}
Tool.appendArgumentsAdjuster(ct::getClangSyntaxOnlyAdjuster());
Statistics& currentStat = Statistics::current();
// Hipify _all_ the things!
if (Tool.runAndSave(&actionFactory)) {
currentStat.hasErrors = true;
Result = 1;
LLVM_DEBUG(llvm::dbgs() << "Skipped some replacements.\n");
}
// Copy the tmpfile to the output
if (!NoOutput && !currentStat.hasErrors) {
EC = sys::fs::copy_file(tmpFile, dst);
if (EC) {
llvm::errs() << "\n" << sHipify << sError << EC.message() << ": while copying " << tmpFile << " to " << dst << "\n";
Result = 1;
continue;
}
}
// Remove the tmp file without error check
if (!SaveTemps) {
sys::fs::remove(tmpFile);
}
Statistics::current().markCompletion();
Statistics::current().print(csv.get(), statPrint);
dst.clear();
}
if (fileSources.size() > 1) {
Statistics::printAggregate(csv.get(), statPrint);
}
return Result;
}
<|endoftext|> |
<commit_before>#define _SECURE_SCL 0
#define _SCL_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <fstream>
#define BOOST_DISABLE_ASSERTS
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/tokenizer.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <htslib/sam.h>
#include <htslib/faidx.h>
#ifdef PROFILE
#include "gperftools/profiler.h"
#endif
#include "version.h"
#include "util.h"
#include "bamstats.h"
#include "count_rna.h"
#include "count_dna.h"
#include "count_junction.h"
#include "annotate.h"
#include "tracks.h"
#include "split.h"
#include "ase.h"
#include "qc.h"
#include "consensus.h"
#include "pwalign.h"
#include "spaced.h"
#include "repliseq.h"
using namespace bamstats;
inline void
asciiArt() {
std::cout << " _ __ _ " << std::endl;
std::cout << " /\\ | |/ _| | |" << std::endl;
std::cout << " / \\ | | |_ _ __ ___ __| |" << std::endl;
std::cout << " / /\\ \\ | | _| '__/ _ \\/ _` |" << std::endl;
std::cout << " / ____ \\| | | | | | __/ (_| |" << std::endl;
std::cout << " /_/ \\_\\_|_| |_| \\___|\\__,_|" << std::endl;
std::cout << std::endl;
}
inline void
displayUsage() {
std::cout << "Usage: alfred <command> <arguments>" << std::endl;
std::cout << std::endl;
std::cout << "Commands:" << std::endl;
std::cout << std::endl;
std::cout << " qc alignment quality control" << std::endl;
std::cout << " count_dna counting DNA reads in windows" << std::endl;
std::cout << " count_rna counting RNA reads in features" << std::endl;
std::cout << " count_jct counting RNA split-reads at exon junctions" << std::endl;
std::cout << " tracks create browser tracks" << std::endl;
std::cout << " annotate annotate peaks" << std::endl;
std::cout << " spaced_motif find spaced motifs" << std::endl;
std::cout << " split split BAM into haplotypes" << std::endl;
std::cout << " consensus consensus computation for error-prone reads" << std::endl;
std::cout << " pwalign pairwise alignment using dynamic programming" << std::endl;
std::cout << " ase allele-specific expression" << std::endl;
std::cout << " replication replication timing (Repli-Seq)" << std::endl;
std::cout << std::endl;
std::cout << std::endl;
}
int main(int argc, char **argv) {
if (argc < 2) {
asciiArt();
printTitle("Alfred");
displayUsage();
return 0;
}
if ((std::string(argv[1]) == "version") || (std::string(argv[1]) == "--version") || (std::string(argv[1]) == "--version-only") || (std::string(argv[1]) == "-v")) {
std::cout << "Alfred version: v" << alfredVersionNumber << std::endl;
return 0;
}
else if ((std::string(argv[1]) == "help") || (std::string(argv[1]) == "--help") || (std::string(argv[1]) == "-h") || (std::string(argv[1]) == "-?")) {
printTitle("Alfred");
displayUsage();
return 0;
}
else if ((std::string(argv[1]) == "warranty") || (std::string(argv[1]) == "--warranty") || (std::string(argv[1]) == "-w")) {
displayWarranty();
return 0;
}
else if ((std::string(argv[1]) == "license") || (std::string(argv[1]) == "--license") || (std::string(argv[1]) == "-l")) {
bsd();
return 0;
}
else if ((std::string(argv[1]) == "qc")) {
return qc(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "count_rna")) {
return count_rna(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "count_dna")) {
return count_dna(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "count_jct")) {
return count_junction(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "tracks")) {
return tracks(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "annotate")) {
return annotate(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "spaced_motif")) {
return spaced(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "split")) {
return split(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "consensus")) {
return consensus(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "pwalign")) {
return pwalign(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "ase")) {
return ase(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "replication")) {
return repliseq(argc-1,argv+1);
}
std::cerr << "Unrecognized command " << std::string(argv[1]) << std::endl;
return 1;
}
<commit_msg>boost and htslib version<commit_after>#define _SECURE_SCL 0
#define _SCL_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <fstream>
#define BOOST_DISABLE_ASSERTS
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/tokenizer.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <htslib/sam.h>
#include <htslib/faidx.h>
#ifdef PROFILE
#include "gperftools/profiler.h"
#endif
#include "version.h"
#include "util.h"
#include "bamstats.h"
#include "count_rna.h"
#include "count_dna.h"
#include "count_junction.h"
#include "annotate.h"
#include "tracks.h"
#include "split.h"
#include "ase.h"
#include "qc.h"
#include "consensus.h"
#include "pwalign.h"
#include "spaced.h"
#include "repliseq.h"
using namespace bamstats;
inline void
asciiArt() {
std::cout << " _ __ _ " << std::endl;
std::cout << " /\\ | |/ _| | |" << std::endl;
std::cout << " / \\ | | |_ _ __ ___ __| |" << std::endl;
std::cout << " / /\\ \\ | | _| '__/ _ \\/ _` |" << std::endl;
std::cout << " / ____ \\| | | | | | __/ (_| |" << std::endl;
std::cout << " /_/ \\_\\_|_| |_| \\___|\\__,_|" << std::endl;
std::cout << std::endl;
}
inline void
displayUsage() {
std::cout << "Usage: alfred <command> <arguments>" << std::endl;
std::cout << std::endl;
std::cout << "Commands:" << std::endl;
std::cout << std::endl;
std::cout << " qc alignment quality control" << std::endl;
std::cout << " count_dna counting DNA reads in windows" << std::endl;
std::cout << " count_rna counting RNA reads in features" << std::endl;
std::cout << " count_jct counting RNA split-reads at exon junctions" << std::endl;
std::cout << " tracks create browser tracks" << std::endl;
std::cout << " annotate annotate peaks" << std::endl;
std::cout << " spaced_motif find spaced motifs" << std::endl;
std::cout << " split split BAM into haplotypes" << std::endl;
std::cout << " consensus consensus computation for error-prone reads" << std::endl;
std::cout << " pwalign pairwise alignment using dynamic programming" << std::endl;
std::cout << " ase allele-specific expression" << std::endl;
std::cout << " replication replication timing (Repli-Seq)" << std::endl;
std::cout << std::endl;
std::cout << std::endl;
}
int main(int argc, char **argv) {
if (argc < 2) {
asciiArt();
printTitle("Alfred");
displayUsage();
return 0;
}
if ((std::string(argv[1]) == "version") || (std::string(argv[1]) == "--version") || (std::string(argv[1]) == "--version-only") || (std::string(argv[1]) == "-v")) {
std::cout << "Alfred version: v" << alfredVersionNumber << std::endl;
std::cout << " using Boost: v" << BOOST_VERSION / 100000 << "." << BOOST_VERSION / 100 % 1000 << "." << BOOST_VERSION % 100 << std::endl;
std::cout << " using HTSlib: v" << hts_version() << std::endl;
return 0;
}
else if ((std::string(argv[1]) == "help") || (std::string(argv[1]) == "--help") || (std::string(argv[1]) == "-h") || (std::string(argv[1]) == "-?")) {
printTitle("Alfred");
displayUsage();
return 0;
}
else if ((std::string(argv[1]) == "warranty") || (std::string(argv[1]) == "--warranty") || (std::string(argv[1]) == "-w")) {
displayWarranty();
return 0;
}
else if ((std::string(argv[1]) == "license") || (std::string(argv[1]) == "--license") || (std::string(argv[1]) == "-l")) {
bsd();
return 0;
}
else if ((std::string(argv[1]) == "qc")) {
return qc(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "count_rna")) {
return count_rna(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "count_dna")) {
return count_dna(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "count_jct")) {
return count_junction(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "tracks")) {
return tracks(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "annotate")) {
return annotate(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "spaced_motif")) {
return spaced(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "split")) {
return split(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "consensus")) {
return consensus(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "pwalign")) {
return pwalign(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "ase")) {
return ase(argc-1,argv+1);
}
else if ((std::string(argv[1]) == "replication")) {
return repliseq(argc-1,argv+1);
}
std::cerr << "Unrecognized command " << std::string(argv[1]) << std::endl;
return 1;
}
<|endoftext|> |
<commit_before>#ifndef HMLIB_RANDOM_XORSHIFT
#define HMLIB_RANDOM_XORSHIFT 100
#
#include<limits>
namespace hmLib{
/*!
@brief Random engine class using algorithm XOrShift.
This random value generating algorithm is faster than mt, and generating better random sequences than linear congruential engines.
@tparam result_type_ Terget type for generating random values
@tparam xval 1st default engine parameter
@tparam yval 2nd default engine parameter
@tparam zval 3rd default engine parameter
@tparam default_seedval default seed value*/
template<typename result_type_, result_type_ xval, result_type_ yval, result_type_ zval, result_type_ default_seedval>
class xorshift_engine{
public:
using result_type = result_type_;
public:
//!@brief Return min value generated by this engine
static constexpr result_type min(){ return std::numeric_limits<result_type>::min(); }
//!@brief Return max value generated by this engine
static constexpr result_type max(){ return std::numeric_limits<result_type>::max(); }
public:
//!@brief Constructor with set seed value by default_seedval.
xorshift_engine()
: x(xval)
, y(yval)
, z(zval)
, w(default_seedval){
}
/*!
@brief Constructor with set seed value by given value.
@param[in] s seed value*/
xorshift_engine(result_type s)
: x(xval)
, y(yval)
, z(zval)
, w(s){
}
//!@brief Copy contstructor.
xorshift_engine(const xorshift_engine& e) = default;
//!@brief Move contstructor.
xorshift_engine(xorshift_engine&& e) = default;
/*!
@brief Generate random value.
@return Generated random value.*/
result_type operator()(){
result_type t = x ^ (x << 11);
x = y;
y = z;
z = w;
return w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
}
/*!
@brief Set seed value of the engine.
@param[in] s seed value*/
void seed(result_type s = default_seedval){w = s;}
void discard(unsigned long long z){
if(z==0)return;
while(z-->0){
operator()();
}
}
private:
result_type x;
result_type y;
result_type z;
result_type w;
};
//!@brief Pre-set default xorshift engine for unsigned int.
using xorshift128 = xorshift_engine<unsigned int, 123456789u, 362436069u, 521288629u, 1u>;
}
#
#endif
<commit_msg>xorshift is now able to use seed seq.<commit_after>#ifndef HMLIB_RANDOM_XORSHIFT
#define HMLIB_RANDOM_XORSHIFT 100
#
#include<limits>
#include<vector>
#include<iterator>
namespace hmLib{
/*!
@brief Random engine class using algorithm XOrShift.
This random value generating algorithm is faster than mt, and generating better random sequences than linear congruential engines.
@tparam result_type_ Terget type for generating random values
@tparam xval 1st default engine parameter
@tparam yval 2nd default engine parameter
@tparam zval 3rd default engine parameter
@tparam default_seedval default seed value*/
template<typename result_type_, result_type_ xval, result_type_ yval, result_type_ zval, result_type_ default_seedval>
class xorshift_engine{
public:
using result_type = result_type_;
public:
//!@brief Return min value generated by this engine
static constexpr result_type min(){ return std::numeric_limits<result_type>::min(); }
//!@brief Return max value generated by this engine
static constexpr result_type max(){ return std::numeric_limits<result_type>::max(); }
public:
//!@brief Constructor with set seed value by default_seedval.
xorshift_engine()
: x(xval)
, y(yval)
, z(zval)
, w(default_seedval){}
/*!
@brief Constructor with set seed value by given value.
@param[in] s seed value*/
xorshift_engine(result_type s)
: x(xval)
, y(yval)
, z(zval)
, w(s){}
template<class Sseq>
xorshift_engine(Sseq&& q)
: x(xval)
, y(yval)
, z(zval)
, w(0){
seed(q);
}
//!@brief Copy contstructor.
xorshift_engine(const xorshift_engine& e) = default;
//!@brief Move contstructor.
xorshift_engine(xorshift_engine&& e) = default;
/*!
@brief Generate random value.
@return Generated random value.*/
result_type operator()(){
result_type t = x ^ (x << 11);
x = y;
y = z;
z = w;
return w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
}
/*!
@brief Set seed value of the engine.
@param[in] s seed value*/
void seed(result_type s = default_seedval){ w = s; }
template<class Sseq>
void seed(Sseq&& q){
// シード列を取得
std::vector<result_type> result;
q.param(std::back_inserter(result));
w = result.front();
}
void discard(unsigned long long z){
if(z == 0)return;
while(z-->0){
operator()();
}
}
private:
result_type x;
result_type y;
result_type z;
result_type w;
};
//!@brief Pre-set default xorshift engine for unsigned int.
using xorshift128 = xorshift_engine<unsigned int, 123456789u, 362436069u, 521288629u, 1u>;
}
#
#endif
<|endoftext|> |
<commit_before>/*
* C S O U N D
*
* L I C E N S E
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "MusicModel.hpp"
#include "Exception.hpp"
#include "Composition.hpp"
#include "System.hpp"
namespace csound
{
MusicModel::MusicModel() :
cppSound(&cppSound_),
go(false)
{
}
MusicModel::~MusicModel()
{
//clear();
}
void MusicModel::initialize()
{
}
void MusicModel::generate()
{
cppSound->removeScore();
if (children.size()) {
score.clear();
}
traverse(getLocalCoordinates(), score);
System::message("Generated %d events.\n", score.size());
}
void MusicModel::render()
{
generate();
perform();
}
void MusicModel::createCsoundScore(std::string addToScore, double extendSeconds)
{
System::inform("addToScore.length(): %d\n", addToScore.length());
if (addToScore.length() > 2) {
cppSound->removeScore();
cppSound->addScoreLine(addToScore);
}
cppSound->addScoreLine(score.getCsoundScore(tonesPerOctave, conformPitches));
char buffer[0x100];
std::sprintf(buffer, "\ns %9.3f", extendSeconds);
cppSound->addScoreLine(buffer);
std::sprintf(buffer, "\ne %9.3f", extendSeconds);
cppSound->addScoreLine(buffer);
cppSound->exportForPerformance();
}
void MusicModel::perform()
{
go = true;
cppSound->setCommand(getCsoundCommand());
createCsoundScore(csoundScoreHeader);
cppSound->perform();
// The Csound command is managed from MusicModel,
// not from CppSound. So we clear out what we set.
cppSound->setCommand("");
}
void MusicModel::clear()
{
Node::clear();
Composition::clear();
cppSound->removeScore();
}
void MusicModel::setCppSound(CppSound *cppSound)
{
if(!cppSound)
{
this->cppSound = &cppSound_;
}
else
{
this->cppSound = cppSound;
}
}
CppSound *MusicModel::getCppSound()
{
return cppSound;
}
void MusicModel::setCsoundOrchestra(std::string orchestra)
{
cppSound->setOrchestra(orchestra);
}
std::string MusicModel::getCsoundOrchestra() const
{
return cppSound->getOrchestra();
}
void MusicModel::setCsoundScoreHeader(std::string header)
{
csoundScoreHeader = header;
}
std::string MusicModel::getCsoundScoreHeader() const
{
return csoundScoreHeader;
}
void MusicModel::arrange(int oldInstrumentNumber, int newInstrumentNumber)
{
score.arrange(oldInstrumentNumber, newInstrumentNumber);
}
void MusicModel::arrange(int oldInstrumentNumber,
int newInstrumentNumber,
double gain)
{
score.arrange(oldInstrumentNumber, newInstrumentNumber, gain);
}
void MusicModel::arrange(int oldInstrumentNumber,
int newInstrumentNumber,
double gain,
double pan)
{
score.arrange(oldInstrumentNumber, newInstrumentNumber, gain, pan);
}
void MusicModel::arrange(int silenceInstrumentNumber, std::string csoundInstrumentName)
{
int csoundInstrumentNumber = cppSound->getInstrumentNumber(csoundInstrumentName);
arrange(silenceInstrumentNumber, csoundInstrumentNumber);
}
void MusicModel::arrange(int silenceInstrumentNumber, std::string csoundInstrumentName, double gain)
{
int csoundInstrumentNumber = cppSound->getInstrumentNumber(csoundInstrumentName);
arrange(silenceInstrumentNumber, csoundInstrumentNumber, gain);
}
void MusicModel::arrange(int silenceInstrumentNumber, std::string csoundInstrumentName, double gain, double pan)
{
int csoundInstrumentNumber = cppSound->getInstrumentNumber(csoundInstrumentName);
arrange(silenceInstrumentNumber, csoundInstrumentNumber, gain, pan);
}
void MusicModel::removeArrangement()
{
score.removeArrangement();
}
void MusicModel::setCsoundCommand(std::string command)
{
cppSound->setCommand(command);
}
std::string MusicModel::getCsoundCommand() const
{
std::string command_ = cppSound->getCommand();
if (command_.size() == 0)
{
char buffer[0x200];
std::sprintf(buffer,
"csound --midi-key=4 --midi-velocity=5 -m99 -RWdfo %s temp.orc temp.sco",
getOutputSoundfileName().c_str());
command_ = buffer;
}
return command_;
}
long MusicModel::getThis()
{
return (long) this;
}
Node *MusicModel::getThisNode()
{
return (Node *)this;
}
void MusicModel::processArgs(const std::vector<std::string> &args)
{
std::map<std::string, std::string> argsmap;
for (size_t i = 0, n = args.size(); i < n; )
{
if (args[i].find("--") == 0)
{
const std::string key = args[i];
++i;
if (args[i].find("--") == std::string::npos)
{
std::string value = args[i];
++i;
argsmap[key] = value;
}
else
{
argsmap[key] = "";
}
}
}
char command[0x200];
go = true;
bool postPossible = false;
if ((argsmap.find("--midi") != argsmap.end()) && go)
{
generate();
cppSound->save(getMidiFilename().c_str());
}
if ((argsmap.find("--csound") != argsmap.end()) && go)
{
postPossible = true;
render();
}
if ((argsmap.find("--pianoteq") != argsmap.end()) && go)
{
std::sprintf(command, "Pianoteq --midi %s", getMidiFilename().c_str());
int result = std::system(command);
}
if ((argsmap.find("--pianoteq-wav") != argsmap.end()) && go)
{
postPossible = true;
std::sprintf(command, "Pianoteq --headless --midi %s --rate 48000 --wav %s", getMidiFilename().c_str(), getOutputSoundfileName().c_str());
int result = std::system(command);
}
if ((argsmap.find("--playmidi") != argsmap.end()) && go)
{
std::sprintf(command, "%s %s", argsmap["--playmidi"].c_str(), getMidiFilename().c_str());
int result = std::system(command);
}
if ((argsmap.find("--playwav") != argsmap.end()) && go)
{
std::sprintf(command, "%s %s", argsmap["--playwav"].c_str(), getOutputSoundfileName().c_str());
int result = std::system(command);
}
if ((argsmap.find("--post") != argsmap.end()) && go && postPossible)
{
translateMaster();
}
}
void MusicModel::stop()
{
std::cout << "MusicModel::stop()..." << std::endl;
go = false;
cppSound->stop();
}
}
<commit_msg>Omit colors from MusicModel's Csound messages.<commit_after>/*
* C S O U N D
*
* L I C E N S E
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "MusicModel.hpp"
#include "Exception.hpp"
#include "Composition.hpp"
#include "System.hpp"
namespace csound
{
MusicModel::MusicModel() :
cppSound(&cppSound_),
go(false)
{
}
MusicModel::~MusicModel()
{
//clear();
}
void MusicModel::initialize()
{
}
void MusicModel::generate()
{
cppSound->removeScore();
if (children.size()) {
score.clear();
}
traverse(getLocalCoordinates(), score);
System::message("Generated %d events.\n", score.size());
}
void MusicModel::render()
{
generate();
perform();
}
void MusicModel::createCsoundScore(std::string addToScore, double extendSeconds)
{
System::inform("addToScore.length(): %d\n", addToScore.length());
if (addToScore.length() > 2) {
cppSound->removeScore();
cppSound->addScoreLine(addToScore);
}
cppSound->addScoreLine(score.getCsoundScore(tonesPerOctave, conformPitches));
char buffer[0x100];
std::sprintf(buffer, "\ns %9.3f", extendSeconds);
cppSound->addScoreLine(buffer);
std::sprintf(buffer, "\ne %9.3f", extendSeconds);
cppSound->addScoreLine(buffer);
cppSound->exportForPerformance();
}
void MusicModel::perform()
{
go = true;
cppSound->setCommand(getCsoundCommand());
createCsoundScore(csoundScoreHeader);
cppSound->perform();
// The Csound command is managed from MusicModel,
// not from CppSound. So we clear out what we set.
cppSound->setCommand("");
}
void MusicModel::clear()
{
Node::clear();
Composition::clear();
cppSound->removeScore();
}
void MusicModel::setCppSound(CppSound *cppSound)
{
if(!cppSound)
{
this->cppSound = &cppSound_;
}
else
{
this->cppSound = cppSound;
}
}
CppSound *MusicModel::getCppSound()
{
return cppSound;
}
void MusicModel::setCsoundOrchestra(std::string orchestra)
{
cppSound->setOrchestra(orchestra);
}
std::string MusicModel::getCsoundOrchestra() const
{
return cppSound->getOrchestra();
}
void MusicModel::setCsoundScoreHeader(std::string header)
{
csoundScoreHeader = header;
}
std::string MusicModel::getCsoundScoreHeader() const
{
return csoundScoreHeader;
}
void MusicModel::arrange(int oldInstrumentNumber, int newInstrumentNumber)
{
score.arrange(oldInstrumentNumber, newInstrumentNumber);
}
void MusicModel::arrange(int oldInstrumentNumber,
int newInstrumentNumber,
double gain)
{
score.arrange(oldInstrumentNumber, newInstrumentNumber, gain);
}
void MusicModel::arrange(int oldInstrumentNumber,
int newInstrumentNumber,
double gain,
double pan)
{
score.arrange(oldInstrumentNumber, newInstrumentNumber, gain, pan);
}
void MusicModel::arrange(int silenceInstrumentNumber, std::string csoundInstrumentName)
{
int csoundInstrumentNumber = cppSound->getInstrumentNumber(csoundInstrumentName);
arrange(silenceInstrumentNumber, csoundInstrumentNumber);
}
void MusicModel::arrange(int silenceInstrumentNumber, std::string csoundInstrumentName, double gain)
{
int csoundInstrumentNumber = cppSound->getInstrumentNumber(csoundInstrumentName);
arrange(silenceInstrumentNumber, csoundInstrumentNumber, gain);
}
void MusicModel::arrange(int silenceInstrumentNumber, std::string csoundInstrumentName, double gain, double pan)
{
int csoundInstrumentNumber = cppSound->getInstrumentNumber(csoundInstrumentName);
arrange(silenceInstrumentNumber, csoundInstrumentNumber, gain, pan);
}
void MusicModel::removeArrangement()
{
score.removeArrangement();
}
void MusicModel::setCsoundCommand(std::string command)
{
cppSound->setCommand(command);
}
std::string MusicModel::getCsoundCommand() const
{
std::string command_ = cppSound->getCommand();
if (command_.size() == 0)
{
char buffer[0x200];
std::sprintf(buffer,
"csound --midi-key=4 --midi-velocity=5 -m167 -RWdfo %s temp.orc temp.sco",
getOutputSoundfileName().c_str());
command_ = buffer;
}
return command_;
}
long MusicModel::getThis()
{
return (long) this;
}
Node *MusicModel::getThisNode()
{
return (Node *)this;
}
void MusicModel::processArgs(const std::vector<std::string> &args)
{
std::map<std::string, std::string> argsmap;
for (size_t i = 0, n = args.size(); i < n; )
{
if (args[i].find("--") == 0)
{
const std::string key = args[i];
++i;
if (args[i].find("--") == std::string::npos)
{
std::string value = args[i];
++i;
argsmap[key] = value;
}
else
{
argsmap[key] = "";
}
}
}
char command[0x200];
go = true;
bool postPossible = false;
if ((argsmap.find("--midi") != argsmap.end()) && go)
{
generate();
cppSound->save(getMidiFilename().c_str());
}
if ((argsmap.find("--csound") != argsmap.end()) && go)
{
postPossible = true;
render();
}
if ((argsmap.find("--pianoteq") != argsmap.end()) && go)
{
std::sprintf(command, "Pianoteq --midi %s", getMidiFilename().c_str());
int result = std::system(command);
}
if ((argsmap.find("--pianoteq-wav") != argsmap.end()) && go)
{
postPossible = true;
std::sprintf(command, "Pianoteq --headless --midi %s --rate 48000 --wav %s", getMidiFilename().c_str(), getOutputSoundfileName().c_str());
int result = std::system(command);
}
if ((argsmap.find("--playmidi") != argsmap.end()) && go)
{
std::sprintf(command, "%s %s", argsmap["--playmidi"].c_str(), getMidiFilename().c_str());
int result = std::system(command);
}
if ((argsmap.find("--playwav") != argsmap.end()) && go)
{
std::sprintf(command, "%s %s", argsmap["--playwav"].c_str(), getOutputSoundfileName().c_str());
int result = std::system(command);
}
if ((argsmap.find("--post") != argsmap.end()) && go && postPossible)
{
translateMaster();
}
}
void MusicModel::stop()
{
std::cout << "MusicModel::stop()..." << std::endl;
go = false;
cppSound->stop();
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 "Library/OSRM.h"
#include "Server/ServerFactory.h"
#include "Util/GitDescription.h"
#include "Util/InputFileUtil.h"
#include "Util/ProgramOptions.h"
#include "Util/SimpleLogger.h"
#include "Util/UUID.h"
#ifdef __linux__
#include <sys/mman.h>
#endif
#include <signal.h>
#include <boost/bind.hpp>
// #include <boost/date_time.hpp>
#include <boost/thread.hpp>
#include <iostream>
#ifdef _WIN32
boost::function0<void> console_ctrl_function;
BOOL WINAPI console_ctrl_handler(DWORD ctrl_type)
{
switch (ctrl_type)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_SHUTDOWN_EVENT:
console_ctrl_function();
return TRUE;
default:
return FALSE;
}
}
#endif
int main (int argc, const char * argv[])
{
try
{
LogPolicy::GetInstance().Unmute();
bool use_shared_memory = false, trial = false;
std::string ip_address;
int ip_port, requested_thread_num;
ServerPaths server_paths;
const unsigned init_result = GenerateServerProgramOptions(argc,
argv,
server_paths,
ip_address,
ip_port,
requested_thread_num,
use_shared_memory,
trial);
if (init_result == INIT_OK_DO_NOT_START_ENGINE)
{
return 0;
}
if (init_result == INIT_FAILED)
{
return 1;
}
#ifdef __linux__
const int lock_flags = MCL_CURRENT | MCL_FUTURE;
if (-1 == mlockall(lock_flags))
{
SimpleLogger().Write(logWARNING) << argv[0] << " could not be locked to RAM";
}
#endif
SimpleLogger().Write() <<
"starting up engines, " << g_GIT_DESCRIPTION << ", " <<
"compiled at " << __DATE__ << ", " __TIME__;
if(use_shared_memory)
{
SimpleLogger().Write(logDEBUG) << "Loading from shared memory";
}
else
{
SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"];
SimpleLogger().Write(logDEBUG) << "Nodes file:\t" << server_paths["nodesdata"];
SimpleLogger().Write(logDEBUG) << "Edges file:\t" << server_paths["edgesdata"];
SimpleLogger().Write(logDEBUG) << "Geometry file:\t" << server_paths["geometries"];
SimpleLogger().Write(logDEBUG) << "RAM file:\t" << server_paths["ramindex"];
SimpleLogger().Write(logDEBUG) << "Index file:\t" << server_paths["fileindex"];
SimpleLogger().Write(logDEBUG) << "Names file:\t" << server_paths["namesdata"];
SimpleLogger().Write(logDEBUG) << "Timestamp file:\t" << server_paths["timestamp"];
SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num;
SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address;
SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port;
}
#ifndef _WIN32
int sig = 0;
sigset_t new_mask;
sigset_t old_mask;
sigfillset(&new_mask);
pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
#endif
OSRM osrm_lib(server_paths, use_shared_memory);
Server * routing_server = ServerFactory::CreateServer(
ip_address,
ip_port,
requested_thread_num
);
routing_server->GetRequestHandlerPtr().RegisterRoutingMachine(&osrm_lib);
if( trial )
{
SimpleLogger().Write() << "trial run, quitting after successful initialization";
}
else
{
boost::thread server_thread(boost::bind(&Server::Run, routing_server));
#ifndef _WIN32
sigset_t wait_mask;
pthread_sigmask(SIG_SETMASK, &old_mask, 0);
sigemptyset(&wait_mask);
sigaddset(&wait_mask, SIGINT);
sigaddset(&wait_mask, SIGQUIT);
sigaddset(&wait_mask, SIGTERM);
pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
SimpleLogger().Write() << "running and waiting for requests";
sigwait(&wait_mask, &sig);
#else
// Set console control handler to allow server to be stopped.
console_ctrl_function = boost::bind(&Server::Stop, routing_server);
SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
SimpleLogger().Write() << "running and waiting for requests";
routing_server->Run();
#endif
SimpleLogger().Write() << "initiating shutdown";
routing_server->Stop();
SimpleLogger().Write() << "stopping threads";
if (!server_thread.timed_join(boost::posix_time::seconds(2)))
{
SimpleLogger().Write(logDEBUG) << "Threads did not finish within 2 seconds. Hard abort!";
}
}
SimpleLogger().Write() << "freeing objects";
delete routing_server;
SimpleLogger().Write() << "shutdown completed";
}
catch (const std::exception& e)
{
SimpleLogger().Write(logWARNING) << "exception: " << e.what();
return 1;
}
#ifdef __linux__
munlockall();
#endif
return 0;
}
<commit_msg>shorten line<commit_after>/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 "Library/OSRM.h"
#include "Server/ServerFactory.h"
#include "Util/GitDescription.h"
#include "Util/InputFileUtil.h"
#include "Util/ProgramOptions.h"
#include "Util/SimpleLogger.h"
#include "Util/UUID.h"
#ifdef __linux__
#include <sys/mman.h>
#endif
#include <signal.h>
#include <boost/bind.hpp>
// #include <boost/date_time.hpp>
#include <boost/thread.hpp>
#include <iostream>
#ifdef _WIN32
boost::function0<void> console_ctrl_function;
BOOL WINAPI console_ctrl_handler(DWORD ctrl_type)
{
switch (ctrl_type)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_SHUTDOWN_EVENT:
console_ctrl_function();
return TRUE;
default:
return FALSE;
}
}
#endif
int main (int argc, const char * argv[])
{
try
{
LogPolicy::GetInstance().Unmute();
bool use_shared_memory = false, trial = false;
std::string ip_address;
int ip_port, requested_thread_num;
ServerPaths server_paths;
const unsigned init_result = GenerateServerProgramOptions(argc,
argv,
server_paths,
ip_address,
ip_port,
requested_thread_num,
use_shared_memory,
trial);
if (init_result == INIT_OK_DO_NOT_START_ENGINE)
{
return 0;
}
if (init_result == INIT_FAILED)
{
return 1;
}
#ifdef __linux__
const int lock_flags = MCL_CURRENT | MCL_FUTURE;
if (-1 == mlockall(lock_flags))
{
SimpleLogger().Write(logWARNING) << argv[0] << " could not be locked to RAM";
}
#endif
SimpleLogger().Write() <<
"starting up engines, " << g_GIT_DESCRIPTION << ", " <<
"compiled at " << __DATE__ << ", " __TIME__;
if(use_shared_memory)
{
SimpleLogger().Write(logDEBUG) << "Loading from shared memory";
}
else
{
SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"];
SimpleLogger().Write(logDEBUG) << "Nodes file:\t" << server_paths["nodesdata"];
SimpleLogger().Write(logDEBUG) << "Edges file:\t" << server_paths["edgesdata"];
SimpleLogger().Write(logDEBUG) << "Geometry file:\t" << server_paths["geometries"];
SimpleLogger().Write(logDEBUG) << "RAM file:\t" << server_paths["ramindex"];
SimpleLogger().Write(logDEBUG) << "Index file:\t" << server_paths["fileindex"];
SimpleLogger().Write(logDEBUG) << "Names file:\t" << server_paths["namesdata"];
SimpleLogger().Write(logDEBUG) << "Timestamp file:\t" << server_paths["timestamp"];
SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num;
SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address;
SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port;
}
#ifndef _WIN32
int sig = 0;
sigset_t new_mask;
sigset_t old_mask;
sigfillset(&new_mask);
pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
#endif
OSRM osrm_lib(server_paths, use_shared_memory);
Server * routing_server = ServerFactory::CreateServer(
ip_address,
ip_port,
requested_thread_num
);
routing_server->GetRequestHandlerPtr().RegisterRoutingMachine(&osrm_lib);
if( trial )
{
SimpleLogger().Write() << "trial run, quitting after successful initialization";
}
else
{
boost::thread server_thread(boost::bind(&Server::Run, routing_server));
#ifndef _WIN32
sigset_t wait_mask;
pthread_sigmask(SIG_SETMASK, &old_mask, 0);
sigemptyset(&wait_mask);
sigaddset(&wait_mask, SIGINT);
sigaddset(&wait_mask, SIGQUIT);
sigaddset(&wait_mask, SIGTERM);
pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
SimpleLogger().Write() << "running and waiting for requests";
sigwait(&wait_mask, &sig);
#else
// Set console control handler to allow server to be stopped.
console_ctrl_function = boost::bind(&Server::Stop, routing_server);
SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
SimpleLogger().Write() << "running and waiting for requests";
routing_server->Run();
#endif
SimpleLogger().Write() << "initiating shutdown";
routing_server->Stop();
SimpleLogger().Write() << "stopping threads";
if (!server_thread.timed_join(boost::posix_time::seconds(2)))
{
SimpleLogger().Write(logWARNING) << "Didn't exit within 2 seconds. Hard abort!";
}
}
SimpleLogger().Write() << "freeing objects";
delete routing_server;
SimpleLogger().Write() << "shutdown completed";
}
catch (const std::exception& e)
{
SimpleLogger().Write(logWARNING) << "exception: " << e.what();
return 1;
}
#ifdef __linux__
munlockall();
#endif
return 0;
}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "Camera.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../graphics/Filterfliprgb.h"
#if defined(AVG_ENABLE_1394_2)
#include "../imaging/FWCamera.h"
#endif
#ifdef AVG_ENABLE_V4L2
#include "../imaging/V4LCamera.h"
#endif
#ifdef AVG_ENABLE_CMU1394
#include "../imaging/CMUCamera.h"
#endif
#ifdef AVG_ENABLE_DSHOW
#include "../imaging/DSCamera.h"
#endif
#include "../imaging/FakeCamera.h"
#include <cstdlib>
#ifdef WIN32
#define strtoll(p, e, b) _strtoi64(p, e, b)
#endif
namespace avg {
using namespace std;
Camera::Camera(PixelFormat camPF, PixelFormat destPF)
: m_CamPF(camPF),
m_DestPF(destPF)
{
// cerr << "Camera: " << Bitmap::getPixelFormatString(camPF) << "-->"
// << Bitmap::getPixelFormatString(destPF) << endl;
}
PixelFormat Camera::getCamPF() const
{
return m_CamPF;
}
void Camera::setCamPF(PixelFormat pf)
{
m_CamPF = pf;
}
PixelFormat Camera::getDestPF() const
{
return m_DestPF;
}
static ProfilingZone CameraConvertProfilingZone("Camera format conversion");
BitmapPtr Camera::convertCamFrameToDestPF(BitmapPtr pCamBmp)
{
ScopeTimer Timer(CameraConvertProfilingZone);
BitmapPtr pDestBmp = BitmapPtr(new Bitmap(pCamBmp->getSize(), m_DestPF));
pDestBmp->copyPixels(*pCamBmp);
if (m_CamPF == R8G8B8 && m_DestPF == B8G8R8X8) {
pDestBmp->setPixelFormat(R8G8B8X8);
FilterFlipRGB().applyInPlace(pDestBmp);
}
return pDestBmp;
}
PixelFormat Camera::fwBayerStringToPF(unsigned long reg)
{
string sBayerFormat((char*)®, 4);
if (sBayerFormat == "RGGB") {
return BAYER8_RGGB;
} else if (sBayerFormat == "GBRG") {
return BAYER8_GBRG;
} else if (sBayerFormat == "GRBG") {
return BAYER8_GRBG;
} else if (sBayerFormat == "BGGR") {
return BAYER8_BGGR;
} else if (sBayerFormat == "YYYY") {
return I8;
} else {
assert(false);
return I8;
}
}
/*
void Camera::fatalError(const string & sMsg)
{
throw Exception(AVG_ERR_CAMERA, sMsg);
}
*/
string cameraFeatureToString(CameraFeature Feature)
{
switch(Feature) {
case CAM_FEATURE_BRIGHTNESS:
return "brightness";
case CAM_FEATURE_EXPOSURE:
return "exposure";
case CAM_FEATURE_SHARPNESS:
return "sharpness";
case CAM_FEATURE_WHITE_BALANCE:
return "white balance";
case CAM_FEATURE_HUE:
return "hue";
case CAM_FEATURE_SATURATION:
return "saturation";
case CAM_FEATURE_GAMMA:
return "gamma";
case CAM_FEATURE_SHUTTER:
return "shutter";
case CAM_FEATURE_GAIN:
return "gain";
case CAM_FEATURE_IRIS:
return "iris";
case CAM_FEATURE_FOCUS:
return "focus";
case CAM_FEATURE_TEMPERATURE:
return "temperature";
case CAM_FEATURE_TRIGGER:
return "trigger";
case CAM_FEATURE_ZOOM:
return "zoom";
case CAM_FEATURE_PAN:
return "pan";
case CAM_FEATURE_TILT:
return "tilt";
case CAM_FEATURE_OPTICAL_FILTER:
return "optical filter";
case CAM_FEATURE_CAPTURE_SIZE:
return "capture size";
case CAM_FEATURE_CAPTURE_QUALITY:
return "capture quality";
case CAM_FEATURE_CONTRAST:
return "contrast";
case CAM_FEATURE_STROBE_DURATION:
return "strobe duration";
default:
return "unknown";
}
}
CameraPtr createCamera(const string& sDriver, const string& sDevice, int unit,
bool bFW800, const IntPoint& captureSize, PixelFormat camPF, PixelFormat destPF,
double frameRate)
{
CameraPtr pCamera;
try {
if (sDriver == "firewire") {
char * pszErr;
long long guid = strtoll(sDevice.c_str(), &pszErr, 10);
if (strlen(pszErr)) {
throw Exception(AVG_ERR_INVALID_ARGS, "'"+sDevice
+"' is not a valid GUID.");
}
#if defined(AVG_ENABLE_1394_2)
pCamera = CameraPtr(new FWCamera(guid, unit, bFW800, captureSize, camPF,
destPF, frameRate));
#elif defined(AVG_ENABLE_CMU1394)
if (unit != -1) {
throw Exception(AVG_ERR_INVALID_ARGS,
"camera 'unit' attribute is not supported when using the cmu firewire driver.");
}
pCamera = CameraPtr(new CMUCamera(guid, bFW800, captureSize, camPF, destPF,
frameRate));
#else
AVG_TRACE(Logger::WARNING, "Firewire camera specified, but firewire "
"support not compiled in.");
#endif
} else if (sDriver == "video4linux") {
#if defined(AVG_ENABLE_V4L2)
pCamera = CameraPtr(new V4LCamera(sDevice, unit, captureSize, camPF,
destPF));
#else
AVG_TRACE(Logger::WARNING, "Video4Linux camera specified, but "
"Video4Linux support not compiled in.");
#endif
} else if (sDriver == "directshow") {
#if defined(AVG_ENABLE_DSHOW)
if (unit != -1) {
throw Exception(AVG_ERR_INVALID_ARGS,
"camera 'unit' attribute is not supported when using the directshow driver.");
}
pCamera = CameraPtr(new DSCamera(sDevice, captureSize, camPF, destPF,
frameRate));
#else
AVG_TRACE(Logger::WARNING, "DirectShow camera specified, but "
"DirectShow is only available under windows.");
#endif
} else {
throw Exception(AVG_ERR_INVALID_ARGS,
"Unable to set up camera. Camera source '"+sDriver+"' unknown.");
}
} catch (const Exception &e) {
if (e.GetCode() == AVG_ERR_CAMERA_NONFATAL) {
AVG_TRACE(Logger::WARNING, e.GetStr());
} else {
throw;
}
}
if (!pCamera){
pCamera = CameraPtr(new FakeCamera(camPF, destPF));
}
return pCamera;
}
void dumpCameras()
{
#ifdef AVG_ENABLE_1394_2
FWCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_CMU1394
CMUCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_V4L2
V4LCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_DSHOW
DSCamera::dumpCameras();
#endif
}
}
<commit_msg>Fixed compile when no libdc1394 is installed.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "Camera.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../graphics/Filterfliprgb.h"
#if defined(AVG_ENABLE_1394_2)
#include "../imaging/FWCamera.h"
#endif
#ifdef AVG_ENABLE_V4L2
#include "../imaging/V4LCamera.h"
#endif
#ifdef AVG_ENABLE_CMU1394
#include "../imaging/CMUCamera.h"
#endif
#ifdef AVG_ENABLE_DSHOW
#include "../imaging/DSCamera.h"
#endif
#include "../imaging/FakeCamera.h"
#include <cstdlib>
#include <string.h>
#ifdef WIN32
#define strtoll(p, e, b) _strtoi64(p, e, b)
#endif
namespace avg {
using namespace std;
Camera::Camera(PixelFormat camPF, PixelFormat destPF)
: m_CamPF(camPF),
m_DestPF(destPF)
{
// cerr << "Camera: " << Bitmap::getPixelFormatString(camPF) << "-->"
// << Bitmap::getPixelFormatString(destPF) << endl;
}
PixelFormat Camera::getCamPF() const
{
return m_CamPF;
}
void Camera::setCamPF(PixelFormat pf)
{
m_CamPF = pf;
}
PixelFormat Camera::getDestPF() const
{
return m_DestPF;
}
static ProfilingZone CameraConvertProfilingZone("Camera format conversion");
BitmapPtr Camera::convertCamFrameToDestPF(BitmapPtr pCamBmp)
{
ScopeTimer Timer(CameraConvertProfilingZone);
BitmapPtr pDestBmp = BitmapPtr(new Bitmap(pCamBmp->getSize(), m_DestPF));
pDestBmp->copyPixels(*pCamBmp);
if (m_CamPF == R8G8B8 && m_DestPF == B8G8R8X8) {
pDestBmp->setPixelFormat(R8G8B8X8);
FilterFlipRGB().applyInPlace(pDestBmp);
}
return pDestBmp;
}
PixelFormat Camera::fwBayerStringToPF(unsigned long reg)
{
string sBayerFormat((char*)®, 4);
if (sBayerFormat == "RGGB") {
return BAYER8_RGGB;
} else if (sBayerFormat == "GBRG") {
return BAYER8_GBRG;
} else if (sBayerFormat == "GRBG") {
return BAYER8_GRBG;
} else if (sBayerFormat == "BGGR") {
return BAYER8_BGGR;
} else if (sBayerFormat == "YYYY") {
return I8;
} else {
assert(false);
return I8;
}
}
/*
void Camera::fatalError(const string & sMsg)
{
throw Exception(AVG_ERR_CAMERA, sMsg);
}
*/
string cameraFeatureToString(CameraFeature Feature)
{
switch(Feature) {
case CAM_FEATURE_BRIGHTNESS:
return "brightness";
case CAM_FEATURE_EXPOSURE:
return "exposure";
case CAM_FEATURE_SHARPNESS:
return "sharpness";
case CAM_FEATURE_WHITE_BALANCE:
return "white balance";
case CAM_FEATURE_HUE:
return "hue";
case CAM_FEATURE_SATURATION:
return "saturation";
case CAM_FEATURE_GAMMA:
return "gamma";
case CAM_FEATURE_SHUTTER:
return "shutter";
case CAM_FEATURE_GAIN:
return "gain";
case CAM_FEATURE_IRIS:
return "iris";
case CAM_FEATURE_FOCUS:
return "focus";
case CAM_FEATURE_TEMPERATURE:
return "temperature";
case CAM_FEATURE_TRIGGER:
return "trigger";
case CAM_FEATURE_ZOOM:
return "zoom";
case CAM_FEATURE_PAN:
return "pan";
case CAM_FEATURE_TILT:
return "tilt";
case CAM_FEATURE_OPTICAL_FILTER:
return "optical filter";
case CAM_FEATURE_CAPTURE_SIZE:
return "capture size";
case CAM_FEATURE_CAPTURE_QUALITY:
return "capture quality";
case CAM_FEATURE_CONTRAST:
return "contrast";
case CAM_FEATURE_STROBE_DURATION:
return "strobe duration";
default:
return "unknown";
}
}
CameraPtr createCamera(const string& sDriver, const string& sDevice, int unit,
bool bFW800, const IntPoint& captureSize, PixelFormat camPF, PixelFormat destPF,
double frameRate)
{
CameraPtr pCamera;
try {
if (sDriver == "firewire") {
char * pszErr;
long long guid = strtoll(sDevice.c_str(), &pszErr, 10);
if (strlen(pszErr)) {
throw Exception(AVG_ERR_INVALID_ARGS, "'"+sDevice
+"' is not a valid GUID.");
}
#if defined(AVG_ENABLE_1394_2)
pCamera = CameraPtr(new FWCamera(guid, unit, bFW800, captureSize, camPF,
destPF, frameRate));
#elif defined(AVG_ENABLE_CMU1394)
if (unit != -1) {
throw Exception(AVG_ERR_INVALID_ARGS,
"camera 'unit' attribute is not supported when using the cmu firewire driver.");
}
pCamera = CameraPtr(new CMUCamera(guid, bFW800, captureSize, camPF, destPF,
frameRate));
#else
AVG_TRACE(Logger::WARNING, "Firewire camera specified, but firewire "
"support not compiled in.");
#endif
} else if (sDriver == "video4linux") {
#if defined(AVG_ENABLE_V4L2)
pCamera = CameraPtr(new V4LCamera(sDevice, unit, captureSize, camPF,
destPF));
#else
AVG_TRACE(Logger::WARNING, "Video4Linux camera specified, but "
"Video4Linux support not compiled in.");
#endif
} else if (sDriver == "directshow") {
#if defined(AVG_ENABLE_DSHOW)
if (unit != -1) {
throw Exception(AVG_ERR_INVALID_ARGS,
"camera 'unit' attribute is not supported when using the directshow driver.");
}
pCamera = CameraPtr(new DSCamera(sDevice, captureSize, camPF, destPF,
frameRate));
#else
AVG_TRACE(Logger::WARNING, "DirectShow camera specified, but "
"DirectShow is only available under windows.");
#endif
} else {
throw Exception(AVG_ERR_INVALID_ARGS,
"Unable to set up camera. Camera source '"+sDriver+"' unknown.");
}
} catch (const Exception &e) {
if (e.GetCode() == AVG_ERR_CAMERA_NONFATAL) {
AVG_TRACE(Logger::WARNING, e.GetStr());
} else {
throw;
}
}
if (!pCamera){
pCamera = CameraPtr(new FakeCamera(camPF, destPF));
}
return pCamera;
}
void dumpCameras()
{
#ifdef AVG_ENABLE_1394_2
FWCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_CMU1394
CMUCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_V4L2
V4LCamera::dumpCameras();
#endif
#ifdef AVG_ENABLE_DSHOW
DSCamera::dumpCameras();
#endif
}
}
<|endoftext|> |
<commit_before>#include "lcf/dbstring.h"
#include <unordered_map>
#include <memory>
#include <iostream>
namespace lcf {
constexpr DBString::size_type DBString::npos;
alignas(DBString::size_type) constexpr char DBString::_empty_str[sizeof(size_type)];
struct DBStringData {
using size_type = DBString::size_type;
size_type size;
const char* data() const {
return reinterpret_cast<const char*>(this + 1);
}
char* data() {
return reinterpret_cast<char*>(this + 1);
}
static size_type alloc_size(StringView str) {
return sizeof(DBStringData) + str.size() + 1;
}
static DBStringData* from_data(char* s) {
return reinterpret_cast<DBStringData*>(s) - 1;
}
};
static char* Alloc(StringView str) {
if (str.empty()) {
return DBString::empty_str();
}
auto* raw = ::operator new(DBStringData::alloc_size(str));
auto* db = new (raw) DBStringData();
db->size = str.size();
std::memcpy(db->data(), str.data(), db->size);
db->data()[db->size] = '\0';
return db->data();
}
static void Free(char* str) {
if (str == DBString::empty_str()) {
return;
}
auto* db = DBStringData::from_data(str);
db->~DBStringData();
::operator delete(db);
}
DBString::DBString(StringView s)
: _storage(Alloc(s))
{
}
DBString& DBString::operator=(const DBString& o) {
if (this != &o) {
// What is strings are the same, skip double lookup?
_reset();
_storage = Alloc(StringView(o));
}
return *this;
}
void DBString::_reset() noexcept {
assert(_storage != nullptr);
Free(_storage);
}
} // namespace lcf
<commit_msg>Remove some includes<commit_after>#include "lcf/dbstring.h"
#include <memory>
namespace lcf {
constexpr DBString::size_type DBString::npos;
alignas(DBString::size_type) constexpr char DBString::_empty_str[sizeof(size_type)];
struct DBStringData {
using size_type = DBString::size_type;
size_type size;
const char* data() const {
return reinterpret_cast<const char*>(this + 1);
}
char* data() {
return reinterpret_cast<char*>(this + 1);
}
static size_type alloc_size(StringView str) {
return sizeof(DBStringData) + str.size() + 1;
}
static DBStringData* from_data(char* s) {
return reinterpret_cast<DBStringData*>(s) - 1;
}
};
static char* Alloc(StringView str) {
if (str.empty()) {
return DBString::empty_str();
}
auto* raw = ::operator new(DBStringData::alloc_size(str));
auto* db = new (raw) DBStringData();
db->size = str.size();
std::memcpy(db->data(), str.data(), db->size);
db->data()[db->size] = '\0';
return db->data();
}
static void Free(char* str) {
if (str == DBString::empty_str()) {
return;
}
auto* db = DBStringData::from_data(str);
db->~DBStringData();
::operator delete(db);
}
DBString::DBString(StringView s)
: _storage(Alloc(s))
{
}
DBString& DBString::operator=(const DBString& o) {
if (this != &o) {
// What is strings are the same, skip double lookup?
_reset();
_storage = Alloc(StringView(o));
}
return *this;
}
void DBString::_reset() noexcept {
assert(_storage != nullptr);
Free(_storage);
}
} // namespace lcf
<|endoftext|> |
<commit_before>#include "ArchiveWriter.h"
#include "BigFix/DataRef.h"
#include "BigFix/DateTime.h"
#include "BigFix/Error.h"
#include "BigFix/Number.h"
#include "BigFix/Stream.h"
namespace BigFix
{
ArchiveWriter::ArchiveWriter( Stream& output ) : m_output( output )
{
}
void ArchiveWriter::Directory( const char* name,
Encoding nameEncoding,
const DateTime& mtime )
{
std::string nameWithSlash = name;
nameWithSlash += "/";
WriteHeader( nameWithSlash.c_str(), nameEncoding, mtime, 0 );
}
void ArchiveWriter::FileStart( const char* name,
Encoding nameEncoding,
const DateTime& mtime,
uint64_t length )
{
WriteHeader( name, nameEncoding, mtime, length );
}
void ArchiveWriter::FileWrite( DataRef data )
{
m_output.Write( data );
}
void ArchiveWriter::FileEnd()
{
}
void ArchiveWriter::End()
{
m_output.Write( DataRef( "_\0" ) );
m_output.End();
}
void ArchiveWriter::WriteHeader( const char* name,
Encoding nameEncoding,
const DateTime& mtime,
uint64_t length )
{
uint8_t buffer[8];
if ( nameEncoding == ENCODING_UTF8 )
m_output.Write( DataRef( "2" ) );
if ( length >= UINT32_MAX )
m_output.Write( DataRef( "1" ) );
else
m_output.Write( DataRef( "_" ) );
size_t nameLengthWithNull = strlen( name ) + 1;
if ( nameLengthWithNull >= 255 )
throw Error( "File or directory name is longer than 254 characters" );
WriteLittleEndian( nameLengthWithNull, buffer, 1 );
m_output.Write( DataRef( buffer, buffer + 1 ) );
m_output.Write(
DataRef( reinterpret_cast<const uint8_t*>( name ),
reinterpret_cast<const uint8_t*>( name ) + nameLengthWithNull ) );
std::string mtimeString = mtime.ToString();
WriteLittleEndian( mtimeString.size(), buffer, 1 );
m_output.Write( DataRef( buffer, buffer + 1 ) );
m_output.Write( DataRef( mtimeString ) );
if ( length >= UINT32_MAX )
{
WriteLittleEndian( length, buffer, 8 );
m_output.Write( DataRef( buffer, buffer + 8 ) );
}
else
{
WriteLittleEndian( length, buffer, 4 );
m_output.Write( DataRef( buffer, buffer + 4 ) );
}
}
}
<commit_msg>Fix linux build<commit_after>#include "ArchiveWriter.h"
#include "BigFix/DataRef.h"
#include "BigFix/DateTime.h"
#include "BigFix/Error.h"
#include "BigFix/Number.h"
#include "BigFix/Stream.h"
#include <string.h>
namespace BigFix
{
ArchiveWriter::ArchiveWriter( Stream& output ) : m_output( output )
{
}
void ArchiveWriter::Directory( const char* name,
Encoding nameEncoding,
const DateTime& mtime )
{
std::string nameWithSlash = name;
nameWithSlash += "/";
WriteHeader( nameWithSlash.c_str(), nameEncoding, mtime, 0 );
}
void ArchiveWriter::FileStart( const char* name,
Encoding nameEncoding,
const DateTime& mtime,
uint64_t length )
{
WriteHeader( name, nameEncoding, mtime, length );
}
void ArchiveWriter::FileWrite( DataRef data )
{
m_output.Write( data );
}
void ArchiveWriter::FileEnd()
{
}
void ArchiveWriter::End()
{
m_output.Write( DataRef( "_\0" ) );
m_output.End();
}
void ArchiveWriter::WriteHeader( const char* name,
Encoding nameEncoding,
const DateTime& mtime,
uint64_t length )
{
uint8_t buffer[8];
if ( nameEncoding == ENCODING_UTF8 )
m_output.Write( DataRef( "2" ) );
if ( length >= UINT32_MAX )
m_output.Write( DataRef( "1" ) );
else
m_output.Write( DataRef( "_" ) );
size_t nameLengthWithNull = strlen( name ) + 1;
if ( nameLengthWithNull >= 255 )
throw Error( "File or directory name is longer than 254 characters" );
WriteLittleEndian( nameLengthWithNull, buffer, 1 );
m_output.Write( DataRef( buffer, buffer + 1 ) );
m_output.Write(
DataRef( reinterpret_cast<const uint8_t*>( name ),
reinterpret_cast<const uint8_t*>( name ) + nameLengthWithNull ) );
std::string mtimeString = mtime.ToString();
WriteLittleEndian( mtimeString.size(), buffer, 1 );
m_output.Write( DataRef( buffer, buffer + 1 ) );
m_output.Write( DataRef( mtimeString ) );
if ( length >= UINT32_MAX )
{
WriteLittleEndian( length, buffer, 8 );
m_output.Write( DataRef( buffer, buffer + 8 ) );
}
else
{
WriteLittleEndian( length, buffer, 4 );
m_output.Write( DataRef( buffer, buffer + 4 ) );
}
}
}
<|endoftext|> |
<commit_before>/*
* Open Source Movement Analysis Library
* Copyright (C) 2016, Moveck Solution Inc., all rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name(s) of the copyright holders nor the names
* of its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "openma/body/utils.h"
#include "openma/body/landmarkstranslator.h"
#include "openma/body/point.h"
#include "openma/body/referenceframe.h"
#include "openma/body/inertialparameters.h"
#include "openma/body/segment.h"
#include "openma/body/skeletonhelper.h"
#include "openma/base/trial.h"
namespace ma
{
namespace body
{
/**
* Returns a collection of mapped time sequences based on the stored LandmarksTranslator in the given @a helper.
* The time sequences are extracted from the child node "TimeSequences" of the given @a trial.
* If no translator was set in the helper, try to use its default translator.
* If no translator was found, the keys used in the collection are directly the name of each time sequence.
* If a translator was found, only the registered landmarks will be extracted, their name converted and stored in the output collection.
*
* There is also extra outputs to determine the common sample rate and the common start time in all extracted landmarks.
* If all the landmarks have the same sample rate, and if the output @a rate is given, its value will be assigned to the found common sample rate (-1.0 otherwise).
* If all the landmarks have the same start time, and if the output @a start is given, its value will be assigned to the found common start time (-1.0 otherwise).
* If all the landmarks have the same sample rate and start time, and if the output @a ok is given, its value will be assigned to true (false otherwise).
*/
std::unordered_map<std::string,math::Map<math::Vector>> extract_landmark_positions(SkeletonHelper* helper, Trial* trial, double* rate, double* start, bool* ok) _OPENMA_NOEXCEPT
{
auto lt = helper->findChild<LandmarksTranslator*>({},{},false);
// No defined translator? Let's use the one embedded within the helper (if any)
if (lt == nullptr)
lt = helper->defaultLandmarksTranslator();
const auto& markers = trial->timeSequences()->findChildren<TimeSequence*>({},{{"type",TimeSequence::Marker},{"components",4}},false);
return extract_landmark_positions(lt,markers,rate,start,ok);
};
/**
* Returns a collection of mapped time sequences based on the given LandmarksTranslator @a lt.
* If no translator was given (i.e. null pointer), the keys used in the collection are directly the name of each time sequence.
*
* There is also extra outputs to determine the common sample rate and the common start time in all extracted landmarks.
* If all the landmarks have the same sample rate, and if the output @a rate is given, its value will be assigned to the found common sample rate (-1.0 otherwise).
* If all the landmarks have the same start time, and if the output @a start is given, its value will be assigned to the found common start time (-1.0 otherwise).
* If all the landmarks have the same sample rate and start time, and if the output @a ok is given, its value will be assigned to true (false otherwise).
*/
std::unordered_map<std::string,math::Map<math::Vector>> extract_landmark_positions(LandmarksTranslator* lt, const std::vector<TimeSequence*>& markers, double* rate, double* start, bool* ok) _OPENMA_NOEXCEPT
{
std::unordered_map<std::string,math::Map<math::Vector>> positions;
double sampleRate = -1.0, startTime = -1.0;
bool common = true;
std::vector<TimeSequence*> landmarks;
// No translator found? Create positions for all the markers found
if (lt == nullptr)
{
for (auto it = markers.cbegin() ; it != markers.cend() ; ++it)
{
positions.insert(std::make_pair((*it)->name(),math::to_position(*it)));
landmarks.push_back(*it);
}
}
// Convert only the markers found in the translator
else
{
for (auto it = markers.cbegin() ; it != markers.cend() ; ++it)
{
std::string name = lt->convertIfExists((*it)->name());
if (!name.empty())
{
positions.insert(std::make_pair(name,math::to_position(*it)));
landmarks.push_back(*it);
}
}
}
// Detect the common sampling information
auto it = landmarks.cbegin();
if (it != landmarks.cend())
{
sampleRate = (*it)->sampleRate();
startTime = (*it)->startTime();
++it;
}
for ( ; it != landmarks.cend() ; ++it)
{
if ((fabs(sampleRate - (*it)->sampleRate()) > std::numeric_limits<float>::epsilon())
|| (fabs(startTime - (*it)->startTime()) > std::numeric_limits<float>::epsilon()))
{
common = false;
sampleRate = -1.0;
startTime = -1.0;
break;
}
}
// Assign the sampling information (if the inout parameters are given)
if (rate != nullptr)
*rate = sampleRate;
if (start != nullptr)
*start = startTime;
if (ok != nullptr)
*ok = common;
return positions;
};
/**
* Returns the transformation of the relative ReferenceFrame @a relframe expressed in the Segment @a seg. The Pose associated with the Segment is given in @a segpose.
* @warning The ReferenceFrame node @a relframe must be a (non-)direct child of the Segment @a seg. Moreover, this function does not check if the input variables (@a relpoint, @a seg, @a pose) are null or not.
* @relates ReferenceFrame
* @ingroup openma_body
*/
math::Pose transform_relative_frame(const ReferenceFrame* relframe, const Segment* seg, const math::Pose& segpose) _OPENMA_NOEXCEPT
{
assert(seg->findChild<const ReferenceFrame*>(relframe->name()) == relframe);
auto path = seg->retrievePath(relframe);
// No path found?
if (path.empty())
return math::Pose();
// Compute the pose
const double res[1] = {0.};
math::Pose temp, mot(1);
mot.residuals().setZero();
std::copy_n(relframe->data(), 12, mot.values().data());
for (size_t i = path.size()-2 ; i > 0 ; --i)
{
auto relrefframe = node_cast<const ReferenceFrame*>(path[i]);
if (relrefframe == nullptr)
continue;
temp = math::Map<const math::Pose>(1,relrefframe->data(),res).transform(mot);
mot = temp;
}
temp = segpose.transform(mot.replicate(segpose.rows()));
return temp;
};
/**
* Returns the transformation of the relative Point @a relpoint expressed in the Segment @a seg. The Pose associated with the Segment is given in @a segpose.
* @warning The Point node @a relpoint must be a (non-)direct child of the Segment @a seg. Moreover, this function does not check if the input variables (@a relpoint, @a seg, @a pose) are null or not.
* @relates Point
* @ingroup openma_body
*/
math::Position transform_relative_point(const Point* relpoint, const Segment* seg, const math::Pose& segpose) _OPENMA_NOEXCEPT
{
assert(seg->findChild<const Point*>(relpoint->name()) == relpoint);
auto path = seg->retrievePath(relpoint);
// No path found?
if (path.empty())
return math::Position();
// Compute the position
const double res[1] = {0.};
math::Position temp, traj(1);
traj.residuals().setZero();
std::copy_n(relpoint->data(), 3, traj.values().data());
for (size_t i = path.size()-2 ; i > 0 ; --i)
{
auto relrefframe = node_cast<const ReferenceFrame*>(path[i]);
if (relrefframe == nullptr)
continue;
temp = math::Map<const math::Pose>(1,relrefframe->data(),res).transform(traj);
traj = temp;
}
temp = segpose.transform(traj.replicate(segpose.rows()));
return temp;
};
math::Array<9> transform_relative_inertia(InertialParameters* relbsip, const Segment* seg, const math::Pose& pose) _OPENMA_NOEXCEPT
{
ReferenceFrame rInertia("rInertia", relbsip->inertia(), relbsip);
return transform_relative_frame(&rInertia, seg, pose).block<9>(0).transform(pose.block<9>(0).transpose());
};
math::Position transform_relative_com(InertialParameters* relbsip, const Segment* seg, const math::Pose& pose) _OPENMA_NOEXCEPT
{
Point rCoM("rCoM", relbsip->centerOfMass(), relbsip);
return transform_relative_point(&rCoM, seg, pose);
};
};
};<commit_msg>Missing documentaition.<commit_after>/*
* Open Source Movement Analysis Library
* Copyright (C) 2016, Moveck Solution Inc., all rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name(s) of the copyright holders nor the names
* of its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "openma/body/utils.h"
#include "openma/body/landmarkstranslator.h"
#include "openma/body/point.h"
#include "openma/body/referenceframe.h"
#include "openma/body/inertialparameters.h"
#include "openma/body/segment.h"
#include "openma/body/skeletonhelper.h"
#include "openma/base/trial.h"
namespace ma
{
namespace body
{
/**
* Returns a collection of mapped time sequences based on the stored LandmarksTranslator in the given @a helper.
* The time sequences are extracted from the child node "TimeSequences" of the given @a trial.
* If no translator was set in the helper, try to use its default translator.
* If no translator was found, the keys used in the collection are directly the name of each time sequence.
* If a translator was found, only the registered landmarks will be extracted, their name converted and stored in the output collection.
*
* There is also extra outputs to determine the common sample rate and the common start time in all extracted landmarks.
* If all the landmarks have the same sample rate, and if the output @a rate is given, its value will be assigned to the found common sample rate (-1.0 otherwise).
* If all the landmarks have the same start time, and if the output @a start is given, its value will be assigned to the found common start time (-1.0 otherwise).
* If all the landmarks have the same sample rate and start time, and if the output @a ok is given, its value will be assigned to true (false otherwise).
*/
std::unordered_map<std::string,math::Map<math::Vector>> extract_landmark_positions(SkeletonHelper* helper, Trial* trial, double* rate, double* start, bool* ok) _OPENMA_NOEXCEPT
{
auto lt = helper->findChild<LandmarksTranslator*>({},{},false);
// No defined translator? Let's use the one embedded within the helper (if any)
if (lt == nullptr)
lt = helper->defaultLandmarksTranslator();
const auto& markers = trial->timeSequences()->findChildren<TimeSequence*>({},{{"type",TimeSequence::Marker},{"components",4}},false);
return extract_landmark_positions(lt,markers,rate,start,ok);
};
/**
* Returns a collection of mapped time sequences based on the given LandmarksTranslator @a lt.
* If no translator was given (i.e. null pointer), the keys used in the collection are directly the name of each time sequence.
*
* There is also extra outputs to determine the common sample rate and the common start time in all extracted landmarks.
* If all the landmarks have the same sample rate, and if the output @a rate is given, its value will be assigned to the found common sample rate (-1.0 otherwise).
* If all the landmarks have the same start time, and if the output @a start is given, its value will be assigned to the found common start time (-1.0 otherwise).
* If all the landmarks have the same sample rate and start time, and if the output @a ok is given, its value will be assigned to true (false otherwise).
*/
std::unordered_map<std::string,math::Map<math::Vector>> extract_landmark_positions(LandmarksTranslator* lt, const std::vector<TimeSequence*>& markers, double* rate, double* start, bool* ok) _OPENMA_NOEXCEPT
{
std::unordered_map<std::string,math::Map<math::Vector>> positions;
double sampleRate = -1.0, startTime = -1.0;
bool common = true;
std::vector<TimeSequence*> landmarks;
// No translator found? Create positions for all the markers found
if (lt == nullptr)
{
for (auto it = markers.cbegin() ; it != markers.cend() ; ++it)
{
positions.insert(std::make_pair((*it)->name(),math::to_position(*it)));
landmarks.push_back(*it);
}
}
// Convert only the markers found in the translator
else
{
for (auto it = markers.cbegin() ; it != markers.cend() ; ++it)
{
std::string name = lt->convertIfExists((*it)->name());
if (!name.empty())
{
positions.insert(std::make_pair(name,math::to_position(*it)));
landmarks.push_back(*it);
}
}
}
// Detect the common sampling information
auto it = landmarks.cbegin();
if (it != landmarks.cend())
{
sampleRate = (*it)->sampleRate();
startTime = (*it)->startTime();
++it;
}
for ( ; it != landmarks.cend() ; ++it)
{
if ((fabs(sampleRate - (*it)->sampleRate()) > std::numeric_limits<float>::epsilon())
|| (fabs(startTime - (*it)->startTime()) > std::numeric_limits<float>::epsilon()))
{
common = false;
sampleRate = -1.0;
startTime = -1.0;
break;
}
}
// Assign the sampling information (if the inout parameters are given)
if (rate != nullptr)
*rate = sampleRate;
if (start != nullptr)
*start = startTime;
if (ok != nullptr)
*ok = common;
return positions;
};
/**
* Returns the transformation of the relative ReferenceFrame @a relframe expressed in the Segment @a seg. The Pose associated with the Segment is given in @a segpose.
* @warning The ReferenceFrame node @a relframe must be a (non-)direct child of the Segment @a seg. Moreover, this function does not check if the input variables (@a relpoint, @a seg, @a pose) are null or not.
* @relates ReferenceFrame
* @ingroup openma_body
*/
math::Pose transform_relative_frame(const ReferenceFrame* relframe, const Segment* seg, const math::Pose& segpose) _OPENMA_NOEXCEPT
{
assert(seg->findChild<const ReferenceFrame*>(relframe->name()) == relframe);
auto path = seg->retrievePath(relframe);
// No path found?
if (path.empty())
return math::Pose();
// Compute the pose
const double res[1] = {0.};
math::Pose temp, mot(1);
mot.residuals().setZero();
std::copy_n(relframe->data(), 12, mot.values().data());
for (size_t i = path.size()-2 ; i > 0 ; --i)
{
auto relrefframe = node_cast<const ReferenceFrame*>(path[i]);
if (relrefframe == nullptr)
continue;
temp = math::Map<const math::Pose>(1,relrefframe->data(),res).transform(mot);
mot = temp;
}
temp = segpose.transform(mot.replicate(segpose.rows()));
return temp;
};
/**
* Returns the transformation of the relative Point @a relpoint expressed in the Segment @a seg. The Pose associated with the Segment is given in @a segpose.
* @warning The Point node @a relpoint must be a (non-)direct child of the Segment @a seg. Moreover, this function does not check if the input variables (@a relpoint, @a seg, @a pose) are null or not.
* @relates Point
* @ingroup openma_body
*/
math::Position transform_relative_point(const Point* relpoint, const Segment* seg, const math::Pose& segpose) _OPENMA_NOEXCEPT
{
assert(seg->findChild<const Point*>(relpoint->name()) == relpoint);
auto path = seg->retrievePath(relpoint);
// No path found?
if (path.empty())
return math::Position();
// Compute the position
const double res[1] = {0.};
math::Position temp, traj(1);
traj.residuals().setZero();
std::copy_n(relpoint->data(), 3, traj.values().data());
for (size_t i = path.size()-2 ; i > 0 ; --i)
{
auto relrefframe = node_cast<const ReferenceFrame*>(path[i]);
if (relrefframe == nullptr)
continue;
temp = math::Map<const math::Pose>(1,relrefframe->data(),res).transform(traj);
traj = temp;
}
temp = segpose.transform(traj.replicate(segpose.rows()));
return temp;
};
/**
* Transform the relative tensor of inertia stored in @a relbsip (and related to the segment @a seg) using the orientation data stored in @a pose.
* @note The formula to transform a tensor of inertia is <em>R x I x Rt</em>
* @ingroup openma_body
*/
math::Array<9> transform_relative_inertia(InertialParameters* relbsip, const Segment* seg, const math::Pose& pose) _OPENMA_NOEXCEPT
{
ReferenceFrame rInertia("rInertia", relbsip->inertia(), relbsip);
return transform_relative_frame(&rInertia, seg, pose).block<9>(0).transform(pose.block<9>(0).transpose());
};
/**
* Transform the relative coordinates of the center of mass stored in @a relbsip (and related to the segment @a seg) using the data stored in @a pose.
* @ingroup openma_body
*/
math::Position transform_relative_com(InertialParameters* relbsip, const Segment* seg, const math::Pose& pose) _OPENMA_NOEXCEPT
{
Point rCoM("rCoM", relbsip->centerOfMass(), relbsip);
return transform_relative_point(&rCoM, seg, pose);
};
};
};<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.