text
stringlengths 54
60.6k
|
|---|
<commit_before>#ifndef CONTAINERS_NAME_STRING_HPP_
#define CONTAINERS_NAME_STRING_HPP_
#include <string>
#include "http/json/json_adapter.hpp"
#include "rpc/serialize_macros.hpp"
// The kind of string that can only contain either the empty string or acceptable names for
// things. You may only assign non-empty strings.
class name_string_t {
public:
// Initializes to the empty string.
name_string_t();
// Succeeds on valid non-empty strings.
MUST_USE bool assign_value(const std::string& s);
const std::string& str() const { return str_; }
bool empty() const { return str_.empty(); } // TODO(1253): get rid of this.
const char *c_str() const { return str_.c_str(); } // TODO(1253): get rid of this.
RDB_MAKE_ME_SERIALIZABLE_1(str_);
static const char *const valid_char_msg;
private:
std::string str_;
};
inline bool operator==(const name_string_t& x, const name_string_t& y) {
return x.str() == y.str();
}
inline bool operator!=(const name_string_t& x, const name_string_t& y) {
return !(x == y);
}
inline bool operator<(const name_string_t& x, const name_string_t& y) {
return x.str() < y.str();
}
// ctx-less json adapter concept for name_string_t
json_adapter_if_t::json_adapter_map_t get_json_subfields(name_string_t *target);
cJSON *render_as_json(name_string_t *target);
void apply_json_to(cJSON *change, name_string_t *target);
void on_subfield_change(name_string_t *);
void debug_print(append_only_printf_buffer_t *buf, const name_string_t& s);
#endif // CONTAINERS_NAME_STRING_HPP_
<commit_msg>Removed some TODO(1253).<commit_after>#ifndef CONTAINERS_NAME_STRING_HPP_
#define CONTAINERS_NAME_STRING_HPP_
#include <string>
#include "http/json/json_adapter.hpp"
#include "rpc/serialize_macros.hpp"
// The kind of string that can only contain either the empty string or acceptable names for
// things. You may only assign non-empty strings.
class name_string_t {
public:
// Initializes to the empty string.
name_string_t();
// Succeeds on valid non-empty strings.
MUST_USE bool assign_value(const std::string& s);
const std::string& str() const { return str_; }
// TODO: We should get rid of this, and code that uses this is known to be untrustworthy.
bool empty() const { return str_.empty(); }
const char *c_str() const { return str_.c_str(); }
RDB_MAKE_ME_SERIALIZABLE_1(str_);
static const char *const valid_char_msg;
private:
std::string str_;
};
inline bool operator==(const name_string_t& x, const name_string_t& y) {
return x.str() == y.str();
}
inline bool operator!=(const name_string_t& x, const name_string_t& y) {
return !(x == y);
}
inline bool operator<(const name_string_t& x, const name_string_t& y) {
return x.str() < y.str();
}
// ctx-less json adapter concept for name_string_t
json_adapter_if_t::json_adapter_map_t get_json_subfields(name_string_t *target);
cJSON *render_as_json(name_string_t *target);
void apply_json_to(cJSON *change, name_string_t *target);
void on_subfield_change(name_string_t *);
void debug_print(append_only_printf_buffer_t *buf, const name_string_t& s);
#endif // CONTAINERS_NAME_STRING_HPP_
<|endoftext|>
|
<commit_before>#include "zpublic.hpp"
#include "stdio.h"
#include <string>
#include <atlbase.h>
#include <fstream>
#include "cpptest-1.1.2/src/cpptest.h"
using namespace Test;
#ifdef _MSC_VER
#pragma warning (disable: 4290)
#endif
void test_mrumap();
void test_thread();
void test_ptr();
void test_vector();
void teststring();
void test_time();
void test_info();
void test_encode();
void test_hashtable();
void test_basic();
void test_heap();
class FailTestSuite : public Test::Suite
{
public:
FailTestSuite()
{
TEST_ADD(FailTestSuite::success)
TEST_ADD(FailTestSuite::always_fail)
}
private:
void success() {}
void always_fail()
{
TEST_FAIL("unconditional fail");
}
};
int main(int argc, char* argv[])
{
setlocale(LC_ALL, "chs");
Suite ts;
ts.add(std::auto_ptr<Test::Suite>(new FailTestSuite));
std::auto_ptr<Test::Output> output(new Test::HtmlOutput); //new Test::TextOutput(Test::TextOutput::Verbose));
ts.run(*output, true);
Test::HtmlOutput* const html = dynamic_cast<Test::HtmlOutput*>(output.get());
if (html)
{
std::ofstream fout("./test.html");
html->generate(fout, true, "TestReport");
}
// const BYTE pp[] = {"124"};
// //cout << hex << zl::ExCRC32(pp, 3) << endl;
// printf("%08x", zl::ExCRC32(pp, 3));
//
//
// const char *pp2 = {"124"};
// printf("%08x", zl::HashKey(pp2));
// printf("%08x", zl::HashKey(100));
//
// zl::Pair<int, int> p;
// p.key =1; p.value =2;
// zl::Pair<int, int> p2(p);
// printf("%d %d", p2.key, p2.value);
//
// zl::Bit b1(1), b2;
// printf("%d %d %d %d %d %d\n", b1, b2, b1<b2, b1&b2, b1|b2, b1^b2);
// //std::cout << b1 << std::endl;
// //<< " "<< b2 << " " << b1<b2 << " " << b1&b2 << " " << b1|b2 << " " << b1^b2 << std::endl;
//
// char source[100] = "what the fuck xxxx qqqqd fsds kevin sadsadeqw";
// char pattern[10] = "kevin";
// size_t ret = zl::SundayMatchString(source, strlen(source), pattern, strlen(pattern), 0);
// printf("%d\n",ret);
//
// zl::CIncreaseMemory<char> mem(8);
// mem.Inc();
// printf("%ld\n", mem.Size());
// mem.Inc();
// printf("%ld\n", mem.Size());
// mem.Release();
//
// int a;
// int *b = 0;
// zl::_Allocate(4, &a);
// zl::_Allocate(b, 10);
// b = zl::_Allocate<int>(10);
//
//
// zl::CArrayFixed<int, 10> arr10 = {0};
// for (int i = 0; i < 10; i++)
// arr10[i] = i * 5;
// printf("%d\n", arr10[1]);
//
// zl::CArrayFixedEx<int, 20> arr20 = {0};
// for (int i = 0; i < 20; i++)
// arr20[i] = i * 5;
//
// zl::CArrayVariable<int> arrX;
// arrX = arr20[zl::DoublePos(13, 17)];
//
// for (size_t i = 0; i < arrX.Size(); i++)
// printf("%d\n", arrX[i]);
//
// printf("\n");
//
// zl::CArrayVariable<int> arrY = arr20[zl::ThreePos(5, 17, 3)];
// for (size_t i = 0; i < arrY.Size(); i++)
// printf("%d\n", arrY[i]);
// zl::basic_string str("hello world");
// printf("%s\n",str.c_str());
// str.upper();
// printf("%s\n",str.c_str());
// str.lower();
// printf("%s\n",str.c_str());
// printf("%d\n",str.find("world"));
// printf("%d\n",str.rfind("or"));
//
//
//
// USES_CONVERSION;
// std::string strB(CW2A(L"hello", CP_UTF8));
// std::string strB2, strB3;
// zl::Base64Encode(strB, &strB2);
// printf("%s\n", strB2.c_str());
// zl::Base64Decode(strB2, &strB3);
// wprintf(CA2W(strB3.c_str(), CP_UTF8));
test_mrumap();
//test_thread();
test_ptr();
///> 躸ר
test_heap();
test_hashtable();
test_vector();
teststring();
///> zapר
test_time();
test_info();
test_encode();
test_basic();
return 0;
}
void test_mrumap()
{
typedef zl::MRUCache<int, int> Cache;
Cache cache(4);
cache.Put(1, 5);
cache.Put(2, 10);
cache.Put(3, 15);
cache.Put(4, 20);
cache.Put(2, 25);
for (Cache::const_iterator p = cache.begin();
p != cache.end();
++p)
{
printf("%d ", p->second);
}
typedef zl::HashingMRUCache<const char*, int> Cache2;
Cache2 cache2(4);
cache2.Put("1", 5);
cache2.Put("2", 10);
cache2.Put("3", 15);
cache2.Put("4", 20);
cache2.Put("2", 25);
for (Cache2::const_iterator p = cache2.begin();
p != cache2.end();
++p)
{
printf("%d ", p->second);
}
}
void test_thread()
{
zl::CEvent xEvent;
xEvent.Create();
xEvent.Wait(5000);
xEvent.Set();
xEvent.Wait(10000);
zl::CSemaphore xSemaphore;
xSemaphore.Create(0, 10);
xSemaphore.Wait(3000);
xSemaphore.Release();
xSemaphore.Release();
xSemaphore.Wait(3000);
xSemaphore.Wait(3000);
xSemaphore.Wait(3000);
}
void test_ptr()
{
class CPtrTest : public zl::RefCounted<CPtrTest>
{
public:
CPtrTest() {}
private:
FREIEND_REFCOUNTED(CPtrTest)
};
CPtrTest *pp1 = new CPtrTest;
pp1->AddRef();
pp1->AddRef();
pp1->Release();
pp1->Release();
}
void test_vector()
{
zl::CSimpleVector<int> vecInt(2);
vecInt.Add(1);
vecInt.Add(2);
vecInt.Add(1);
vecInt.Add(2);
vecInt.Add(1);
vecInt.Add(2);
vecInt.Add(1);
vecInt.Add(2);
vecInt.Add(1);
vecInt.Add(2);
vecInt.RemoveAt(3);
zl::CSimpleVector<int> vecInt2 = vecInt;
for (int i=0; i<vecInt2.GetSize(); i++)
{
printf("%d ", vecInt2[i]);
}
}
void teststring()
{
zl::CArrayVariable<zl::basic_string*> stringlist;
zl::basic_string a = "hello kevin fuck you kevin yes true";
zl::basic_string sub;
zl::basic_string b;
zl::CSimpleVector<zl::basic_string *> vecSplit;
a.split(" ", vecSplit);
b = a + " fuck you";
printf("%s\n",b.c_str());
b = a.GetSub(6,5);
zl::basic_string x;
b.swap(x);
printf("%s\n",x.c_str());
b = a.replace("kevin", "()");
zl::basic_string str1 = "kzvin";
zl::basic_string str2 = "kevin";
printf("%d", str1 <= str2);
//stringlist[0] = &a;
// zl::basic_string a = "hello kevin";
// zl::basic_string sub;
// if(a.GetSub(&sub, 6, 5))
// {
// printf("%s\n",sub.c_str());
// }
//stringlist[0] = &a;
//a.split(" ", stringlist);
}
void test_time()
{
// LARGE_INTEGER llTimeBegin = {0};
// zl::CTimeInterval::GetTime(llTimeBegin);
//
// __time64_t t1 = 0;
// zl::GetFileTimeInfo(L"c:\\windows\\notepad.exe", &t1, 0, 0);
// FILETIME ft = zl::Time642FileTime(t1);
//
// SYSTEMTIME sTime;
// GetSystemTime(&sTime);
// wchar_t strTime[TIME_STRING_MAX_LEN] = {0};
// zl::Time2Str(sTime, strTime);
// zl::Str2Time(strTime, sTime);
//
//
// double dfTimeInterval = 0.0;
// zl::CTimeInterval::Calc(llTimeBegin, dfTimeInterval);
// printf("%.2f", dfTimeInterval);
zl::timer t;
printf("\n%f ", zl::timer_elapsed_min);
::Sleep(1000);
printf("%f\n", t.elapsed());
}
void test_info()
{
std::wstring sGuid = zl::GenerateGUID();
zl::IsValidGUID(sGuid);
}
void test_encode()
{
std::wstring sHello1(L"hello");
std::string sHello2 = zl::WideToUTF8(sHello1);
std::wstring sHello3 = zl::UTF8ToWide(sHello2);
}
void test_hashtable()
{
struct st
{
int key;
int value;
};
struct st_equal
{
bool operator() (const st& first, const st& second) const
{
return first.value == second.value;
}
};
struct st_hash
{
unsigned long operator() (const st& first, const unsigned long n) const
{
return first.value % n;
}
};
zl::HashTable<st, st_hash, st_equal> myHashTable(10);
st tmp;
int count = 0;
for(unsigned long i = 0; i<100; i++)
{
tmp.key = 10;
tmp.value = i;
myHashTable.insert_unique(tmp);
}
tmp.value = 10;
myHashTable.find(tmp);
tmp.key = 21;
tmp.value = 64;
myHashTable.find(tmp);
}
void test_basic()
{
// zl::singleton<std::string>::Instance() = "123";
// printf("\n%s\n", zl::singleton<std::string>::Instance().c_str());
//
// zl::scoped_ptr<std::string> p(new std::string("1234"));
// p->c_str();
zl::scoped_arr<int> arrInt(new int[10]);
}
void test_heap()
{
zl::Heap<zl::basic_string> heap;
zl::Heap<int> heap2;
int array[11] = {68, 32, 19, 21, 16, 31, 50, 24, 13, 26, 65};
char str[10][20] = {"kevin", "lily", "david", "zapline", "lafeng", "laopan", "animal", "dachu", "moster"};
//int array[11] = {31, 65, 68};
zl::basic_string x;
for(int i=0; i<9; i++)
heap.push(str[i]);
//heap.print_heap();
for(int i = 0; i < 9; i++)
{
if(heap.pop(x))
printf("%s ", x.c_str());
}
int b;
for(int i = 0; i < 11; i++)
heap2.push(array[i]);
//heap2.print_heap1();
for(int i = 0; i < 11; i++)
{
if(heap2.pop(b))
printf("%d ", b);
}
//heap.print_heap();
}<commit_msg>修改测试输出目录<commit_after>#include "zpublic.hpp"
#include "stdio.h"
#include <string>
#include <atlbase.h>
#include <fstream>
#include "cpptest-1.1.2/src/cpptest.h"
using namespace Test;
#ifdef _MSC_VER
#pragma warning (disable: 4290)
#endif
void test_mrumap();
void test_thread();
void test_ptr();
void test_vector();
void teststring();
void test_time();
void test_info();
void test_encode();
void test_hashtable();
void test_basic();
void test_heap();
class FailTestSuite : public Test::Suite
{
public:
FailTestSuite()
{
TEST_ADD(FailTestSuite::success)
TEST_ADD(FailTestSuite::always_fail)
}
private:
void success() {}
void always_fail()
{
TEST_FAIL("unconditional fail");
}
};
int main(int argc, char* argv[])
{
setlocale(LC_ALL, "chs");
Suite ts;
ts.add(std::auto_ptr<Test::Suite>(new FailTestSuite));
std::auto_ptr<Test::Output> output(new Test::HtmlOutput); //new Test::TextOutput(Test::TextOutput::Verbose));
ts.run(*output, true);
Test::HtmlOutput* const html = dynamic_cast<Test::HtmlOutput*>(output.get());
if (html)
{
std::ofstream fout("./bin/test.html");
html->generate(fout, true, "TestReport");
}
// const BYTE pp[] = {"124"};
// //cout << hex << zl::ExCRC32(pp, 3) << endl;
// printf("%08x", zl::ExCRC32(pp, 3));
//
//
// const char *pp2 = {"124"};
// printf("%08x", zl::HashKey(pp2));
// printf("%08x", zl::HashKey(100));
//
// zl::Pair<int, int> p;
// p.key =1; p.value =2;
// zl::Pair<int, int> p2(p);
// printf("%d %d", p2.key, p2.value);
//
// zl::Bit b1(1), b2;
// printf("%d %d %d %d %d %d\n", b1, b2, b1<b2, b1&b2, b1|b2, b1^b2);
// //std::cout << b1 << std::endl;
// //<< " "<< b2 << " " << b1<b2 << " " << b1&b2 << " " << b1|b2 << " " << b1^b2 << std::endl;
//
// char source[100] = "what the fuck xxxx qqqqd fsds kevin sadsadeqw";
// char pattern[10] = "kevin";
// size_t ret = zl::SundayMatchString(source, strlen(source), pattern, strlen(pattern), 0);
// printf("%d\n",ret);
//
// zl::CIncreaseMemory<char> mem(8);
// mem.Inc();
// printf("%ld\n", mem.Size());
// mem.Inc();
// printf("%ld\n", mem.Size());
// mem.Release();
//
// int a;
// int *b = 0;
// zl::_Allocate(4, &a);
// zl::_Allocate(b, 10);
// b = zl::_Allocate<int>(10);
//
//
// zl::CArrayFixed<int, 10> arr10 = {0};
// for (int i = 0; i < 10; i++)
// arr10[i] = i * 5;
// printf("%d\n", arr10[1]);
//
// zl::CArrayFixedEx<int, 20> arr20 = {0};
// for (int i = 0; i < 20; i++)
// arr20[i] = i * 5;
//
// zl::CArrayVariable<int> arrX;
// arrX = arr20[zl::DoublePos(13, 17)];
//
// for (size_t i = 0; i < arrX.Size(); i++)
// printf("%d\n", arrX[i]);
//
// printf("\n");
//
// zl::CArrayVariable<int> arrY = arr20[zl::ThreePos(5, 17, 3)];
// for (size_t i = 0; i < arrY.Size(); i++)
// printf("%d\n", arrY[i]);
// zl::basic_string str("hello world");
// printf("%s\n",str.c_str());
// str.upper();
// printf("%s\n",str.c_str());
// str.lower();
// printf("%s\n",str.c_str());
// printf("%d\n",str.find("world"));
// printf("%d\n",str.rfind("or"));
//
//
//
// USES_CONVERSION;
// std::string strB(CW2A(L"hello", CP_UTF8));
// std::string strB2, strB3;
// zl::Base64Encode(strB, &strB2);
// printf("%s\n", strB2.c_str());
// zl::Base64Decode(strB2, &strB3);
// wprintf(CA2W(strB3.c_str(), CP_UTF8));
test_mrumap();
//test_thread();
test_ptr();
///> 躸ר
test_heap();
test_hashtable();
test_vector();
teststring();
///> zapר
test_time();
test_info();
test_encode();
test_basic();
return 0;
}
void test_mrumap()
{
typedef zl::MRUCache<int, int> Cache;
Cache cache(4);
cache.Put(1, 5);
cache.Put(2, 10);
cache.Put(3, 15);
cache.Put(4, 20);
cache.Put(2, 25);
for (Cache::const_iterator p = cache.begin();
p != cache.end();
++p)
{
printf("%d ", p->second);
}
typedef zl::HashingMRUCache<const char*, int> Cache2;
Cache2 cache2(4);
cache2.Put("1", 5);
cache2.Put("2", 10);
cache2.Put("3", 15);
cache2.Put("4", 20);
cache2.Put("2", 25);
for (Cache2::const_iterator p = cache2.begin();
p != cache2.end();
++p)
{
printf("%d ", p->second);
}
}
void test_thread()
{
zl::CEvent xEvent;
xEvent.Create();
xEvent.Wait(5000);
xEvent.Set();
xEvent.Wait(10000);
zl::CSemaphore xSemaphore;
xSemaphore.Create(0, 10);
xSemaphore.Wait(3000);
xSemaphore.Release();
xSemaphore.Release();
xSemaphore.Wait(3000);
xSemaphore.Wait(3000);
xSemaphore.Wait(3000);
}
void test_ptr()
{
class CPtrTest : public zl::RefCounted<CPtrTest>
{
public:
CPtrTest() {}
private:
FREIEND_REFCOUNTED(CPtrTest)
};
CPtrTest *pp1 = new CPtrTest;
pp1->AddRef();
pp1->AddRef();
pp1->Release();
pp1->Release();
}
void test_vector()
{
zl::CSimpleVector<int> vecInt(2);
vecInt.Add(1);
vecInt.Add(2);
vecInt.Add(1);
vecInt.Add(2);
vecInt.Add(1);
vecInt.Add(2);
vecInt.Add(1);
vecInt.Add(2);
vecInt.Add(1);
vecInt.Add(2);
vecInt.RemoveAt(3);
zl::CSimpleVector<int> vecInt2 = vecInt;
for (int i=0; i<vecInt2.GetSize(); i++)
{
printf("%d ", vecInt2[i]);
}
}
void teststring()
{
zl::CArrayVariable<zl::basic_string*> stringlist;
zl::basic_string a = "hello kevin fuck you kevin yes true";
zl::basic_string sub;
zl::basic_string b;
zl::CSimpleVector<zl::basic_string *> vecSplit;
a.split(" ", vecSplit);
b = a + " fuck you";
printf("%s\n",b.c_str());
b = a.GetSub(6,5);
zl::basic_string x;
b.swap(x);
printf("%s\n",x.c_str());
b = a.replace("kevin", "()");
zl::basic_string str1 = "kzvin";
zl::basic_string str2 = "kevin";
printf("%d", str1 <= str2);
//stringlist[0] = &a;
// zl::basic_string a = "hello kevin";
// zl::basic_string sub;
// if(a.GetSub(&sub, 6, 5))
// {
// printf("%s\n",sub.c_str());
// }
//stringlist[0] = &a;
//a.split(" ", stringlist);
}
void test_time()
{
// LARGE_INTEGER llTimeBegin = {0};
// zl::CTimeInterval::GetTime(llTimeBegin);
//
// __time64_t t1 = 0;
// zl::GetFileTimeInfo(L"c:\\windows\\notepad.exe", &t1, 0, 0);
// FILETIME ft = zl::Time642FileTime(t1);
//
// SYSTEMTIME sTime;
// GetSystemTime(&sTime);
// wchar_t strTime[TIME_STRING_MAX_LEN] = {0};
// zl::Time2Str(sTime, strTime);
// zl::Str2Time(strTime, sTime);
//
//
// double dfTimeInterval = 0.0;
// zl::CTimeInterval::Calc(llTimeBegin, dfTimeInterval);
// printf("%.2f", dfTimeInterval);
zl::timer t;
printf("\n%f ", zl::timer_elapsed_min);
::Sleep(1000);
printf("%f\n", t.elapsed());
}
void test_info()
{
std::wstring sGuid = zl::GenerateGUID();
zl::IsValidGUID(sGuid);
}
void test_encode()
{
std::wstring sHello1(L"hello");
std::string sHello2 = zl::WideToUTF8(sHello1);
std::wstring sHello3 = zl::UTF8ToWide(sHello2);
}
void test_hashtable()
{
struct st
{
int key;
int value;
};
struct st_equal
{
bool operator() (const st& first, const st& second) const
{
return first.value == second.value;
}
};
struct st_hash
{
unsigned long operator() (const st& first, const unsigned long n) const
{
return first.value % n;
}
};
zl::HashTable<st, st_hash, st_equal> myHashTable(10);
st tmp;
int count = 0;
for(unsigned long i = 0; i<100; i++)
{
tmp.key = 10;
tmp.value = i;
myHashTable.insert_unique(tmp);
}
tmp.value = 10;
myHashTable.find(tmp);
tmp.key = 21;
tmp.value = 64;
myHashTable.find(tmp);
}
void test_basic()
{
// zl::singleton<std::string>::Instance() = "123";
// printf("\n%s\n", zl::singleton<std::string>::Instance().c_str());
//
// zl::scoped_ptr<std::string> p(new std::string("1234"));
// p->c_str();
zl::scoped_arr<int> arrInt(new int[10]);
}
void test_heap()
{
zl::Heap<zl::basic_string> heap;
zl::Heap<int> heap2;
int array[11] = {68, 32, 19, 21, 16, 31, 50, 24, 13, 26, 65};
char str[10][20] = {"kevin", "lily", "david", "zapline", "lafeng", "laopan", "animal", "dachu", "moster"};
//int array[11] = {31, 65, 68};
zl::basic_string x;
for(int i=0; i<9; i++)
heap.push(str[i]);
//heap.print_heap();
for(int i = 0; i < 9; i++)
{
if(heap.pop(x))
printf("%s ", x.c_str());
}
int b;
for(int i = 0; i < 11; i++)
heap2.push(array[i]);
//heap2.print_heap1();
for(int i = 0; i < 11; i++)
{
if(heap2.pop(b))
printf("%d ", b);
}
//heap.print_heap();
}<|endoftext|>
|
<commit_before>//
// ofxLaserDacBase.cpp
//
// Created by Seb Lee-Delisle on 07/11/2017.
//
//
#include "ofxLaserDacHelios.h"
using namespace ofxLaser;
DacHelios:: DacHelios() : heliosManager(DacHeliosManager::getInstance()) {
pps = 30000;
newPPS = 30000;
frameMode = true;
connected = false;
newArmed = false; // as in the PPS system, this knows
// if armed status has changed and sends
// signal to DAC
deviceId = "";
dacDevice = nullptr;
}
DacHelios:: ~DacHelios() {
ofLogNotice("DacHelios destructor");
//stopThread();
close();
}
void DacHelios::close() {
if(isThreadRunning()) {
waitForThread(true); // also stops the thread
if(lock()) {
if(dacDevice!=nullptr) {
dacDevice->SetClosed();
dacDevice = nullptr;
}
unlock();
}
delete dacDevice;
}
}
void DacHelios::setup(string name) {
deviceName = name; // the parameter which shows the name
ofLogNotice("DacHelios::setup "+name);
connectToDevice(deviceName);
pointBufferDisplay.set("Point Buffer", 0,0,1799);
displayData.push_back(&deviceName);
displayData.push_back(&pointBufferDisplay);
startThread();
}
const vector<ofAbstractParameter*>& DacHelios :: getDisplayData() {
if(lock()) {
//pointBufferDisplay += (response.status.buffer_fullness-pointBufferDisplay)*1;
//int pointssincelastmessage = (float)((ofGetElapsedTimeMicros()-lastMessageTimeMicros)*response.status.point_rate)/1000000.0f;
//pointBufferDisplay = bufferedPoints.size();
//latencyDisplay += (latencyMicros - latencyDisplay)*0.1;
//reconnectCount = prepareSendCount;
unlock();
}
return displayData;
}
bool DacHelios::connectToDevice(string name) {
dacDevice = heliosManager.getDacDeviceForName(name);
if(dacDevice!=nullptr) {
deviceId = deviceName = dacDevice->nameStr;
if(dacDevice->isClosed()) { // not sure why it should be but hey
ofLogError("HeliosDac device is closed before it's used!"+ name);
heliosManager.deleteDevice(dacDevice);
connected = false;
dacDevice = nullptr;
} else {
connected = true;
}
} else {
connected = false;
}
return connected;
}
bool DacHelios:: sendFrame(const vector<Point>& points){
if(!connected) return false;
// get frame object
DacHeliosFrame* frame = new DacHeliosFrame();
// add all points into the frame object
frameMode = true;
for(ofxLaser::Point p : points) {
frame->addPoint(p);
}
// add the frame object to the frame channel
framesChannel.send(frame);
return true;
}
bool DacHelios::sendPoints(const vector<Point>& points) {
return false;
// if(bufferedPoints.size()>pps*0.5) {
// return false;
// }
// frameMode = false;
// HeliosPoint p1;
// if(lock()) {
// frameMode = false;
//
// for(size_t i= 0; i<points.size(); i++) {
// const Point& p2 = points[i];
// p1.x = ofMap(p2.x,0,800, HELIOS_MIN, HELIOS_MAX);
// p1.y = ofMap(p2.y,800,0, HELIOS_MIN, HELIOS_MAX); // Y is UP
// p1.r = roundf(p2.r);
// p1.g = roundf(p2.g);
// p1.b = roundf(p2.b);
// p1.i = 255;
// addPoint(p1);
// }
// unlock();
// }
// return true;
};
bool DacHelios::setPointsPerSecond(uint32_t newpps) {
ofLog(OF_LOG_NOTICE, "setPointsPerSecond " + ofToString(newpps));
while(!lock());
newPPS = newpps;
unlock();
return true;
};
void DacHelios :: setActive(bool active){
newArmed = active;
}
void DacHelios :: reset() {
if(lock()) {
resetFlag = true;
unlock();
}
}
void DacHelios :: threadedFunction(){
//const uint32_t samples_per_packet = 1024;
const int minBuffer = 500; // TODO make this dependent on pointrate
//HeliosPoint * samples = (HeliosPoint *)calloc(sizeof(HeliosPoint), samples_per_packet);
DacHeliosFrame* currentFrame = nullptr;
DacHeliosFrame* nextFrame = nullptr;
DacHeliosFrame* newFrame = nullptr;
while(isThreadRunning()) {
if(connected && (newPPS!=pps)) {
pps = newPPS;
}
if(connected && (newArmed!=armed)) {
if((dacDevice!=nullptr) && (dacDevice->SetShutter(newArmed)==HELIOS_SUCCESS)) {
armed = newArmed;
}
}
if(connected && isThreadRunning()) {
// is there a new frame?
// if so, store it
bool dacReady = false;
int status = 0;
while(!dacReady) {
if(framesChannel.tryReceive(newFrame)) {
if(nextFrame!=nullptr) {
delete nextFrame;
}
nextFrame = newFrame;
}
if(dacDevice!=nullptr) status = dacDevice->GetStatus();
dacReady = (status == 1);
if(!dacReady) {
if(status>1)
ofLog(OF_LOG_NOTICE, "heliosDac.getStatus : "+ ofToString(status));
sleep(1);
}
}
// if we got to here then the dac is ready but we might not have a
// currentFrame yet...
if(nextFrame!=nullptr) {
if(currentFrame!=nullptr) {
delete currentFrame;
}
currentFrame = nextFrame;
nextFrame = nullptr;
}
if(currentFrame!=nullptr) {
int result = 0;
if(dacDevice!=nullptr) result = dacDevice->SendFrame(pps, HELIOS_FLAGS_SINGLE_MODE, currentFrame->samples, currentFrame->numSamples);
//ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame : "+ ofToString(result));
if(result <=-5000){ // then we have a USB connection error
ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame failed. LIBUSB error : "+ ofToString(result));
if(result!=-5007) setConnected(false); // time out error
} else if(result!=HELIOS_SUCCESS) {
ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame failed. Error : "+ ofToString(result));
setConnected(false);
} else {
setConnected(true);
}
}
} else {
// DO RECONNECT
//resetFlag = false;
// TODO : handle reconnection better
// try to reconnect!
if(isThreadRunning()) {
if(lock()) {
if(connectToDevice(deviceName)) {
setConnected(true);
// wait half a second?
unlock();
} else {
unlock();
for(size_t i = 0; (i<10)&&(isThreadRunning()); i++ ) {
sleep(50);
}
}
}
yield();
}
}
}
//free(samples);
}
void DacHelios :: setConnected(bool state) {
if(connected!=state) {
while(!lock()){};
connected = state;
if(!connected) {
//heliosManager.deviceDisconnected(deviceName);
armed = !newArmed;
heliosManager.deleteDevice(dacDevice);
dacDevice = nullptr;
}
ofLogNotice("Helios Dac changed connection state : "+ofToString(connected));
unlock();
}
}
<commit_msg>HeliosDac refactors<commit_after>//
// ofxLaserDacBase.cpp
//
// Created by Seb Lee-Delisle on 07/11/2017.
//
//
#include "ofxLaserDacHelios.h"
using namespace ofxLaser;
DacHelios:: DacHelios() : heliosManager(DacHeliosManager::getInstance()) {
pps = 30000;
newPPS = 30000;
frameMode = true;
connected = false;
newArmed = false; // as in the PPS system, this knows
// if armed status has changed and sends
// signal to DAC
deviceId = "";
dacDevice = nullptr;
}
DacHelios:: ~DacHelios() {
ofLogNotice("DacHelios destructor");
//stopThread();
close();
}
void DacHelios::close() {
if(isThreadRunning()) {
waitForThread(true); // also stops the thread
if(lock()) {
if(dacDevice!=nullptr) {
dacDevice->SetClosed();
dacDevice = nullptr;
}
unlock();
}
delete dacDevice;
}
}
void DacHelios::setup(string name) {
deviceName = name; // the parameter which shows the name
ofLogNotice("DacHelios::setup "+name);
connectToDevice(deviceName);
pointBufferDisplay.set("Point Buffer", 0,0,1799);
displayData.push_back(&deviceName);
displayData.push_back(&pointBufferDisplay);
startThread();
}
const vector<ofAbstractParameter*>& DacHelios :: getDisplayData() {
if(lock()) {
//pointBufferDisplay += (response.status.buffer_fullness-pointBufferDisplay)*1;
//int pointssincelastmessage = (float)((ofGetElapsedTimeMicros()-lastMessageTimeMicros)*response.status.point_rate)/1000000.0f;
//pointBufferDisplay = bufferedPoints.size();
//latencyDisplay += (latencyMicros - latencyDisplay)*0.1;
//reconnectCount = prepareSendCount;
unlock();
}
return displayData;
}
bool DacHelios::connectToDevice(string name) {
dacDevice = heliosManager.getDacDeviceForName(name);
if(dacDevice!=nullptr) {
deviceId = deviceName = dacDevice->nameStr;
if(dacDevice->isClosed()) { // not sure why it should be but hey
ofLogError("HeliosDac device is closed before it's used!"+ name);
heliosManager.deleteDevice(dacDevice);
connected = false;
dacDevice = nullptr;
} else {
connected = true;
}
} else {
connected = false;
}
return connected;
}
bool DacHelios:: sendFrame(const vector<Point>& points){
if(!connected) return false;
// get frame object
DacHeliosFrame* frame = new DacHeliosFrame();
// add all points into the frame object
frameMode = true;
for(ofxLaser::Point p : points) {
frame->addPoint(p);
}
// add the frame object to the frame channel
framesChannel.send(frame);
return true;
}
bool DacHelios::sendPoints(const vector<Point>& points) {
return false;
// if(bufferedPoints.size()>pps*0.5) {
// return false;
// }
// frameMode = false;
// HeliosPoint p1;
// if(lock()) {
// frameMode = false;
//
// for(size_t i= 0; i<points.size(); i++) {
// const Point& p2 = points[i];
// p1.x = ofMap(p2.x,0,800, HELIOS_MIN, HELIOS_MAX);
// p1.y = ofMap(p2.y,800,0, HELIOS_MIN, HELIOS_MAX); // Y is UP
// p1.r = roundf(p2.r);
// p1.g = roundf(p2.g);
// p1.b = roundf(p2.b);
// p1.i = 255;
// addPoint(p1);
// }
// unlock();
// }
// return true;
};
bool DacHelios::setPointsPerSecond(uint32_t newpps) {
ofLog(OF_LOG_NOTICE, "setPointsPerSecond " + ofToString(newpps));
while(!lock());
newPPS = newpps;
unlock();
return true;
};
void DacHelios :: setActive(bool active){
newArmed = active;
}
void DacHelios :: reset() {
if(lock()) {
resetFlag = true;
unlock();
}
}
void DacHelios :: threadedFunction(){
//HeliosPoint * samples = (HeliosPoint *)calloc(sizeof(HeliosPoint), samples_per_packet);
DacHeliosFrame* currentFrame = nullptr;
DacHeliosFrame* nextFrame = nullptr;
DacHeliosFrame* newFrame = nullptr;
while(isThreadRunning()) {
if(connected && (newPPS!=pps)) {
pps = newPPS;
}
if(connected && (newArmed!=armed)) {
if((dacDevice!=nullptr) && (dacDevice->SetShutter(newArmed)==HELIOS_SUCCESS)) {
armed = newArmed;
}
}
if(connected && isThreadRunning()) {
// is there a new frame?
// if so, store it
bool dacReady = false;
int status = 0;
while(!dacReady) {
if(framesChannel.tryReceive(newFrame)) {
if(nextFrame!=nullptr) {
delete nextFrame;
}
nextFrame = newFrame;
}
//float time = ofGetElapsedTimef();
if(dacDevice!=nullptr) status = dacDevice->GetStatus();
//cout << status << " " << ofGetElapsedTimef()-time << endl;
dacReady = (status == 1);
if(!dacReady) {
if(status<0) {
ofLog(OF_LOG_NOTICE, "heliosDac.getStatus error: "+ ofToString(status));
sleep(1);
//cout << ".";
}
}
// if we got to here then the dac is ready but we might not have a
// currentFrame yet...
if(nextFrame!=nullptr) {
if(currentFrame!=nullptr) {
delete currentFrame;
}
currentFrame = nextFrame;
nextFrame = nullptr;
}
if(currentFrame!=nullptr) {
int result = 0;
if(dacDevice!=nullptr) result = dacDevice->SendFrame(pps, HELIOS_FLAGS_SINGLE_MODE, currentFrame->samples, currentFrame->numSamples);
//ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame : "+ ofToString(result));
if(result <=-5000){ // then we have a USB connection error
ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame failed. LIBUSB error : "+ ofToString(result));
if(result!=-5007) setConnected(false); // time out error
} else if(result!=HELIOS_SUCCESS) {
ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame failed. Error : "+ ofToString(result));
setConnected(false);
} else {
setConnected(true);
}
}
} else {
// DO RECONNECT
//resetFlag = false;
// TODO : handle reconnection better
// try to reconnect!
if(isThreadRunning()) {
if(lock()) {
if(connectToDevice(deviceName)) {
setConnected(true);
// wait half a second?
unlock();
} else {
unlock();
for(size_t i = 0; (i<10)&&(isThreadRunning()); i++ ) {
sleep(50);
}
}
}
yield();
}
}
}
//free(samples);
}
void DacHelios :: setConnected(bool state) {
if(connected!=state) {
while(!lock()){};
connected = state;
if(!connected) {
//heliosManager.deviceDisconnected(deviceName);
armed = !newArmed;
heliosManager.deleteDevice(dacDevice);
dacDevice = nullptr;
}
ofLogNotice("Helios Dac changed connection state : "+ofToString(connected));
unlock();
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (C) 2013 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @ file md25.cpp
*
* Driver for MD25 I2C Motor Driver
*
* references:
* http://www.robot-electronics.co.uk/htm/md25tech.htm
* http://www.robot-electronics.co.uk/files/rpi_md25.c
*
*/
#include <nuttx/config.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <systemlib/systemlib.h>
#include <systemlib/param/param.h>
#include <arch/board/board.h>
#include "MD25.hpp"
static bool thread_should_exit = false; /**< Deamon exit flag */
static bool thread_running = false; /**< Deamon status flag */
static int deamon_task; /**< Handle of deamon task / thread */
/**
* Deamon management function.
*/
extern "C" __EXPORT int md25_main(int argc, char *argv[]);
/**
* Mainloop of deamon.
*/
int md25_thread_main(int argc, char *argv[]);
/**
* Print the correct usage.
*/
static void usage(const char *reason);
static void
usage(const char *reason)
{
if (reason)
fprintf(stderr, "%s\n", reason);
fprintf(stderr, "usage: md25 {start|stop|status|search|test|change_address}\n\n");
exit(1);
}
/**
* The deamon app only briefly exists to start
* the background job. The stack size assigned in the
* Makefile does only apply to this management task.
*
* The actual stack size should be set in the call
* to task_create().
*/
int md25_main(int argc, char *argv[])
{
if (argc < 1)
usage("missing command");
if (!strcmp(argv[1], "start")) {
if (thread_running) {
printf("md25 already running\n");
/* this is not an error */
exit(0);
}
thread_should_exit = false;
deamon_task = task_spawn("md25",
SCHED_DEFAULT,
SCHED_PRIORITY_MAX - 10,
2048,
md25_thread_main,
(const char **)argv);
exit(0);
}
if (!strcmp(argv[1], "test")) {
if (argc < 4) {
printf("usage: md25 test bus address\n");
exit(0);
}
const char *deviceName = "/dev/md25";
uint8_t bus = strtoul(argv[2], nullptr, 0);
uint8_t address = strtoul(argv[3], nullptr, 0);
md25Test(deviceName, bus, address);
exit(0);
}
if (!strcmp(argv[1], "probe")) {
if (argc < 4) {
printf("usage: md25 probe bus address\n");
exit(0);
}
const char *deviceName = "/dev/md25";
uint8_t bus = strtoul(argv[2], nullptr, 0);
uint8_t address = strtoul(argv[3], nullptr, 0);
MD25 md25(deviceName, bus, address);
int ret = md25.probe();
if (ret == OK) {
printf("MD25 found on bus %d at address 0x%X\n", bus, md25.get_address());
} else {
printf("MD25 not found on bus %d\n", bus);
}
exit(0);
}
if (!strcmp(argv[1], "search")) {
if (argc < 3) {
printf("usage: md25 search bus\n");
exit(0);
}
const char *deviceName = "/dev/md25";
uint8_t bus = strtoul(argv[2], nullptr, 0);
uint8_t address = strtoul(argv[3], nullptr, 0);
MD25 md25(deviceName, bus, address);
md25.search();
exit(0);
}
if (!strcmp(argv[1], "change_address")) {
if (argc < 5) {
printf("usage: md25 change_address bus old_address new_address\n");
exit(0);
}
const char *deviceName = "/dev/md25";
uint8_t bus = strtoul(argv[2], nullptr, 0);
uint8_t old_address = strtoul(argv[3], nullptr, 0);
uint8_t new_address = strtoul(argv[4], nullptr, 0);
MD25 md25(deviceName, bus, old_address);
int ret = md25.setDeviceAddress(new_address);
if (ret == OK) {
printf("MD25 new address set to 0x%X\n", new_address);
} else {
printf("MD25 failed to set address to 0x%X\n", new_address);
}
exit(0);
}
if (!strcmp(argv[1], "stop")) {
thread_should_exit = true;
exit(0);
}
if (!strcmp(argv[1], "status")) {
if (thread_running) {
printf("\tmd25 app is running\n");
} else {
printf("\tmd25 app not started\n");
}
exit(0);
}
usage("unrecognized command");
exit(1);
}
int md25_thread_main(int argc, char *argv[])
{
printf("[MD25] starting\n");
if (argc < 5) {
// extra md25 in arg list since this is a thread
printf("usage: md25 start bus address\n");
exit(0);
}
const char *deviceName = "/dev/md25";
uint8_t bus = strtoul(argv[3], nullptr, 0);
uint8_t address = strtoul(argv[4], nullptr, 0);
// start
MD25 md25("/dev/md25", bus, address);
thread_running = true;
// loop
while (!thread_should_exit) {
md25.update();
}
// exit
printf("[MD25] exiting.\n");
thread_running = false;
return 0;
}
// vi:noet:smarttab:autoindent:ts=4:sw=4:tw=78
<commit_msg>fix capitalisation of include file name<commit_after>/****************************************************************************
*
* Copyright (C) 2013 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @ file md25.cpp
*
* Driver for MD25 I2C Motor Driver
*
* references:
* http://www.robot-electronics.co.uk/htm/md25tech.htm
* http://www.robot-electronics.co.uk/files/rpi_md25.c
*
*/
#include <nuttx/config.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <systemlib/systemlib.h>
#include <systemlib/param/param.h>
#include <arch/board/board.h>
#include "md25.hpp"
static bool thread_should_exit = false; /**< Deamon exit flag */
static bool thread_running = false; /**< Deamon status flag */
static int deamon_task; /**< Handle of deamon task / thread */
/**
* Deamon management function.
*/
extern "C" __EXPORT int md25_main(int argc, char *argv[]);
/**
* Mainloop of deamon.
*/
int md25_thread_main(int argc, char *argv[]);
/**
* Print the correct usage.
*/
static void usage(const char *reason);
static void
usage(const char *reason)
{
if (reason)
fprintf(stderr, "%s\n", reason);
fprintf(stderr, "usage: md25 {start|stop|status|search|test|change_address}\n\n");
exit(1);
}
/**
* The deamon app only briefly exists to start
* the background job. The stack size assigned in the
* Makefile does only apply to this management task.
*
* The actual stack size should be set in the call
* to task_create().
*/
int md25_main(int argc, char *argv[])
{
if (argc < 1)
usage("missing command");
if (!strcmp(argv[1], "start")) {
if (thread_running) {
printf("md25 already running\n");
/* this is not an error */
exit(0);
}
thread_should_exit = false;
deamon_task = task_spawn("md25",
SCHED_DEFAULT,
SCHED_PRIORITY_MAX - 10,
2048,
md25_thread_main,
(const char **)argv);
exit(0);
}
if (!strcmp(argv[1], "test")) {
if (argc < 4) {
printf("usage: md25 test bus address\n");
exit(0);
}
const char *deviceName = "/dev/md25";
uint8_t bus = strtoul(argv[2], nullptr, 0);
uint8_t address = strtoul(argv[3], nullptr, 0);
md25Test(deviceName, bus, address);
exit(0);
}
if (!strcmp(argv[1], "probe")) {
if (argc < 4) {
printf("usage: md25 probe bus address\n");
exit(0);
}
const char *deviceName = "/dev/md25";
uint8_t bus = strtoul(argv[2], nullptr, 0);
uint8_t address = strtoul(argv[3], nullptr, 0);
MD25 md25(deviceName, bus, address);
int ret = md25.probe();
if (ret == OK) {
printf("MD25 found on bus %d at address 0x%X\n", bus, md25.get_address());
} else {
printf("MD25 not found on bus %d\n", bus);
}
exit(0);
}
if (!strcmp(argv[1], "search")) {
if (argc < 3) {
printf("usage: md25 search bus\n");
exit(0);
}
const char *deviceName = "/dev/md25";
uint8_t bus = strtoul(argv[2], nullptr, 0);
uint8_t address = strtoul(argv[3], nullptr, 0);
MD25 md25(deviceName, bus, address);
md25.search();
exit(0);
}
if (!strcmp(argv[1], "change_address")) {
if (argc < 5) {
printf("usage: md25 change_address bus old_address new_address\n");
exit(0);
}
const char *deviceName = "/dev/md25";
uint8_t bus = strtoul(argv[2], nullptr, 0);
uint8_t old_address = strtoul(argv[3], nullptr, 0);
uint8_t new_address = strtoul(argv[4], nullptr, 0);
MD25 md25(deviceName, bus, old_address);
int ret = md25.setDeviceAddress(new_address);
if (ret == OK) {
printf("MD25 new address set to 0x%X\n", new_address);
} else {
printf("MD25 failed to set address to 0x%X\n", new_address);
}
exit(0);
}
if (!strcmp(argv[1], "stop")) {
thread_should_exit = true;
exit(0);
}
if (!strcmp(argv[1], "status")) {
if (thread_running) {
printf("\tmd25 app is running\n");
} else {
printf("\tmd25 app not started\n");
}
exit(0);
}
usage("unrecognized command");
exit(1);
}
int md25_thread_main(int argc, char *argv[])
{
printf("[MD25] starting\n");
if (argc < 5) {
// extra md25 in arg list since this is a thread
printf("usage: md25 start bus address\n");
exit(0);
}
const char *deviceName = "/dev/md25";
uint8_t bus = strtoul(argv[3], nullptr, 0);
uint8_t address = strtoul(argv[4], nullptr, 0);
// start
MD25 md25("/dev/md25", bus, address);
thread_running = true;
// loop
while (!thread_should_exit) {
md25.update();
}
// exit
printf("[MD25] exiting.\n");
thread_running = false;
return 0;
}
// vi:noet:smarttab:autoindent:ts=4:sw=4:tw=78
<|endoftext|>
|
<commit_before><commit_msg>clang<commit_after><|endoftext|>
|
<commit_before>#include "SilentCompiler.h"
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
//File reader
class fileReader{
public:
fileReader()
{
}
string readAllText(string path)
{
string output;
ifstream file(path);
output.assign((istreambuf_iterator<char>(file)),
(istreambuf_iterator<char>()));
return output;
}
vector<string> readAllLines(string path)
{
vector<string> output;
ifstream file(path);
//if(source.is_open())
return output;
}
string readLine(string path)
{
string output;
ifstream file(path);
return output;
}
};
//Compiler structures
enum silentTokenType
{
//Symbols
silentPlusToken,
silentMinusToken,
silentMultiplyToken,
silentDivideToken,
silentParenthesToken,
silentQuotationToken,
silentSemicolonToken,
//Structure
silentClassToken,
silentFunctionToken,
silentStructToken,
silentArrayToken,
//Access
silentPublicToken,
silentPrivateToken,
silentProtectedToken,
//Data
silentByteToken,
silentIntegerToken,
silentFloatToken,
silentLongToken,
silentDoubleToken,
silentStringToken,
};
typedef struct silentToken
{
silentTokenType type;
std::string value;
}silentToken;
enum silentNodeType
{
//Value
silentCharacterNode,
silentStringNode,
silentIntegerNode,
silentLongNode,
silentFloatNode,
silentDoubleNode,
//Functionality
silentAdditionNode,
silentSubtractionNode,
silentMultiplicationNode,
silentDivisionNode,
silentAssignNode,
silentReturnNode,
//Structure
silentIfNode,
silentWhileNode,
silentForNode,
};
typedef struct silentValueNode
{
silentNodeType type;
string value;
}silentValueNode;
typedef struct silentExpressionNode
{
silentNodeType type;
silentValueNode parameters[2];
}silentExpressionNode;
typedef struct silentFunctionNode
{
}silentFunctionNode;
//Helper functions
char silentTestLetter(char character)
{
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for(int i = 0; i < letters.length(); i++)
{
if(character == letters[i])
{
return 1;
break;
}
}
return 0;
}
char silentTestNumber(char character)
{
string numbers = "1234567890";
for(int i = 0; i < numbers.length(); i++)
{
if(character == numbers[i])
{
return 1;
break;
}
}
return 0;
}
char silentTestWhitespace(char character)
{
if(isspace(character))
{
return 1;
}
else
{
return 0;
}
}
//Tokenizer
vector<silentToken> silentTokenize(string source)
{
long currentChar = 0;
long currentLine = 0;
vector<silentToken> tokens;
for(int i = 0; i < source.length(); i++)
{
}
return tokens;
}
//Parser
//Transform
//Code Generation
string* silentCompile(string path)
{
fileReader fr;
string rawSource = fr.readAllText(path);//no AST
vector<silentToken> tokens = silentTokenize(rawSource);
}
<commit_msg>add to tokenizer<commit_after>#include "SilentCompiler.h"
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
//File reader
class fileReader{
public:
fileReader()
{
}
//Read all characters from a file
string readAllText(string path)
{
string output;
ifstream file(path);
output.assign((istreambuf_iterator<char>(file)),
(istreambuf_iterator<char>()));
return output;
}
//Read all lines from a file
vector<string> readAllLines(string path)
{
vector<string> output;
ifstream file(path);
//if(source.is_open())
return output;
}
//Read a single line from a file
string readLine(string path)
{
string output;
ifstream file(path);
return output;
}
};
//Compiler structures
enum silentTokenType
{
//Symbols
silentPlusToken,
silentMinusToken,
silentMultiplyToken,
silentDivideToken,
silentParenthesToken,
silentQuotationToken,
silentSemicolonToken,
//Structure
silentClassToken,
silentFunctionToken,
silentStructToken,
silentArrayToken,
//Access
silentPublicToken,
silentPrivateToken,
silentProtectedToken,
//Data
silentByteToken,
silentIntegerToken,
silentFloatToken,
silentLongToken,
silentDoubleToken,
silentStringToken,
};
typedef struct silentToken
{
silentTokenType type;
std::string value;
}silentToken;
enum silentNodeType
{
//Value
silentCharacterNode,
silentStringNode,
silentIntegerNode,
silentLongNode,
silentFloatNode,
silentDoubleNode,
//Functionality
silentAdditionNode,
silentSubtractionNode,
silentMultiplicationNode,
silentDivisionNode,
silentAssignNode,
silentReturnNode,
//Structure
silentIfNode,
silentWhileNode,
silentForNode,
};
typedef struct silentValueNode
{
silentNodeType type;
string value;
}silentValueNode;
typedef struct silentExpressionNode
{
silentNodeType type;
silentValueNode parameters[2];
}silentExpressionNode;
typedef struct silentFunctionNode
{
vector<silentExpressionNode> expressions;
}silentFunctionNode;
//Helper functions
//Test whether the passed token is a character
char silentTestLetter(char character)
{
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for(int i = 0; i < letters.length(); i++)
{
if(character == letters[i])
{
return 1;
break;
}
}
return 0;
}
//Test whether the passed token is a number
char silentTestNumber(char character)
{
string numbers = "1234567890";
for(int i = 0; i < numbers.length(); i++)
{
if(character == numbers[i])
{
return 1;
break;
}
}
return 0;
}
//Test whether the passed token is whitespace
char silentTestWhitespace(char character)
{
if(isspace(character))
{
return 1;
}
else
{
return 0;
}
}
//Tokenizer
vector<silentToken> silentTokenize(string source)
{
long currentChar = 0;
long currentLine = 0;
vector<silentToken> tokens;
for(int i = 0; i < source.length(); i++)
{
silentToken token;
if((source[i] == *"(") || (source[i] == *")"))
{
token.type = silentParenthesToken;
token.value = source[i];
}
if(source[i] == *"\"")
{
token.type = silentQuotationToken;
token.value = "";
for(int j = 1; source[i+j] != *"\"";j++)
{
token.value += source[i+j];
}
}
if(silentTestWhitespace(source[i]))
{
continue;
}
tokens.push_back(token);
}
return tokens;
}
//Parser
//Transform
//Code Generation
string* silentCompile(string path)
{
fileReader fr;
string rawSource = fr.readAllText(path);//no AST
vector<silentToken> tokens = silentTokenize(rawSource);
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// Copyright (c) 2020 John D. Haughton
//
// 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 <atomic>
#include <cstdint>
#include <thread>
#include "MTL/Metal.h"
#include "GUI/Frame.h"
#include "PLT/Event.h"
std::atomic<uint8_t> gpio{0};
class VirtualDevice
{
public:
VirtualDevice()
{
frame.clear(STB::BLACK);
frame.refresh();
PLT::Event::setTimer(50);
}
int eventLoop()
{
return PLT::Event::eventLoop(callback, this);
}
private:
static void callback(const PLT::Event::Message& event, void* ptr)
{
VirtualDevice* that = (VirtualDevice*)ptr;
switch(event.type)
{
case PLT::Event::TIMER:
that->redraw();
break;
default:
break;
}
}
void redraw()
{
for(size_t i=0; i<8; i++)
{
bool state = ((gpio >> i) & 1) != 0;
if (state)
{
frame.fillRect(STB::RED, 10 + i * 40, 10, 30 + i * 40, 25);
}
else
{
frame.fillRect(STB::GREEN, 10 + i * 40, 10, 30 + i * 40, 25);
}
}
frame.refresh();
}
GUI::Frame frame{"Metal", 400, 100};
};
int main()
{
VirtualDevice device;
std::thread thread{mtlMain};
thread.detach();
return device.eventLoop();
}
<commit_msg>Some tidy of the virtual metal platform<commit_after>//------------------------------------------------------------------------------
// Copyright (c) 2020 John D. Haughton
//
// 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 <atomic>
#include <cstdint>
#include <thread>
#include "MTL/Metal.h"
#include "GUI/Frame.h"
#include "PLT/Event.h"
std::atomic<uint8_t> gpio{0};
//! Virtual Metal platform
class VirtualMetalPlatform
{
public:
VirtualMetalPlatform()
{
frame.clear(STB::BLACK);
frame.refresh();
PLT::Event::setTimer(1000 / REFRESH_RATE_HZ);
}
int eventLoop()
{
return PLT::Event::eventLoop(callback, this);
}
private:
static void callback(const PLT::Event::Message& event, void* ptr)
{
VirtualMetalPlatform* that = (VirtualMetalPlatform*)ptr;
that->handleEvent(event);
}
void handleEvent(const PLT::Event::Message& event)
{
switch(event.type)
{
case PLT::Event::TIMER:
if (launch_application)
{
launch_application = false;
// Start the metal application
std::thread thread{mtlMain};
thread.detach();
}
redraw();
break;
default:
break;
}
}
void drawLED(unsigned x, unsigned y, bool state)
{
STB::Colour colour = state ? STB::RED
: STB::RGB(0x40, 0, 0);
frame.fillRect(colour, x, y, x + 20, y + 15);
}
void redraw()
{
for(size_t i=0; i<8; i++)
{
unsigned x = 10 + (8 - i) * 40;
unsigned y = 10;
bool state = ((gpio >> i) & 1) != 0;
drawLED(x, y, state);
}
frame.refresh();
}
static const unsigned REFRESH_RATE_HZ = 20;
GUI::Frame frame{"Metal", 400, 100};
bool launch_application{true};
};
int main()
{
return VirtualMetalPlatform().eventLoop();
}
<|endoftext|>
|
<commit_before>/*
** Copyright 2011 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <QCoreApplication>
#include <QMutexLocker>
#include <QReadLocker>
#include <QTimer>
#include <QWriteLocker>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/exceptions/with_pointer.hh"
#include "com/centreon/broker/io/exceptions/shutdown.hh"
#include "com/centreon/broker/io/raw.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/publisher.hh"
#include "com/centreon/broker/multiplexing/subscriber.hh"
#include "com/centreon/broker/processing/failover.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::processing;
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Constructor.
*
* @param[in] is_out true if the failover thread is an output thread.
*/
failover::failover(bool is_out)
: _initial(true),
_is_out(is_out),
_retry_interval(30),
_immediate(true),
_should_exit(false),
_should_exitm(QMutex::Recursive) {
if (_is_out)
_from = QSharedPointer<io::stream>(new multiplexing::subscriber);
else
_to = QSharedPointer<io::stream>(new multiplexing::publisher);
}
/**
* Copy constructor.
*
* @param[in] f Object to copy.
*/
failover::failover(failover const& f)
: QThread(),
io::stream(),
_endpoint(f._endpoint),
_failover(f._failover),
_initial(true),
_is_out(f._is_out),
_retry_interval(f._retry_interval),
_immediate(true),
_should_exit(false),
_should_exitm(QMutex::Recursive) {
{
QMutexLocker lock(&f._datam);
_data = f._data;
}
{
QWriteLocker lock(&f._fromm);
_from = f._from;
}
{
QWriteLocker lock(&f._tom);
_to = f._to;
}
}
/**
* Destructor.
*/
failover::~failover() {}
/**
* Assignment operator.
*
* @param[in] f Object to copy.
*
* @return This object.
*/
failover& failover::operator=(failover const& f) {
if (this != &f) {
_endpoint = f._endpoint;
_failover = f._failover;
_is_out = f._is_out;
_retry_interval = f._retry_interval;
{
QMutexLocker lock(&f._datam);
_data = f._data;
}
{
QWriteLocker lock(&f._fromm);
_from = f._from;
}
{
QWriteLocker lock(&f._tom);
_to = f._to;
}
}
return (*this);
}
/**
* Get retry interval.
*
* @return Failover thread retry interval.
*/
time_t failover::get_retry_interval() const throw () {
return (_retry_interval);
}
/**
* Stop or start processing.
*
* @param[in] in true to process inputs.
* @param[in] out true to process outputs.
*/
void failover::process(bool in, bool out) {
// Set exit flag.
QMutexLocker lock(&_should_exitm);
bool should_exit = _should_exit;
_immediate = (!in && out);
_should_exit = (!in || !out);
// Quit event loop.
if ((!in || !out) && isRunning()) {
QTimer::singleShot(0, this, SLOT(quit()));
QCoreApplication::processEvents();
}
// Full delayed shutdown.
if (!in && !out) {
_endpoint->close();
bool tweaked_in(_failover.isNull());
QReadLocker lock(&_fromm);
if (!_from.isNull())
_from->process(tweaked_in, false);
}
// Single delayed shutdown.
else if (in && !out) {
_endpoint->close();
QReadLocker lock(&_fromm);
if (!_from.isNull())
_from->process(true, false);
}
// Immediate shutdown.
else if (!in && out) {
_endpoint->close();
QList<QSharedPointer<QMutexLocker> > locks;
bool all_failover_not_running(true);
failover* last(this);
for (QSharedPointer<failover> fo = _failover;
!fo.isNull();
fo = fo->_failover) {
QSharedPointer<QMutexLocker>
lock(new QMutexLocker(&fo->_should_exitm));
all_failover_not_running
= all_failover_not_running && !fo->isRunning();
locks.push_back(lock);
last = fo.data();
}
// Shutdown subscriber.
if (all_failover_not_running) {
QReadLocker rl(&last->_fromm);
if (!last->_from.isNull())
last->_from->process(false, true);
}
// Wait for thread to terminate.
locks.clear();
lock.unlock();
QThread::wait();
logging::debug(logging::medium) << "failover: thread "
<< this << " terminated";
lock.relock();
process(true, !should_exit);
lock.unlock();
}
// Reinitialization.
else {
QReadLocker rl(&_fromm);
if (!_from.isNull())
_from->process(true, true);
}
return ;
}
/**
* Read data.
*
* @param[out] data Data buffer.
* @param[out] type Data type.
*/
QSharedPointer<io::data> failover::read() {
// Read retained data.
QSharedPointer<io::data> data;
QMutexLocker exit_lock(&_should_exitm);
if (isRunning() && QThread::currentThread() != this) {
// Release thread lock.
exit_lock.unlock();
// Read data from destination.
logging::debug(logging::low)
<< "failover: reading retained data from failover thread";
bool caught(false);
QReadLocker tom(&_tom);
try {
if (!_to.isNull())
data = _to->read();
logging::debug(logging::low)
<< "failover: got retained event from failover thread";
}
catch (...) {
caught = true;
}
// End of destination is reached, shutdown this thread.
if (caught || data.isNull()) {
logging::debug(logging::low)
<< "failover: could not get event from failover thread "
<< this;
logging::info(logging::medium)
<< "failover: requesting failover thread " << this
<< " termination";
// Reset lock.
_to.clear();
_tom.unlock();
// Reread should exit.
exit_lock.relock();
bool should_exit(_should_exit);
exit_lock.unlock();
// Exit this thread immediately.
process(false, true);
// Recursive data reading.
if (!should_exit)
data = this->read();
}
}
// Fetch next available event.
else {
// Release thread lock.
exit_lock.unlock();
// Try the one retained event.
QMutexLocker lock(&_datam);
if (!_data.isNull()) {
data = _data;
_data.clear();
lock.unlock();
}
// Read from source.
else {
lock.unlock();
QReadLocker fromm(&_fromm);
data = _from->read();
}
logging::debug(logging::low)
<< "failover: got event from normal source";
}
return (data);
}
/**
* Thread core function.
*/
void failover::run() {
// Check endpoint.
if (_endpoint.isNull()) {
logging::error(logging::high) << "failover: attempt to run a " \
"thread with a non-existent endpoint";
return ;
}
// Launch subfailover to fetch retained data.
if (_initial && !_failover.isNull()) {
connect(&*_failover, SIGNAL(exception_caught()), SLOT(quit()));
connect(&*_failover, SIGNAL(initial_lock()), SLOT(quit()));
connect(&*_failover, SIGNAL(finished()), SLOT(quit()));
connect(&*_failover, SIGNAL(terminated()), SLOT(quit()));
_failover->start();
exec();
disconnect(
&*_failover,
SIGNAL(exception_caught()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(initial_lock()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(finished()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(terminated()),
this,
SLOT(quit()));
_initial = false;
}
// Failover should continue as long as not exit request was received.
logging::debug(logging::medium) << "failover: launching loop";
QMutexLocker exit_lock(&_should_exitm);
_should_exit = false;
while (!_should_exit) {
QSharedPointer<io::stream> copy_handler;
exit_lock.unlock();
try {
// Close previous endpoint if any and then open it.
logging::debug(logging::medium) << "failover: opening endpoint";
QReadWriteLock* rwl;
QSharedPointer<io::stream>* s;
if (_is_out) {
rwl = &_tom;
s = &_to;
}
else {
rwl = &_fromm;
s = &_from;
}
{
QWriteLocker wl(rwl);
s->clear();
wl.unlock();
QSharedPointer<io::stream> tmp(_endpoint->open());
wl.relock();
emit initial_lock();
*s = tmp;
if (s->isNull()) { // Retry connection.
logging::debug(logging::medium)
<< "failover: resulting stream is nul, retrying";
exit_lock.relock();
continue ;
}
copy_handler = *s;
}
// Process input and output.
logging::debug(logging::medium) << "failover: launching feeding";
QSharedPointer<io::data> data;
exit_lock.relock();
while (!_should_exit || !_immediate) {
exit_lock.unlock();
try {
{
QReadLocker lock(&_fromm);
if (!_from.isNull())
data = _from->read();
}
if (data.isNull()) {
exit_lock.relock();
_immediate = true;
_should_exit = true;
exit_lock.unlock();
}
else {
QWriteLocker lock(&_tom);
if (!_to.isNull())
_to->write(data);
}
}
catch (exceptions::msg const& e) {
try {
throw (exceptions::with_pointer(e, data));
}
catch (exceptions::with_pointer const& e) {
throw ;
}
catch (...) {}
throw ;
}
data.clear();
exit_lock.relock();
}
}
catch (exceptions::with_pointer const& e) {
logging::error(logging::high) << e.what();
if (!e.ptr().isNull() && !_failover.isNull() && !_failover->isRunning())
_failover->write(e.ptr());
}
catch (io::exceptions::shutdown const& e) {
logging::info(logging::medium)
<< "failover: a stream has shutdown: " << e.what();
}
catch (exceptions::msg const& e) {
logging::error(logging::high) << e.what();
}
catch (std::exception const& e) {
logging::error(logging::high)
<< "failover: standard library error: " << e.what();
}
catch (...) {
logging::error(logging::high)
<< "failover: unknown error caught in processing thread";
}
emit exception_caught();
if (_is_out) {
QWriteLocker lock(&_tom);
_to.clear();
}
else {
QWriteLocker lock(&_fromm);
_from.clear();
}
// Relock thread lock.
exit_lock.relock();
if (!_failover.isNull() && !_failover->isRunning() && !_should_exit) {
connect(&*_failover, SIGNAL(exception_caught()), SLOT(quit()));
connect(&*_failover, SIGNAL(initial_lock()), SLOT(quit()));
connect(&*_failover, SIGNAL(finished()), SLOT(quit()));
connect(&*_failover, SIGNAL(terminated()), SLOT(quit()));
_failover->start();
exec();
disconnect(
&*_failover,
SIGNAL(exception_caught()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(initial_lock()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(finished()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(terminated()),
this,
SLOT(quit()));
}
if (!_should_exit) {
// Unlock thread lock.
exit_lock.unlock();
logging::info(logging::medium) << "failover: sleeping "
<< _retry_interval << " seconds before reconnection";
QTimer::singleShot(_retry_interval * 1000, this, SLOT(quit()));
exec();
// Relock thread lock.
exit_lock.relock();
}
}
return ;
}
/**
* Set thread endpoint.
*
* @param[in] endp Thread endpoint.
*/
void failover::set_endpoint(QSharedPointer<io::endpoint> endp) {
_endpoint = endp;
return ;
}
/**
* Set the thread's failover.
*
* @param[in] fo Thread's failover.
*/
void failover::set_failover(QSharedPointer<failover> fo) {
_failover = fo;
if (!fo.isNull() && _is_out) { // failover object will act as input for output threads.
QWriteLocker lock(&_fromm);
_from = _failover;
}
return ;
}
/**
* Set the connection retry interval.
*
* @param[in] retry_interval Time to wait between two connection
* attempts.
*/
void failover::set_retry_interval(time_t retry_interval) {
_retry_interval = retry_interval;
return ;
}
/**
* Wait for this thread to terminate along with other failovers.
*
* @param[in] time Maximum time to wait for thread termination.
*/
bool failover::wait(unsigned long time) {
if (!_failover.isNull())
_failover->wait(time);
return (this->QThread::wait(time));
}
/**
* Write data.
*
* @param[in] d Unused.
*
* @return Does not return, throw an exception.
*/
void failover::write(QSharedPointer<io::data> d) {
QMutexLocker lock(&_datam);
_data = d;
return ;
}
<commit_msg>Add QThread::wait into the failover destructor.<commit_after>/*
** Copyright 2011 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <QCoreApplication>
#include <QMutexLocker>
#include <QReadLocker>
#include <QTimer>
#include <QWriteLocker>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/exceptions/with_pointer.hh"
#include "com/centreon/broker/io/exceptions/shutdown.hh"
#include "com/centreon/broker/io/raw.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/publisher.hh"
#include "com/centreon/broker/multiplexing/subscriber.hh"
#include "com/centreon/broker/processing/failover.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::processing;
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Constructor.
*
* @param[in] is_out true if the failover thread is an output thread.
*/
failover::failover(bool is_out)
: _initial(true),
_is_out(is_out),
_retry_interval(30),
_immediate(true),
_should_exit(false),
_should_exitm(QMutex::Recursive) {
if (_is_out)
_from = QSharedPointer<io::stream>(new multiplexing::subscriber);
else
_to = QSharedPointer<io::stream>(new multiplexing::publisher);
}
/**
* Copy constructor.
*
* @param[in] f Object to copy.
*/
failover::failover(failover const& f)
: QThread(),
io::stream(),
_endpoint(f._endpoint),
_failover(f._failover),
_initial(true),
_is_out(f._is_out),
_retry_interval(f._retry_interval),
_immediate(true),
_should_exit(false),
_should_exitm(QMutex::Recursive) {
{
QMutexLocker lock(&f._datam);
_data = f._data;
}
{
QWriteLocker lock(&f._fromm);
_from = f._from;
}
{
QWriteLocker lock(&f._tom);
_to = f._to;
}
}
/**
* Destructor.
*/
failover::~failover() { QThread::wait(); }
/**
* Assignment operator.
*
* @param[in] f Object to copy.
*
* @return This object.
*/
failover& failover::operator=(failover const& f) {
if (this != &f) {
_endpoint = f._endpoint;
_failover = f._failover;
_is_out = f._is_out;
_retry_interval = f._retry_interval;
{
QMutexLocker lock(&f._datam);
_data = f._data;
}
{
QWriteLocker lock(&f._fromm);
_from = f._from;
}
{
QWriteLocker lock(&f._tom);
_to = f._to;
}
}
return (*this);
}
/**
* Get retry interval.
*
* @return Failover thread retry interval.
*/
time_t failover::get_retry_interval() const throw () {
return (_retry_interval);
}
/**
* Stop or start processing.
*
* @param[in] in true to process inputs.
* @param[in] out true to process outputs.
*/
void failover::process(bool in, bool out) {
// Set exit flag.
QMutexLocker lock(&_should_exitm);
bool should_exit = _should_exit;
_immediate = (!in && out);
_should_exit = (!in || !out);
// Quit event loop.
if ((!in || !out) && isRunning()) {
QTimer::singleShot(0, this, SLOT(quit()));
QCoreApplication::processEvents();
}
// Full delayed shutdown.
if (!in && !out) {
_endpoint->close();
bool tweaked_in(_failover.isNull());
QReadLocker lock(&_fromm);
if (!_from.isNull())
_from->process(tweaked_in, false);
}
// Single delayed shutdown.
else if (in && !out) {
_endpoint->close();
QReadLocker lock(&_fromm);
if (!_from.isNull())
_from->process(true, false);
}
// Immediate shutdown.
else if (!in && out) {
_endpoint->close();
QList<QSharedPointer<QMutexLocker> > locks;
bool all_failover_not_running(true);
failover* last(this);
for (QSharedPointer<failover> fo = _failover;
!fo.isNull();
fo = fo->_failover) {
QSharedPointer<QMutexLocker>
lock(new QMutexLocker(&fo->_should_exitm));
all_failover_not_running
= all_failover_not_running && !fo->isRunning();
locks.push_back(lock);
last = fo.data();
}
// Shutdown subscriber.
if (all_failover_not_running) {
QReadLocker rl(&last->_fromm);
if (!last->_from.isNull())
last->_from->process(false, true);
}
// Wait for thread to terminate.
locks.clear();
lock.unlock();
QThread::wait();
logging::debug(logging::medium) << "failover: thread "
<< this << " terminated";
lock.relock();
process(true, !should_exit);
lock.unlock();
}
// Reinitialization.
else {
QReadLocker rl(&_fromm);
if (!_from.isNull())
_from->process(true, true);
}
return ;
}
/**
* Read data.
*
* @param[out] data Data buffer.
* @param[out] type Data type.
*/
QSharedPointer<io::data> failover::read() {
// Read retained data.
QSharedPointer<io::data> data;
QMutexLocker exit_lock(&_should_exitm);
if (isRunning() && QThread::currentThread() != this) {
// Release thread lock.
exit_lock.unlock();
// Read data from destination.
logging::debug(logging::low)
<< "failover: reading retained data from failover thread";
bool caught(false);
QReadLocker tom(&_tom);
try {
if (!_to.isNull())
data = _to->read();
logging::debug(logging::low)
<< "failover: got retained event from failover thread";
}
catch (...) {
caught = true;
}
// End of destination is reached, shutdown this thread.
if (caught || data.isNull()) {
logging::debug(logging::low)
<< "failover: could not get event from failover thread "
<< this;
logging::info(logging::medium)
<< "failover: requesting failover thread " << this
<< " termination";
// Reset lock.
_to.clear();
_tom.unlock();
// Reread should exit.
exit_lock.relock();
bool should_exit(_should_exit);
exit_lock.unlock();
// Exit this thread immediately.
process(false, true);
// Recursive data reading.
if (!should_exit)
data = this->read();
}
}
// Fetch next available event.
else {
// Release thread lock.
exit_lock.unlock();
// Try the one retained event.
QMutexLocker lock(&_datam);
if (!_data.isNull()) {
data = _data;
_data.clear();
lock.unlock();
}
// Read from source.
else {
lock.unlock();
QReadLocker fromm(&_fromm);
data = _from->read();
}
logging::debug(logging::low)
<< "failover: got event from normal source";
}
return (data);
}
/**
* Thread core function.
*/
void failover::run() {
// Check endpoint.
if (_endpoint.isNull()) {
logging::error(logging::high) << "failover: attempt to run a " \
"thread with a non-existent endpoint";
return ;
}
// Launch subfailover to fetch retained data.
if (_initial && !_failover.isNull()) {
connect(&*_failover, SIGNAL(exception_caught()), SLOT(quit()));
connect(&*_failover, SIGNAL(initial_lock()), SLOT(quit()));
connect(&*_failover, SIGNAL(finished()), SLOT(quit()));
connect(&*_failover, SIGNAL(terminated()), SLOT(quit()));
_failover->start();
exec();
disconnect(
&*_failover,
SIGNAL(exception_caught()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(initial_lock()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(finished()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(terminated()),
this,
SLOT(quit()));
_initial = false;
}
// Failover should continue as long as not exit request was received.
logging::debug(logging::medium) << "failover: launching loop";
QMutexLocker exit_lock(&_should_exitm);
_should_exit = false;
while (!_should_exit) {
QSharedPointer<io::stream> copy_handler;
exit_lock.unlock();
try {
// Close previous endpoint if any and then open it.
logging::debug(logging::medium) << "failover: opening endpoint";
QReadWriteLock* rwl;
QSharedPointer<io::stream>* s;
if (_is_out) {
rwl = &_tom;
s = &_to;
}
else {
rwl = &_fromm;
s = &_from;
}
{
QWriteLocker wl(rwl);
s->clear();
wl.unlock();
QSharedPointer<io::stream> tmp(_endpoint->open());
wl.relock();
emit initial_lock();
*s = tmp;
if (s->isNull()) { // Retry connection.
logging::debug(logging::medium)
<< "failover: resulting stream is nul, retrying";
exit_lock.relock();
continue ;
}
copy_handler = *s;
}
// Process input and output.
logging::debug(logging::medium) << "failover: launching feeding";
QSharedPointer<io::data> data;
exit_lock.relock();
while (!_should_exit || !_immediate) {
exit_lock.unlock();
try {
{
QReadLocker lock(&_fromm);
if (!_from.isNull())
data = _from->read();
}
if (data.isNull()) {
exit_lock.relock();
_immediate = true;
_should_exit = true;
exit_lock.unlock();
}
else {
QWriteLocker lock(&_tom);
if (!_to.isNull())
_to->write(data);
}
}
catch (exceptions::msg const& e) {
try {
throw (exceptions::with_pointer(e, data));
}
catch (exceptions::with_pointer const& e) {
throw ;
}
catch (...) {}
throw ;
}
data.clear();
exit_lock.relock();
}
}
catch (exceptions::with_pointer const& e) {
logging::error(logging::high) << e.what();
if (!e.ptr().isNull() && !_failover.isNull() && !_failover->isRunning())
_failover->write(e.ptr());
}
catch (io::exceptions::shutdown const& e) {
logging::info(logging::medium)
<< "failover: a stream has shutdown: " << e.what();
}
catch (exceptions::msg const& e) {
logging::error(logging::high) << e.what();
}
catch (std::exception const& e) {
logging::error(logging::high)
<< "failover: standard library error: " << e.what();
}
catch (...) {
logging::error(logging::high)
<< "failover: unknown error caught in processing thread";
}
emit exception_caught();
if (_is_out) {
QWriteLocker lock(&_tom);
_to.clear();
}
else {
QWriteLocker lock(&_fromm);
_from.clear();
}
// Relock thread lock.
exit_lock.relock();
if (!_failover.isNull() && !_failover->isRunning() && !_should_exit) {
connect(&*_failover, SIGNAL(exception_caught()), SLOT(quit()));
connect(&*_failover, SIGNAL(initial_lock()), SLOT(quit()));
connect(&*_failover, SIGNAL(finished()), SLOT(quit()));
connect(&*_failover, SIGNAL(terminated()), SLOT(quit()));
_failover->start();
exec();
disconnect(
&*_failover,
SIGNAL(exception_caught()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(initial_lock()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(finished()),
this,
SLOT(quit()));
disconnect(
&*_failover,
SIGNAL(terminated()),
this,
SLOT(quit()));
}
if (!_should_exit) {
// Unlock thread lock.
exit_lock.unlock();
logging::info(logging::medium) << "failover: sleeping "
<< _retry_interval << " seconds before reconnection";
QTimer::singleShot(_retry_interval * 1000, this, SLOT(quit()));
exec();
// Relock thread lock.
exit_lock.relock();
}
}
return ;
}
/**
* Set thread endpoint.
*
* @param[in] endp Thread endpoint.
*/
void failover::set_endpoint(QSharedPointer<io::endpoint> endp) {
_endpoint = endp;
return ;
}
/**
* Set the thread's failover.
*
* @param[in] fo Thread's failover.
*/
void failover::set_failover(QSharedPointer<failover> fo) {
_failover = fo;
if (!fo.isNull() && _is_out) { // failover object will act as input for output threads.
QWriteLocker lock(&_fromm);
_from = _failover;
}
return ;
}
/**
* Set the connection retry interval.
*
* @param[in] retry_interval Time to wait between two connection
* attempts.
*/
void failover::set_retry_interval(time_t retry_interval) {
_retry_interval = retry_interval;
return ;
}
/**
* Wait for this thread to terminate along with other failovers.
*
* @param[in] time Maximum time to wait for thread termination.
*/
bool failover::wait(unsigned long time) {
if (!_failover.isNull())
_failover->wait(time);
return (this->QThread::wait(time));
}
/**
* Write data.
*
* @param[in] d Unused.
*
* @return Does not return, throw an exception.
*/
void failover::write(QSharedPointer<io::data> d) {
QMutexLocker lock(&_datam);
_data = d;
return ;
}
<|endoftext|>
|
<commit_before>// #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include <iostream>
#include <chrono>
#include <thread>
#include <cassert>
#include <cstring>
#include <list>
#include <atomic>
#include <mutex>
// #include "catch.hpp"
#include "i_stat.hpp"
#include "i_probe.hpp"
#include "task_0.hpp"
#include "scheduler_0.hpp"
#include "thread_0.hpp"
using namespace std;
using namespace e2::mt;
using namespace e2::interface;
// std::mutex mtx;
int increment( int * v ){
// std::lock_guard<std::mutex> lck( mtx );
if( v ) ++(*v);
return *v;
}
int main(){
bool ret;
scheduler_0 * sch = new scheduler_0;
vector< thread_0 * > thread_allocated;
int num_threads = 3;
for( int i = 0; i < num_threads; ++i ){
thread_0 * new_t = new thread_0;
thread_allocated.push_back( new_t );
ret = sch->scheduler_process( ::e2::interface::e_scheduler_action::ADD_THREAD, new_t );
assert( ret );
}
std::vector< int > vals( 100, 0);
auto t0 = std::chrono::high_resolution_clock::now();
std::list< ::e2::mt::task_0 > tks;
int ans = 0;
// while(true){
// for( int i = 0; i < 6; ++i ){
for( int i = 0; i < 10000000; ++i ){
::e2::mt::task_0 tk;
tk.set( &ans, increment, &vals[i%2] );
tks.push_back( tk );
// bool ret = sch->scheduler_process( ::e2::interface::e_scheduler_action::ADD_TASK, &tk );
bool ret = sch->scheduler_add_task( &tks.back() );
std::this_thread::yield();
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
// auto t1 = std::chrono::high_resolution_clock::now();
// std::chrono::duration<double> dur = t1 - t0;
// auto dur_ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
// if( dur_ms.count() > 20000 )
// break;
// }
std::this_thread::sleep_for( std::chrono::milliseconds(20000) );
ret = sch->scheduler_process( ::e2::interface::e_scheduler_action::END );
assert( ret );
std::cout << "end add." << std::endl;
std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
size_t expected_count_tasks = 0;
std::cout << "vals: " << std::endl;
for( int i = 0; i < 6; ++i ){
// assert( 0 != vals[i] );
std::cout << vals[i] << std::endl;
expected_count_tasks += vals[i];
}
std::cout << "ans: " << ans << std::endl;
::e2::interface::i_stat_threads stat;
ret = sch->probe_process( ::e2::interface::e_probe_action::PROBE_FILTER_SINGLE, &stat );
assert( ret );
std::cout << "count total thread calls: " << stat._stat_count_thread_calls << std::endl;
std::cout << "num thread busy: " << stat._stat_num_thread_busy << std::endl;
std::cout << "num thread idle: " << stat._stat_num_thread_idle << std::endl;
// assert( 0 == stat._stat_count_thread_calls );
// assert( 0 == stat._stat_num_thread_busy );
// assert( 0 == stat._stat_num_thread_idle );
// ret = sch->probe_process( ::e2::interface::e_probe_action::PROBE_FILTER_SINGLE, &stat );
// assert( ret );
// std::cout << "count total thread calls: " << stat._stat_count_thread_calls << std::endl;
// std::cout << "num thread busy: " << stat._stat_num_thread_busy << std::endl;
// std::cout << "num thread idle: " << stat._stat_num_thread_idle << std::endl;
// assert( 0 == stat._stat_count_thread_calls );
// assert( 0 == stat._stat_num_thread_busy );
// assert( num_threads == stat._stat_num_thread_idle );
for( auto & i : thread_allocated ){
ret = sch->scheduler_process( ::e2::interface::e_scheduler_action::REMOVE_THREAD, i );
}
std::cout << "terminating scheduler activity." << std::endl;
for( auto & i : thread_allocated ){
if( i )
delete i;
}
delete sch;
std::cout << "terminated scheduler." << std::endl;
std::this_thread::sleep_for( std::chrono::milliseconds(20000) );
return 0;
}
<commit_msg>revised scheduler testcase.<commit_after>// #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include <iostream>
#include <chrono>
#include <thread>
#include <cassert>
#include <cstring>
#include <list>
#include <atomic>
#include <mutex>
// #include "catch.hpp"
#include "i_stat.hpp"
#include "i_probe.hpp"
#include "task_0.hpp"
#include "scheduler_0.hpp"
#include "thread_0.hpp"
using namespace std;
using namespace e2::mt;
using namespace e2::interface;
// std::mutex mtx;
int increment( int * v ){
// std::lock_guard<std::mutex> lck( mtx );
if( v ) ++(*v);
return *v;
}
int main(){
bool ret;
scheduler_0 * sch = new scheduler_0;
vector< thread_0 * > thread_allocated;
constexpr int num_threads = 3;
for( int i = 0; i < num_threads; ++i ){
thread_0 * new_t = new thread_0;
thread_allocated.push_back( new_t );
ret = sch->scheduler_process( ::e2::interface::e_scheduler_action::ADD_THREAD, new_t );
assert( ret );
}
constexpr int num_vals = 6;
std::vector< int > vals( num_vals, 0);
auto t0 = std::chrono::high_resolution_clock::now();
int ans = 0;
for( int i = 0; i < 10000000; ++i ){
::e2::mt::task_0 tk;
tk.set( &ans, increment, &vals[ i % num_vals ] );
bool ret = sch->scheduler_add_task( &tk );
auto t1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> dur = t1 - t0;
auto dur_ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
if( dur_ms.count() > 5000 ){
::e2::interface::i_stat_threads stat;
ret = sch->probe_process( ::e2::interface::e_probe_action::PROBE_FILTER_SINGLE, &stat );
assert( ret );
std::cout << "count total thread calls: " << stat._stat_count_thread_calls << std::endl;
std::cout << "num thread busy: " << stat._stat_num_thread_busy << std::endl;
std::cout << "num thread idle: " << stat._stat_num_thread_idle << std::endl;
t0 = t1;
}
}
std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
ret = sch->scheduler_process( ::e2::interface::e_scheduler_action::END );
assert( ret );
std::cout << "end add." << std::endl;
std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
bool ret_val_check = false;
size_t expected_count_tasks = 0;
std::cout << "vals: " << std::endl;
for( int i = 0; i < num_vals; ++i ){
assert( 0 != vals[i] );
std::cout << vals[i] << std::endl;
expected_count_tasks += vals[i];
if( ans == vals[i] )
ret_val_check = true;
}
std::cout << "ans: " << ans << std::endl;
assert( 0 < ans );
assert( ret_val_check );
{
::e2::interface::i_stat_threads stat;
ret = sch->probe_process( ::e2::interface::e_probe_action::PROBE_FILTER_SINGLE, &stat );
assert( ret );
std::cout << "count total thread calls: " << stat._stat_count_thread_calls << std::endl;
std::cout << "num thread busy: " << stat._stat_num_thread_busy << std::endl;
std::cout << "num thread idle: " << stat._stat_num_thread_idle << std::endl;
assert( 0 < stat._stat_count_thread_calls );
assert( 0 == stat._stat_num_thread_busy );
assert( num_threads == stat._stat_num_thread_idle );
//stat again
ret = sch->probe_process( ::e2::interface::e_probe_action::PROBE_FILTER_SINGLE, &stat );
assert( ret );
assert( 0 == stat._stat_count_thread_calls );
assert( 0 == stat._stat_num_thread_busy );
assert( num_threads == stat._stat_num_thread_idle );
}
for( auto & i : thread_allocated ){
ret = sch->scheduler_process( ::e2::interface::e_scheduler_action::REMOVE_THREAD, i );
}
std::cout << "terminating scheduler activity." << std::endl;
for( auto & i : thread_allocated ){
if( i ) delete i;
}
delete sch;
std::cout << "terminated scheduler." << std::endl;
std::this_thread::sleep_for( std::chrono::milliseconds(5000) );
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/html/HTMLImageElement.h"
#include "CSSPropertyNames.h"
#include "HTMLNames.h"
#include "bindings/v8/ScriptEventListener.h"
#include "core/dom/Attribute.h"
#include "core/dom/EventNames.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/loader/cache/CachedImage.h"
#include "core/rendering/RenderImage.h"
using namespace std;
namespace WebCore {
using namespace HTMLNames;
HTMLImageElement::HTMLImageElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
: HTMLElement(tagName, document)
, m_imageLoader(this)
, m_form(form)
, m_compositeOperator(CompositeSourceOver)
{
ASSERT(hasTagName(imgTag));
ScriptWrappable::init(this);
if (form)
form->registerImgElement(this);
}
PassRefPtr<HTMLImageElement> HTMLImageElement::create(Document* document)
{
return adoptRef(new HTMLImageElement(imgTag, document));
}
PassRefPtr<HTMLImageElement> HTMLImageElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
{
return adoptRef(new HTMLImageElement(tagName, document, form));
}
HTMLImageElement::~HTMLImageElement()
{
if (m_form)
m_form->removeImgElement(this);
}
PassRefPtr<HTMLImageElement> HTMLImageElement::createForJSConstructor(Document* document, const int* optionalWidth, const int* optionalHeight)
{
RefPtr<HTMLImageElement> image = adoptRef(new HTMLImageElement(imgTag, document));
if (optionalWidth)
image->setWidth(*optionalWidth);
if (optionalHeight)
image->setHeight(*optionalHeight);
return image.release();
}
bool HTMLImageElement::isPresentationAttribute(const QualifiedName& name) const
{
if (name == widthAttr || name == heightAttr || name == borderAttr || name == vspaceAttr || name == hspaceAttr || name == alignAttr || name == valignAttr)
return true;
return HTMLElement::isPresentationAttribute(name);
}
void HTMLImageElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
if (name == widthAttr)
addHTMLLengthToStyle(style, CSSPropertyWidth, value);
else if (name == heightAttr)
addHTMLLengthToStyle(style, CSSPropertyHeight, value);
else if (name == borderAttr)
applyBorderAttributeToStyle(value, style);
else if (name == vspaceAttr) {
addHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
addHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
} else if (name == hspaceAttr) {
addHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
addHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
} else if (name == alignAttr)
applyAlignmentAttributeToStyle(value, style);
else if (name == valignAttr)
addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, value);
else
HTMLElement::collectStyleForPresentationAttribute(name, value, style);
}
void HTMLImageElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == altAttr) {
if (renderer() && renderer()->isImage())
toRenderImage(renderer())->updateAltText();
} else if (name == srcAttr)
m_imageLoader.updateFromElementIgnoringPreviousError();
else if (name == usemapAttr)
setIsLink(!value.isNull());
else if (name == onbeforeloadAttr)
setAttributeEventListener(eventNames().beforeloadEvent, createAttributeEventListener(this, name, value));
else if (name == compositeAttr) {
// FIXME: images don't support blend modes in their compositing attribute.
BlendMode blendOp = BlendModeNormal;
if (!parseCompositeAndBlendOperator(value, m_compositeOperator, blendOp))
m_compositeOperator = CompositeSourceOver;
} else
HTMLElement::parseAttribute(name, value);
}
String HTMLImageElement::altText() const
{
// lets figure out the alt text.. magic stuff
// http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen
// also heavily discussed by Hixie on bugzilla
String alt = getAttribute(altAttr);
// fall back to title attribute
if (alt.isNull())
alt = getAttribute(titleAttr);
return alt;
}
RenderObject* HTMLImageElement::createRenderer(RenderStyle* style)
{
if (style->hasContent())
return RenderObject::createObject(this, style);
RenderImage* image = new RenderImage(this);
image->setImageResource(RenderImageResource::create());
return image;
}
bool HTMLImageElement::canStartSelection() const
{
if (shadow())
return HTMLElement::canStartSelection();
return false;
}
void HTMLImageElement::attach(const AttachContext& context)
{
HTMLElement::attach(context);
if (renderer() && renderer()->isImage() && !m_imageLoader.hasPendingBeforeLoadEvent()) {
RenderImage* renderImage = toRenderImage(renderer());
RenderImageResource* renderImageResource = renderImage->imageResource();
if (renderImageResource->hasImage())
return;
renderImageResource->setCachedImage(m_imageLoader.image());
// If we have no image at all because we have no src attribute, set
// image height and width for the alt text instead.
if (!m_imageLoader.image() && !renderImageResource->cachedImage())
renderImage->setImageSizeForAltText();
}
}
Node::InsertionNotificationRequest HTMLImageElement::insertedInto(ContainerNode* insertionPoint)
{
// m_form can be non-null if it was set in constructor.
if (!m_form) {
m_form = findFormAncestor();
if (m_form)
m_form->registerImgElement(this);
}
// If we have been inserted from a renderer-less document,
// our loader may have not fetched the image, so do it now.
if (insertionPoint->inDocument() && !m_imageLoader.image())
m_imageLoader.updateFromElement();
return HTMLElement::insertedInto(insertionPoint);
}
void HTMLImageElement::removedFrom(ContainerNode* insertionPoint)
{
if (m_form)
m_form->removeImgElement(this);
m_form = 0;
HTMLElement::removedFrom(insertionPoint);
}
int HTMLImageElement::width(bool ignorePendingStylesheets)
{
if (!renderer()) {
// check the attribute first for an explicit pixel value
bool ok;
int width = getAttribute(widthAttr).toInt(&ok);
if (ok)
return width;
// if the image is available, use its width
if (m_imageLoader.image())
return m_imageLoader.image()->imageSizeForRenderer(renderer(), 1.0f).width();
}
if (ignorePendingStylesheets)
document()->updateLayoutIgnorePendingStylesheets();
else
document()->updateLayout();
RenderBox* box = renderBox();
return box ? adjustForAbsoluteZoom(box->contentBoxRect().pixelSnappedWidth(), box) : 0;
}
int HTMLImageElement::height(bool ignorePendingStylesheets)
{
if (!renderer()) {
// check the attribute first for an explicit pixel value
bool ok;
int height = getAttribute(heightAttr).toInt(&ok);
if (ok)
return height;
// if the image is available, use its height
if (m_imageLoader.image())
return m_imageLoader.image()->imageSizeForRenderer(renderer(), 1.0f).height();
}
if (ignorePendingStylesheets)
document()->updateLayoutIgnorePendingStylesheets();
else
document()->updateLayout();
RenderBox* box = renderBox();
return box ? adjustForAbsoluteZoom(box->contentBoxRect().pixelSnappedHeight(), box) : 0;
}
int HTMLImageElement::naturalWidth() const
{
if (!m_imageLoader.image())
return 0;
return m_imageLoader.image()->imageSizeForRenderer(renderer(), 1.0f).width();
}
int HTMLImageElement::naturalHeight() const
{
if (!m_imageLoader.image())
return 0;
return m_imageLoader.image()->imageSizeForRenderer(renderer(), 1.0f).height();
}
bool HTMLImageElement::isURLAttribute(const Attribute& attribute) const
{
return attribute.name() == srcAttr
|| attribute.name() == lowsrcAttr
|| attribute.name() == longdescAttr
|| (attribute.name() == usemapAttr && attribute.value().string()[0] != '#')
|| HTMLElement::isURLAttribute(attribute);
}
const AtomicString& HTMLImageElement::alt() const
{
return getAttribute(altAttr);
}
bool HTMLImageElement::draggable() const
{
// Image elements are draggable by default.
return !equalIgnoringCase(getAttribute(draggableAttr), "false");
}
void HTMLImageElement::setHeight(int value)
{
setAttribute(heightAttr, String::number(value));
}
KURL HTMLImageElement::src() const
{
return document()->completeURL(getAttribute(srcAttr));
}
void HTMLImageElement::setSrc(const String& value)
{
setAttribute(srcAttr, value);
}
void HTMLImageElement::setWidth(int value)
{
setAttribute(widthAttr, String::number(value));
}
int HTMLImageElement::x() const
{
RenderObject* r = renderer();
if (!r)
return 0;
// FIXME: This doesn't work correctly with transforms.
FloatPoint absPos = r->localToAbsolute();
return absPos.x();
}
int HTMLImageElement::y() const
{
RenderObject* r = renderer();
if (!r)
return 0;
// FIXME: This doesn't work correctly with transforms.
FloatPoint absPos = r->localToAbsolute();
return absPos.y();
}
bool HTMLImageElement::complete() const
{
return m_imageLoader.imageComplete();
}
void HTMLImageElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
{
HTMLElement::addSubresourceAttributeURLs(urls);
addSubresourceURL(urls, src());
// FIXME: What about when the usemap attribute begins with "#"?
addSubresourceURL(urls, document()->completeURL(getAttribute(usemapAttr)));
}
void HTMLImageElement::didMoveToNewDocument(Document* oldDocument)
{
m_imageLoader.elementDidMoveToNewDocument();
HTMLElement::didMoveToNewDocument(oldDocument);
}
bool HTMLImageElement::isServerMap() const
{
if (!fastHasAttribute(ismapAttr))
return false;
const AtomicString& usemap = fastGetAttribute(usemapAttr);
// If the usemap attribute starts with '#', it refers to a map element in the document.
if (usemap.string()[0] == '#')
return false;
return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(usemap)).isEmpty();
}
Image* HTMLImageElement::imageContents()
{
if (!m_imageLoader.imageComplete())
return 0;
return m_imageLoader.image()->image();
}
}
<commit_msg>Refactor code for <img> size calculation during attach<commit_after>/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/html/HTMLImageElement.h"
#include "CSSPropertyNames.h"
#include "HTMLNames.h"
#include "bindings/v8/ScriptEventListener.h"
#include "core/dom/Attribute.h"
#include "core/dom/EventNames.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/loader/cache/CachedImage.h"
#include "core/rendering/RenderImage.h"
using namespace std;
namespace WebCore {
using namespace HTMLNames;
HTMLImageElement::HTMLImageElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
: HTMLElement(tagName, document)
, m_imageLoader(this)
, m_form(form)
, m_compositeOperator(CompositeSourceOver)
{
ASSERT(hasTagName(imgTag));
ScriptWrappable::init(this);
if (form)
form->registerImgElement(this);
}
PassRefPtr<HTMLImageElement> HTMLImageElement::create(Document* document)
{
return adoptRef(new HTMLImageElement(imgTag, document));
}
PassRefPtr<HTMLImageElement> HTMLImageElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
{
return adoptRef(new HTMLImageElement(tagName, document, form));
}
HTMLImageElement::~HTMLImageElement()
{
if (m_form)
m_form->removeImgElement(this);
}
PassRefPtr<HTMLImageElement> HTMLImageElement::createForJSConstructor(Document* document, const int* optionalWidth, const int* optionalHeight)
{
RefPtr<HTMLImageElement> image = adoptRef(new HTMLImageElement(imgTag, document));
if (optionalWidth)
image->setWidth(*optionalWidth);
if (optionalHeight)
image->setHeight(*optionalHeight);
return image.release();
}
bool HTMLImageElement::isPresentationAttribute(const QualifiedName& name) const
{
if (name == widthAttr || name == heightAttr || name == borderAttr || name == vspaceAttr || name == hspaceAttr || name == alignAttr || name == valignAttr)
return true;
return HTMLElement::isPresentationAttribute(name);
}
void HTMLImageElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
if (name == widthAttr)
addHTMLLengthToStyle(style, CSSPropertyWidth, value);
else if (name == heightAttr)
addHTMLLengthToStyle(style, CSSPropertyHeight, value);
else if (name == borderAttr)
applyBorderAttributeToStyle(value, style);
else if (name == vspaceAttr) {
addHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
addHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
} else if (name == hspaceAttr) {
addHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
addHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
} else if (name == alignAttr)
applyAlignmentAttributeToStyle(value, style);
else if (name == valignAttr)
addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, value);
else
HTMLElement::collectStyleForPresentationAttribute(name, value, style);
}
void HTMLImageElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == altAttr) {
if (renderer() && renderer()->isImage())
toRenderImage(renderer())->updateAltText();
} else if (name == srcAttr)
m_imageLoader.updateFromElementIgnoringPreviousError();
else if (name == usemapAttr)
setIsLink(!value.isNull());
else if (name == onbeforeloadAttr)
setAttributeEventListener(eventNames().beforeloadEvent, createAttributeEventListener(this, name, value));
else if (name == compositeAttr) {
// FIXME: images don't support blend modes in their compositing attribute.
BlendMode blendOp = BlendModeNormal;
if (!parseCompositeAndBlendOperator(value, m_compositeOperator, blendOp))
m_compositeOperator = CompositeSourceOver;
} else
HTMLElement::parseAttribute(name, value);
}
String HTMLImageElement::altText() const
{
// lets figure out the alt text.. magic stuff
// http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen
// also heavily discussed by Hixie on bugzilla
String alt = getAttribute(altAttr);
// fall back to title attribute
if (alt.isNull())
alt = getAttribute(titleAttr);
return alt;
}
RenderObject* HTMLImageElement::createRenderer(RenderStyle* style)
{
if (style->hasContent())
return RenderObject::createObject(this, style);
RenderImage* image = new RenderImage(this);
image->setImageResource(RenderImageResource::create());
return image;
}
bool HTMLImageElement::canStartSelection() const
{
if (shadow())
return HTMLElement::canStartSelection();
return false;
}
void HTMLImageElement::attach(const AttachContext& context)
{
HTMLElement::attach(context);
if (renderer() && renderer()->isImage() && !m_imageLoader.hasPendingBeforeLoadEvent()) {
RenderImage* renderImage = toRenderImage(renderer());
RenderImageResource* renderImageResource = renderImage->imageResource();
if (renderImageResource->hasImage())
return;
// If we have no image at all because we have no src attribute, set
// image height and width for the alt text instead.
if (!m_imageLoader.image() && !renderImageResource->cachedImage())
renderImage->setImageSizeForAltText();
else
renderImageResource->setCachedImage(m_imageLoader.image());
}
}
Node::InsertionNotificationRequest HTMLImageElement::insertedInto(ContainerNode* insertionPoint)
{
// m_form can be non-null if it was set in constructor.
if (!m_form) {
m_form = findFormAncestor();
if (m_form)
m_form->registerImgElement(this);
}
// If we have been inserted from a renderer-less document,
// our loader may have not fetched the image, so do it now.
if (insertionPoint->inDocument() && !m_imageLoader.image())
m_imageLoader.updateFromElement();
return HTMLElement::insertedInto(insertionPoint);
}
void HTMLImageElement::removedFrom(ContainerNode* insertionPoint)
{
if (m_form)
m_form->removeImgElement(this);
m_form = 0;
HTMLElement::removedFrom(insertionPoint);
}
int HTMLImageElement::width(bool ignorePendingStylesheets)
{
if (!renderer()) {
// check the attribute first for an explicit pixel value
bool ok;
int width = getAttribute(widthAttr).toInt(&ok);
if (ok)
return width;
// if the image is available, use its width
if (m_imageLoader.image())
return m_imageLoader.image()->imageSizeForRenderer(renderer(), 1.0f).width();
}
if (ignorePendingStylesheets)
document()->updateLayoutIgnorePendingStylesheets();
else
document()->updateLayout();
RenderBox* box = renderBox();
return box ? adjustForAbsoluteZoom(box->contentBoxRect().pixelSnappedWidth(), box) : 0;
}
int HTMLImageElement::height(bool ignorePendingStylesheets)
{
if (!renderer()) {
// check the attribute first for an explicit pixel value
bool ok;
int height = getAttribute(heightAttr).toInt(&ok);
if (ok)
return height;
// if the image is available, use its height
if (m_imageLoader.image())
return m_imageLoader.image()->imageSizeForRenderer(renderer(), 1.0f).height();
}
if (ignorePendingStylesheets)
document()->updateLayoutIgnorePendingStylesheets();
else
document()->updateLayout();
RenderBox* box = renderBox();
return box ? adjustForAbsoluteZoom(box->contentBoxRect().pixelSnappedHeight(), box) : 0;
}
int HTMLImageElement::naturalWidth() const
{
if (!m_imageLoader.image())
return 0;
return m_imageLoader.image()->imageSizeForRenderer(renderer(), 1.0f).width();
}
int HTMLImageElement::naturalHeight() const
{
if (!m_imageLoader.image())
return 0;
return m_imageLoader.image()->imageSizeForRenderer(renderer(), 1.0f).height();
}
bool HTMLImageElement::isURLAttribute(const Attribute& attribute) const
{
return attribute.name() == srcAttr
|| attribute.name() == lowsrcAttr
|| attribute.name() == longdescAttr
|| (attribute.name() == usemapAttr && attribute.value().string()[0] != '#')
|| HTMLElement::isURLAttribute(attribute);
}
const AtomicString& HTMLImageElement::alt() const
{
return getAttribute(altAttr);
}
bool HTMLImageElement::draggable() const
{
// Image elements are draggable by default.
return !equalIgnoringCase(getAttribute(draggableAttr), "false");
}
void HTMLImageElement::setHeight(int value)
{
setAttribute(heightAttr, String::number(value));
}
KURL HTMLImageElement::src() const
{
return document()->completeURL(getAttribute(srcAttr));
}
void HTMLImageElement::setSrc(const String& value)
{
setAttribute(srcAttr, value);
}
void HTMLImageElement::setWidth(int value)
{
setAttribute(widthAttr, String::number(value));
}
int HTMLImageElement::x() const
{
RenderObject* r = renderer();
if (!r)
return 0;
// FIXME: This doesn't work correctly with transforms.
FloatPoint absPos = r->localToAbsolute();
return absPos.x();
}
int HTMLImageElement::y() const
{
RenderObject* r = renderer();
if (!r)
return 0;
// FIXME: This doesn't work correctly with transforms.
FloatPoint absPos = r->localToAbsolute();
return absPos.y();
}
bool HTMLImageElement::complete() const
{
return m_imageLoader.imageComplete();
}
void HTMLImageElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
{
HTMLElement::addSubresourceAttributeURLs(urls);
addSubresourceURL(urls, src());
// FIXME: What about when the usemap attribute begins with "#"?
addSubresourceURL(urls, document()->completeURL(getAttribute(usemapAttr)));
}
void HTMLImageElement::didMoveToNewDocument(Document* oldDocument)
{
m_imageLoader.elementDidMoveToNewDocument();
HTMLElement::didMoveToNewDocument(oldDocument);
}
bool HTMLImageElement::isServerMap() const
{
if (!fastHasAttribute(ismapAttr))
return false;
const AtomicString& usemap = fastGetAttribute(usemapAttr);
// If the usemap attribute starts with '#', it refers to a map element in the document.
if (usemap.string()[0] == '#')
return false;
return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(usemap)).isEmpty();
}
Image* HTMLImageElement::imageContents()
{
if (!m_imageLoader.imageComplete())
return 0;
return m_imageLoader.image()->image();
}
}
<|endoftext|>
|
<commit_before>/*Santiago Zubieta*/
#include <iostream>
#include <numeric>
#include <fstream>
#include <climits>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>
using namespace std;
vector< vector<int> > graph;
int main() {
int N, M;
int numCase = 1;
while(cin >> N >> M) {
if(!N && !M) {
// Input terminates with 0 0
break;
}
graph.clear();
for(int k = 0; k <= N; k++) {
// We'll have a graph, which will be a list of list of integers. Each
// list will have the numbers each position goes to, including itself.
vector<int> v;
graph.push_back(v);
}
for(int k = 1; k <= M; k++) {
// Read the graph, define bidirectional relations, as in, p1 and p2 are
// a couple persons that belong to the same religion.
int p1, p2;
cin >> p1 >> p2;
graph[p1].push_back(p2);
graph[p2].push_back(p1);
}
for(int k = 0; k <= N; k++) {
// Then, we'll mark each number as having its own religion
graph[k].push_back(k);
}
int religions = 0;
for(int i = 1; i <= N; i++) {
// At each i (each person), the list of relations that person has is
// also the list of persons belonging to its same religion. So, all the
// persons found in this list will be 'cleared', since we don't have
// to re-check for this same religion. A person that hasn't been cle-
// ared this far belongs to a yet un-checked religion. If we didn't add
// a person to its own list of religions, the size of that person's own
// list would be 0, which would coincide with an already cleared person
// and we want this person whom we don't know anything about to count
// as its own possible religion, for finding the upper bounding limit.
if(graph[i].size() > 0) {
religions++;
}
else {
continue;
}
queue<int> q;
q.push(i);
// We'll clear the lists of the persons related to the current per-
// son, and also the lists of the persons related to those persons,
// and so on, until all people from a same religion is cleared so
// we don't check them anymore in the future.
while(q.size() > 0) {
int p1 = q.front();
q.pop();
for(int j = 0; j < graph[p1].size(); j++) {
int p2 = graph[p1][j];
q.push(p2);
}
graph[p1].clear();
}
}
cout << "Case " << numCase << ": " << religions << endl;
numCase++;
}
}<commit_msg>Added first batch of problems from Summer Training, 2014<commit_after>/*Santiago Zubieta*/
#include <iostream>
#include <numeric>
#include <fstream>
#include <climits>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>
using namespace std;
vector< vector<int> > graph;
int main() {
int N, M;
int numCase = 1;
while(cin >> N >> M) {
if(!N && !M) {
// Input terminates with 0 0
break;
}
graph.clear();
for(int k = 0; k <= N; k++) {
// We'll have a graph, which will be a list of list of integers. Each
// list will have the numbers each position goes to, including itself.
vector<int> v;
graph.push_back(v);
}
for(int k = 1; k <= M; k++) {
// Read the graph, define bidirectional relations, as in, p1 and p2 are
// a couple persons that belong to the same religion.
int p1, p2;
cin >> p1 >> p2;
graph[p1].push_back(p2);
graph[p2].push_back(p1);
}
for(int k = 0; k <= N; k++) {
// Then, we'll mark each number as having its own religion
graph[k].push_back(k);
}
int religions = 0;
for(int i = 1; i <= N; i++) {
// At each i (each person), the list of relations that person has is
// also the list of persons belonging to its same religion. So, all the
// persons found in this list will be 'cleared', since we don't have
// to re-check for this same religion. A person that hasn't been cle-
// ared this far belongs to a yet un-checked religion. If we didn't add
// a person to its own list of religions, the size of that person's own
// list would be 0, which would coincide with an already cleared person
// and we want this person whom we don't know anything about to count
// as its own possible religion, for finding the upper bounding limit.
if(graph[i].size() > 0) {
religions++;
}
else {
continue;
}
queue<int> q;
q.push(i);
// We'll clear the lists of the persons related to the current per-
// son, and also the lists of the persons related to those persons,
// and so on, until all people from a same religion is cleared so
// we don't check them anymore in the future.
while(q.size() > 0) {
int p1 = q.front();
q.pop();
for(int j = 0; j < graph[p1].size(); j++) {
int p2 = graph[p1][j];
q.push(p2);
}
graph[p1].clear();
}
}
cout << "Case " << numCase << ": " << religions << endl;
numCase++;
}
}<|endoftext|>
|
<commit_before>//===-- SocketTest.cpp ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <cstdio>
#include <functional>
#include <thread>
#include "gtest/gtest.h"
#include "lldb/Host/Config.h"
#include "lldb/Host/Socket.h"
#include "lldb/Host/common/TCPSocket.h"
#include "lldb/Host/common/UDPSocket.h"
#ifndef LLDB_DISABLE_POSIX
#include "lldb/Host/posix/DomainSocket.h"
#endif
using namespace lldb_private;
class SocketTest : public testing::Test {
public:
void SetUp() override {
#if defined(_MSC_VER)
WSADATA data;
::WSAStartup(MAKEWORD(2, 2), &data);
#endif
}
void TearDown() override {
#if defined(_MSC_VER)
::WSACleanup();
#endif
}
protected:
static void AcceptThread(Socket *listen_socket,
const char *listen_remote_address,
bool child_processes_inherit, Socket **accept_socket,
Error *error) {
*error = listen_socket->Accept(listen_remote_address,
child_processes_inherit, *accept_socket);
}
template <typename SocketType>
void CreateConnectedSockets(
const char *listen_remote_address,
const std::function<std::string(const SocketType &)> &get_connect_addr,
std::unique_ptr<SocketType> *a_up, std::unique_ptr<SocketType> *b_up) {
bool child_processes_inherit = false;
Error error;
std::unique_ptr<SocketType> listen_socket_up(
new SocketType(child_processes_inherit, error));
EXPECT_FALSE(error.Fail());
error = listen_socket_up->Listen(listen_remote_address, 5);
EXPECT_FALSE(error.Fail());
EXPECT_TRUE(listen_socket_up->IsValid());
Error accept_error;
Socket *accept_socket;
std::thread accept_thread(AcceptThread, listen_socket_up.get(),
listen_remote_address, child_processes_inherit,
&accept_socket, &accept_error);
std::string connect_remote_address = get_connect_addr(*listen_socket_up);
std::unique_ptr<SocketType> connect_socket_up(
new SocketType(child_processes_inherit, error));
EXPECT_FALSE(error.Fail());
error = connect_socket_up->Connect(connect_remote_address);
EXPECT_FALSE(error.Fail());
EXPECT_TRUE(connect_socket_up->IsValid());
a_up->swap(connect_socket_up);
EXPECT_TRUE(error.Success());
EXPECT_NE(nullptr, a_up->get());
EXPECT_TRUE((*a_up)->IsValid());
accept_thread.join();
b_up->reset(static_cast<SocketType *>(accept_socket));
EXPECT_TRUE(accept_error.Success());
EXPECT_NE(nullptr, b_up->get());
EXPECT_TRUE((*b_up)->IsValid());
listen_socket_up.reset();
}
};
TEST_F(SocketTest, DecodeHostAndPort) {
std::string host_str;
std::string port_str;
int32_t port;
Error error;
EXPECT_TRUE(Socket::DecodeHostAndPort("localhost:1138", host_str, port_str,
port, &error));
EXPECT_STREQ("localhost", host_str.c_str());
EXPECT_STREQ("1138", port_str.c_str());
EXPECT_EQ(1138, port);
EXPECT_TRUE(error.Success());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
error.AsCString());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:-1138", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:-1138'",
error.AsCString());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
error.AsCString());
EXPECT_TRUE(
Socket::DecodeHostAndPort("12345", host_str, port_str, port, &error));
EXPECT_STREQ("", host_str.c_str());
EXPECT_STREQ("12345", port_str.c_str());
EXPECT_EQ(12345, port);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(
Socket::DecodeHostAndPort("*:0", host_str, port_str, port, &error));
EXPECT_STREQ("*", host_str.c_str());
EXPECT_STREQ("0", port_str.c_str());
EXPECT_EQ(0, port);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(
Socket::DecodeHostAndPort("*:65535", host_str, port_str, port, &error));
EXPECT_STREQ("*", host_str.c_str());
EXPECT_STREQ("65535", port_str.c_str());
EXPECT_EQ(65535, port);
EXPECT_TRUE(error.Success());
}
#ifndef LLDB_DISABLE_POSIX
TEST_F(SocketTest, DomainListenConnectAccept) {
char *file_name_str = tempnam(nullptr, nullptr);
EXPECT_NE(nullptr, file_name_str);
const std::string file_name(file_name_str);
free(file_name_str);
std::unique_ptr<DomainSocket> socket_a_up;
std::unique_ptr<DomainSocket> socket_b_up;
CreateConnectedSockets<DomainSocket>(
file_name.c_str(), [=](const DomainSocket &) { return file_name; },
&socket_a_up, &socket_b_up);
}
#endif
TEST_F(SocketTest, TCPListen0ConnectAccept) {
std::unique_ptr<TCPSocket> socket_a_up;
std::unique_ptr<TCPSocket> socket_b_up;
CreateConnectedSockets<TCPSocket>(
"127.0.0.1:0",
[=](const TCPSocket &s) {
char connect_remote_address[64];
snprintf(connect_remote_address, sizeof(connect_remote_address),
"localhost:%u", s.GetLocalPortNumber());
return std::string(connect_remote_address);
},
&socket_a_up, &socket_b_up);
}
TEST_F(SocketTest, TCPGetAddress) {
std::unique_ptr<TCPSocket> socket_a_up;
std::unique_ptr<TCPSocket> socket_b_up;
CreateConnectedSockets<TCPSocket>(
"127.0.0.1:0",
[=](const TCPSocket &s) {
char connect_remote_address[64];
snprintf(connect_remote_address, sizeof(connect_remote_address),
"localhost:%u", s.GetLocalPortNumber());
return std::string(connect_remote_address);
},
&socket_a_up, &socket_b_up);
EXPECT_EQ(socket_a_up->GetLocalPortNumber(),
socket_b_up->GetRemotePortNumber());
EXPECT_EQ(socket_b_up->GetLocalPortNumber(),
socket_a_up->GetRemotePortNumber());
EXPECT_NE(socket_a_up->GetLocalPortNumber(),
socket_b_up->GetLocalPortNumber());
EXPECT_STREQ("127.0.0.1", socket_a_up->GetRemoteIPAddress().c_str());
EXPECT_STREQ("127.0.0.1", socket_b_up->GetRemoteIPAddress().c_str());
}
TEST_F(SocketTest, UDPConnect) {
Socket *socket_a;
Socket *socket_b;
bool child_processes_inherit = false;
auto error = UDPSocket::Connect("127.0.0.1:0", child_processes_inherit,
socket_a, socket_b);
std::unique_ptr<Socket> a_up(socket_a);
std::unique_ptr<Socket> b_up(socket_b);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(a_up->IsValid());
EXPECT_TRUE(b_up->IsValid());
}
<commit_msg>Update unittests/Host/SocketTest.cpp to also use the new one-socket API.<commit_after>//===-- SocketTest.cpp ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <cstdio>
#include <functional>
#include <thread>
#include "gtest/gtest.h"
#include "lldb/Host/Config.h"
#include "lldb/Host/Socket.h"
#include "lldb/Host/common/TCPSocket.h"
#include "lldb/Host/common/UDPSocket.h"
#ifndef LLDB_DISABLE_POSIX
#include "lldb/Host/posix/DomainSocket.h"
#endif
using namespace lldb_private;
class SocketTest : public testing::Test {
public:
void SetUp() override {
#if defined(_MSC_VER)
WSADATA data;
::WSAStartup(MAKEWORD(2, 2), &data);
#endif
}
void TearDown() override {
#if defined(_MSC_VER)
::WSACleanup();
#endif
}
protected:
static void AcceptThread(Socket *listen_socket,
const char *listen_remote_address,
bool child_processes_inherit, Socket **accept_socket,
Error *error) {
*error = listen_socket->Accept(listen_remote_address,
child_processes_inherit, *accept_socket);
}
template <typename SocketType>
void CreateConnectedSockets(
const char *listen_remote_address,
const std::function<std::string(const SocketType &)> &get_connect_addr,
std::unique_ptr<SocketType> *a_up, std::unique_ptr<SocketType> *b_up) {
bool child_processes_inherit = false;
Error error;
std::unique_ptr<SocketType> listen_socket_up(
new SocketType(child_processes_inherit, error));
EXPECT_FALSE(error.Fail());
error = listen_socket_up->Listen(listen_remote_address, 5);
EXPECT_FALSE(error.Fail());
EXPECT_TRUE(listen_socket_up->IsValid());
Error accept_error;
Socket *accept_socket;
std::thread accept_thread(AcceptThread, listen_socket_up.get(),
listen_remote_address, child_processes_inherit,
&accept_socket, &accept_error);
std::string connect_remote_address = get_connect_addr(*listen_socket_up);
std::unique_ptr<SocketType> connect_socket_up(
new SocketType(child_processes_inherit, error));
EXPECT_FALSE(error.Fail());
error = connect_socket_up->Connect(connect_remote_address);
EXPECT_FALSE(error.Fail());
EXPECT_TRUE(connect_socket_up->IsValid());
a_up->swap(connect_socket_up);
EXPECT_TRUE(error.Success());
EXPECT_NE(nullptr, a_up->get());
EXPECT_TRUE((*a_up)->IsValid());
accept_thread.join();
b_up->reset(static_cast<SocketType *>(accept_socket));
EXPECT_TRUE(accept_error.Success());
EXPECT_NE(nullptr, b_up->get());
EXPECT_TRUE((*b_up)->IsValid());
listen_socket_up.reset();
}
};
TEST_F(SocketTest, DecodeHostAndPort) {
std::string host_str;
std::string port_str;
int32_t port;
Error error;
EXPECT_TRUE(Socket::DecodeHostAndPort("localhost:1138", host_str, port_str,
port, &error));
EXPECT_STREQ("localhost", host_str.c_str());
EXPECT_STREQ("1138", port_str.c_str());
EXPECT_EQ(1138, port);
EXPECT_TRUE(error.Success());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
error.AsCString());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:-1138", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:-1138'",
error.AsCString());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
error.AsCString());
EXPECT_TRUE(
Socket::DecodeHostAndPort("12345", host_str, port_str, port, &error));
EXPECT_STREQ("", host_str.c_str());
EXPECT_STREQ("12345", port_str.c_str());
EXPECT_EQ(12345, port);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(
Socket::DecodeHostAndPort("*:0", host_str, port_str, port, &error));
EXPECT_STREQ("*", host_str.c_str());
EXPECT_STREQ("0", port_str.c_str());
EXPECT_EQ(0, port);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(
Socket::DecodeHostAndPort("*:65535", host_str, port_str, port, &error));
EXPECT_STREQ("*", host_str.c_str());
EXPECT_STREQ("65535", port_str.c_str());
EXPECT_EQ(65535, port);
EXPECT_TRUE(error.Success());
}
#ifndef LLDB_DISABLE_POSIX
TEST_F(SocketTest, DomainListenConnectAccept) {
char *file_name_str = tempnam(nullptr, nullptr);
EXPECT_NE(nullptr, file_name_str);
const std::string file_name(file_name_str);
free(file_name_str);
std::unique_ptr<DomainSocket> socket_a_up;
std::unique_ptr<DomainSocket> socket_b_up;
CreateConnectedSockets<DomainSocket>(
file_name.c_str(), [=](const DomainSocket &) { return file_name; },
&socket_a_up, &socket_b_up);
}
#endif
TEST_F(SocketTest, TCPListen0ConnectAccept) {
std::unique_ptr<TCPSocket> socket_a_up;
std::unique_ptr<TCPSocket> socket_b_up;
CreateConnectedSockets<TCPSocket>(
"127.0.0.1:0",
[=](const TCPSocket &s) {
char connect_remote_address[64];
snprintf(connect_remote_address, sizeof(connect_remote_address),
"localhost:%u", s.GetLocalPortNumber());
return std::string(connect_remote_address);
},
&socket_a_up, &socket_b_up);
}
TEST_F(SocketTest, TCPGetAddress) {
std::unique_ptr<TCPSocket> socket_a_up;
std::unique_ptr<TCPSocket> socket_b_up;
CreateConnectedSockets<TCPSocket>(
"127.0.0.1:0",
[=](const TCPSocket &s) {
char connect_remote_address[64];
snprintf(connect_remote_address, sizeof(connect_remote_address),
"localhost:%u", s.GetLocalPortNumber());
return std::string(connect_remote_address);
},
&socket_a_up, &socket_b_up);
EXPECT_EQ(socket_a_up->GetLocalPortNumber(),
socket_b_up->GetRemotePortNumber());
EXPECT_EQ(socket_b_up->GetLocalPortNumber(),
socket_a_up->GetRemotePortNumber());
EXPECT_NE(socket_a_up->GetLocalPortNumber(),
socket_b_up->GetLocalPortNumber());
EXPECT_STREQ("127.0.0.1", socket_a_up->GetRemoteIPAddress().c_str());
EXPECT_STREQ("127.0.0.1", socket_b_up->GetRemoteIPAddress().c_str());
}
TEST_F(SocketTest, UDPConnect) {
Socket *socket;
bool child_processes_inherit = false;
auto error = UDPSocket::Connect("127.0.0.1:0", child_processes_inherit,
socket);
std::unique_ptr<Socket> socket_up(socket);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(socket_up->IsValid());
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: atom.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: pl $ $Date: 2001-12-12 13:57:09 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <unotools/atom.hxx>
using namespace utl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
#define NMSP_UTIL ::com::sun::star::util
AtomProvider::AtomProvider()
{
m_nAtoms = 1;
}
AtomProvider::~AtomProvider()
{
}
int AtomProvider::getAtom( const ::rtl::OUString& rString, sal_Bool bCreate )
{
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::iterator it = m_aAtomMap.find( rString );
if( it != m_aAtomMap.end() )
return it->second;
if( ! bCreate )
return INVALID_ATOM;
m_aAtomMap[ rString ] = m_nAtoms;
m_aStringMap[ m_nAtoms ] = rString;
m_nAtoms++;
return m_nAtoms-1;
}
void AtomProvider::getAll( ::std::list< ::utl::AtomDescription >& atoms )
{
atoms.clear();
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin();
::utl::AtomDescription aDesc;
while( it != m_aAtomMap.end() )
{
aDesc.atom = it->second;
aDesc.description = it->first;
atoms.push_back( aDesc );
++it;
}
}
void AtomProvider::getRecent( int atom, ::std::list< ::utl::AtomDescription >& atoms )
{
atoms.clear();
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin();
::utl::AtomDescription aDesc;
while( it != m_aAtomMap.end() )
{
if( it->second > atom )
{
aDesc.atom = it->second;
aDesc.description = it->first;
atoms.push_back( aDesc );
}
++it;
}
}
const ::rtl::OUString& AtomProvider::getString( int nAtom ) const
{
static ::rtl::OUString aEmpty;
::std::hash_map< int, ::rtl::OUString, ::std::hash< int > >::const_iterator it = m_aStringMap.find( nAtom );
return it == m_aStringMap.end() ? aEmpty : it->second;
}
void AtomProvider::overrideAtom( int atom, const ::rtl::OUString& description )
{
m_aAtomMap[ description ] = atom;
m_aStringMap[ atom ] = description;
if( m_nAtoms <= atom )
m_nAtoms=atom+1;
}
sal_Bool AtomProvider::hasAtom( int atom ) const
{
return m_aStringMap.find( atom ) != m_aStringMap.end() ? sal_True : sal_False;
}
// -----------------------------------------------------------------------
MultiAtomProvider::MultiAtomProvider()
{
}
MultiAtomProvider::~MultiAtomProvider()
{
for( ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it = m_aAtomLists.begin(); it != m_aAtomLists.end(); ++it )
delete it->second;
}
sal_Bool MultiAtomProvider::insertAtomClass( int atomClass )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return sal_False;
m_aAtomLists[ atomClass ] = new AtomProvider();
return sal_True;
}
int MultiAtomProvider::getAtom( int atomClass, const ::rtl::OUString& rString, sal_Bool bCreate )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return it->second->getAtom( rString, bCreate );
if( bCreate )
{
AtomProvider* pNewClass;
m_aAtomLists[ atomClass ] = pNewClass = new AtomProvider();
return pNewClass->getAtom( rString, bCreate );
}
return INVALID_ATOM;
}
int MultiAtomProvider::getLastAtom( int atomClass ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
return it != m_aAtomLists.end() ? it->second->getLastAtom() : INVALID_ATOM;
}
void MultiAtomProvider::getRecent( int atomClass, int atom, ::std::list< ::utl::AtomDescription >& atoms )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
it->second->getRecent( atom, atoms );
else
atoms.clear();
}
const ::rtl::OUString& MultiAtomProvider::getString( int atomClass, int atom ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return it->second->getString( atom );
static ::rtl::OUString aEmpty;
return aEmpty;
}
sal_Bool MultiAtomProvider::hasAtom( int atomClass, int atom ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
return it != m_aAtomLists.end() ? it->second->hasAtom( atom ) : sal_False;
}
void MultiAtomProvider::getClass( int atomClass, ::std::list< ::utl::AtomDescription >& atoms) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
it->second->getAll( atoms );
else
atoms.clear();
}
void MultiAtomProvider::overrideAtom( int atomClass, int atom, const ::rtl::OUString& description )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
if( it == m_aAtomLists.end() )
m_aAtomLists[ atomClass ] = new AtomProvider();
m_aAtomLists[ atomClass ]->overrideAtom( atom, description );
}
// -----------------------------------------------------------------------
AtomServer::AtomServer()
{
}
AtomServer::~AtomServer()
{
}
sal_Int32 AtomServer::getAtom( sal_Int32 atomClass, const ::rtl::OUString& description, sal_Bool create ) throw()
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
return m_aProvider.getAtom( atomClass, description, create );
}
Sequence< Sequence< NMSP_UTIL::AtomDescription > > AtomServer::getClasses( const Sequence< sal_Int32 >& atomClasses ) throw()
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
Sequence< Sequence< NMSP_UTIL::AtomDescription > > aRet( atomClasses.getLength() );
for( int i = 0; i < atomClasses.getLength(); i++ )
{
aRet.getArray()[i] = getClass( atomClasses.getConstArray()[i] );
}
return aRet;
}
Sequence< NMSP_UTIL::AtomDescription > AtomServer::getClass( sal_Int32 atomClass ) throw()
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
::std::list< ::utl::AtomDescription > atoms;
m_aProvider.getClass( atomClass, atoms );
Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() );
for( int i = aRet.getLength()-1; i >= 0; i-- )
{
aRet.getArray()[i].atom = atoms.back().atom;
aRet.getArray()[i].description = atoms.back().description;
atoms.pop_back();
}
return aRet;
}
Sequence< NMSP_UTIL::AtomDescription > AtomServer::getRecentAtoms( sal_Int32 atomClass, sal_Int32 atom ) throw()
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
::std::list< ::utl::AtomDescription > atoms;
m_aProvider.getRecent( atomClass, atom, atoms );
Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() );
for( int i = aRet.getLength()-1; i >= 0; i-- )
{
aRet.getArray()[i].atom = atoms.back().atom;
aRet.getArray()[i].description = atoms.back().description;
atoms.pop_back();
}
return aRet;
}
Sequence< ::rtl::OUString > AtomServer::getAtomDescriptions( const Sequence< AtomClassRequest >& atoms ) throw()
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
int nStrings = 0, i;
for( i = 0; i < atoms.getLength(); i++ )
nStrings += atoms.getConstArray()[ i ].atoms.getLength();
Sequence< ::rtl::OUString > aRet( nStrings );
for( i = 0, nStrings = 0; i < atoms.getLength(); i++ )
{
const AtomClassRequest& rRequest = atoms.getConstArray()[i];
for( int n = 0; n < rRequest.atoms.getLength(); n++ )
aRet.getArray()[ nStrings++ ] = m_aProvider.getString( rRequest.atomClass, rRequest.atoms.getConstArray()[ n ] );
}
return aRet;
}
// -----------------------------------------------------------------------
AtomClient::AtomClient( const Reference< XAtomServer >& xServer ) :
m_xServer( xServer )
{
}
AtomClient::~AtomClient()
{
}
int AtomClient::getAtom( int atomClass, const ::rtl::OUString& description, sal_Bool bCreate )
{
int nAtom = m_aProvider.getAtom( atomClass, description, sal_False );
if( nAtom == INVALID_ATOM && bCreate )
{
try
{
nAtom = m_xServer->getAtom( atomClass, description, bCreate );
}
catch( RuntimeException& )
{
return INVALID_ATOM;
}
if( nAtom != INVALID_ATOM )
m_aProvider.overrideAtom( atomClass, nAtom, description );
}
return nAtom;
}
const ::rtl::OUString& AtomClient::getString( int atomClass, int atom )
{
static ::rtl::OUString aEmpty;
if( ! m_aProvider.hasAtom( atomClass, atom ) )
{
Sequence< NMSP_UTIL::AtomDescription > aSeq;
try
{
aSeq = m_xServer->getRecentAtoms( atomClass, m_aProvider.getLastAtom( atomClass ) );
}
catch( RuntimeException& )
{
return aEmpty;
}
const NMSP_UTIL::AtomDescription* pDescriptions = aSeq.getConstArray();
for( int i = 0; i < aSeq.getLength(); i++ )
m_aProvider.overrideAtom( atomClass,
pDescriptions[i].atom,
pDescriptions[i].description
);
if( ! m_aProvider.hasAtom( atomClass, atom ) )
{
// holes may occur by the above procedure!
Sequence< AtomClassRequest > aSeq( 1 );
aSeq.getArray()[0].atomClass = atomClass;
aSeq.getArray()[0].atoms.realloc( 1 );
aSeq.getArray()[0].atoms.getArray()[0] = atom;
Sequence< ::rtl::OUString > aRet;
try
{
aRet = m_xServer->getAtomDescriptions( aSeq );
}
catch( RuntimeException& )
{
return aEmpty;
}
if( aRet.getLength() == 1 )
m_aProvider.overrideAtom( atomClass, atom, aRet.getConstArray()[0] );
}
}
return m_aProvider.getString( atomClass, atom );
}
void AtomClient::updateAtomClasses( const Sequence< sal_Int32 >& atomClasses )
{
Sequence< Sequence< NMSP_UTIL::AtomDescription > > aUpdate;
try
{
aUpdate = m_xServer->getClasses( atomClasses );
}
catch( RuntimeException& )
{
return;
}
for( int i = 0; i < atomClasses.getLength(); i++ )
{
int nClass = atomClasses.getConstArray()[i];
const Sequence< NMSP_UTIL::AtomDescription >& rClass = aUpdate.getConstArray()[i];
const NMSP_UTIL::AtomDescription* pDesc = rClass.getConstArray();
for( int n = 0; n < rClass.getLength(); n++, pDesc++ )
m_aProvider.overrideAtom( nClass, pDesc->atom, pDesc->description );
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.246); FILE MERGED 2005/09/05 14:01:06 rt 1.6.246.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: atom.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 09:46:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <unotools/atom.hxx>
using namespace utl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
#define NMSP_UTIL ::com::sun::star::util
AtomProvider::AtomProvider()
{
m_nAtoms = 1;
}
AtomProvider::~AtomProvider()
{
}
int AtomProvider::getAtom( const ::rtl::OUString& rString, sal_Bool bCreate )
{
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::iterator it = m_aAtomMap.find( rString );
if( it != m_aAtomMap.end() )
return it->second;
if( ! bCreate )
return INVALID_ATOM;
m_aAtomMap[ rString ] = m_nAtoms;
m_aStringMap[ m_nAtoms ] = rString;
m_nAtoms++;
return m_nAtoms-1;
}
void AtomProvider::getAll( ::std::list< ::utl::AtomDescription >& atoms )
{
atoms.clear();
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin();
::utl::AtomDescription aDesc;
while( it != m_aAtomMap.end() )
{
aDesc.atom = it->second;
aDesc.description = it->first;
atoms.push_back( aDesc );
++it;
}
}
void AtomProvider::getRecent( int atom, ::std::list< ::utl::AtomDescription >& atoms )
{
atoms.clear();
::std::hash_map< ::rtl::OUString, int, ::rtl::OUStringHash >::const_iterator it = m_aAtomMap.begin();
::utl::AtomDescription aDesc;
while( it != m_aAtomMap.end() )
{
if( it->second > atom )
{
aDesc.atom = it->second;
aDesc.description = it->first;
atoms.push_back( aDesc );
}
++it;
}
}
const ::rtl::OUString& AtomProvider::getString( int nAtom ) const
{
static ::rtl::OUString aEmpty;
::std::hash_map< int, ::rtl::OUString, ::std::hash< int > >::const_iterator it = m_aStringMap.find( nAtom );
return it == m_aStringMap.end() ? aEmpty : it->second;
}
void AtomProvider::overrideAtom( int atom, const ::rtl::OUString& description )
{
m_aAtomMap[ description ] = atom;
m_aStringMap[ atom ] = description;
if( m_nAtoms <= atom )
m_nAtoms=atom+1;
}
sal_Bool AtomProvider::hasAtom( int atom ) const
{
return m_aStringMap.find( atom ) != m_aStringMap.end() ? sal_True : sal_False;
}
// -----------------------------------------------------------------------
MultiAtomProvider::MultiAtomProvider()
{
}
MultiAtomProvider::~MultiAtomProvider()
{
for( ::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it = m_aAtomLists.begin(); it != m_aAtomLists.end(); ++it )
delete it->second;
}
sal_Bool MultiAtomProvider::insertAtomClass( int atomClass )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return sal_False;
m_aAtomLists[ atomClass ] = new AtomProvider();
return sal_True;
}
int MultiAtomProvider::getAtom( int atomClass, const ::rtl::OUString& rString, sal_Bool bCreate )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return it->second->getAtom( rString, bCreate );
if( bCreate )
{
AtomProvider* pNewClass;
m_aAtomLists[ atomClass ] = pNewClass = new AtomProvider();
return pNewClass->getAtom( rString, bCreate );
}
return INVALID_ATOM;
}
int MultiAtomProvider::getLastAtom( int atomClass ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
return it != m_aAtomLists.end() ? it->second->getLastAtom() : INVALID_ATOM;
}
void MultiAtomProvider::getRecent( int atomClass, int atom, ::std::list< ::utl::AtomDescription >& atoms )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
it->second->getRecent( atom, atoms );
else
atoms.clear();
}
const ::rtl::OUString& MultiAtomProvider::getString( int atomClass, int atom ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it =
m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
return it->second->getString( atom );
static ::rtl::OUString aEmpty;
return aEmpty;
}
sal_Bool MultiAtomProvider::hasAtom( int atomClass, int atom ) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
return it != m_aAtomLists.end() ? it->second->hasAtom( atom ) : sal_False;
}
void MultiAtomProvider::getClass( int atomClass, ::std::list< ::utl::AtomDescription >& atoms) const
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
if( it != m_aAtomLists.end() )
it->second->getAll( atoms );
else
atoms.clear();
}
void MultiAtomProvider::overrideAtom( int atomClass, int atom, const ::rtl::OUString& description )
{
::std::hash_map< int, AtomProvider*, ::std::hash< int > >::const_iterator it = m_aAtomLists.find( atomClass );
if( it == m_aAtomLists.end() )
m_aAtomLists[ atomClass ] = new AtomProvider();
m_aAtomLists[ atomClass ]->overrideAtom( atom, description );
}
// -----------------------------------------------------------------------
AtomServer::AtomServer()
{
}
AtomServer::~AtomServer()
{
}
sal_Int32 AtomServer::getAtom( sal_Int32 atomClass, const ::rtl::OUString& description, sal_Bool create ) throw()
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
return m_aProvider.getAtom( atomClass, description, create );
}
Sequence< Sequence< NMSP_UTIL::AtomDescription > > AtomServer::getClasses( const Sequence< sal_Int32 >& atomClasses ) throw()
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
Sequence< Sequence< NMSP_UTIL::AtomDescription > > aRet( atomClasses.getLength() );
for( int i = 0; i < atomClasses.getLength(); i++ )
{
aRet.getArray()[i] = getClass( atomClasses.getConstArray()[i] );
}
return aRet;
}
Sequence< NMSP_UTIL::AtomDescription > AtomServer::getClass( sal_Int32 atomClass ) throw()
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
::std::list< ::utl::AtomDescription > atoms;
m_aProvider.getClass( atomClass, atoms );
Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() );
for( int i = aRet.getLength()-1; i >= 0; i-- )
{
aRet.getArray()[i].atom = atoms.back().atom;
aRet.getArray()[i].description = atoms.back().description;
atoms.pop_back();
}
return aRet;
}
Sequence< NMSP_UTIL::AtomDescription > AtomServer::getRecentAtoms( sal_Int32 atomClass, sal_Int32 atom ) throw()
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
::std::list< ::utl::AtomDescription > atoms;
m_aProvider.getRecent( atomClass, atom, atoms );
Sequence< NMSP_UTIL::AtomDescription > aRet( atoms.size() );
for( int i = aRet.getLength()-1; i >= 0; i-- )
{
aRet.getArray()[i].atom = atoms.back().atom;
aRet.getArray()[i].description = atoms.back().description;
atoms.pop_back();
}
return aRet;
}
Sequence< ::rtl::OUString > AtomServer::getAtomDescriptions( const Sequence< AtomClassRequest >& atoms ) throw()
{
::osl::Guard< ::osl::Mutex > guard( m_aMutex );
int nStrings = 0, i;
for( i = 0; i < atoms.getLength(); i++ )
nStrings += atoms.getConstArray()[ i ].atoms.getLength();
Sequence< ::rtl::OUString > aRet( nStrings );
for( i = 0, nStrings = 0; i < atoms.getLength(); i++ )
{
const AtomClassRequest& rRequest = atoms.getConstArray()[i];
for( int n = 0; n < rRequest.atoms.getLength(); n++ )
aRet.getArray()[ nStrings++ ] = m_aProvider.getString( rRequest.atomClass, rRequest.atoms.getConstArray()[ n ] );
}
return aRet;
}
// -----------------------------------------------------------------------
AtomClient::AtomClient( const Reference< XAtomServer >& xServer ) :
m_xServer( xServer )
{
}
AtomClient::~AtomClient()
{
}
int AtomClient::getAtom( int atomClass, const ::rtl::OUString& description, sal_Bool bCreate )
{
int nAtom = m_aProvider.getAtom( atomClass, description, sal_False );
if( nAtom == INVALID_ATOM && bCreate )
{
try
{
nAtom = m_xServer->getAtom( atomClass, description, bCreate );
}
catch( RuntimeException& )
{
return INVALID_ATOM;
}
if( nAtom != INVALID_ATOM )
m_aProvider.overrideAtom( atomClass, nAtom, description );
}
return nAtom;
}
const ::rtl::OUString& AtomClient::getString( int atomClass, int atom )
{
static ::rtl::OUString aEmpty;
if( ! m_aProvider.hasAtom( atomClass, atom ) )
{
Sequence< NMSP_UTIL::AtomDescription > aSeq;
try
{
aSeq = m_xServer->getRecentAtoms( atomClass, m_aProvider.getLastAtom( atomClass ) );
}
catch( RuntimeException& )
{
return aEmpty;
}
const NMSP_UTIL::AtomDescription* pDescriptions = aSeq.getConstArray();
for( int i = 0; i < aSeq.getLength(); i++ )
m_aProvider.overrideAtom( atomClass,
pDescriptions[i].atom,
pDescriptions[i].description
);
if( ! m_aProvider.hasAtom( atomClass, atom ) )
{
// holes may occur by the above procedure!
Sequence< AtomClassRequest > aSeq( 1 );
aSeq.getArray()[0].atomClass = atomClass;
aSeq.getArray()[0].atoms.realloc( 1 );
aSeq.getArray()[0].atoms.getArray()[0] = atom;
Sequence< ::rtl::OUString > aRet;
try
{
aRet = m_xServer->getAtomDescriptions( aSeq );
}
catch( RuntimeException& )
{
return aEmpty;
}
if( aRet.getLength() == 1 )
m_aProvider.overrideAtom( atomClass, atom, aRet.getConstArray()[0] );
}
}
return m_aProvider.getString( atomClass, atom );
}
void AtomClient::updateAtomClasses( const Sequence< sal_Int32 >& atomClasses )
{
Sequence< Sequence< NMSP_UTIL::AtomDescription > > aUpdate;
try
{
aUpdate = m_xServer->getClasses( atomClasses );
}
catch( RuntimeException& )
{
return;
}
for( int i = 0; i < atomClasses.getLength(); i++ )
{
int nClass = atomClasses.getConstArray()[i];
const Sequence< NMSP_UTIL::AtomDescription >& rClass = aUpdate.getConstArray()[i];
const NMSP_UTIL::AtomDescription* pDesc = rClass.getConstArray();
for( int n = 0; n < rClass.getLength(); n++, pDesc++ )
m_aProvider.overrideAtom( nClass, pDesc->atom, pDesc->description );
}
}
<|endoftext|>
|
<commit_before>#ifndef ENTT_SIGNAL_DISPATCHER_HPP
#define ENTT_SIGNAL_DISPATCHER_HPP
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include "../config/config.h"
#include "../core/fwd.hpp"
#include "../core/type_info.hpp"
#include "sigh.hpp"
namespace entt {
/**
* @brief Basic dispatcher implementation.
*
* A dispatcher can be used either to trigger an immediate event or to enqueue
* events to be published all together once per tick.<br/>
* Listeners are provided in the form of member functions. For each event of
* type `Event`, listeners are such that they can be invoked with an argument of
* type `const Event &`, no matter what the return type is.
*
* The dispatcher creates instances of the `sigh` class internally. Refer to the
* documentation of the latter for more details.
*/
class dispatcher {
struct basic_pool {
virtual ~basic_pool() = default;
virtual void publish() = 0;
virtual void clear() ENTT_NOEXCEPT = 0;
virtual id_type type_id() const ENTT_NOEXCEPT = 0;
};
template<typename Event>
struct pool_handler final: basic_pool {
using signal_type = sigh<void(const Event &)>;
using sink_type = typename signal_type::sink_type;
void publish() override {
const auto length = events.size();
for(std::size_t pos{}; pos < length; ++pos) {
signal.publish(events[pos]);
}
events.erase(events.cbegin(), events.cbegin()+length);
}
void clear() ENTT_NOEXCEPT override {
events.clear();
}
sink_type sink() ENTT_NOEXCEPT {
return entt::sink{signal};
}
template<typename... Args>
void trigger(Args &&... args) {
signal.publish(Event{std::forward<Args>(args)...});
}
template<typename... Args>
void enqueue(Args &&... args) {
events.emplace_back(std::forward<Args>(args)...);
}
id_type type_id() const ENTT_NOEXCEPT override {
return type_info<Event>::id();
}
private:
signal_type signal{};
std::vector<Event> events;
};
template<typename Event>
pool_handler<Event> & assure() {
static_assert(std::is_same_v<Event, std::decay_t<Event>>);
const auto index = type_index<Event>::value();
if(!(index < pools.size())) {
pools.resize(index+1);
}
if(!pools[index]) {
pools[index].reset(new pool_handler<Event>{});
}
return static_cast<pool_handler<Event> &>(*pools[index]);
}
public:
/**
* @brief Returns a sink object for the given event.
*
* A sink is an opaque object used to connect listeners to events.
*
* The function type for a listener is:
* @code{.cpp}
* void(const Event &);
* @endcode
*
* The order of invocation of the listeners isn't guaranteed.
*
* @sa sink
*
* @tparam Event Type of event of which to get the sink.
* @return A temporary sink object.
*/
template<typename Event>
auto sink() {
return assure<Event>().sink();
}
/**
* @brief Triggers an immediate event of the given type.
*
* All the listeners registered for the given type are immediately notified.
* The event is discarded after the execution.
*
* @tparam Event Type of event to trigger.
* @tparam Args Types of arguments to use to construct the event.
* @param args Arguments to use to construct the event.
*/
template<typename Event, typename... Args>
void trigger(Args &&... args) {
assure<Event>().trigger(std::forward<Args>(args)...);
}
/**
* @brief Triggers an immediate event of the given type.
*
* All the listeners registered for the given type are immediately notified.
* The event is discarded after the execution.
*
* @tparam Event Type of event to trigger.
* @param event An instance of the given type of event.
*/
template<typename Event>
void trigger(Event &&event) {
assure<std::decay_t<Event>>().trigger(std::forward<Event>(event));
}
/**
* @brief Enqueues an event of the given type.
*
* An event of the given type is queued. No listener is invoked. Use the
* `update` member function to notify listeners when ready.
*
* @tparam Event Type of event to enqueue.
* @tparam Args Types of arguments to use to construct the event.
* @param args Arguments to use to construct the event.
*/
template<typename Event, typename... Args>
void enqueue(Args &&... args) {
assure<Event>().enqueue(std::forward<Args>(args)...);
}
/**
* @brief Enqueues an event of the given type.
*
* An event of the given type is queued. No listener is invoked. Use the
* `update` member function to notify listeners when ready.
*
* @tparam Event Type of event to enqueue.
* @param event An instance of the given type of event.
*/
template<typename Event>
void enqueue(Event &&event) {
assure<std::decay_t<Event>>().enqueue(std::forward<Event>(event));
}
/**
* @brief Discards all the events queued so far.
*
* If no types are provided, the dispatcher will clear all the existing
* pools.
*
* @tparam Event Type of events to discard.
*/
template<typename... Event>
void clear() {
if constexpr(sizeof...(Event) == 0) {
for(auto &&cpool: pools) {
if(cpool) {
cpool->clear();
}
}
} else {
(assure<Event>().clear(), ...);
}
}
/**
* @brief Delivers all the pending events of the given type.
*
* This method is blocking and it doesn't return until all the events are
* delivered to the registered listeners. It's responsibility of the users
* to reduce at a minimum the time spent in the bodies of the listeners.
*
* @tparam Event Type of events to send.
*/
template<typename Event>
void update() {
assure<Event>().publish();
}
/**
* @brief Delivers all the pending events.
*
* This method is blocking and it doesn't return until all the events are
* delivered to the registered listeners. It's responsibility of the users
* to reduce at a minimum the time spent in the bodies of the listeners.
*/
void update() const {
for(auto pos = pools.size(); pos; --pos) {
if(auto &&cpool = pools[pos-1]; cpool) {
cpool->publish();
}
}
}
private:
std::vector<std::unique_ptr<basic_pool>> pools;
};
}
#endif
<commit_msg>dispatcher: use fast path if available, standard path otherwise<commit_after>#ifndef ENTT_SIGNAL_DISPATCHER_HPP
#define ENTT_SIGNAL_DISPATCHER_HPP
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include "../config/config.h"
#include "../core/fwd.hpp"
#include "../core/type_info.hpp"
#include "sigh.hpp"
namespace entt {
/**
* @brief Basic dispatcher implementation.
*
* A dispatcher can be used either to trigger an immediate event or to enqueue
* events to be published all together once per tick.<br/>
* Listeners are provided in the form of member functions. For each event of
* type `Event`, listeners are such that they can be invoked with an argument of
* type `const Event &`, no matter what the return type is.
*
* The dispatcher creates instances of the `sigh` class internally. Refer to the
* documentation of the latter for more details.
*/
class dispatcher {
struct basic_pool {
virtual ~basic_pool() = default;
virtual void publish() = 0;
virtual void clear() ENTT_NOEXCEPT = 0;
virtual id_type type_id() const ENTT_NOEXCEPT = 0;
};
template<typename Event>
struct pool_handler final: basic_pool {
using signal_type = sigh<void(const Event &)>;
using sink_type = typename signal_type::sink_type;
void publish() override {
const auto length = events.size();
for(std::size_t pos{}; pos < length; ++pos) {
signal.publish(events[pos]);
}
events.erase(events.cbegin(), events.cbegin()+length);
}
void clear() ENTT_NOEXCEPT override {
events.clear();
}
sink_type sink() ENTT_NOEXCEPT {
return entt::sink{signal};
}
template<typename... Args>
void trigger(Args &&... args) {
signal.publish(Event{std::forward<Args>(args)...});
}
template<typename... Args>
void enqueue(Args &&... args) {
events.emplace_back(std::forward<Args>(args)...);
}
id_type type_id() const ENTT_NOEXCEPT override {
return type_info<Event>::id();
}
private:
signal_type signal{};
std::vector<Event> events;
};
template<typename Event>
pool_handler<Event> & assure() {
static_assert(std::is_same_v<Event, std::decay_t<Event>>);
if constexpr(has_type_index_v<Event>) {
const auto index = type_index<Event>::value();
if(!(index < pools.size())) {
pools.resize(index+1);
}
if(!pools[index]) {
pools[index].reset(new pool_handler<Event>{});
}
return static_cast<pool_handler<Event> &>(*pools[index]);
} else {
auto it = std::find_if(pools.begin(), pools.end(), [id = type_info<Event>::id()](const auto &cpool) { return id == cpool->type_id(); });
return static_cast<pool_handler<Event> &>(it == pools.cend() ? *pools.emplace_back(new pool_handler<Event>{}) : **it);
}
}
public:
/**
* @brief Returns a sink object for the given event.
*
* A sink is an opaque object used to connect listeners to events.
*
* The function type for a listener is:
* @code{.cpp}
* void(const Event &);
* @endcode
*
* The order of invocation of the listeners isn't guaranteed.
*
* @sa sink
*
* @tparam Event Type of event of which to get the sink.
* @return A temporary sink object.
*/
template<typename Event>
auto sink() {
return assure<Event>().sink();
}
/**
* @brief Triggers an immediate event of the given type.
*
* All the listeners registered for the given type are immediately notified.
* The event is discarded after the execution.
*
* @tparam Event Type of event to trigger.
* @tparam Args Types of arguments to use to construct the event.
* @param args Arguments to use to construct the event.
*/
template<typename Event, typename... Args>
void trigger(Args &&... args) {
assure<Event>().trigger(std::forward<Args>(args)...);
}
/**
* @brief Triggers an immediate event of the given type.
*
* All the listeners registered for the given type are immediately notified.
* The event is discarded after the execution.
*
* @tparam Event Type of event to trigger.
* @param event An instance of the given type of event.
*/
template<typename Event>
void trigger(Event &&event) {
assure<std::decay_t<Event>>().trigger(std::forward<Event>(event));
}
/**
* @brief Enqueues an event of the given type.
*
* An event of the given type is queued. No listener is invoked. Use the
* `update` member function to notify listeners when ready.
*
* @tparam Event Type of event to enqueue.
* @tparam Args Types of arguments to use to construct the event.
* @param args Arguments to use to construct the event.
*/
template<typename Event, typename... Args>
void enqueue(Args &&... args) {
assure<Event>().enqueue(std::forward<Args>(args)...);
}
/**
* @brief Enqueues an event of the given type.
*
* An event of the given type is queued. No listener is invoked. Use the
* `update` member function to notify listeners when ready.
*
* @tparam Event Type of event to enqueue.
* @param event An instance of the given type of event.
*/
template<typename Event>
void enqueue(Event &&event) {
assure<std::decay_t<Event>>().enqueue(std::forward<Event>(event));
}
/**
* @brief Discards all the events queued so far.
*
* If no types are provided, the dispatcher will clear all the existing
* pools.
*
* @tparam Event Type of events to discard.
*/
template<typename... Event>
void clear() {
if constexpr(sizeof...(Event) == 0) {
for(auto &&cpool: pools) {
if(cpool) {
cpool->clear();
}
}
} else {
(assure<Event>().clear(), ...);
}
}
/**
* @brief Delivers all the pending events of the given type.
*
* This method is blocking and it doesn't return until all the events are
* delivered to the registered listeners. It's responsibility of the users
* to reduce at a minimum the time spent in the bodies of the listeners.
*
* @tparam Event Type of events to send.
*/
template<typename Event>
void update() {
assure<Event>().publish();
}
/**
* @brief Delivers all the pending events.
*
* This method is blocking and it doesn't return until all the events are
* delivered to the registered listeners. It's responsibility of the users
* to reduce at a minimum the time spent in the bodies of the listeners.
*/
void update() const {
for(auto pos = pools.size(); pos; --pos) {
if(auto &&cpool = pools[pos-1]; cpool) {
cpool->publish();
}
}
}
private:
std::vector<std::unique_ptr<basic_pool>> pools;
};
}
#endif
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.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 <unistd.h>
#include <sys/uio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <ctime>
#include <sys/time.h>
#include <sys/types.h>
#include <thread>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "eventql/util/http/httpserverconnection.h"
#include "eventql/eventql.h"
#include "eventql/server/listener.h"
#include "eventql/server/session.h"
#include "eventql/db/database.h"
#include "eventql/util/return_code.h"
#include "eventql/util/logging.h"
#include "eventql/transport/native/connection_tcp.h"
namespace eventql {
uint64_t getMonoTime() {
#ifdef __MACH__
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
return std::uint64_t(mts.tv_sec) * 1000000 + mts.tv_nsec / 1000;
#else
timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
logFatal("clock_gettime(CLOCK_MONOTONIC) failed");
abort();
} else {
return std::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000;
}
#endif
}
Listener::Listener(
Database* database) :
database_(database),
io_timeout_(
std::max(
database->getConfig()->getInt("server.s2s_io_timeout").get(),
database->getConfig()->getInt("server.c2s_io_timeout").get())),
running_(true),
ssock_(-1),
http_transport_(database),
native_server_(database) {}
ReturnCode Listener::bind(int listen_port) {
ssock_ = ::socket(AF_INET, SOCK_STREAM, 0);
if (ssock_ == 0) {
return ReturnCode::error(
"IOERR",
"create socket() failed: %s",
strerror(errno));
}
int opt = 1;
if (::setsockopt(ssock_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
return ReturnCode::error(
"IOERR",
"setsockopt(SO_REUSEADDR) failed: %s",
strerror(errno));
}
int flags = ::fcntl(ssock_, F_GETFL, 0);
flags = flags | O_NONBLOCK;
if (::fcntl(ssock_, F_SETFL, flags) != 0) {
return ReturnCode::error(
"IOERR",
"fcntl(F_SETFL, O_NONBLOCK) failed: %s",
strerror(errno));
}
struct sockaddr_in addr;
memset((char *) &addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(listen_port);
if (::bind(ssock_, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
return ReturnCode::error(
"IOERR",
"bind() failed: %s",
strerror(errno));
}
if (::listen(ssock_, 1024) == -1) {
return ReturnCode::error(
"IOERR",
"listen() failed: %s",
strerror(errno));
}
logNotice("eventql", "Listening on port $0", listen_port);
return ReturnCode::success();
}
void Listener::run() {
http_transport_.startIOThread();
while (running_.load()) {
fd_set op_read, op_write, op_error;
FD_ZERO(&op_read);
FD_ZERO(&op_write);
FD_ZERO(&op_error);
int max_fd = ssock_;
FD_SET(ssock_, &op_read);
auto now = getMonoTime();
while (!connections_.empty()) {
if (connections_.front().accepted_at + io_timeout_ > now) {
break;
}
logError(
"eventql",
"timeout while reading first byte, closing connection");
close(connections_.front().fd);
connections_.pop_front();
}
uint64_t timeout = 0;
if (!connections_.empty()) {
timeout = (connections_.front().accepted_at + io_timeout_) - now;
}
for (const auto& c : connections_) {
if (c.fd > max_fd) {
max_fd = c.fd;
}
FD_SET(c.fd, &op_read);
}
int res;
if (timeout) {
struct timeval tv;
tv.tv_sec = timeout / kMicrosPerSecond;
tv.tv_usec = timeout % kMicrosPerSecond;
res = select(max_fd + 1, &op_read, &op_write, &op_error, &tv);
} else {
res = select(max_fd + 1, &op_read, &op_write, &op_error, NULL);
}
switch (res) {
case 0:
continue;
case -1:
if (errno == EINTR) {
continue;
}
logError("eventql", "select() failed");
goto exit;
}
if (FD_ISSET(ssock_, &op_read)) {
int conn_fd = ::accept(ssock_, NULL, NULL);
if (conn_fd < 0) {
logError("eventql", "accept() failed");
}
int flags = ::fcntl(conn_fd, F_GETFL, 0);
flags = flags | O_NONBLOCK;
if (::fcntl(conn_fd, F_SETFL, flags) != 0) {
logError(
"eventql",
"fcntl(F_SETFL, O_NONBLOCK) failed, closing connection: $0",
strerror(errno));
close(conn_fd);
continue;
}
EstablishingConnection c;
c.fd = conn_fd;
c.accepted_at = getMonoTime();
connections_.emplace_back(c);
}
auto iter = connections_.begin();
while (iter != connections_.end()) {
if (FD_ISSET(iter->fd, &op_read)) {
open(iter->fd);
iter = connections_.erase(iter);
} else {
iter++;
}
}
}
exit:
http_transport_.stopIOThread();
return;
}
void Listener::shutdown() {
}
void Listener::open(int fd) {
char first_byte;
auto res = ::read(fd, &first_byte, 1);
if (res != 1) {
logError(
"eventql",
"error while reading first byte, closing connection: $0",
strerror(errno));
close(fd);
return;
}
int flags = ::fcntl(fd, F_GETFL, 0);
flags = flags & ~O_NONBLOCK;
if (::fcntl(fd, F_SETFL, flags) != 0) {
logError(
"eventql",
"fcntl(F_SETFL, O_NONBLOCK) failed, closing connection: $0",
strerror(errno));
close(fd);
return;
}
switch (first_byte) {
// native
case '^': {
native_server_.startConnection(
std::unique_ptr<native_transport::NativeConnection>(
new native_transport::TCPConnection(
fd,
io_timeout_,
std::string(&first_byte, 1))));
break;
}
// http
default:
http_transport_.handleConnection(fd, std::string(&first_byte, 1));
break;
}
}
} // namespace eventql
<commit_msg>use MonotonicClock::now in Listener<commit_after>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.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 <unistd.h>
#include <sys/uio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <ctime>
#include <sys/time.h>
#include <sys/types.h>
#include <thread>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "eventql/util/http/httpserverconnection.h"
#include "eventql/eventql.h"
#include "eventql/server/listener.h"
#include "eventql/server/session.h"
#include "eventql/db/database.h"
#include "eventql/util/return_code.h"
#include "eventql/util/logging.h"
#include "eventql/transport/native/connection_tcp.h"
namespace eventql {
Listener::Listener(
Database* database) :
database_(database),
io_timeout_(
std::max(
database->getConfig()->getInt("server.s2s_io_timeout").get(),
database->getConfig()->getInt("server.c2s_io_timeout").get())),
running_(true),
ssock_(-1),
http_transport_(database),
native_server_(database) {}
ReturnCode Listener::bind(int listen_port) {
ssock_ = ::socket(AF_INET, SOCK_STREAM, 0);
if (ssock_ == 0) {
return ReturnCode::error(
"IOERR",
"create socket() failed: %s",
strerror(errno));
}
int opt = 1;
if (::setsockopt(ssock_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
return ReturnCode::error(
"IOERR",
"setsockopt(SO_REUSEADDR) failed: %s",
strerror(errno));
}
int flags = ::fcntl(ssock_, F_GETFL, 0);
flags = flags | O_NONBLOCK;
if (::fcntl(ssock_, F_SETFL, flags) != 0) {
return ReturnCode::error(
"IOERR",
"fcntl(F_SETFL, O_NONBLOCK) failed: %s",
strerror(errno));
}
struct sockaddr_in addr;
memset((char *) &addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(listen_port);
if (::bind(ssock_, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
return ReturnCode::error(
"IOERR",
"bind() failed: %s",
strerror(errno));
}
if (::listen(ssock_, 1024) == -1) {
return ReturnCode::error(
"IOERR",
"listen() failed: %s",
strerror(errno));
}
logNotice("eventql", "Listening on port $0", listen_port);
return ReturnCode::success();
}
void Listener::run() {
http_transport_.startIOThread();
while (running_.load()) {
fd_set op_read, op_write, op_error;
FD_ZERO(&op_read);
FD_ZERO(&op_write);
FD_ZERO(&op_error);
int max_fd = ssock_;
FD_SET(ssock_, &op_read);
auto now = MonotonicClock::now();
while (!connections_.empty()) {
if (connections_.front().accepted_at + io_timeout_ > now) {
break;
}
logError(
"eventql",
"timeout while reading first byte, closing connection");
close(connections_.front().fd);
connections_.pop_front();
}
uint64_t timeout = 0;
if (!connections_.empty()) {
timeout = (connections_.front().accepted_at + io_timeout_) - now;
}
for (const auto& c : connections_) {
if (c.fd > max_fd) {
max_fd = c.fd;
}
FD_SET(c.fd, &op_read);
}
int res;
if (timeout) {
struct timeval tv;
tv.tv_sec = timeout / kMicrosPerSecond;
tv.tv_usec = timeout % kMicrosPerSecond;
res = select(max_fd + 1, &op_read, &op_write, &op_error, &tv);
} else {
res = select(max_fd + 1, &op_read, &op_write, &op_error, NULL);
}
switch (res) {
case 0:
continue;
case -1:
if (errno == EINTR) {
continue;
}
logError("eventql", "select() failed");
goto exit;
}
if (FD_ISSET(ssock_, &op_read)) {
int conn_fd = ::accept(ssock_, NULL, NULL);
if (conn_fd < 0) {
logError("eventql", "accept() failed");
}
int flags = ::fcntl(conn_fd, F_GETFL, 0);
flags = flags | O_NONBLOCK;
if (::fcntl(conn_fd, F_SETFL, flags) != 0) {
logError(
"eventql",
"fcntl(F_SETFL, O_NONBLOCK) failed, closing connection: $0",
strerror(errno));
close(conn_fd);
continue;
}
EstablishingConnection c;
c.fd = conn_fd;
c.accepted_at = MonotonicClock::now();
connections_.emplace_back(c);
}
auto iter = connections_.begin();
while (iter != connections_.end()) {
if (FD_ISSET(iter->fd, &op_read)) {
open(iter->fd);
iter = connections_.erase(iter);
} else {
iter++;
}
}
}
exit:
http_transport_.stopIOThread();
return;
}
void Listener::shutdown() {
}
void Listener::open(int fd) {
char first_byte;
auto res = ::read(fd, &first_byte, 1);
if (res != 1) {
logError(
"eventql",
"error while reading first byte, closing connection: $0",
strerror(errno));
close(fd);
return;
}
int flags = ::fcntl(fd, F_GETFL, 0);
flags = flags & ~O_NONBLOCK;
if (::fcntl(fd, F_SETFL, flags) != 0) {
logError(
"eventql",
"fcntl(F_SETFL, O_NONBLOCK) failed, closing connection: $0",
strerror(errno));
close(fd);
return;
}
switch (first_byte) {
// native
case '^': {
native_server_.startConnection(
std::unique_ptr<native_transport::NativeConnection>(
new native_transport::TCPConnection(
fd,
io_timeout_,
std::string(&first_byte, 1))));
break;
}
// http
default:
http_transport_.handleConnection(fd, std::string(&first_byte, 1));
break;
}
}
} // namespace eventql
<|endoftext|>
|
<commit_before>#include "util.hpp"
#include "distributed-node.hpp"
DistributedNode::DistributedNode(std::string new_keyfile)
:status(OBJECT),
ddata(OBJECT),
keyfile(new_keyfile){
uint16_t port = 30000;
while(true){
try{
this->server = new SymmetricEpollServer(this->keyfile, port, 10);
}catch(std::runtime_error& e){
if(errno != 98){
PRINT("ERROR: " << errno)
throw e;
}
port++;
continue;
}
break;
}
this->server->on_read = [&](int fd, const char* data, ssize_t data_length)->ssize_t{
PRINT(data)
JsonObject request;
request.parse(data);
PRINT(request.stringify(true))
JsonObject response(OBJECT);
if(request.HasObj("hash", STRING)){
PRINT("GIVEN HASH: " << request.GetStr("hash"))
PRINT("MY HASH: " << this->status.GetStr("hash"))
if(request.GetStr("hash") == this->status.GetStr("hash")){
response.objectValues["status"] = new JsonObject("Up to date.");
}else{
response.objectValues["status"] = new JsonObject("Out of date.");
}
}else{
response.objectValues["hash"] = new JsonObject(this->status.GetStr("hash"));
}
if(this->server->send(fd, response.stringify(false))){
ERROR("DistributedNode send")
return -1;
}
return data_length;
};
// Returns and runs on a single thread.
this->server->run(true, 1);
start_thread = std::thread(&DistributedNode::start, this);
PRINT("DISTRIBUTED NODE INITIALIZED.")
}
void DistributedNode::add_client(const char* ip_address, uint16_t port){
std::string client = std::string(ip_address) + ':' + std::to_string(port);
this->clients_mutex.lock();
this->clients[client] = new SymmetricTcpClient(ip_address, port, this->keyfile);
this->clients_mutex.unlock();
}
bool DistributedNode::set_ddata(std::string data){
this->ddata.objectValues.clear();
this->ddata.parse(data.c_str());
this->status.objectValues["hash"] = new JsonObject(Util::sha256_hash(this->ddata.stringify(false)));
return true;
}
void DistributedNode::start(){
std::string response;
while(true){
this->clients_mutex.lock();
for(auto iter = this->clients.begin(); iter != this->clients.end(); ++iter){
response = iter->second->communicate(status.stringify(false));
if(response.empty()){
PRINT(iter->first << " DISCONNECTED")
}else{
PRINT(iter->first << " -> " << response)
}
}
this->clients_mutex.unlock();
sleep(5);
}
}
<commit_msg>Improved port selection for distributed node. Hmph.<commit_after>#include "util.hpp"
#include "distributed-node.hpp"
DistributedNode::DistributedNode(std::string new_keyfile)
:status(OBJECT),
ddata(OBJECT),
keyfile(new_keyfile){
uint16_t port = 30000;
while(true){
try{
this->server = new SymmetricEpollServer(this->keyfile, port, 10);
}catch(std::runtime_error& e){
if(errno != 98 && errno != 22){
PRINT("ERROR: " << errno << ':' << port)
throw e;
}
port++;
sleep(1);
continue;
}
break;
}
this->server->on_read = [&](int fd, const char* data, ssize_t data_length)->ssize_t{
PRINT(data)
JsonObject request;
request.parse(data);
PRINT(request.stringify(true))
JsonObject response(OBJECT);
if(request.HasObj("hash", STRING)){
PRINT("GIVEN HASH: " << request.GetStr("hash"))
PRINT("MY HASH: " << this->status.GetStr("hash"))
if(request.GetStr("hash") == this->status.GetStr("hash")){
response.objectValues["status"] = new JsonObject("Up to date.");
}else{
response.objectValues["status"] = new JsonObject("Out of date.");
}
}else{
response.objectValues["hash"] = new JsonObject(this->status.GetStr("hash"));
}
if(this->server->send(fd, response.stringify(false))){
ERROR("DistributedNode send")
return -1;
}
return data_length;
};
// Returns and runs on a single thread.
this->server->run(true, 1);
start_thread = std::thread(&DistributedNode::start, this);
PRINT("DISTRIBUTED NODE INITIALIZED.")
}
void DistributedNode::add_client(const char* ip_address, uint16_t port){
std::string client = std::string(ip_address) + ':' + std::to_string(port);
this->clients_mutex.lock();
this->clients[client] = new SymmetricTcpClient(ip_address, port, this->keyfile);
this->clients_mutex.unlock();
}
bool DistributedNode::set_ddata(std::string data){
this->ddata.objectValues.clear();
this->ddata.parse(data.c_str());
this->status.objectValues["hash"] = new JsonObject(Util::sha256_hash(this->ddata.stringify(false)));
return true;
}
void DistributedNode::start(){
std::string response;
while(true){
this->clients_mutex.lock();
for(auto iter = this->clients.begin(); iter != this->clients.end(); ++iter){
response = iter->second->communicate(status.stringify(false));
if(response.empty()){
PRINT(iter->first << " DISCONNECTED")
}else{
PRINT(iter->first << " -> " << response)
}
}
this->clients_mutex.unlock();
sleep(5);
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net>
*
* 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
*/
#include "analyzer.h"
#include "translator.h"
#include "yaml.h"
using namespace std;
using namespace std::placeholders;
Model initModel(string path)
{
eraseSuffix(&path, ".yaml");
auto dirPos = path.rfind('/');
// The below code assumes that npos == -1 and that unsigned overflow works
return Model(path.substr(0, dirPos + 1), path.substr(dirPos + 1));
}
Analyzer::Analyzer(string filePath, string basePath,
const Translator& translator)
: fileName(filePath), baseDir(move(basePath))
, model(initModel(move(filePath))), translator(translator)
{ }
TypeUsage Analyzer::analyzeType(const YamlMap& node, InOut inOut, string scope,
IsTopLevel isTopLevel)
{
auto yamlTypeNode = node["type"];
if (yamlTypeNode && yamlTypeNode.IsSequence())
return translator.mapType("object"); // TODO: Multitype/variant support
auto yamlType = yamlTypeNode.as<string>("object");
if (yamlType == "array")
{
if (auto yamlElemType = node["items"].asMap())
if (!yamlElemType.empty())
{
auto elemType =
analyzeType(yamlElemType, inOut, move(scope));
const auto& protoType =
translator.mapType("array", elemType.baseName, "array");
return protoType.instantiate(move(elemType));
}
return translator.mapType("array");
}
if (yamlType == "object")
{
auto schema = analyzeSchema(node, inOut, move(scope));
if (isTopLevel && inOut&Out && schema.empty())
return TypeUsage(""); // Non-existent object, void
if (!schema.name.empty()) // Only ever filled for non-empty schemas
{
model.addSchema(schema);
auto tu = translator.mapType("schema");
tu.scope = schema.scope;
tu.name = tu.baseName = schema.name;
return tu;
}
if (schema.trivial()) // An alias for another type
return schema.parentTypes.front();
// An In empty object is schemaless but existing, mapType("object")
// Also, a nameless non-empty schema is now treated as a generic
// mapType("object"). TODO, low priority: ad-hoc typing (via tuples?)
}
auto tu = translator.mapType(yamlType, node["format"].as<string>(""));
if (!tu.empty())
return tu;
throw YamlException(node, "Unknown type: " + yamlType);
}
ObjectSchema Analyzer::analyzeSchema(const YamlMap& yamlSchema, InOut inOut,
string scope, string locus)
{
ObjectSchema schema;
schema.inOut = inOut;
vector<string> refPaths;
if (auto yamlRef = yamlSchema["$ref"])
refPaths.emplace_back(yamlRef.as<string>());
else if (auto yamlAllOf = yamlSchema["allOf"].asSequence())
{
refPaths.resize(yamlAllOf.size());
transform(yamlAllOf.begin(), yamlAllOf.end(), refPaths.begin(),
[](YamlMap p) { return p.get("$ref").as<string>(); });
}
for (const auto& refPath: refPaths)
{
// First try to resolve refPath in types map; if there's no match, load
// the schema from the reference path.
auto tu = translator.mapType("object", refPath);
if (!tu.empty())
{
cout << "Using type " << tu.name << " for " << refPath << endl;
schema.parentTypes.emplace_back(move(tu));
continue;
}
// The referenced file's path is relative to the current file's path;
// we have to append a path to the current file's directory in order to
// find the file.
cout << "Sub-processing schema in "
<< model.fileDir << "./" << refPath << endl;
const Model& m =
translator.processFile(model.fileDir + refPath, baseDir);
if (m.types.empty())
throw YamlException(yamlSchema, "The target file has no schemas");
schema.parentTypes.emplace_back(
m.types.back().name,
m.dstFiles.empty() ? string{} : "\"" + m.dstFiles.front() + "\"");
// TODO: distinguish between interface files (that should be imported,
// headers in C/C+) and implementation files (that should not).
// filesList.front() assumes that there's only one interface file, and
// it's at the front of the list, which is very naive.
}
if (schema.empty() && yamlSchema["type"].as<string>("object") != "object")
{
auto parentType = analyzeType(yamlSchema, inOut, scope);
if (!parentType.empty())
schema.parentTypes.emplace_back(move(parentType));
}
if (const auto properties = yamlSchema["properties"].asMap())
{
const auto requiredList = yamlSchema["required"].asSequence();
for (const YamlNodePair property: properties)
{
const auto baseName = property.first.as<string>();
auto required = any_of(requiredList.begin(), requiredList.end(),
[&baseName](const YamlNode& n)
{ return baseName == n.as<string>(); } );
addVarDecl(schema.fields, analyzeType(property.second, inOut, scope),
baseName, required);
}
}
if (!schema.empty())
{
auto name = camelCase(yamlSchema["title"].as<string>(""));
// Checking for name difference commented out due to #28
if (!schema.trivial()/* || name != qualifiedName(s.parentTypes.front()) */)
{
// If the schema is not just an alias for another type, name it.
schema.name = move(name);
schema.scope.swap(scope);
}
if (!schema.name.empty() || !schema.trivial())
{
cout << yamlSchema.location() << ": Found "
<< (!locus.empty() ? locus + " schema"
: "schema " + qualifiedName(schema))
<< " for "
<< (schema.inOut == In ? "input" :
schema.inOut == Out ? "output" :
schema.inOut == (In|Out) ? "in/out" : "undefined use");
if (schema.trivial())
cout << " mapped to "
<< qualifiedName(schema.parentTypes.front()) << endl;
else
cout << " (parent(s): " << schema.parentTypes.size()
<< ", field(s): " << schema.fields.size() << ")" << endl;
}
}
return schema;
}
void Analyzer::addParamsFromSchema(VarDecls& varList,
const string& baseName, bool required, const ObjectSchema& paramSchema)
{
if (paramSchema.parentTypes.empty())
{
for (const auto & param: paramSchema.fields)
model.addVarDecl(varList, param);
} else if (paramSchema.trivial())
{
// The schema consists of a single parent type, use that type instead.
addVarDecl(varList, paramSchema.parentTypes.front(), baseName, required);
} else
{
cerr << "Warning: found non-trivial schema for " << baseName
<< "; these are not supported, expect invalid parameter set"
<< endl;
const auto typeName =
paramSchema.name.empty() ? camelCase(baseName) : paramSchema.name;
model.addSchema(paramSchema);
addVarDecl(varList, TypeUsage(typeName), baseName, required);
}
}
vector<string> loadContentTypes(const YamlMap& yaml, const char* keyName)
{
if (auto yamlTypes = yaml[keyName].asSequence())
{
vector<string> result { yamlTypes.size() };
transform(yamlTypes.begin(), yamlTypes.end(),
result.begin(), mem_fn(&YamlNode::as<string>));
return result;
}
return {};
}
Model Analyzer::loadModel(const pair_vector_t<string>& substitutions,
InOut inOut)
{
cout << "Loading from " << baseDir + fileName << endl;
auto yaml = YamlMap::loadFromFile(baseDir + fileName, substitutions);
// Detect which file we have: API description or just data definition
// TODO: This should be refactored to two separate methods, since we shouldn't
// allow loading an API description file referenced from another API description.
if (const auto paths = yaml.get("paths", true).asMap())
{
if (yaml.get("swagger").as<string>() != "2.0")
throw Exception(
"This software only supports swagger version 2.0 for now");
auto defaultConsumed = loadContentTypes(yaml, "consumes");
auto defaultProduced = loadContentTypes(yaml, "produces");
model.hostAddress = yaml["host"].as<string>("");
model.basePath = yaml["basePath"].as<string>("");
for (const YamlNodePair& yaml_path: paths)
try {
const Path path { yaml_path.first.as<string>() };
for (const YamlNodePair& yaml_call_pair: yaml_path.second.asMap())
{
auto verb = yaml_call_pair.first.as<string>();
const YamlMap yamlCall { yaml_call_pair.second };
auto operationId = yamlCall.get("operationId").as<string>();
bool needsSecurity = false;
if (const auto security = yamlCall["security"].asSequence())
needsSecurity = security[0]["accessToken"].IsDefined();
cout << yamlCall.location() << ": Found operation "
<< operationId
<< " (" << path << ", " << verb << ')' << endl;
Call& call =
model.addCall(path, move(verb), move(operationId),
needsSecurity);
call.consumedContentTypes =
loadContentTypes(yamlCall, "consumes");
if (call.consumedContentTypes.empty())
call.consumedContentTypes = defaultConsumed;
call.producedContentTypes =
loadContentTypes(yamlCall, "produces");
if (call.producedContentTypes.empty())
call.producedContentTypes = defaultProduced;
const auto yamlParams = yamlCall["parameters"].asSequence();
for (const YamlMap yamlParam: yamlParams)
{
const auto& name = yamlParam.get("name").as<string>();
auto&& in = yamlParam.get("in").as<string>();
auto required = yamlParam["required"].as<bool>(false);
if (!required && in == "path")
{
clog << yamlParam.location() << ": warning: '" << name
<< "' is in path but has no 'required' attribute"
<< " - treating as required anyway" << endl;
required = true;
}
// clog << "Parameter: " << name << endl;
// for (const YamlNodePair p: yamlParam)
// {
// clog << " At " << p.first.location() << ": " << p.first.as<string>() << endl;
// }
if (in != "body")
{
addVarDecl(call.getParamsBlock(in),
analyzeType(yamlParam, In, call.name, TopLevel),
name, required, yamlParam["default"].as<string>(""));
continue;
}
auto&& bodySchema =
analyzeSchema(yamlParam.get("schema"), In, call.name,
"request body");
if (bodySchema.empty())
{
// Special case: an empty schema for a body parameter
// means a freeform object.
call.inlineBody = true;
addVarDecl(call.bodyParams(),
translator.mapType("object"), name, false);
} else {
// The schema consists of a single parent type, inline that type.
if (bodySchema.trivial())
call.inlineBody = true;
addParamsFromSchema(call.bodyParams(),
name, required, bodySchema);
}
}
const auto yamlResponses = yamlCall.get("responses").asMap();
if (const auto yamlResponse = yamlResponses["200"].asMap())
{
Response response { "200" };
if (auto yamlHeaders = yamlResponse["headers"])
for (const auto& yamlHeader: yamlHeaders.asMap())
{
addVarDecl(response.headers,
analyzeType(yamlHeader.second, Out, call.name,
TopLevel),
yamlHeader.first.as<string>(), false);
}
if (auto yamlSchema = yamlResponse["schema"])
{
auto&& responseSchema =
analyzeSchema(yamlSchema, Out, call.name, "response");
if (!responseSchema.empty())
addParamsFromSchema(response.properties,
"content", true, responseSchema);
}
call.responses.emplace_back(move(response));
}
}
}
catch (ModelException& me)
{
throw YamlException(yaml_path.first, me.message);
}
} else {
auto schema = analyzeSchema(yaml, inOut);
if (schema.name.empty())
schema.name = camelCase(model.srcFilename);
model.addSchema(schema);
}
return std::move(model);
}
<commit_msg>Support additionalProperties<commit_after>/******************************************************************************
* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net>
*
* 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
*/
#include "analyzer.h"
#include "translator.h"
#include "yaml.h"
using namespace std;
using namespace std::placeholders;
Model initModel(string path)
{
eraseSuffix(&path, ".yaml");
auto dirPos = path.rfind('/');
// The below code assumes that npos == -1 and that unsigned overflow works
return Model(path.substr(0, dirPos + 1), path.substr(dirPos + 1));
}
Analyzer::Analyzer(string filePath, string basePath,
const Translator& translator)
: fileName(filePath), baseDir(move(basePath))
, model(initModel(move(filePath))), translator(translator)
{ }
TypeUsage Analyzer::analyzeType(const YamlMap& node, InOut inOut, string scope,
IsTopLevel isTopLevel)
{
auto yamlTypeNode = node["type"];
if (yamlTypeNode && yamlTypeNode.IsSequence())
return translator.mapType("object"); // TODO: Multitype/variant support
auto yamlType = yamlTypeNode.as<string>("object");
if (yamlType == "array")
{
if (auto yamlElemType = node["items"].asMap())
if (!yamlElemType.empty())
{
auto elemType =
analyzeType(yamlElemType, inOut, move(scope));
const auto& protoType =
translator.mapType("array", elemType.baseName, "array");
return protoType.instantiate(move(elemType));
}
return translator.mapType("array");
}
if (yamlType == "object")
{
auto schema = analyzeSchema(node, inOut, scope);
if (schema.empty())
{
if (const auto propertyMap = node["additionalProperties"])
switch (propertyMap.Type())
{
case YAML::NodeType::Map:
{
auto elemType =
analyzeType(propertyMap.asMap(), inOut, scope);
const auto& protoType =
translator.mapType("map", elemType.baseName,
"additionalProperties");
return protoType.instantiate(move(elemType));
}
case YAML::NodeType::Scalar:
if (propertyMap.as<bool>()) // Generic map
return translator.mapType("map");
else // Additional properties forbidden - no special treatment
break;
default:
throw YamlException(propertyMap,
"additionalProperties should be either a boolean or a map");
}
if (isTopLevel && inOut&Out)
return TypeUsage(""); // The type returned by this API is void
}
if (!schema.name.empty()) // Only ever filled for non-empty schemas
{
model.addSchema(schema);
auto tu = translator.mapType("schema");
tu.scope = schema.scope;
tu.name = tu.baseName = schema.name;
return tu;
}
if (schema.trivial()) // An alias for another type
return schema.parentTypes.front();
// An In empty object is schemaless but existing, mapType("object")
// Also, a nameless non-empty schema is now treated as a generic
// mapType("object"). TODO, low priority: ad-hoc typing (via tuples?)
}
auto tu = translator.mapType(yamlType, node["format"].as<string>(""));
if (!tu.empty())
return tu;
throw YamlException(node, "Unknown type: " + yamlType);
}
ObjectSchema Analyzer::analyzeSchema(const YamlMap& yamlSchema, InOut inOut,
string scope, string locus)
{
ObjectSchema schema;
schema.inOut = inOut;
vector<string> refPaths;
if (auto yamlRef = yamlSchema["$ref"])
refPaths.emplace_back(yamlRef.as<string>());
else if (auto yamlAllOf = yamlSchema["allOf"].asSequence())
{
refPaths.resize(yamlAllOf.size());
transform(yamlAllOf.begin(), yamlAllOf.end(), refPaths.begin(),
[](YamlMap p) { return p.get("$ref").as<string>(); });
}
for (const auto& refPath: refPaths)
{
// First try to resolve refPath in types map; if there's no match, load
// the schema from the reference path.
auto tu = translator.mapType("object", refPath);
if (!tu.empty())
{
cout << "Using type " << tu.name << " for " << refPath << endl;
schema.parentTypes.emplace_back(move(tu));
continue;
}
// The referenced file's path is relative to the current file's path;
// we have to append a path to the current file's directory in order to
// find the file.
cout << "Sub-processing schema in "
<< model.fileDir << "./" << refPath << endl;
const Model& m =
translator.processFile(model.fileDir + refPath, baseDir);
if (m.types.empty())
throw YamlException(yamlSchema, "The target file has no schemas");
schema.parentTypes.emplace_back(
m.types.back().name,
m.dstFiles.empty() ? string{} : "\"" + m.dstFiles.front() + "\"");
// TODO: distinguish between interface files (that should be imported,
// headers in C/C+) and implementation files (that should not).
// filesList.front() assumes that there's only one interface file, and
// it's at the front of the list, which is very naive.
}
if (schema.empty() && yamlSchema["type"].as<string>("object") != "object")
{
auto parentType = analyzeType(yamlSchema, inOut, scope);
if (!parentType.empty())
schema.parentTypes.emplace_back(move(parentType));
}
if (const auto properties = yamlSchema["properties"].asMap())
{
const auto requiredList = yamlSchema["required"].asSequence();
for (const YamlNodePair property: properties)
{
const auto baseName = property.first.as<string>();
auto required = any_of(requiredList.begin(), requiredList.end(),
[&baseName](const YamlNode& n)
{ return baseName == n.as<string>(); } );
addVarDecl(schema.fields, analyzeType(property.second, inOut, scope),
baseName, required);
}
}
if (!schema.empty())
{
auto name = camelCase(yamlSchema["title"].as<string>(""));
// Checking for name difference commented out due to #28
if (!schema.trivial()/* || name != qualifiedName(s.parentTypes.front()) */)
{
// If the schema is not just an alias for another type, name it.
schema.name = move(name);
schema.scope.swap(scope);
}
if (!schema.name.empty() || !schema.trivial())
{
cout << yamlSchema.location() << ": Found "
<< (!locus.empty() ? locus + " schema"
: "schema " + qualifiedName(schema))
<< " for "
<< (schema.inOut == In ? "input" :
schema.inOut == Out ? "output" :
schema.inOut == (In|Out) ? "in/out" : "undefined use");
if (schema.trivial())
cout << " mapped to "
<< qualifiedName(schema.parentTypes.front()) << endl;
else
cout << " (parent(s): " << schema.parentTypes.size()
<< ", field(s): " << schema.fields.size() << ")" << endl;
}
}
return schema;
}
void Analyzer::addParamsFromSchema(VarDecls& varList,
const string& baseName, bool required, const ObjectSchema& paramSchema)
{
if (paramSchema.parentTypes.empty())
{
for (const auto & param: paramSchema.fields)
model.addVarDecl(varList, param);
} else if (paramSchema.trivial())
{
// The schema consists of a single parent type, use that type instead.
addVarDecl(varList, paramSchema.parentTypes.front(), baseName, required);
} else
{
cerr << "Warning: found non-trivial schema for " << baseName
<< "; these are not supported, expect invalid parameter set"
<< endl;
const auto typeName =
paramSchema.name.empty() ? camelCase(baseName) : paramSchema.name;
model.addSchema(paramSchema);
addVarDecl(varList, TypeUsage(typeName), baseName, required);
}
}
vector<string> loadContentTypes(const YamlMap& yaml, const char* keyName)
{
if (auto yamlTypes = yaml[keyName].asSequence())
{
vector<string> result { yamlTypes.size() };
transform(yamlTypes.begin(), yamlTypes.end(),
result.begin(), mem_fn(&YamlNode::as<string>));
return result;
}
return {};
}
Model Analyzer::loadModel(const pair_vector_t<string>& substitutions,
InOut inOut)
{
cout << "Loading from " << baseDir + fileName << endl;
auto yaml = YamlMap::loadFromFile(baseDir + fileName, substitutions);
// Detect which file we have: API description or just data definition
// TODO: This should be refactored to two separate methods, since we shouldn't
// allow loading an API description file referenced from another API description.
if (const auto paths = yaml.get("paths", true).asMap())
{
if (yaml.get("swagger").as<string>() != "2.0")
throw Exception(
"This software only supports swagger version 2.0 for now");
auto defaultConsumed = loadContentTypes(yaml, "consumes");
auto defaultProduced = loadContentTypes(yaml, "produces");
model.hostAddress = yaml["host"].as<string>("");
model.basePath = yaml["basePath"].as<string>("");
for (const YamlNodePair& yaml_path: paths)
try {
const Path path { yaml_path.first.as<string>() };
for (const YamlNodePair& yaml_call_pair: yaml_path.second.asMap())
{
auto verb = yaml_call_pair.first.as<string>();
const YamlMap yamlCall { yaml_call_pair.second };
auto operationId = yamlCall.get("operationId").as<string>();
bool needsSecurity = false;
if (const auto security = yamlCall["security"].asSequence())
needsSecurity = security[0]["accessToken"].IsDefined();
cout << yamlCall.location() << ": Found operation "
<< operationId
<< " (" << path << ", " << verb << ')' << endl;
Call& call =
model.addCall(path, move(verb), move(operationId),
needsSecurity);
call.consumedContentTypes =
loadContentTypes(yamlCall, "consumes");
if (call.consumedContentTypes.empty())
call.consumedContentTypes = defaultConsumed;
call.producedContentTypes =
loadContentTypes(yamlCall, "produces");
if (call.producedContentTypes.empty())
call.producedContentTypes = defaultProduced;
const auto yamlParams = yamlCall["parameters"].asSequence();
for (const YamlMap yamlParam: yamlParams)
{
const auto& name = yamlParam.get("name").as<string>();
auto&& in = yamlParam.get("in").as<string>();
auto required = yamlParam["required"].as<bool>(false);
if (!required && in == "path")
{
clog << yamlParam.location() << ": warning: '" << name
<< "' is in path but has no 'required' attribute"
<< " - treating as required anyway" << endl;
required = true;
}
// clog << "Parameter: " << name << endl;
// for (const YamlNodePair p: yamlParam)
// {
// clog << " At " << p.first.location() << ": " << p.first.as<string>() << endl;
// }
if (in != "body")
{
addVarDecl(call.getParamsBlock(in),
analyzeType(yamlParam, In, call.name, TopLevel),
name, required, yamlParam["default"].as<string>(""));
continue;
}
auto&& bodySchema =
analyzeSchema(yamlParam.get("schema"), In, call.name,
"request body");
if (bodySchema.empty())
{
// Special case: an empty schema for a body parameter
// means a freeform object.
call.inlineBody = true;
addVarDecl(call.bodyParams(),
translator.mapType("object"), name, false);
} else {
// The schema consists of a single parent type, inline that type.
if (bodySchema.trivial())
call.inlineBody = true;
addParamsFromSchema(call.bodyParams(),
name, required, bodySchema);
}
}
const auto yamlResponses = yamlCall.get("responses").asMap();
if (const auto yamlResponse = yamlResponses["200"].asMap())
{
Response response { "200" };
if (auto yamlHeaders = yamlResponse["headers"])
for (const auto& yamlHeader: yamlHeaders.asMap())
{
addVarDecl(response.headers,
analyzeType(yamlHeader.second, Out, call.name,
TopLevel),
yamlHeader.first.as<string>(), false);
}
if (auto yamlSchema = yamlResponse["schema"])
{
auto&& responseSchema =
analyzeSchema(yamlSchema, Out, call.name, "response");
if (!responseSchema.empty())
addParamsFromSchema(response.properties,
"content", true, responseSchema);
}
call.responses.emplace_back(move(response));
}
}
}
catch (ModelException& me)
{
throw YamlException(yaml_path.first, me.message);
}
} else {
auto schema = analyzeSchema(yaml, inOut);
if (schema.name.empty())
schema.name = camelCase(model.srcFilename);
model.addSchema(schema);
}
return std::move(model);
}
<|endoftext|>
|
<commit_before>//!
//! @file ParameterDialog.cpp
//! @author Björn Eriksson <bjorn.eriksson@liu.se>
//! @date 2010-03-01
//!
//! @brief Contains a class for interact with paramters
//!
//$Id$
#include <QtGui>
#include <cassert>
#include "ParameterDialog.h"
#include "HopsanCore.h"
//! Constructor.
//! @param coreComponent is a ponter to the core component.
//! @param parent defines a parent to the new instanced object.
ParameterDialog::ParameterDialog(Component *coreComponent, QWidget *parent)
: QDialog(parent)
{
mpCoreComponent = coreComponent;
std::vector<CompParameter>::iterator it;
vector<CompParameter> paramVector = mpCoreComponent->getParameterVector();
for ( it=paramVector.begin() ; it !=paramVector.end(); it++ )
{
mVarVector.push_back(new QLabel(QString::fromStdString(it->getName())));
mVarVector.back()->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
mDescriptionVector.push_back(new QLabel(QString::fromStdString(it->getDesc())));
mUnitVector.push_back(new QLabel(QString::fromStdString(it->getUnit())));
mValueVector.push_back(new QLineEdit());
mValueVector.back()->setValidator(new QDoubleValidator(-999.0, 999.0, 6, mValueVector.back()));
QString valueTxt;
valueTxt.setNum(it->getValue(), 'g', 6 );
mValueVector.back()->setText(valueTxt);
mVarVector.back()->setBuddy(mValueVector.back());
}
okButton = new QPushButton(tr("&Ok"));
okButton->setDefault(true);
cancelButton = new QPushButton(tr("&Cancel"));
cancelButton->setDefault(false);
buttonBox = new QDialogButtonBox(Qt::Vertical);
buttonBox->addButton(okButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(cancelButton, QDialogButtonBox::ActionRole);
connect(okButton, SIGNAL(pressed()), SLOT(setParameters()));
connect(cancelButton, SIGNAL(pressed()), SLOT(close()));
QVBoxLayout *topLeftLayout1 = new QVBoxLayout;
QVBoxLayout *topLeftLayout2 = new QVBoxLayout;
QVBoxLayout *topLeftLayout3 = new QVBoxLayout;
QVBoxLayout *topLeftLayout4 = new QVBoxLayout;
for (size_t i=0 ; i <mVarVector.size(); ++i )
{
topLeftLayout1->addWidget(mDescriptionVector[i]);
topLeftLayout2->addWidget(mVarVector[i]);
topLeftLayout3->addWidget(mValueVector[i]);
topLeftLayout4->addWidget(mUnitVector[i]);
}
QHBoxLayout *leftLayout = new QHBoxLayout;
leftLayout->addLayout(topLeftLayout1);
leftLayout->addLayout(topLeftLayout2);
leftLayout->addLayout(topLeftLayout3);
leftLayout->addLayout(topLeftLayout4);
leftLayout->addStretch(1);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->setSizeConstraint(QLayout::SetFixedSize);
mainLayout->addLayout(leftLayout, 0, 0);
mainLayout->addWidget(buttonBox, 0, 1);
setLayout(mainLayout);
setWindowTitle(tr("Parameters"));
}
//! Sets the parameters in the core component. Read the values from the dialog and write them into the core component.
void ParameterDialog::setParameters()
{
for (size_t i=0 ; i < mValueVector.size(); ++i )
{
bool ok;
mpCoreComponent->setParameter(mVarVector[i]->text().toStdString(), mValueVector[i]->text().toDouble(&ok));
//std::cout << "i: " << i << qPrintable(labelList[i]->text()) << " " << mpCoreComponent->getParameterVector().at(i).getName() << std::endl;
if (!ok)
{
assert(false);
}
}
std::cout << "Parameters updated." << std::endl;
this->close();
}
<commit_msg>handle empty input in parameterdialogs<commit_after>//!
//! @file ParameterDialog.cpp
//! @author Björn Eriksson <bjorn.eriksson@liu.se>
//! @date 2010-03-01
//!
//! @brief Contains a class for interact with paramters
//!
//$Id$
#include <QtGui>
#include <cassert>
#include "ParameterDialog.h"
#include "HopsanCore.h"
//! Constructor.
//! @param coreComponent is a ponter to the core component.
//! @param parent defines a parent to the new instanced object.
ParameterDialog::ParameterDialog(Component *coreComponent, QWidget *parent)
: QDialog(parent)
{
mpCoreComponent = coreComponent;
std::vector<CompParameter>::iterator it;
vector<CompParameter> paramVector = mpCoreComponent->getParameterVector();
for ( it=paramVector.begin() ; it !=paramVector.end(); it++ )
{
mVarVector.push_back(new QLabel(QString::fromStdString(it->getName())));
mVarVector.back()->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
mDescriptionVector.push_back(new QLabel(QString::fromStdString(it->getDesc())));
mUnitVector.push_back(new QLabel(QString::fromStdString(it->getUnit())));
mValueVector.push_back(new QLineEdit());
mValueVector.back()->setValidator(new QDoubleValidator(-999.0, 999.0, 6, mValueVector.back()));
QString valueTxt;
valueTxt.setNum(it->getValue(), 'g', 6 );
mValueVector.back()->setText(valueTxt);
mVarVector.back()->setBuddy(mValueVector.back());
}
okButton = new QPushButton(tr("&Ok"));
okButton->setDefault(true);
cancelButton = new QPushButton(tr("&Cancel"));
cancelButton->setDefault(false);
buttonBox = new QDialogButtonBox(Qt::Vertical);
buttonBox->addButton(okButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(cancelButton, QDialogButtonBox::ActionRole);
connect(okButton, SIGNAL(pressed()), SLOT(setParameters()));
connect(cancelButton, SIGNAL(pressed()), SLOT(close()));
QVBoxLayout *topLeftLayout1 = new QVBoxLayout;
QVBoxLayout *topLeftLayout2 = new QVBoxLayout;
QVBoxLayout *topLeftLayout3 = new QVBoxLayout;
QVBoxLayout *topLeftLayout4 = new QVBoxLayout;
for (size_t i=0 ; i <mVarVector.size(); ++i )
{
topLeftLayout1->addWidget(mDescriptionVector[i]);
topLeftLayout2->addWidget(mVarVector[i]);
topLeftLayout3->addWidget(mValueVector[i]);
topLeftLayout4->addWidget(mUnitVector[i]);
}
QHBoxLayout *leftLayout = new QHBoxLayout;
leftLayout->addLayout(topLeftLayout1);
leftLayout->addLayout(topLeftLayout2);
leftLayout->addLayout(topLeftLayout3);
leftLayout->addLayout(topLeftLayout4);
leftLayout->addStretch(1);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->setSizeConstraint(QLayout::SetFixedSize);
mainLayout->addLayout(leftLayout, 0, 0);
mainLayout->addWidget(buttonBox, 0, 1);
setLayout(mainLayout);
setWindowTitle(tr("Parameters"));
}
//! Sets the parameters in the core component. Read the values from the dialog and write them into the core component.
void ParameterDialog::setParameters()
{
for (size_t i=0 ; i < mValueVector.size(); ++i )
{
bool ok;
double newValue = mValueVector[i]->text().toDouble(&ok);
//std::cout << "i: " << i << qPrintable(labelList[i]->text()) << " " << mpCoreComponent->getParameterVector().at(i).getName() << std::endl;
if (!ok)
{
std::cout << "ParameterDialog::setParameters(): You must give a correct value for '" << mVarVector[i]->text().toStdString() << "'', putz. Try again!" << std::endl;
//this->parent()->parent()->parent()
return;
}
mpCoreComponent->setParameter(mVarVector[i]->text().toStdString(), newValue);
}
std::cout << "Parameters updated." << std::endl;
this->close();
}
<|endoftext|>
|
<commit_before>/** \file krimdok_flag_pda_records.cc
* \brief A tool for adding a PDA field to KrimDok records.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
* \author Johannes Riedl (johannes.riedl@uni-tuebingen.de)
*
* \copyright 2016,2017,2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <cstdlib>
#include "MARC.h"
#include "StringUtil.h"
#include "TimeUtil.h"
#include "util.h"
void Usage() {
std::cerr << "Usage: " << ::progname << " no_of_years marc_input_file marc_output_file\n";
std::exit(EXIT_FAILURE);
}
bool IsMatchingRecord(const MARC::Record &record, const std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> &local_block_boundaries,
std::vector<std::string> &matching_subfield_a_values)
{
for (const auto local_block_boundary : local_block_boundaries) {
std::vector<MARC::Record::const_iterator> fields;
if (record.findFieldsInLocalBlock("852", "??", local_block_boundary, &fields) == 0)
return false;
for (const auto &field : fields) {
std::vector<std::string> subfield_a_values(field->getSubfields().extractSubfields('a'));
for (const auto &subfield_a_value : subfield_a_values)
for (const auto &matching_subfield_a_value : matching_subfield_a_values)
if (subfield_a_value == matching_subfield_a_value)
return true;
}
}
return false;
}
bool IsMPIRecord(const MARC::Record &record, const std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> &local_block_boundaries) {
static std::vector<std::string> subfield_a_values{ "DE-Frei85" };
return IsMatchingRecord(record, local_block_boundaries, subfield_a_values);
}
bool IsUBOrIFKRecord(const MARC::Record &record, const std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> &local_block_boundaries) {
static std::vector<std::string> subfield_a_values{ "DE-21", "DE-21-110" };
return IsMatchingRecord(record, local_block_boundaries, subfield_a_values);
}
bool IsARecognisableYear(const std::string &year_candidate) {
if (year_candidate.length() != 4)
return false;
for (char ch : year_candidate) {
if (not StringUtil::IsDigit(ch))
return false;
}
return true;
}
// If we can find a recognisable year in 260$c we return it, o/w we return the empty string.
std::string GetPublicationYear(const MARC::Record &record) {
for (const auto &_260_field : record.getTagRange("260")) {
for (const auto &year_candidate : _260_field.getSubfields().extractSubfields('c'))
if (IsARecognisableYear(year_candidate))
return year_candidate;
}
return "";
}
void FindNonMPIInstitutions(const MARC::Record &record,
const std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> &local_block_boundaries,
std::vector<std::string> * const non_mpi_institutions)
{
non_mpi_institutions->clear();
for (const auto local_block_boundary : local_block_boundaries) {
std::vector<MARC::Record::const_iterator> fields;
if (record.findFieldsInLocalBlock("852", "??", local_block_boundary, &fields) == 0)
return;
for (const auto &field : fields) {
std::vector<std::string> subfield_a_values(field->getSubfields().extractSubfields('a'));
for (const auto &subfield_a_value : subfield_a_values)
if (subfield_a_value != "DE-Frei85")
non_mpi_institutions->emplace_back(subfield_a_value);
}
}
}
void AddPDAFieldToRecords(const std::string &cutoff_year, MARC::Reader * const marc_reader,
MARC::Writer * const marc_writer)
{
unsigned pda_field_added_count(0);
while (MARC::Record record = marc_reader->read()) {
if (not record.isMonograph()) {
marc_writer->write(record);
continue;
}
std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> local_block_boundaries;
record.findAllLocalDataBlocks(&local_block_boundaries);
if (IsMPIRecord(record, local_block_boundaries) and not IsUBOrIFKRecord(record, local_block_boundaries)) {
const std::string publication_year(GetPublicationYear(record));
if (publication_year >= cutoff_year) {
std::vector<std::string> non_mpi_institutions;
FindNonMPIInstitutions(record, local_block_boundaries, &non_mpi_institutions);
if (non_mpi_institutions.empty()) {
++pda_field_added_count;
record.insertField("PDA", MARC::Subfields({ MARC::Subfield('a', "yes") }));
marc_writer->write(record);
continue;
}
}
}
marc_writer->write(record);
}
std::cout << "Added a PDA field to " << pda_field_added_count << " record(s).\n";
}
std::string GetCutoffYear(const unsigned no_of_years) {
const unsigned current_year(StringUtil::ToUnsigned(TimeUtil::GetCurrentYear(TimeUtil::LOCAL)));
return std::to_string(current_year - no_of_years);
}
const unsigned MAX_NO_OF_YEARS_TO_CONSIDER(10);
int main(int argc, char *argv[]) {
::progname = argv[0];
try {
if (argc != 4)
Usage();
const unsigned no_of_years(StringUtil::ToUnsigned(argv[1]));
if (no_of_years > MAX_NO_OF_YEARS_TO_CONSIDER)
logger->error("the number of years we want to consider is probably incorrect!");
const std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[2], MARC::Reader::AUTO));
const std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(argv[3], MARC::Writer::AUTO));
AddPDAFieldToRecords(GetCutoffYear(no_of_years), marc_reader.get(), marc_writer.get());
} catch (const std::exception &x) {
logger->error("caught exception: " + std::string(x.what()));
}
}
<commit_msg>Minor improvements<commit_after>/** \file krimdok_flag_pda_records.cc
* \brief A tool for adding a PDA field to KrimDok records.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
* \author Johannes Riedl (johannes.riedl@uni-tuebingen.de)
*
* \copyright 2016,2017,2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <cstdlib>
#include "MARC.h"
#include "StringUtil.h"
#include "TimeUtil.h"
#include "util.h"
void Usage() {
std::cerr << "Usage: " << ::progname << " no_of_years marc_input_file marc_output_file\n";
std::exit(EXIT_FAILURE);
}
bool IsMatchingRecord(const MARC::Record &record, const std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> &local_block_boundaries,
std::vector<std::string> &matching_subfield_a_values)
{
for (const auto local_block_boundary : local_block_boundaries) {
std::vector<MARC::Record::const_iterator> fields;
if (record.findFieldsInLocalBlock("852", "??", local_block_boundary, &fields) == 0)
return false;
for (const auto &field : fields) {
std::vector<std::string> subfield_a_values(field->getSubfields().extractSubfields('a'));
for (const auto &subfield_a_value : subfield_a_values)
for (const auto &matching_subfield_a_value : matching_subfield_a_values)
if (subfield_a_value == matching_subfield_a_value)
return true;
}
}
return false;
}
bool IsMPIRecord(const MARC::Record &record, const std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> &local_block_boundaries) {
static std::vector<std::string> subfield_a_values{ "DE-Frei85" };
return IsMatchingRecord(record, local_block_boundaries, subfield_a_values);
}
bool IsUBOrIFKRecord(const MARC::Record &record, const std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> &local_block_boundaries) {
static std::vector<std::string> subfield_a_values{ "DE-21", "DE-21-110" };
return IsMatchingRecord(record, local_block_boundaries, subfield_a_values);
}
bool IsARecognisableYear(const std::string &year_candidate) {
if (year_candidate.length() != 4)
return false;
for (char ch : year_candidate) {
if (not StringUtil::IsDigit(ch))
return false;
}
return true;
}
// If we can find a recognisable year in 260$c we return it, o/w we return the empty string.
std::string GetPublicationYear(const MARC::Record &record) {
for (const auto &_260_field : record.getTagRange("260")) {
for (const auto &year_candidate : _260_field.getSubfields().extractSubfields('c'))
if (IsARecognisableYear(year_candidate))
return year_candidate;
}
return "";
}
void FindNonMPIInstitutions(const MARC::Record &record,
const std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> &local_block_boundaries,
std::vector<std::string> * const non_mpi_institutions)
{
non_mpi_institutions->clear();
for (const auto &local_block_boundary : local_block_boundaries) {
std::vector<MARC::Record::const_iterator> fields;
if (record.findFieldsInLocalBlock("852", "??", local_block_boundary, &fields) == 0)
return;
for (const auto &field : fields) {
std::vector<std::string> subfield_a_values(field->getSubfields().extractSubfields('a'));
for (const auto &subfield_a_value : subfield_a_values)
if (subfield_a_value != "DE-Frei85")
non_mpi_institutions->emplace_back(subfield_a_value);
}
}
}
void AddPDAFieldToRecords(const std::string &cutoff_year, MARC::Reader * const marc_reader,
MARC::Writer * const marc_writer)
{
unsigned pda_field_added_count(0);
while (MARC::Record record = marc_reader->read()) {
if (not record.isMonograph()) {
marc_writer->write(record);
continue;
}
std::vector<std::pair<MARC::Record::const_iterator, MARC::Record::const_iterator>> local_block_boundaries;
record.findAllLocalDataBlocks(&local_block_boundaries);
if (IsMPIRecord(record, local_block_boundaries) and not IsUBOrIFKRecord(record, local_block_boundaries)) {
const std::string publication_year(GetPublicationYear(record));
if (publication_year >= cutoff_year) {
std::vector<std::string> non_mpi_institutions;
FindNonMPIInstitutions(record, local_block_boundaries, &non_mpi_institutions);
if (non_mpi_institutions.empty()) {
++pda_field_added_count;
record.insertField("PDA", { { 'a', "yes" } });
marc_writer->write(record);
continue;
}
}
}
marc_writer->write(record);
}
std::cout << "Added a PDA field to " << pda_field_added_count << " record(s).\n";
}
std::string GetCutoffYear(const unsigned no_of_years) {
const unsigned current_year(StringUtil::ToUnsigned(TimeUtil::GetCurrentYear(TimeUtil::LOCAL)));
return std::to_string(current_year - no_of_years);
}
int main(int argc, char *argv[]) {
::progname = argv[0];
try {
if (argc != 4)
Usage();
const unsigned no_of_years(StringUtil::ToUnsigned(argv[1]));
const std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[2], MARC::Reader::AUTO));
const std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(argv[3], MARC::Writer::AUTO));
AddPDAFieldToRecords(GetCutoffYear(no_of_years), marc_reader.get(), marc_writer.get());
} catch (const std::exception &x) {
logger->error("caught exception: " + std::string(x.what()));
}
}
<|endoftext|>
|
<commit_before>#include "queue.h"
#include "gtest/gtest.h"
class queueTest : public testing::Test {
protected:
// SetUp() & TearDown() are virtual functions from testting::Test,
// so we just signify that we override them here
virtual void SetUp() {
q1_.push(1);
q1_.push(2);
q2_.push(1);
q2_.push(3);
}
virtual void TearDown() {
}
// setup fixtures
queue<int> q0_;
queue<int> q1_;
queue<int> q2_;
};
// Use TEST_F to test with fixtures.
TEST_F(queueTest, DefaultConstructor) {
EXPECT_EQ(0u, q0_.size());
}
TEST_F(queueTest, frontback) {
EXPECT_EQ(1, q1_.front());
EXPECT_EQ(1, q2_.front());
EXPECT_EQ(2, q1_.back());
EXPECT_EQ(3, q2_.back());
}
TEST_F(queueTest, push){
EXPECT_EQ(2u, q1_.size());
EXPECT_EQ(2u, q2_.size());
q2_.push(100);
EXPECT_EQ(3u, q2_.size());
EXPECT_EQ(100, q2_.back());
}
TEST_F(queueTest, pop){
EXPECT_EQ(2u, q2_.size());
EXPECT_EQ(1, q2_.front());
q2_.pop();
EXPECT_EQ(3, q2_.front());
q2_.pop();
EXPECT_TRUE(q2_.empty());
}
TEST_F(queueTest, clear) {
q2_.clear();
EXPECT_TRUE(q2_.empty());
}
<commit_msg>queue: write tests for the move version of push().<commit_after>#include "queue.h"
#include "gtest/gtest.h"
#include <string>
class queueTest : public testing::Test {
protected:
// SetUp() & TearDown() are virtual functions from testting::Test,
// so we just signify that we override them here
virtual void SetUp() {
q1_.push(1);
q1_.push(2);
q2_.push(1);
q2_.push(3);
}
virtual void TearDown() {
}
// setup fixtures
queue<int> q0_;
queue<int> q1_;
queue<int> q2_;
};
// Use TEST_F to test with fixtures.
TEST_F(queueTest, DefaultConstructor) {
EXPECT_EQ(0u, q0_.size());
}
TEST_F(queueTest, frontback) {
EXPECT_EQ(1, q1_.front());
EXPECT_EQ(1, q2_.front());
EXPECT_EQ(2, q1_.back());
EXPECT_EQ(3, q2_.back());
}
TEST_F(queueTest, push){
EXPECT_EQ(2u, q1_.size());
EXPECT_EQ(2u, q2_.size());
q2_.push(100); // this is move push
EXPECT_EQ(3u, q2_.size());
EXPECT_EQ(100, q2_.back());
// test normal push
int item = 1000;
q2_.push(item);
EXPECT_EQ(1000, q2_.back());
EXPECT_EQ(1000, item);
}
TEST_F(queueTest, pop){
EXPECT_EQ(2u, q2_.size());
EXPECT_EQ(1, q2_.front());
q2_.pop();
EXPECT_EQ(3, q2_.front());
q2_.pop();
EXPECT_TRUE(q2_.empty());
}
TEST_F(queueTest, clear) {
q2_.clear();
EXPECT_TRUE(q2_.empty());
}
// test the move version of push
// use std::string here for non-trivial object
// that we can actually increase efficiency by
// the new move operation
TEST_F(queueTest, movepush) {
queue<std::string> qstr;
qstr.push("First string");
EXPECT_EQ(qstr.front(), "First string");
// test copy push: after the push, str_item is the same
std::string str_item("Second string");
qstr.push(str_item);
EXPECT_EQ(qstr.back(), "Second string");
EXPECT_EQ(str_item, "Second string");
// test move push: after the push, str_item is empty
str_item = "Third string";
qstr.push(std::move(str_item));
EXPECT_EQ(qstr.back(), "Third string");
EXPECT_TRUE(str_item.empty());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 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 "PlatformString.h"
#undef LOG
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/devtools/devtools_mock_rpc.h"
#include "webkit/glue/devtools/devtools_rpc.h"
namespace {
#define TEST_RPC_STRUCT(METHOD0, METHOD1, METHOD2, METHOD3) \
METHOD0(Method0) \
METHOD1(Method1, int) \
METHOD2(Method2, int, String) \
METHOD3(Method3, int, String, Value)
DEFINE_RPC_CLASS(TestRpcClass, TEST_RPC_STRUCT)
#define ANOTHER_TEST_RPC_STRUCT(METHOD0, METHOD1, METHOD2, METHOD3) \
METHOD0(Method0)
DEFINE_RPC_CLASS(AnotherTestRpcClass, ANOTHER_TEST_RPC_STRUCT)
class MockTestRpcClass : public TestRpcClassStub,
public DevToolsMockRpc {
public:
MockTestRpcClass() : TestRpcClassStub(NULL) {
set_delegate(this);
}
~MockTestRpcClass() {}
};
class MockAnotherTestRpcClass : public AnotherTestRpcClassStub,
public DevToolsMockRpc {
public:
MockAnotherTestRpcClass() : AnotherTestRpcClassStub(NULL) {
set_delegate(this);
}
~MockAnotherTestRpcClass() {}
};
class DevToolsRpcTests : public testing::Test {
public:
DevToolsRpcTests() {}
protected:
virtual void SetUp() {}
virtual void TearDown() {}
};
// Tests method call serialization.
TEST_F(DevToolsRpcTests, TestSerialize) {
MockTestRpcClass mock;
mock.Method0();
int id = RpcTypeToNumber<TestRpcClass>::number;
EXPECT_EQ(StringPrintf("[%d,0]", id), mock.get_log());
mock.Reset();
mock.Method1(10);
EXPECT_EQ(StringPrintf("[%d,1,10]", id), mock.get_log());
mock.Reset();
mock.Method2(20, "foo");
EXPECT_EQ(StringPrintf("[%d,2,20,\"foo\"]", id), mock.get_log());
mock.Reset();
StringValue value("bar");
mock.Method3(30, "foo", value);
EXPECT_EQ(StringPrintf("[%d,3,30,\"foo\",\"bar\"]", id), mock.get_log());
mock.Reset();
}
// Tests method call dispatch.
TEST_F(DevToolsRpcTests, TestDispatch) {
MockTestRpcClass local;
MockTestRpcClass remote;
// Call 1.
local.Reset();
local.Method0();
remote.Reset();
remote.Method0();
remote.Replay();
TestRpcClassDispatch::Dispatch(&remote, local.get_log());
remote.Verify();
// Call 2.
local.Reset();
local.Method1(10);
remote.Reset();
remote.Method1(10);
remote.Replay();
TestRpcClassDispatch::Dispatch(&remote, local.get_log());
remote.Verify();
// Call 3.
local.Reset();
remote.Reset();
local.Method2(20, "foo");
remote.Method2(20, "foo");
remote.Replay();
TestRpcClassDispatch::Dispatch(&remote, local.get_log());
remote.Verify();
// Call 4.
local.Reset();
remote.Reset();
StringValue value("bar");
local.Method3(30, "foo", value);
remote.Method3(30, "foo", value);
remote.Replay();
TestRpcClassDispatch::Dispatch(&remote, local.get_log());
remote.Verify();
}
// Tests class unique id.
TEST_F(DevToolsRpcTests, TestClassId) {
MockAnotherTestRpcClass mock;
ASSERT_TRUE(RpcTypeToNumber<TestRpcClass>::number !=
RpcTypeToNumber<AnotherTestRpcClass>::number);
int id = RpcTypeToNumber<AnotherTestRpcClass>::number;
mock.Method0();
ASSERT_EQ(StringPrintf("[%d,0]", id), mock.get_log());
}
} // namespace
<commit_msg>Fix devtools tests.<commit_after>// Copyright (c) 2009 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 "PlatformString.h"
#undef LOG
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/devtools/devtools_mock_rpc.h"
#include "webkit/glue/devtools/devtools_rpc.h"
namespace {
#define TEST_RPC_STRUCT(METHOD0, METHOD1, METHOD2, METHOD3, METHOD4) \
METHOD0(Method0) \
METHOD1(Method1, int) \
METHOD2(Method2, int, String) \
METHOD3(Method3, int, String, Value)
DEFINE_RPC_CLASS(TestRpcClass, TEST_RPC_STRUCT)
#define ANOTHER_TEST_RPC_STRUCT(METHOD0, METHOD1, METHOD2, METHOD3, METHOD4) \
METHOD0(Method0)
DEFINE_RPC_CLASS(AnotherTestRpcClass, ANOTHER_TEST_RPC_STRUCT)
class MockTestRpcClass : public TestRpcClassStub,
public DevToolsMockRpc {
public:
MockTestRpcClass() : TestRpcClassStub(NULL) {
set_delegate(this);
}
~MockTestRpcClass() {}
};
class MockAnotherTestRpcClass : public AnotherTestRpcClassStub,
public DevToolsMockRpc {
public:
MockAnotherTestRpcClass() : AnotherTestRpcClassStub(NULL) {
set_delegate(this);
}
~MockAnotherTestRpcClass() {}
};
class DevToolsRpcTests : public testing::Test {
public:
DevToolsRpcTests() {}
protected:
virtual void SetUp() {}
virtual void TearDown() {}
};
// Tests method call serialization.
TEST_F(DevToolsRpcTests, TestSerialize) {
MockTestRpcClass mock;
mock.Method0();
int id = RpcTypeToNumber<TestRpcClass>::number;
EXPECT_EQ(StringPrintf("[%d,0]", id), mock.get_log());
mock.Reset();
mock.Method1(10);
EXPECT_EQ(StringPrintf("[%d,1,10]", id), mock.get_log());
mock.Reset();
mock.Method2(20, "foo");
EXPECT_EQ(StringPrintf("[%d,2,20,\"foo\"]", id), mock.get_log());
mock.Reset();
StringValue value("bar");
mock.Method3(30, "foo", value);
EXPECT_EQ(StringPrintf("[%d,3,30,\"foo\",\"bar\"]", id), mock.get_log());
mock.Reset();
}
// Tests method call dispatch.
TEST_F(DevToolsRpcTests, TestDispatch) {
MockTestRpcClass local;
MockTestRpcClass remote;
// Call 1.
local.Reset();
local.Method0();
remote.Reset();
remote.Method0();
remote.Replay();
TestRpcClassDispatch::Dispatch(&remote, local.get_log());
remote.Verify();
// Call 2.
local.Reset();
local.Method1(10);
remote.Reset();
remote.Method1(10);
remote.Replay();
TestRpcClassDispatch::Dispatch(&remote, local.get_log());
remote.Verify();
// Call 3.
local.Reset();
remote.Reset();
local.Method2(20, "foo");
remote.Method2(20, "foo");
remote.Replay();
TestRpcClassDispatch::Dispatch(&remote, local.get_log());
remote.Verify();
// Call 4.
local.Reset();
remote.Reset();
StringValue value("bar");
local.Method3(30, "foo", value);
remote.Method3(30, "foo", value);
remote.Replay();
TestRpcClassDispatch::Dispatch(&remote, local.get_log());
remote.Verify();
}
// Tests class unique id.
TEST_F(DevToolsRpcTests, TestClassId) {
MockAnotherTestRpcClass mock;
ASSERT_TRUE(RpcTypeToNumber<TestRpcClass>::number !=
RpcTypeToNumber<AnotherTestRpcClass>::number);
int id = RpcTypeToNumber<AnotherTestRpcClass>::number;
mock.Method0();
ASSERT_EQ(StringPrintf("[%d,0]", id), mock.get_log());
}
} // namespace
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization
//
// 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.
//
#ifdef _WIN32
// appleseed.foundation headers.
#include "foundation/platform/windows.h"
// Standard headers.
#include <ios>
#include <stdio.h>
// Platform headers.
#include <fcntl.h>
#include <io.h>
using namespace std;
namespace
{
void redirect(FILE* fp, const char* mode, const DWORD std_device)
{
#pragma warning (push)
#pragma warning (disable : 4311) // 'variable' : pointer truncation from 'type' to 'type'
const long handle = (long)GetStdHandle(std_device);
const int fd = _open_osfhandle(handle, _O_TEXT);
*fp = *_fdopen(fd, mode);
setvbuf(fp, NULL, _IONBF, 0);
#pragma warning (pop)
}
void open_console()
{
// Allocates a console for this process.
AllocConsole();
// Redirect stdout, stdin and stderr to the console.
redirect(stdout, "w", STD_OUTPUT_HANDLE);
redirect(stdin, "r", STD_INPUT_HANDLE);
redirect(stderr, "w", STD_ERROR_HANDLE);
// Make cout, wcout, cin, wcin, cerr, wcerr, clog and wclog point to the console as well.
ios::sync_with_stdio();
}
}
//
// DLL entry point.
//
BOOL APIENTRY DllMain(
HINSTANCE module,
DWORD reason,
LPVOID /*reserved*/)
{
if (reason == DLL_PROCESS_ATTACH)
{
#ifndef SHIP
// Open a console.
// open_console();
#endif
}
return TRUE;
}
#endif // _WIN32
<commit_msg>Code cleanup<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization
//
// 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.
//
#ifdef _WIN32
// appleseed.foundation headers.
#include "foundation/platform/windows.h"
// Standard headers.
#include <ios>
#include <stdio.h>
// Platform headers.
#include <fcntl.h>
#include <io.h>
using namespace std;
namespace
{
void redirect(FILE* fp, const char* mode, const DWORD std_device)
{
const intptr_t handle = (intptr_t)GetStdHandle(std_device);
const int fd = _open_osfhandle(handle, _O_TEXT);
*fp = *_fdopen(fd, mode);
setvbuf(fp, NULL, _IONBF, 0);
}
void open_console()
{
// Allocates a console for this process.
AllocConsole();
// Redirect stdout, stdin and stderr to the console.
redirect(stdout, "w", STD_OUTPUT_HANDLE);
redirect(stdin, "r", STD_INPUT_HANDLE);
redirect(stderr, "w", STD_ERROR_HANDLE);
// Make cout, wcout, cin, wcin, cerr, wcerr, clog and wclog point to the console as well.
ios::sync_with_stdio();
}
}
//
// DLL entry point.
//
BOOL APIENTRY DllMain(
HINSTANCE module,
DWORD reason,
LPVOID /*reserved*/)
{
if (reason == DLL_PROCESS_ATTACH)
{
#ifndef SHIP
// Open a console.
// open_console();
#endif
}
return TRUE;
}
#endif // _WIN32
<|endoftext|>
|
<commit_before>#include "videoplayer.h"
#include <QGuiApplication>
#include <QTimer>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QMouseEvent>
#define PROGRAM_VERTEX_ATTRIBUTE 0
#define PROGRAM_TEXCOORD_ATTRIBUTE 1
VideoPlayer::VideoPlayer(QWidget *parent)
: QOpenGLWidget(parent),
clearColor(Qt::black)
{
}
VideoPlayer::~VideoPlayer() {
makeCurrent();
vbo.destroy();
delete program;
doneCurrent();
}
void VideoPlayer::open(const QString &filename) {
_pipeline->open(filename);
}
void VideoPlayer::stop() {
_pipeline->stop();
}
QSize VideoPlayer::minimumSizeHint() const
{
return QSize(50, 50);
}
QSize VideoPlayer::sizeHint() const
{
return QSize(200, 200);
}
void VideoPlayer::setClearColor(const QColor &color)
{
clearColor = color;
update();
}
void VideoPlayer::initializeGL()
{
initializeOpenGLFunctions();
makeObject();
QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
const char *vsrc =
"attribute highp vec4 vertex;\n"
"attribute mediump vec4 texCoord;\n"
"varying mediump vec4 texc;\n"
"uniform mediump mat4 matrix;\n"
"void main(void)\n"
"{\n"
" gl_Position = matrix * vertex;\n"
" texc = texCoord;\n"
"}\n";
vshader->compileSourceCode(vsrc);
QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
const char *fsrc =
"uniform sampler2D texture;\n"
"varying mediump vec4 texc;\n"
"void main(void)\n"
"{\n"
" gl_FragColor = texture2D(texture, texc.st);\n"
"}\n";
fshader->compileSourceCode(fsrc);
program = new QOpenGLShaderProgram;
program->addShader(vshader);
program->addShader(fshader);
program->bindAttributeLocation("vertex", PROGRAM_VERTEX_ATTRIBUTE);
program->bindAttributeLocation("texCoord", PROGRAM_TEXCOORD_ATTRIBUTE);
program->link();
program->bind();
program->setUniformValue("texture", 0);
}
void VideoPlayer::paintGL() {
glClearColor(clearColor.redF(), clearColor.greenF(), clearColor.blueF(), clearColor.alphaF());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
program->setUniformValue("matrix", matrix);
program->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
program->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
program->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0, 3, 5 * sizeof(GLfloat));
program->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT, 3 * sizeof(GLfloat), 2, 5 * sizeof(GLfloat));
glBindTexture (GL_TEXTURE_2D, textureId);
glDrawArrays(GL_TRIANGLES, 0, 6);
if (_pipeline) {
_pipeline->frameDrawn();
}
}
void VideoPlayer::resizeGL(int width, int height) {
glViewport(0, 0, width, height);
makeObject();
}
void VideoPlayer::makeObject() {
static const GLfloat coords[6][3] =
{ { -1.0f, -1.0f, 0.0f },
{ 1.0f, -1.0f, 0.0f },
{ -1.0f, 1.0f, 0.0f },
{ -1.0f, 1.0f, 0.0f },
{ 1.0f, 1.0f, 0.0f },
{ 1.0f, -1.0f, 0.0f } };
QVector<GLfloat> vertData;
double scaledWidth = (double) width() / (double) _videoWidth;
double scaledHeight = (double) height() / (double) _videoHeight;
if (scaledWidth < scaledHeight) {
double modHeight = ((double) _videoHeight * (double) width()) / (double) _videoWidth;
double totalHeight = (double) modHeight / (double) height();
for (int i = 0; i < 6; i++) {
// vertex position
vertData.append(coords[i][0]);
vertData.append(coords[i][1] * totalHeight);
vertData.append(coords[i][2]);
// texture coordinate
vertData.append(coords[i][0] > 0 ? 1 : 0);
vertData.append(coords[i][1] > 0 ? 0 : 1);
}
} else if (scaledWidth > scaledHeight) {
double modWidth = ((double) _videoWidth * (double) height()) / (double) _videoHeight;
double totalWidth = (double) modWidth / (double) width();
for (int i = 0; i < 6; i++) {
// vertex position
vertData.append(coords[i][0] * totalWidth);
vertData.append(coords[i][1]);
vertData.append(coords[i][2]);
// texture coordinate
vertData.append(coords[i][0] > 0 ? 1 : 0);
vertData.append(coords[i][1] > 0 ? 0 : 1);
}
} else {
for (int i = 0; i < 6; i++) {
// vertex position
vertData.append(coords[i][0]);
vertData.append(coords[i][1]);
vertData.append(coords[i][2]);
// texture coordinate
vertData.append(coords[i][0] > 0 ? 1 : 0);
vertData.append(coords[i][1] > 0 ? 0 : 1);
}
}
// new
if (! vbo.isCreated()) {
vbo.create();
}
vbo.bind();
vbo.allocate(vertData.constData(), vertData.count() * sizeof(GLfloat));
}
void VideoPlayer::videoSize(int width, int height) {
_videoWidth = width;
_videoHeight = height;
makeObject();
}
void VideoPlayer::newFrame (GLuint texture) {
textureId = texture;
update();
}
void VideoPlayer::initPipeline() {
if (! _pipeline) {
_pipeline = std::unique_ptr<GstreamerPipeline>(new GstreamerPipeline());
_pipeline->initialize(context());
connect(_pipeline.get(), &GstreamerPipeline::newFrameReady, this, &VideoPlayer::newFrame, Qt::DirectConnection);
connect(_pipeline.get(), &GstreamerPipeline::videoSize, this, &VideoPlayer::videoSize);
connect(_pipeline.get(), &GstreamerPipeline::finished, this, &VideoPlayer::finished);
}
}
<commit_msg>make sure the context is current when updating the object<commit_after>#include "videoplayer.h"
#include <QGuiApplication>
#include <QTimer>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QMouseEvent>
#define PROGRAM_VERTEX_ATTRIBUTE 0
#define PROGRAM_TEXCOORD_ATTRIBUTE 1
VideoPlayer::VideoPlayer(QWidget *parent)
: QOpenGLWidget(parent),
clearColor(Qt::black)
{
}
VideoPlayer::~VideoPlayer() {
makeCurrent();
vbo.destroy();
delete program;
doneCurrent();
}
void VideoPlayer::open(const QString &filename) {
_pipeline->open(filename);
}
void VideoPlayer::stop() {
_pipeline->stop();
}
QSize VideoPlayer::minimumSizeHint() const
{
return QSize(50, 50);
}
QSize VideoPlayer::sizeHint() const
{
return QSize(200, 200);
}
void VideoPlayer::setClearColor(const QColor &color)
{
clearColor = color;
update();
}
void VideoPlayer::initializeGL()
{
initializeOpenGLFunctions();
makeObject();
QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
const char *vsrc =
"attribute highp vec4 vertex;\n"
"attribute mediump vec4 texCoord;\n"
"varying mediump vec4 texc;\n"
"uniform mediump mat4 matrix;\n"
"void main(void)\n"
"{\n"
" gl_Position = matrix * vertex;\n"
" texc = texCoord;\n"
"}\n";
vshader->compileSourceCode(vsrc);
QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
const char *fsrc =
"uniform sampler2D texture;\n"
"varying mediump vec4 texc;\n"
"void main(void)\n"
"{\n"
" gl_FragColor = texture2D(texture, texc.st);\n"
"}\n";
fshader->compileSourceCode(fsrc);
program = new QOpenGLShaderProgram;
program->addShader(vshader);
program->addShader(fshader);
program->bindAttributeLocation("vertex", PROGRAM_VERTEX_ATTRIBUTE);
program->bindAttributeLocation("texCoord", PROGRAM_TEXCOORD_ATTRIBUTE);
program->link();
program->bind();
program->setUniformValue("texture", 0);
}
void VideoPlayer::paintGL() {
glClearColor(clearColor.redF(), clearColor.greenF(), clearColor.blueF(), clearColor.alphaF());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
program->setUniformValue("matrix", matrix);
program->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
program->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
program->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0, 3, 5 * sizeof(GLfloat));
program->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT, 3 * sizeof(GLfloat), 2, 5 * sizeof(GLfloat));
glBindTexture (GL_TEXTURE_2D, textureId);
glDrawArrays(GL_TRIANGLES, 0, 6);
if (_pipeline) {
_pipeline->frameDrawn();
}
}
void VideoPlayer::resizeGL(int width, int height) {
glViewport(0, 0, width, height);
makeObject();
}
void VideoPlayer::makeObject() {
static const GLfloat coords[6][3] =
{ { -1.0f, -1.0f, 0.0f },
{ 1.0f, -1.0f, 0.0f },
{ -1.0f, 1.0f, 0.0f },
{ -1.0f, 1.0f, 0.0f },
{ 1.0f, 1.0f, 0.0f },
{ 1.0f, -1.0f, 0.0f } };
QVector<GLfloat> vertData;
double scaledWidth = (double) width() / (double) _videoWidth;
double scaledHeight = (double) height() / (double) _videoHeight;
if (scaledWidth < scaledHeight) {
double modHeight = ((double) _videoHeight * (double) width()) / (double) _videoWidth;
double totalHeight = (double) modHeight / (double) height();
for (int i = 0; i < 6; i++) {
// vertex position
vertData.append(coords[i][0]);
vertData.append(coords[i][1] * totalHeight);
vertData.append(coords[i][2]);
// texture coordinate
vertData.append(coords[i][0] > 0 ? 1 : 0);
vertData.append(coords[i][1] > 0 ? 0 : 1);
}
} else if (scaledWidth > scaledHeight) {
double modWidth = ((double) _videoWidth * (double) height()) / (double) _videoHeight;
double totalWidth = (double) modWidth / (double) width();
for (int i = 0; i < 6; i++) {
// vertex position
vertData.append(coords[i][0] * totalWidth);
vertData.append(coords[i][1]);
vertData.append(coords[i][2]);
// texture coordinate
vertData.append(coords[i][0] > 0 ? 1 : 0);
vertData.append(coords[i][1] > 0 ? 0 : 1);
}
} else {
for (int i = 0; i < 6; i++) {
// vertex position
vertData.append(coords[i][0]);
vertData.append(coords[i][1]);
vertData.append(coords[i][2]);
// texture coordinate
vertData.append(coords[i][0] > 0 ? 1 : 0);
vertData.append(coords[i][1] > 0 ? 0 : 1);
}
}
// new
if (! vbo.isCreated()) {
vbo.create();
}
vbo.bind();
vbo.allocate(vertData.constData(), vertData.count() * sizeof(GLfloat));
}
void VideoPlayer::videoSize(int width, int height) {
_videoWidth = width;
_videoHeight = height;
makeCurrent();
makeObject();
doneCurrent();
}
void VideoPlayer::newFrame (GLuint texture) {
textureId = texture;
update();
}
void VideoPlayer::initPipeline() {
if (! _pipeline) {
_pipeline = std::unique_ptr<GstreamerPipeline>(new GstreamerPipeline());
_pipeline->initialize(context());
connect(_pipeline.get(), &GstreamerPipeline::newFrameReady, this, &VideoPlayer::newFrame, Qt::DirectConnection);
connect(_pipeline.get(), &GstreamerPipeline::videoSize, this, &VideoPlayer::videoSize);
connect(_pipeline.get(), &GstreamerPipeline::finished, this, &VideoPlayer::finished);
}
}
<|endoftext|>
|
<commit_before>
#include <UnitTest++.h>
#include <TestReporterStdout.h>
#include <OSGConfig.h>
#include <OSGBaseInitFunctions.h>
int main(int argc, char *argv[])
{
OSG::osgInit(argc, argv);
return UnitTest::RunAllTests();
// UnitTest::TestReporterStdout rep;
// return UnitTest::RunAllTests(rep, UnitTest::Test::GetTestList(), argv[1]);
}
<commit_msg>removed: svn:externals for unittest-cpp on Tools/ it moved to Tools/unittest-cpp<commit_after>
#include <UnitTest++.h>
#include <TestReporterStdout.h>
#include <OSGConfig.h>
#include <OSGBaseInitFunctions.h>
struct TestNameEquals
{
TestNameEquals(const std::string &testName)
: _testName(testName)
{
}
bool operator()(const UnitTest::Test * const test) const
{
return (_testName == test->m_details.testName);
}
std::string _testName;
};
int main(int argc, char *argv[])
{
OSG::osgInit(argc, argv);
int retVal = -1;
if(argc > 1)
{
TestNameEquals pred(argv[1]);
UnitTest::TestReporterStdout rep;
UnitTest::TestRunner runner(rep);
retVal = runner.RunTestsIf(
UnitTest::Test::GetTestList(), NULL, pred, 0);
}
else
{
retVal = UnitTest::RunAllTests();
}
OSG::osgExit();
return retVal;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gl/builders/GrGLProgramBuilder.h"
#include "GrGLProgramDesc.h"
#include "GrBackendEffectFactory.h"
#include "GrEffect.h"
#include "GrGpuGL.h"
#include "GrOptDrawState.h"
#include "SkChecksum.h"
/**
* The key for an individual coord transform is made up of a matrix type and a bit that
* indicates the source of the input coords.
*/
enum {
kMatrixTypeKeyBits = 1,
kMatrixTypeKeyMask = (1 << kMatrixTypeKeyBits) - 1,
kPositionCoords_Flag = (1 << kMatrixTypeKeyBits),
kTransformKeyBits = kMatrixTypeKeyBits + 1,
};
/**
* We specialize the vertex code for each of these matrix types.
*/
enum MatrixType {
kNoPersp_MatrixType = 0,
kGeneral_MatrixType = 1,
};
/**
* Do we need to either map r,g,b->a or a->r. configComponentMask indicates which channels are
* present in the texture's config. swizzleComponentMask indicates the channels present in the
* shader swizzle.
*/
static bool swizzle_requires_alpha_remapping(const GrGLCaps& caps,
uint32_t configComponentMask,
uint32_t swizzleComponentMask) {
if (caps.textureSwizzleSupport()) {
// Any remapping is handled using texture swizzling not shader modifications.
return false;
}
// check if the texture is alpha-only
if (kA_GrColorComponentFlag == configComponentMask) {
if (caps.textureRedSupport() && (kA_GrColorComponentFlag & swizzleComponentMask)) {
// we must map the swizzle 'a's to 'r'.
return true;
}
if (kRGB_GrColorComponentFlags & swizzleComponentMask) {
// The 'r', 'g', and/or 'b's must be mapped to 'a' according to our semantics that
// alpha-only textures smear alpha across all four channels when read.
return true;
}
}
return false;
}
static uint32_t gen_attrib_key(const GrEffect* effect) {
uint32_t key = 0;
const GrEffect::VertexAttribArray& vars = effect->getVertexAttribs();
int numAttributes = vars.count();
SkASSERT(numAttributes <= 2);
for (int a = 0; a < numAttributes; ++a) {
uint32_t value = 1 << a;
key |= value;
}
return key;
}
static uint32_t gen_transform_key(const GrEffectStage& effectStage,
bool useExplicitLocalCoords) {
uint32_t totalKey = 0;
int numTransforms = effectStage.getEffect()->numTransforms();
for (int t = 0; t < numTransforms; ++t) {
uint32_t key = 0;
if (effectStage.isPerspectiveCoordTransform(t, useExplicitLocalCoords)) {
key |= kGeneral_MatrixType;
} else {
key |= kNoPersp_MatrixType;
}
const GrCoordTransform& coordTransform = effectStage.getEffect()->coordTransform(t);
if (kLocal_GrCoordSet != coordTransform.sourceCoords() && useExplicitLocalCoords) {
key |= kPositionCoords_Flag;
}
key <<= kTransformKeyBits * t;
SkASSERT(0 == (totalKey & key)); // keys for each transform ought not to overlap
totalKey |= key;
}
return totalKey;
}
static uint32_t gen_texture_key(const GrEffect* effect, const GrGLCaps& caps) {
uint32_t key = 0;
int numTextures = effect->numTextures();
for (int t = 0; t < numTextures; ++t) {
const GrTextureAccess& access = effect->textureAccess(t);
uint32_t configComponentMask = GrPixelConfigComponentMask(access.getTexture()->config());
if (swizzle_requires_alpha_remapping(caps, configComponentMask, access.swizzleMask())) {
key |= 1 << t;
}
}
return key;
}
/**
* A function which emits a meta key into the key builder. This is required because shader code may
* be dependent on properties of the effect that the effect itself doesn't use
* in its key (e.g. the pixel format of textures used). So we create a meta-key for
* every effect using this function. It is also responsible for inserting the effect's class ID
* which must be different for every GrEffect subclass. It can fail if an effect uses too many
* textures, attributes, etc for the space allotted in the meta-key.
*/
static bool gen_effect_meta_key(const GrEffectStage& effectStage,
bool useExplicitLocalCoords,
const GrGLCaps& caps,
GrEffectKeyBuilder* b) {
uint32_t textureKey = gen_texture_key(effectStage.getEffect(), caps);
uint32_t transformKey = gen_transform_key(effectStage,useExplicitLocalCoords);
uint32_t attribKey = gen_attrib_key(effectStage.getEffect());
uint32_t classID = effectStage.getEffect()->getFactory().effectClassID();
// Currently we allow 16 bits for each of the above portions of the meta-key. Fail if they
// don't fit.
static const uint32_t kMetaKeyInvalidMask = ~((uint32_t) SK_MaxU16);
if ((textureKey | transformKey | attribKey | classID) & kMetaKeyInvalidMask) {
return false;
}
uint32_t* key = b->add32n(2);
key[0] = (textureKey << 16 | transformKey);
key[1] = (classID << 16 | attribKey);
return true;
}
bool GrGLProgramDesc::GetEffectKey(const GrEffectStage& stage, const GrGLCaps& caps,
bool useExplicitLocalCoords, GrEffectKeyBuilder* b,
uint16_t* effectKeySize) {
const GrBackendEffectFactory& factory = stage.getEffect()->getFactory();
const GrEffect& effect = *stage.getEffect();
factory.getGLEffectKey(effect, caps, b);
size_t size = b->size();
if (size > SK_MaxU16) {
*effectKeySize = 0; // suppresses a warning.
return false;
}
*effectKeySize = SkToU16(size);
if (!gen_effect_meta_key(stage, useExplicitLocalCoords, caps, b)) {
return false;
}
return true;
}
bool GrGLProgramDesc::Build(const GrOptDrawState& optState,
GrGpu::DrawType drawType,
GrBlendCoeff srcCoeff,
GrBlendCoeff dstCoeff,
GrGpuGL* gpu,
const GrDeviceCoordTexture* dstCopy,
const GrEffectStage** geometryProcessor,
SkTArray<const GrEffectStage*, true>* colorStages,
SkTArray<const GrEffectStage*, true>* coverageStages,
GrGLProgramDesc* desc) {
colorStages->reset();
coverageStages->reset();
bool inputColorIsUsed = optState.inputColorIsUsed();
bool inputCoverageIsUsed = optState.inputColorIsUsed();
// The descriptor is used as a cache key. Thus when a field of the
// descriptor will not affect program generation (because of the attribute
// bindings in use or other descriptor field settings) it should be set
// to a canonical value to avoid duplicate programs with different keys.
bool requiresColorAttrib = optState.hasColorVertexAttribute();
bool requiresCoverageAttrib = optState.hasCoverageVertexAttribute();
bool requiresLocalCoordAttrib = optState.requiresLocalCoordAttrib();
int numStages = optState.numTotalStages();
GR_STATIC_ASSERT(0 == kEffectKeyOffsetsAndLengthOffset % sizeof(uint32_t));
// Make room for everything up to and including the array of offsets to effect keys.
desc->fKey.reset();
desc->fKey.push_back_n(kEffectKeyOffsetsAndLengthOffset + 2 * sizeof(uint16_t) * numStages);
int offsetAndSizeIndex = 0;
bool effectKeySuccess = true;
KeyHeader* header = desc->header();
// make sure any padding in the header is zeroed.
memset(desc->header(), 0, kHeaderSize);
// We can only have one effect which touches the vertex shader
if (optState.hasGeometryProcessor()) {
uint16_t* offsetAndSize =
reinterpret_cast<uint16_t*>(desc->fKey.begin() + kEffectKeyOffsetsAndLengthOffset +
offsetAndSizeIndex * 2 * sizeof(uint16_t));
GrEffectKeyBuilder b(&desc->fKey);
uint16_t effectKeySize;
uint32_t effectOffset = desc->fKey.count();
effectKeySuccess |= GetEffectKey(*optState.getGeometryProcessor(), gpu->glCaps(),
requiresLocalCoordAttrib, &b, &effectKeySize);
effectKeySuccess |= (effectOffset <= SK_MaxU16);
offsetAndSize[0] = SkToU16(effectOffset);
offsetAndSize[1] = effectKeySize;
++offsetAndSizeIndex;
*geometryProcessor = optState.getGeometryProcessor();
header->fHasGeometryProcessor = true;
}
for (int s = 0; s < optState.numColorStages(); ++s) {
uint16_t* offsetAndSize =
reinterpret_cast<uint16_t*>(desc->fKey.begin() + kEffectKeyOffsetsAndLengthOffset +
offsetAndSizeIndex * 2 * sizeof(uint16_t));
GrEffectKeyBuilder b(&desc->fKey);
uint16_t effectKeySize;
uint32_t effectOffset = desc->fKey.count();
effectKeySuccess |= GetEffectKey(optState.getColorStage(s), gpu->glCaps(),
requiresLocalCoordAttrib, &b, &effectKeySize);
effectKeySuccess |= (effectOffset <= SK_MaxU16);
offsetAndSize[0] = SkToU16(effectOffset);
offsetAndSize[1] = effectKeySize;
++offsetAndSizeIndex;
}
for (int s = 0; s < optState.numCoverageStages(); ++s) {
uint16_t* offsetAndSize =
reinterpret_cast<uint16_t*>(desc->fKey.begin() + kEffectKeyOffsetsAndLengthOffset +
offsetAndSizeIndex * 2 * sizeof(uint16_t));
GrEffectKeyBuilder b(&desc->fKey);
uint16_t effectKeySize;
uint32_t effectOffset = desc->fKey.count();
effectKeySuccess |= GetEffectKey(optState.getCoverageStage(s), gpu->glCaps(),
requiresLocalCoordAttrib, &b, &effectKeySize);
effectKeySuccess |= (effectOffset <= SK_MaxU16);
offsetAndSize[0] = SkToU16(effectOffset);
offsetAndSize[1] = effectKeySize;
++offsetAndSizeIndex;
}
if (!effectKeySuccess) {
desc->fKey.reset();
return false;
}
// Because header is a pointer into the dynamic array, we can't push any new data into the key
// below here.
header->fUseFragShaderOnly = gpu->caps()->pathRenderingSupport() &&
GrGpu::IsPathRenderingDrawType(drawType) &&
gpu->glPathRendering()->texturingMode() == GrGLPathRendering::FixedFunction_TexturingMode;
SkASSERT(!header->fUseFragShaderOnly || !optState.hasGeometryProcessor());
header->fEmitsPointSize = GrGpu::kDrawPoints_DrawType == drawType;
// Currently the experimental GS will only work with triangle prims (and it doesn't do anything
// other than pass through values from the VS to the FS anyway).
#if GR_GL_EXPERIMENTAL_GS
#if 0
header->fExperimentalGS = gpu->caps().geometryShaderSupport();
#else
header->fExperimentalGS = false;
#endif
#endif
bool defaultToUniformInputs = GR_GL_NO_CONSTANT_ATTRIBUTES || header->fUseFragShaderOnly;
if (!inputColorIsUsed) {
header->fColorInput = kAllOnes_ColorInput;
} else if (defaultToUniformInputs && !requiresColorAttrib) {
header->fColorInput = kUniform_ColorInput;
} else {
header->fColorInput = kAttribute_ColorInput;
header->fUseFragShaderOnly = false;
}
bool covIsSolidWhite = !requiresCoverageAttrib && 0xffffffff == optState.getCoverageColor();
if (covIsSolidWhite || !inputCoverageIsUsed) {
header->fCoverageInput = kAllOnes_ColorInput;
} else if (defaultToUniformInputs && !requiresCoverageAttrib) {
header->fCoverageInput = kUniform_ColorInput;
} else {
header->fCoverageInput = kAttribute_ColorInput;
header->fUseFragShaderOnly = false;
}
if (optState.readsDst()) {
SkASSERT(dstCopy || gpu->caps()->dstReadInShaderSupport());
const GrTexture* dstCopyTexture = NULL;
if (dstCopy) {
dstCopyTexture = dstCopy->texture();
}
header->fDstReadKey = GrGLFragmentShaderBuilder::KeyForDstRead(dstCopyTexture,
gpu->glCaps());
SkASSERT(0 != header->fDstReadKey);
} else {
header->fDstReadKey = 0;
}
if (optState.readsFragPosition()) {
header->fFragPosKey = GrGLFragmentShaderBuilder::KeyForFragmentPosition(
optState.getRenderTarget(), gpu->glCaps());
} else {
header->fFragPosKey = 0;
}
// Record attribute indices
header->fPositionAttributeIndex = optState.positionAttributeIndex();
header->fLocalCoordAttributeIndex = optState.localCoordAttributeIndex();
// For constant color and coverage we need an attribute with an index beyond those already set
int availableAttributeIndex = optState.getVertexAttribCount();
if (requiresColorAttrib) {
header->fColorAttributeIndex = optState.colorVertexAttributeIndex();
} else if (GrGLProgramDesc::kAttribute_ColorInput == header->fColorInput) {
SkASSERT(availableAttributeIndex < GrDrawState::kMaxVertexAttribCnt);
header->fColorAttributeIndex = availableAttributeIndex;
availableAttributeIndex++;
} else {
header->fColorAttributeIndex = -1;
}
if (requiresCoverageAttrib) {
header->fCoverageAttributeIndex = optState.coverageVertexAttributeIndex();
} else if (GrGLProgramDesc::kAttribute_ColorInput == header->fCoverageInput) {
SkASSERT(availableAttributeIndex < GrDrawState::kMaxVertexAttribCnt);
header->fCoverageAttributeIndex = availableAttributeIndex;
} else {
header->fCoverageAttributeIndex = -1;
}
header->fPrimaryOutputType = optState.getPrimaryOutputType();
header->fSecondaryOutputType = optState.getSecondaryOutputType();
for (int s = 0; s < optState.numColorStages(); ++s) {
colorStages->push_back(&optState.getColorStage(s));
}
for (int s = 0; s < optState.numCoverageStages(); ++s) {
coverageStages->push_back(&optState.getCoverageStage(s));
}
header->fColorEffectCnt = colorStages->count();
header->fCoverageEffectCnt = coverageStages->count();
desc->finalize();
return true;
}
void GrGLProgramDesc::finalize() {
int keyLength = fKey.count();
SkASSERT(0 == (keyLength % 4));
*this->atOffset<uint32_t, kLengthOffset>() = SkToU32(keyLength);
uint32_t* checksum = this->atOffset<uint32_t, kChecksumOffset>();
*checksum = 0;
*checksum = SkChecksum::Compute(reinterpret_cast<uint32_t*>(fKey.begin()), keyLength);
}
GrGLProgramDesc& GrGLProgramDesc::operator= (const GrGLProgramDesc& other) {
size_t keyLength = other.keyLength();
fKey.reset(keyLength);
memcpy(fKey.begin(), other.fKey.begin(), keyLength);
return *this;
}
<commit_msg>Fix inputCoverageIsUsed bug in GrGLProgramDesc<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gl/builders/GrGLProgramBuilder.h"
#include "GrGLProgramDesc.h"
#include "GrBackendEffectFactory.h"
#include "GrEffect.h"
#include "GrGpuGL.h"
#include "GrOptDrawState.h"
#include "SkChecksum.h"
/**
* The key for an individual coord transform is made up of a matrix type and a bit that
* indicates the source of the input coords.
*/
enum {
kMatrixTypeKeyBits = 1,
kMatrixTypeKeyMask = (1 << kMatrixTypeKeyBits) - 1,
kPositionCoords_Flag = (1 << kMatrixTypeKeyBits),
kTransformKeyBits = kMatrixTypeKeyBits + 1,
};
/**
* We specialize the vertex code for each of these matrix types.
*/
enum MatrixType {
kNoPersp_MatrixType = 0,
kGeneral_MatrixType = 1,
};
/**
* Do we need to either map r,g,b->a or a->r. configComponentMask indicates which channels are
* present in the texture's config. swizzleComponentMask indicates the channels present in the
* shader swizzle.
*/
static bool swizzle_requires_alpha_remapping(const GrGLCaps& caps,
uint32_t configComponentMask,
uint32_t swizzleComponentMask) {
if (caps.textureSwizzleSupport()) {
// Any remapping is handled using texture swizzling not shader modifications.
return false;
}
// check if the texture is alpha-only
if (kA_GrColorComponentFlag == configComponentMask) {
if (caps.textureRedSupport() && (kA_GrColorComponentFlag & swizzleComponentMask)) {
// we must map the swizzle 'a's to 'r'.
return true;
}
if (kRGB_GrColorComponentFlags & swizzleComponentMask) {
// The 'r', 'g', and/or 'b's must be mapped to 'a' according to our semantics that
// alpha-only textures smear alpha across all four channels when read.
return true;
}
}
return false;
}
static uint32_t gen_attrib_key(const GrEffect* effect) {
uint32_t key = 0;
const GrEffect::VertexAttribArray& vars = effect->getVertexAttribs();
int numAttributes = vars.count();
SkASSERT(numAttributes <= 2);
for (int a = 0; a < numAttributes; ++a) {
uint32_t value = 1 << a;
key |= value;
}
return key;
}
static uint32_t gen_transform_key(const GrEffectStage& effectStage,
bool useExplicitLocalCoords) {
uint32_t totalKey = 0;
int numTransforms = effectStage.getEffect()->numTransforms();
for (int t = 0; t < numTransforms; ++t) {
uint32_t key = 0;
if (effectStage.isPerspectiveCoordTransform(t, useExplicitLocalCoords)) {
key |= kGeneral_MatrixType;
} else {
key |= kNoPersp_MatrixType;
}
const GrCoordTransform& coordTransform = effectStage.getEffect()->coordTransform(t);
if (kLocal_GrCoordSet != coordTransform.sourceCoords() && useExplicitLocalCoords) {
key |= kPositionCoords_Flag;
}
key <<= kTransformKeyBits * t;
SkASSERT(0 == (totalKey & key)); // keys for each transform ought not to overlap
totalKey |= key;
}
return totalKey;
}
static uint32_t gen_texture_key(const GrEffect* effect, const GrGLCaps& caps) {
uint32_t key = 0;
int numTextures = effect->numTextures();
for (int t = 0; t < numTextures; ++t) {
const GrTextureAccess& access = effect->textureAccess(t);
uint32_t configComponentMask = GrPixelConfigComponentMask(access.getTexture()->config());
if (swizzle_requires_alpha_remapping(caps, configComponentMask, access.swizzleMask())) {
key |= 1 << t;
}
}
return key;
}
/**
* A function which emits a meta key into the key builder. This is required because shader code may
* be dependent on properties of the effect that the effect itself doesn't use
* in its key (e.g. the pixel format of textures used). So we create a meta-key for
* every effect using this function. It is also responsible for inserting the effect's class ID
* which must be different for every GrEffect subclass. It can fail if an effect uses too many
* textures, attributes, etc for the space allotted in the meta-key.
*/
static bool gen_effect_meta_key(const GrEffectStage& effectStage,
bool useExplicitLocalCoords,
const GrGLCaps& caps,
GrEffectKeyBuilder* b) {
uint32_t textureKey = gen_texture_key(effectStage.getEffect(), caps);
uint32_t transformKey = gen_transform_key(effectStage,useExplicitLocalCoords);
uint32_t attribKey = gen_attrib_key(effectStage.getEffect());
uint32_t classID = effectStage.getEffect()->getFactory().effectClassID();
// Currently we allow 16 bits for each of the above portions of the meta-key. Fail if they
// don't fit.
static const uint32_t kMetaKeyInvalidMask = ~((uint32_t) SK_MaxU16);
if ((textureKey | transformKey | attribKey | classID) & kMetaKeyInvalidMask) {
return false;
}
uint32_t* key = b->add32n(2);
key[0] = (textureKey << 16 | transformKey);
key[1] = (classID << 16 | attribKey);
return true;
}
bool GrGLProgramDesc::GetEffectKey(const GrEffectStage& stage, const GrGLCaps& caps,
bool useExplicitLocalCoords, GrEffectKeyBuilder* b,
uint16_t* effectKeySize) {
const GrBackendEffectFactory& factory = stage.getEffect()->getFactory();
const GrEffect& effect = *stage.getEffect();
factory.getGLEffectKey(effect, caps, b);
size_t size = b->size();
if (size > SK_MaxU16) {
*effectKeySize = 0; // suppresses a warning.
return false;
}
*effectKeySize = SkToU16(size);
if (!gen_effect_meta_key(stage, useExplicitLocalCoords, caps, b)) {
return false;
}
return true;
}
bool GrGLProgramDesc::Build(const GrOptDrawState& optState,
GrGpu::DrawType drawType,
GrBlendCoeff srcCoeff,
GrBlendCoeff dstCoeff,
GrGpuGL* gpu,
const GrDeviceCoordTexture* dstCopy,
const GrEffectStage** geometryProcessor,
SkTArray<const GrEffectStage*, true>* colorStages,
SkTArray<const GrEffectStage*, true>* coverageStages,
GrGLProgramDesc* desc) {
colorStages->reset();
coverageStages->reset();
bool inputColorIsUsed = optState.inputColorIsUsed();
bool inputCoverageIsUsed = optState.inputCoverageIsUsed();
// The descriptor is used as a cache key. Thus when a field of the
// descriptor will not affect program generation (because of the attribute
// bindings in use or other descriptor field settings) it should be set
// to a canonical value to avoid duplicate programs with different keys.
bool requiresColorAttrib = optState.hasColorVertexAttribute();
bool requiresCoverageAttrib = optState.hasCoverageVertexAttribute();
bool requiresLocalCoordAttrib = optState.requiresLocalCoordAttrib();
int numStages = optState.numTotalStages();
GR_STATIC_ASSERT(0 == kEffectKeyOffsetsAndLengthOffset % sizeof(uint32_t));
// Make room for everything up to and including the array of offsets to effect keys.
desc->fKey.reset();
desc->fKey.push_back_n(kEffectKeyOffsetsAndLengthOffset + 2 * sizeof(uint16_t) * numStages);
int offsetAndSizeIndex = 0;
bool effectKeySuccess = true;
KeyHeader* header = desc->header();
// make sure any padding in the header is zeroed.
memset(desc->header(), 0, kHeaderSize);
// We can only have one effect which touches the vertex shader
if (optState.hasGeometryProcessor()) {
uint16_t* offsetAndSize =
reinterpret_cast<uint16_t*>(desc->fKey.begin() + kEffectKeyOffsetsAndLengthOffset +
offsetAndSizeIndex * 2 * sizeof(uint16_t));
GrEffectKeyBuilder b(&desc->fKey);
uint16_t effectKeySize;
uint32_t effectOffset = desc->fKey.count();
effectKeySuccess |= GetEffectKey(*optState.getGeometryProcessor(), gpu->glCaps(),
requiresLocalCoordAttrib, &b, &effectKeySize);
effectKeySuccess |= (effectOffset <= SK_MaxU16);
offsetAndSize[0] = SkToU16(effectOffset);
offsetAndSize[1] = effectKeySize;
++offsetAndSizeIndex;
*geometryProcessor = optState.getGeometryProcessor();
header->fHasGeometryProcessor = true;
}
for (int s = 0; s < optState.numColorStages(); ++s) {
uint16_t* offsetAndSize =
reinterpret_cast<uint16_t*>(desc->fKey.begin() + kEffectKeyOffsetsAndLengthOffset +
offsetAndSizeIndex * 2 * sizeof(uint16_t));
GrEffectKeyBuilder b(&desc->fKey);
uint16_t effectKeySize;
uint32_t effectOffset = desc->fKey.count();
effectKeySuccess |= GetEffectKey(optState.getColorStage(s), gpu->glCaps(),
requiresLocalCoordAttrib, &b, &effectKeySize);
effectKeySuccess |= (effectOffset <= SK_MaxU16);
offsetAndSize[0] = SkToU16(effectOffset);
offsetAndSize[1] = effectKeySize;
++offsetAndSizeIndex;
}
for (int s = 0; s < optState.numCoverageStages(); ++s) {
uint16_t* offsetAndSize =
reinterpret_cast<uint16_t*>(desc->fKey.begin() + kEffectKeyOffsetsAndLengthOffset +
offsetAndSizeIndex * 2 * sizeof(uint16_t));
GrEffectKeyBuilder b(&desc->fKey);
uint16_t effectKeySize;
uint32_t effectOffset = desc->fKey.count();
effectKeySuccess |= GetEffectKey(optState.getCoverageStage(s), gpu->glCaps(),
requiresLocalCoordAttrib, &b, &effectKeySize);
effectKeySuccess |= (effectOffset <= SK_MaxU16);
offsetAndSize[0] = SkToU16(effectOffset);
offsetAndSize[1] = effectKeySize;
++offsetAndSizeIndex;
}
if (!effectKeySuccess) {
desc->fKey.reset();
return false;
}
// Because header is a pointer into the dynamic array, we can't push any new data into the key
// below here.
header->fUseFragShaderOnly = gpu->caps()->pathRenderingSupport() &&
GrGpu::IsPathRenderingDrawType(drawType) &&
gpu->glPathRendering()->texturingMode() == GrGLPathRendering::FixedFunction_TexturingMode;
SkASSERT(!header->fUseFragShaderOnly || !optState.hasGeometryProcessor());
header->fEmitsPointSize = GrGpu::kDrawPoints_DrawType == drawType;
// Currently the experimental GS will only work with triangle prims (and it doesn't do anything
// other than pass through values from the VS to the FS anyway).
#if GR_GL_EXPERIMENTAL_GS
#if 0
header->fExperimentalGS = gpu->caps().geometryShaderSupport();
#else
header->fExperimentalGS = false;
#endif
#endif
bool defaultToUniformInputs = GR_GL_NO_CONSTANT_ATTRIBUTES || header->fUseFragShaderOnly;
if (!inputColorIsUsed) {
header->fColorInput = kAllOnes_ColorInput;
} else if (defaultToUniformInputs && !requiresColorAttrib) {
header->fColorInput = kUniform_ColorInput;
} else {
header->fColorInput = kAttribute_ColorInput;
header->fUseFragShaderOnly = false;
}
bool covIsSolidWhite = !requiresCoverageAttrib && 0xffffffff == optState.getCoverageColor();
if (covIsSolidWhite || !inputCoverageIsUsed) {
header->fCoverageInput = kAllOnes_ColorInput;
} else if (defaultToUniformInputs && !requiresCoverageAttrib) {
header->fCoverageInput = kUniform_ColorInput;
} else {
header->fCoverageInput = kAttribute_ColorInput;
header->fUseFragShaderOnly = false;
}
if (optState.readsDst()) {
SkASSERT(dstCopy || gpu->caps()->dstReadInShaderSupport());
const GrTexture* dstCopyTexture = NULL;
if (dstCopy) {
dstCopyTexture = dstCopy->texture();
}
header->fDstReadKey = GrGLFragmentShaderBuilder::KeyForDstRead(dstCopyTexture,
gpu->glCaps());
SkASSERT(0 != header->fDstReadKey);
} else {
header->fDstReadKey = 0;
}
if (optState.readsFragPosition()) {
header->fFragPosKey = GrGLFragmentShaderBuilder::KeyForFragmentPosition(
optState.getRenderTarget(), gpu->glCaps());
} else {
header->fFragPosKey = 0;
}
// Record attribute indices
header->fPositionAttributeIndex = optState.positionAttributeIndex();
header->fLocalCoordAttributeIndex = optState.localCoordAttributeIndex();
// For constant color and coverage we need an attribute with an index beyond those already set
int availableAttributeIndex = optState.getVertexAttribCount();
if (requiresColorAttrib) {
header->fColorAttributeIndex = optState.colorVertexAttributeIndex();
} else if (GrGLProgramDesc::kAttribute_ColorInput == header->fColorInput) {
SkASSERT(availableAttributeIndex < GrDrawState::kMaxVertexAttribCnt);
header->fColorAttributeIndex = availableAttributeIndex;
availableAttributeIndex++;
} else {
header->fColorAttributeIndex = -1;
}
if (requiresCoverageAttrib) {
header->fCoverageAttributeIndex = optState.coverageVertexAttributeIndex();
} else if (GrGLProgramDesc::kAttribute_ColorInput == header->fCoverageInput) {
SkASSERT(availableAttributeIndex < GrDrawState::kMaxVertexAttribCnt);
header->fCoverageAttributeIndex = availableAttributeIndex;
} else {
header->fCoverageAttributeIndex = -1;
}
header->fPrimaryOutputType = optState.getPrimaryOutputType();
header->fSecondaryOutputType = optState.getSecondaryOutputType();
for (int s = 0; s < optState.numColorStages(); ++s) {
colorStages->push_back(&optState.getColorStage(s));
}
for (int s = 0; s < optState.numCoverageStages(); ++s) {
coverageStages->push_back(&optState.getCoverageStage(s));
}
header->fColorEffectCnt = colorStages->count();
header->fCoverageEffectCnt = coverageStages->count();
desc->finalize();
return true;
}
void GrGLProgramDesc::finalize() {
int keyLength = fKey.count();
SkASSERT(0 == (keyLength % 4));
*this->atOffset<uint32_t, kLengthOffset>() = SkToU32(keyLength);
uint32_t* checksum = this->atOffset<uint32_t, kChecksumOffset>();
*checksum = 0;
*checksum = SkChecksum::Compute(reinterpret_cast<uint32_t*>(fKey.begin()), keyLength);
}
GrGLProgramDesc& GrGLProgramDesc::operator= (const GrGLProgramDesc& other) {
size_t keyLength = other.keyLength();
fKey.reset(keyLength);
memcpy(fKey.begin(), other.fKey.begin(), keyLength);
return *this;
}
<|endoftext|>
|
<commit_before>#ifndef __BUF_PATCH_HPP__
#define __BUF_PATCH_HPP__
/*
* This file provides the basic buf_patch_t type as well as a few low-level binary
* patch implementations (currently memmove and memcpy patches)
*/
class buf_patch_t;
#include "buffer_cache/types.hpp"
#include "serializer/types.hpp"
typedef uint32_t patch_counter_t;
typedef byte patch_operation_code_t;
/*
* A buf_patch_t is an in-memory representation for a patch. A patch describes
* a specific change which can be applied to a buffer.
* Each buffer patch has a patch counter as well as a transaction id. The transaction id
* is used to determine to which version of a block the patch applies. Within
* one version of a block, the patch counter explicitly encodes an ordering, which
* is used to ensure that patches can be applied in the correct order
* (even if they get serialized to disk in a different order).
*
* While buf_patch_t provides the general interface of a buffer patch and a few
* universal methods, subclasses are required to implement an apply_to_buf method
* (which executes the actual patch operation) as well as methods which handle
* serializing and deserializing the subtype specific data.
*/
class buf_patch_t {
public:
virtual ~buf_patch_t() { }
// Unserializes a patch an returns a buf_patch_t object
// If *(uint16_t*)source is 0, it returns NULL
//
// TODO: This allocates a patch, which you have to manually delete it. Fix it.
static buf_patch_t* load_patch(const char* source);
// Serializes the patch to the given destination address
void serialize(char* destination) const;
inline uint16_t get_serialized_size() const {
return sizeof(uint16_t) + sizeof(block_id) + sizeof(patch_counter) + sizeof(applies_to_transaction_id) + sizeof(operation_code) + get_data_size();
}
inline static uint16_t get_min_serialized_size() {
return sizeof(uint16_t) + sizeof(block_id) + sizeof(patch_counter) + sizeof(applies_to_transaction_id) + sizeof(operation_code);
}
inline patch_counter_t get_patch_counter() const {
return patch_counter;
}
inline ser_transaction_id_t get_transaction_id() const {
return applies_to_transaction_id;
}
inline void set_transaction_id(const ser_transaction_id_t transaction_id) {
applies_to_transaction_id = transaction_id;
}
inline block_id_t get_block_id() const {
return block_id;
}
virtual size_t get_affected_data_size() const = 0;
// This is called from buf_t
virtual void apply_to_buf(char* buf_data) = 0;
bool operator<(const buf_patch_t& p) const;
protected:
// These are for usage in subclasses
buf_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const patch_operation_code_t operation_code);
virtual void serialize_data(char* destination) const = 0;
virtual uint16_t get_data_size() const = 0;
static const patch_operation_code_t OPER_MEMCPY = 0;
static const patch_operation_code_t OPER_MEMMOVE = 1;
static const patch_operation_code_t OPER_LEAF_SHIFT_PAIRS = 2;
static const patch_operation_code_t OPER_LEAF_INSERT_PAIR = 3;
static const patch_operation_code_t OPER_LEAF_INSERT = 4;
static const patch_operation_code_t OPER_LEAF_REMOVE = 5;
/* Assign an operation id to new subtypes here */
/* Please note: you also have to "register" new operations in buf_patch_t::load_patch() */
private:
block_id_t block_id;
patch_counter_t patch_counter;
ser_transaction_id_t applies_to_transaction_id;
patch_operation_code_t operation_code;
};
/* Binary patches */
/* memcpy_patch_t copies n bytes from src to the offset dest_offset of a buffer */
class memcpy_patch_t : public buf_patch_t {
public:
memcpy_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const uint16_t dest_offset, const char *src, const uint16_t n);
memcpy_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const char* data, const uint16_t data_length);
virtual ~memcpy_patch_t();
virtual void apply_to_buf(char* buf_data);
virtual size_t get_affected_data_size() const;
protected:
virtual void serialize_data(char* destination) const;
virtual uint16_t get_data_size() const;
private:
uint16_t dest_offset;
uint16_t n;
char* src_buf;
};
/* memove_patch_t moves data from src_offset to dest_offset within a single buffer (with semantics equivalent to memmove()) */
class memmove_patch_t : public buf_patch_t {
public:
memmove_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const uint16_t dest_offset, const uint16_t src_offset, const uint16_t n);
memmove_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const char* data, const uint16_t data_length);
virtual void apply_to_buf(char* buf_data);
virtual size_t get_affected_data_size() const;
protected:
virtual void serialize_data(char* destination) const;
virtual uint16_t get_data_size() const;
private:
uint16_t dest_offset;
uint16_t src_offset;
uint16_t n;
};
#endif /* __BUF_PATCH_HPP__ */
<commit_msg>Switch sizeof(variable)s to sizeof(type).<commit_after>#ifndef __BUF_PATCH_HPP__
#define __BUF_PATCH_HPP__
/*
* This file provides the basic buf_patch_t type as well as a few low-level binary
* patch implementations (currently memmove and memcpy patches)
*/
class buf_patch_t;
#include "buffer_cache/types.hpp"
#include "serializer/types.hpp"
typedef uint32_t patch_counter_t;
typedef byte patch_operation_code_t;
/*
* A buf_patch_t is an in-memory representation for a patch. A patch describes
* a specific change which can be applied to a buffer.
* Each buffer patch has a patch counter as well as a transaction id. The transaction id
* is used to determine to which version of a block the patch applies. Within
* one version of a block, the patch counter explicitly encodes an ordering, which
* is used to ensure that patches can be applied in the correct order
* (even if they get serialized to disk in a different order).
*
* While buf_patch_t provides the general interface of a buffer patch and a few
* universal methods, subclasses are required to implement an apply_to_buf method
* (which executes the actual patch operation) as well as methods which handle
* serializing and deserializing the subtype specific data.
*/
class buf_patch_t {
public:
virtual ~buf_patch_t() { }
// Unserializes a patch an returns a buf_patch_t object
// If *(uint16_t*)source is 0, it returns NULL
//
// TODO: This allocates a patch, which you have to manually delete it. Fix it.
static buf_patch_t* load_patch(const char* source);
// Serializes the patch to the given destination address
void serialize(char* destination) const;
inline uint16_t get_serialized_size() const {
return sizeof(uint16_t) + sizeof(block_id) + sizeof(patch_counter_t) + sizeof(ser_transaction_id_t) + sizeof(patch_operation_code_t) + get_data_size();
}
inline static uint16_t get_min_serialized_size() {
return sizeof(uint16_t) + sizeof(block_id_t) + sizeof(patch_counter_t) + sizeof(ser_transaction_id_t) + sizeof(patch_operation_code_t);
}
inline patch_counter_t get_patch_counter() const {
return patch_counter;
}
inline ser_transaction_id_t get_transaction_id() const {
return applies_to_transaction_id;
}
inline void set_transaction_id(const ser_transaction_id_t transaction_id) {
applies_to_transaction_id = transaction_id;
}
inline block_id_t get_block_id() const {
return block_id;
}
virtual size_t get_affected_data_size() const = 0;
// This is called from buf_t
virtual void apply_to_buf(char* buf_data) = 0;
bool operator<(const buf_patch_t& p) const;
protected:
// These are for usage in subclasses
buf_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const patch_operation_code_t operation_code);
virtual void serialize_data(char* destination) const = 0;
virtual uint16_t get_data_size() const = 0;
static const patch_operation_code_t OPER_MEMCPY = 0;
static const patch_operation_code_t OPER_MEMMOVE = 1;
static const patch_operation_code_t OPER_LEAF_SHIFT_PAIRS = 2;
static const patch_operation_code_t OPER_LEAF_INSERT_PAIR = 3;
static const patch_operation_code_t OPER_LEAF_INSERT = 4;
static const patch_operation_code_t OPER_LEAF_REMOVE = 5;
/* Assign an operation id to new subtypes here */
/* Please note: you also have to "register" new operations in buf_patch_t::load_patch() */
private:
block_id_t block_id;
patch_counter_t patch_counter;
ser_transaction_id_t applies_to_transaction_id;
patch_operation_code_t operation_code;
};
/* Binary patches */
/* memcpy_patch_t copies n bytes from src to the offset dest_offset of a buffer */
class memcpy_patch_t : public buf_patch_t {
public:
memcpy_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const uint16_t dest_offset, const char *src, const uint16_t n);
memcpy_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const char* data, const uint16_t data_length);
virtual ~memcpy_patch_t();
virtual void apply_to_buf(char* buf_data);
virtual size_t get_affected_data_size() const;
protected:
virtual void serialize_data(char* destination) const;
virtual uint16_t get_data_size() const;
private:
uint16_t dest_offset;
uint16_t n;
char* src_buf;
};
/* memove_patch_t moves data from src_offset to dest_offset within a single buffer (with semantics equivalent to memmove()) */
class memmove_patch_t : public buf_patch_t {
public:
memmove_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const uint16_t dest_offset, const uint16_t src_offset, const uint16_t n);
memmove_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const char* data, const uint16_t data_length);
virtual void apply_to_buf(char* buf_data);
virtual size_t get_affected_data_size() const;
protected:
virtual void serialize_data(char* destination) const;
virtual uint16_t get_data_size() const;
private:
uint16_t dest_offset;
uint16_t src_offset;
uint16_t n;
};
#endif /* __BUF_PATCH_HPP__ */
<|endoftext|>
|
<commit_before>//===- Driver.cpp ---------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Common/Driver.h"
#include "Config.h"
#include "SymbolTable.h"
#include "Writer.h"
#include "lld/Common/Args.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/Memory.h"
#include "lld/Common/Threads.h"
#include "lld/Common/Version.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Object/Wasm.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
using namespace llvm;
using namespace llvm::sys;
using namespace llvm::wasm;
using namespace lld;
using namespace lld::wasm;
namespace {
// Parses command line options.
class WasmOptTable : public llvm::opt::OptTable {
public:
WasmOptTable();
llvm::opt::InputArgList parse(ArrayRef<const char *> Argv);
};
// Create enum with OPT_xxx values for each option in Options.td
enum {
OPT_INVALID = 0,
#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
#include "Options.inc"
#undef OPTION
};
class LinkerDriver {
public:
void link(ArrayRef<const char *> ArgsArr);
private:
void createFiles(llvm::opt::InputArgList &Args);
void addFile(StringRef Path);
void addLibrary(StringRef Name);
std::vector<InputFile *> Files;
};
} // anonymous namespace
Configuration *lld::wasm::Config;
bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly,
raw_ostream &Error) {
errorHandler().LogName = Args[0];
errorHandler().ErrorOS = &Error;
errorHandler().ColorDiagnostics = Error.has_colors();
errorHandler().ErrorLimitExceededMsg =
"too many errors emitted, stopping now (use "
"-error-limit=0 to see all errors)";
Config = make<Configuration>();
Symtab = make<SymbolTable>();
LinkerDriver().link(Args);
// Exit immediately if we don't need to return to the caller.
// This saves time because the overhead of calling destructors
// for all globally-allocated objects is not negligible.
if (CanExitEarly)
exitLld(errorCount() ? 1 : 0);
freeArena();
return !errorCount();
}
// Create OptTable
// Create prefix string literals used in Options.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Options.inc"
#undef PREFIX
// Create table mapping all options defined in Options.td
static const opt::OptTable::Info OptInfo[] = {
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
{X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
#include "Options.inc"
#undef OPTION
};
// Set color diagnostics according to -color-diagnostics={auto,always,never}
// or -no-color-diagnostics flags.
static void handleColorDiagnostics(opt::InputArgList &Args) {
auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
OPT_no_color_diagnostics);
if (!Arg)
return;
if (Arg->getOption().getID() == OPT_color_diagnostics)
errorHandler().ColorDiagnostics = true;
else if (Arg->getOption().getID() == OPT_no_color_diagnostics)
errorHandler().ColorDiagnostics = false;
else {
StringRef S = Arg->getValue();
if (S == "always")
errorHandler().ColorDiagnostics = true;
if (S == "never")
errorHandler().ColorDiagnostics = false;
if (S != "auto")
error("unknown option: -color-diagnostics=" + S);
}
}
// Find a file by concatenating given paths.
static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
SmallString<128> S;
path::append(S, Path1, Path2);
if (fs::exists(S))
return S.str().str();
return None;
}
// Inject a new wasm global into the output binary with the given value.
// Wasm global are used in relocatable object files to model symbol imports
// and exports. In the final exectuable the only use of wasm globals is the
// for the exlicit stack pointer (__stack_pointer).
static void addSyntheticGlobal(StringRef Name, int32_t Value) {
log("injecting global: " + Name);
Symbol *S = Symtab->addDefinedGlobal(Name);
S->setOutputIndex(Config->SyntheticGlobals.size());
WasmGlobal Global;
Global.Mutable = true;
Global.Type = WASM_TYPE_I32;
Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Global.InitExpr.Value.Int32 = Value;
Config->SyntheticGlobals.emplace_back(S, Global);
}
// Inject a new undefined symbol into the link. This will cause the link to
// fail unless this symbol can be found.
static void addSyntheticUndefinedFunction(StringRef Name) {
log("injecting undefined func: " + Name);
Symtab->addUndefinedFunction(Name);
}
static void printHelp(const char *Argv0) {
WasmOptTable Table;
Table.PrintHelp(outs(), Argv0, "LLVM Linker", false);
}
WasmOptTable::WasmOptTable() : OptTable(OptInfo) {}
opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
unsigned MissingIndex;
unsigned MissingCount;
opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
handleColorDiagnostics(Args);
for (auto *Arg : Args.filtered(OPT_UNKNOWN))
error("unknown argument: " + Arg->getSpelling());
return Args;
}
void LinkerDriver::addFile(StringRef Path) {
Optional<MemoryBufferRef> Buffer = readFile(Path);
if (!Buffer.hasValue())
return;
MemoryBufferRef MBRef = *Buffer;
if (identify_magic(MBRef.getBuffer()) == file_magic::archive)
Files.push_back(make<ArchiveFile>(MBRef));
else
Files.push_back(make<ObjFile>(MBRef));
}
// Add a given library by searching it from input search paths.
void LinkerDriver::addLibrary(StringRef Name) {
for (StringRef Dir : Config->SearchPaths) {
if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
addFile(*S);
return;
}
}
error("unable to find library -l" + Name);
}
void LinkerDriver::createFiles(opt::InputArgList &Args) {
for (auto *Arg : Args) {
switch (Arg->getOption().getUnaliasedOption().getID()) {
case OPT_l:
addLibrary(Arg->getValue());
break;
case OPT_INPUT:
addFile(Arg->getValue());
break;
}
}
if (Files.empty())
error("no input files");
}
void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
WasmOptTable Parser;
opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
// Handle --help
if (Args.hasArg(OPT_help)) {
printHelp(ArgsArr[0]);
return;
}
// Parse and evaluate -mllvm options.
std::vector<const char *> V;
V.push_back("lld-link (LLVM option parsing)");
for (auto *Arg : Args.filtered(OPT_mllvm))
V.push_back(Arg->getValue());
cl::ParseCommandLineOptions(V.size(), V.data());
errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
outs() << getLLDVersion() << "\n";
return;
}
Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
Config->Entry = Args.getLastArgValue(OPT_entry);
Config->ImportMemory = Args.hasArg(OPT_import_memory);
Config->OutputFile = Args.getLastArgValue(OPT_o);
Config->Relocatable = Args.hasArg(OPT_relocatable);
Config->SearchPaths = args::getStrings(Args, OPT_L);
Config->StripAll = Args.hasArg(OPT_strip_all);
Config->StripDebug = Args.hasArg(OPT_strip_debug);
Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
errorHandler().Verbose = Args.hasArg(OPT_verbose);
ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
Config->ZStackSize =
args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
if (Optional<MemoryBufferRef> Buf = readFile(Arg->getValue()))
for (StringRef Sym : args::getLines(*Buf))
Config->AllowUndefinedSymbols.insert(Sym);
if (Config->OutputFile.empty())
error("no output file specified");
if (!Args.hasArg(OPT_INPUT))
error("no input files");
if (Config->Relocatable && !Config->Entry.empty())
error("entry point specified for relocatable output file");
if (!Config->Relocatable) {
if (Config->Entry.empty())
Config->Entry = "_start";
addSyntheticUndefinedFunction(Config->Entry);
addSyntheticGlobal("__stack_pointer", 0);
}
createFiles(Args);
if (errorCount())
return;
// Add all files to the symbol table. This will add almost all
// symbols that we need to the symbol table.
for (InputFile *F : Files)
Symtab->addFile(F);
// Make sure we have resolved all symbols.
if (!Config->Relocatable && !Config->AllowUndefined) {
Symtab->reportRemainingUndefines();
if (errorCount())
return;
}
if (!Config->Entry.empty()) {
Symbol *Sym = Symtab->find(Config->Entry);
if (!Sym->isFunction())
fatal("entry point is not a function: " + Sym->getName());
}
// Write the result to the file.
writeResult();
}
<commit_msg>Fix spelling. NFC.<commit_after>//===- Driver.cpp ---------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Common/Driver.h"
#include "Config.h"
#include "SymbolTable.h"
#include "Writer.h"
#include "lld/Common/Args.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/Memory.h"
#include "lld/Common/Threads.h"
#include "lld/Common/Version.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Object/Wasm.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
using namespace llvm;
using namespace llvm::sys;
using namespace llvm::wasm;
using namespace lld;
using namespace lld::wasm;
namespace {
// Parses command line options.
class WasmOptTable : public llvm::opt::OptTable {
public:
WasmOptTable();
llvm::opt::InputArgList parse(ArrayRef<const char *> Argv);
};
// Create enum with OPT_xxx values for each option in Options.td
enum {
OPT_INVALID = 0,
#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
#include "Options.inc"
#undef OPTION
};
class LinkerDriver {
public:
void link(ArrayRef<const char *> ArgsArr);
private:
void createFiles(llvm::opt::InputArgList &Args);
void addFile(StringRef Path);
void addLibrary(StringRef Name);
std::vector<InputFile *> Files;
};
} // anonymous namespace
Configuration *lld::wasm::Config;
bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly,
raw_ostream &Error) {
errorHandler().LogName = Args[0];
errorHandler().ErrorOS = &Error;
errorHandler().ColorDiagnostics = Error.has_colors();
errorHandler().ErrorLimitExceededMsg =
"too many errors emitted, stopping now (use "
"-error-limit=0 to see all errors)";
Config = make<Configuration>();
Symtab = make<SymbolTable>();
LinkerDriver().link(Args);
// Exit immediately if we don't need to return to the caller.
// This saves time because the overhead of calling destructors
// for all globally-allocated objects is not negligible.
if (CanExitEarly)
exitLld(errorCount() ? 1 : 0);
freeArena();
return !errorCount();
}
// Create OptTable
// Create prefix string literals used in Options.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Options.inc"
#undef PREFIX
// Create table mapping all options defined in Options.td
static const opt::OptTable::Info OptInfo[] = {
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
{X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
#include "Options.inc"
#undef OPTION
};
// Set color diagnostics according to -color-diagnostics={auto,always,never}
// or -no-color-diagnostics flags.
static void handleColorDiagnostics(opt::InputArgList &Args) {
auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
OPT_no_color_diagnostics);
if (!Arg)
return;
if (Arg->getOption().getID() == OPT_color_diagnostics)
errorHandler().ColorDiagnostics = true;
else if (Arg->getOption().getID() == OPT_no_color_diagnostics)
errorHandler().ColorDiagnostics = false;
else {
StringRef S = Arg->getValue();
if (S == "always")
errorHandler().ColorDiagnostics = true;
if (S == "never")
errorHandler().ColorDiagnostics = false;
if (S != "auto")
error("unknown option: -color-diagnostics=" + S);
}
}
// Find a file by concatenating given paths.
static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
SmallString<128> S;
path::append(S, Path1, Path2);
if (fs::exists(S))
return S.str().str();
return None;
}
// Inject a new wasm global into the output binary with the given value.
// Wasm global are used in relocatable object files to model symbol imports
// and exports. In the final exectuable the only use of wasm globals is the
// for the exlicit stack pointer (__stack_pointer).
static void addSyntheticGlobal(StringRef Name, int32_t Value) {
log("injecting global: " + Name);
Symbol *S = Symtab->addDefinedGlobal(Name);
S->setOutputIndex(Config->SyntheticGlobals.size());
WasmGlobal Global;
Global.Mutable = true;
Global.Type = WASM_TYPE_I32;
Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Global.InitExpr.Value.Int32 = Value;
Config->SyntheticGlobals.emplace_back(S, Global);
}
// Inject a new undefined symbol into the link. This will cause the link to
// fail unless this symbol can be found.
static void addSyntheticUndefinedFunction(StringRef Name) {
log("injecting undefined func: " + Name);
Symtab->addUndefinedFunction(Name);
}
static void printHelp(const char *Argv0) {
WasmOptTable Table;
Table.PrintHelp(outs(), Argv0, "LLVM Linker", false);
}
WasmOptTable::WasmOptTable() : OptTable(OptInfo) {}
opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
unsigned MissingIndex;
unsigned MissingCount;
opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
handleColorDiagnostics(Args);
for (auto *Arg : Args.filtered(OPT_UNKNOWN))
error("unknown argument: " + Arg->getSpelling());
return Args;
}
void LinkerDriver::addFile(StringRef Path) {
Optional<MemoryBufferRef> Buffer = readFile(Path);
if (!Buffer.hasValue())
return;
MemoryBufferRef MBRef = *Buffer;
if (identify_magic(MBRef.getBuffer()) == file_magic::archive)
Files.push_back(make<ArchiveFile>(MBRef));
else
Files.push_back(make<ObjFile>(MBRef));
}
// Add a given library by searching it from input search paths.
void LinkerDriver::addLibrary(StringRef Name) {
for (StringRef Dir : Config->SearchPaths) {
if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
addFile(*S);
return;
}
}
error("unable to find library -l" + Name);
}
void LinkerDriver::createFiles(opt::InputArgList &Args) {
for (auto *Arg : Args) {
switch (Arg->getOption().getUnaliasedOption().getID()) {
case OPT_l:
addLibrary(Arg->getValue());
break;
case OPT_INPUT:
addFile(Arg->getValue());
break;
}
}
if (Files.empty())
error("no input files");
}
void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
WasmOptTable Parser;
opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
// Handle --help
if (Args.hasArg(OPT_help)) {
printHelp(ArgsArr[0]);
return;
}
// Parse and evaluate -mllvm options.
std::vector<const char *> V;
V.push_back("wasm-ld (LLVM option parsing)");
for (auto *Arg : Args.filtered(OPT_mllvm))
V.push_back(Arg->getValue());
cl::ParseCommandLineOptions(V.size(), V.data());
errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
outs() << getLLDVersion() << "\n";
return;
}
Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
Config->Entry = Args.getLastArgValue(OPT_entry);
Config->ImportMemory = Args.hasArg(OPT_import_memory);
Config->OutputFile = Args.getLastArgValue(OPT_o);
Config->Relocatable = Args.hasArg(OPT_relocatable);
Config->SearchPaths = args::getStrings(Args, OPT_L);
Config->StripAll = Args.hasArg(OPT_strip_all);
Config->StripDebug = Args.hasArg(OPT_strip_debug);
Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
errorHandler().Verbose = Args.hasArg(OPT_verbose);
ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
Config->ZStackSize =
args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
if (Optional<MemoryBufferRef> Buf = readFile(Arg->getValue()))
for (StringRef Sym : args::getLines(*Buf))
Config->AllowUndefinedSymbols.insert(Sym);
if (Config->OutputFile.empty())
error("no output file specified");
if (!Args.hasArg(OPT_INPUT))
error("no input files");
if (Config->Relocatable && !Config->Entry.empty())
error("entry point specified for relocatable output file");
if (!Config->Relocatable) {
if (Config->Entry.empty())
Config->Entry = "_start";
addSyntheticUndefinedFunction(Config->Entry);
addSyntheticGlobal("__stack_pointer", 0);
}
createFiles(Args);
if (errorCount())
return;
// Add all files to the symbol table. This will add almost all
// symbols that we need to the symbol table.
for (InputFile *F : Files)
Symtab->addFile(F);
// Make sure we have resolved all symbols.
if (!Config->Relocatable && !Config->AllowUndefined) {
Symtab->reportRemainingUndefines();
if (errorCount())
return;
}
if (!Config->Entry.empty()) {
Symbol *Sym = Symtab->find(Config->Entry);
if (!Sym->isFunction())
fatal("entry point is not a function: " + Sym->getName());
}
// Write the result to the file.
writeResult();
}
<|endoftext|>
|
<commit_before>#include "Runtime/Weapon/CBomb.hpp"
#include "Runtime/GameGlobalObjects.hpp"
#include "Runtime/Graphics/CBooRenderer.hpp"
#include "Runtime/Particle/CElementGen.hpp"
#include "Runtime/World/CGameLight.hpp"
#include "Runtime/World/CMorphBall.hpp"
#include "Runtime/World/CPlayer.hpp"
#include "DataSpec/DNAMP1/SFX/Weapons.h"
#include "TCastTo.hpp" // Generated file, do not modify include path
namespace urde {
CBomb::CBomb(const TCachedToken<CGenDescription>& particle1, const TCachedToken<CGenDescription>& particle2,
TUniqueId uid, TAreaId aid, TUniqueId playerId, float f1, const zeus::CTransform& xf,
const CDamageInfo& dInfo)
: CWeapon(uid, aid, true, playerId, EWeaponType::Bomb, "Bomb", xf,
CMaterialFilter::MakeIncludeExclude(
{EMaterialTypes::Solid, EMaterialTypes::Trigger, EMaterialTypes::NonSolidDamageable},
{EMaterialTypes::Projectile, EMaterialTypes::Bomb}),
{EMaterialTypes::Projectile, EMaterialTypes::Bomb}, dInfo, EProjectileAttrib::Bombs,
CModelData::CModelDataNull())
, x17c_fuseTime(f1)
, x180_particle1(std::make_unique<CElementGen>(particle1, CElementGen::EModelOrientationType::Normal,
CElementGen::EOptionalSystemFlags::One))
, x184_particle2(std::make_unique<CElementGen>(particle2, CElementGen::EModelOrientationType::Normal,
CElementGen::EOptionalSystemFlags::One))
, x18c_particle2Obj(particle2.GetObj())
, x190_24_isNotDetonated(true)
, x190_25_beingDragged(false)
, x190_26_disableFuse(false) {
x180_particle1->SetGlobalTranslation(xf.origin);
x184_particle2->SetGlobalTranslation(xf.origin);
}
void CBomb::Accept(urde::IVisitor& visitor) { visitor.Visit(this); }
void CBomb::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) {
if (msg == EScriptObjectMessage::Registered) {
x188_lightId = mgr.AllocateUniqueId();
CGameLight* gameLight = new CGameLight(x188_lightId, GetAreaIdAlways(), false,
std::string("Bomb_PLight") + GetName().data(), GetTransform(), GetUniqueId(),
x184_particle2->GetLight(), reinterpret_cast<size_t>(x18c_particle2Obj), 1, 0.f);
mgr.AddObject(gameLight);
mgr.AddWeaponId(xec_ownerId, xf0_weaponType);
CSfxManager::AddEmitter(SFXwpn_bomb_drop, GetTranslation(), {}, true, false, 0x7f, -1);
mgr.InformListeners(GetTranslation(), EListenNoiseType::BombExplode);
return;
} else if (msg == EScriptObjectMessage::Deleted) {
if (x188_lightId != kInvalidUniqueId)
mgr.FreeScriptObject(x188_lightId);
if (x190_24_isNotDetonated)
mgr.RemoveWeaponId(xec_ownerId, xf0_weaponType);
return;
}
CActor::AcceptScriptMsg(msg, uid, mgr);
}
static CMaterialFilter kSolidFilter =
CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {EMaterialTypes::Character, EMaterialTypes::Player,
EMaterialTypes::ProjectilePassthrough});
void CBomb::Think(float dt, urde::CStateManager& mgr) {
CWeapon::Think(dt, mgr);
if (x190_24_isNotDetonated) {
if (x17c_fuseTime <= 0.f) {
Explode(GetTranslation(), mgr);
if (TCastToPtr<CGameLight> light = mgr.ObjectById(x188_lightId))
light->SetActive(true);
}
if (x17c_fuseTime > 0.5f)
x180_particle1->Update(dt);
else
UpdateLight(dt, mgr);
if (!x190_26_disableFuse)
x17c_fuseTime -= dt;
} else {
UpdateLight(dt, mgr);
if (x184_particle2->IsSystemDeletable())
mgr.FreeScriptObject(GetUniqueId());
}
if (x190_24_isNotDetonated) {
if (x164_acceleration.magSquared() > 0.f)
x158_velocity += dt * x164_acceleration;
if (x158_velocity.magSquared() > 0.f) {
x170_prevLocation = GetTranslation();
CActor::SetTranslation((dt * x158_velocity) + GetTranslation());
zeus::CVector3f diffVec = (GetTranslation() - x170_prevLocation);
float diffMag = diffVec.magnitude();
if (diffMag == 0.f)
Explode(GetTranslation(), mgr);
else {
CRayCastResult res =
mgr.RayStaticIntersection(x170_prevLocation, (1.f / diffMag) * diffVec, diffMag, kSolidFilter);
if (res.IsValid())
Explode(GetTranslation(), mgr);
}
}
}
x180_particle1->SetGlobalTranslation(GetTranslation());
x184_particle2->SetGlobalTranslation(GetTranslation());
}
void CBomb::AddToRenderer(const zeus::CFrustum& frustum, const urde::CStateManager& mgr) const {
zeus::CVector3f origin = GetTranslation();
float ballRadius = mgr.GetPlayer().GetMorphBall()->GetBallRadius();
zeus::CAABox aabox(origin - (0.9f * ballRadius), origin + (0.9f * ballRadius));
zeus::CVector3f closestPoint = aabox.closestPointAlongVector(CGraphics::g_ViewMatrix.frontVector());
if (x190_24_isNotDetonated && x17c_fuseTime > 0.5f)
g_Renderer->AddParticleGen(*x180_particle1, closestPoint, aabox);
else
g_Renderer->AddParticleGen(*x184_particle2, closestPoint, aabox);
}
void CBomb::Touch(CActor&, urde::CStateManager&) {
#if 0
x190_24_isNotDetonated; /* wat? */
#endif
}
std::optional<zeus::CAABox> CBomb::GetTouchBounds() const {
float radius = (x190_24_isNotDetonated ? 0.2f : x12c_curDamageInfo.GetRadius());
float minX = (x170_prevLocation.x() >= GetTranslation().x() ? x170_prevLocation.x() : GetTranslation().x()) - radius;
float minY = (x170_prevLocation.y() >= GetTranslation().y() ? x170_prevLocation.y() : GetTranslation().y()) - radius;
float minZ = (x170_prevLocation.z() >= GetTranslation().z() ? x170_prevLocation.z() : GetTranslation().z()) - radius;
float maxX = (x170_prevLocation.x() >= GetTranslation().x() ? x170_prevLocation.x() : GetTranslation().x()) + radius;
float maxY = (x170_prevLocation.y() >= GetTranslation().y() ? x170_prevLocation.y() : GetTranslation().y()) + radius;
float maxZ = (x170_prevLocation.z() >= GetTranslation().z() ? x170_prevLocation.z() : GetTranslation().z()) + radius;
return {{minX, minY, minZ, maxX, maxY, maxZ}};
}
void CBomb::Explode(const zeus::CVector3f& pos, CStateManager& mgr) {
mgr.ApplyDamageToWorld(xec_ownerId, *this, pos, x12c_curDamageInfo, xf8_filter);
CSfxManager::AddEmitter(SFXwpn_bomb_explo, GetTranslation(), {}, true, false, 0x7f, -1);
mgr.InformListeners(pos, EListenNoiseType::BombExplode);
mgr.RemoveWeaponId(xec_ownerId, xf0_weaponType);
x190_24_isNotDetonated = false;
}
void CBomb::UpdateLight(float dt, CStateManager& mgr) {
x184_particle2->Update(dt);
if (x188_lightId == kInvalidUniqueId)
return;
if (TCastToPtr<CGameLight> light = mgr.ObjectById(x188_lightId))
if (light->GetActive())
light->SetLight(x184_particle2->GetLight());
}
} // namespace urde
<commit_msg>CBomb: Make file-scope material filter constexpr<commit_after>#include "Runtime/Weapon/CBomb.hpp"
#include "Runtime/GameGlobalObjects.hpp"
#include "Runtime/Graphics/CBooRenderer.hpp"
#include "Runtime/Particle/CElementGen.hpp"
#include "Runtime/World/CGameLight.hpp"
#include "Runtime/World/CMorphBall.hpp"
#include "Runtime/World/CPlayer.hpp"
#include "DataSpec/DNAMP1/SFX/Weapons.h"
#include "TCastTo.hpp" // Generated file, do not modify include path
namespace urde {
CBomb::CBomb(const TCachedToken<CGenDescription>& particle1, const TCachedToken<CGenDescription>& particle2,
TUniqueId uid, TAreaId aid, TUniqueId playerId, float f1, const zeus::CTransform& xf,
const CDamageInfo& dInfo)
: CWeapon(uid, aid, true, playerId, EWeaponType::Bomb, "Bomb", xf,
CMaterialFilter::MakeIncludeExclude(
{EMaterialTypes::Solid, EMaterialTypes::Trigger, EMaterialTypes::NonSolidDamageable},
{EMaterialTypes::Projectile, EMaterialTypes::Bomb}),
{EMaterialTypes::Projectile, EMaterialTypes::Bomb}, dInfo, EProjectileAttrib::Bombs,
CModelData::CModelDataNull())
, x17c_fuseTime(f1)
, x180_particle1(std::make_unique<CElementGen>(particle1, CElementGen::EModelOrientationType::Normal,
CElementGen::EOptionalSystemFlags::One))
, x184_particle2(std::make_unique<CElementGen>(particle2, CElementGen::EModelOrientationType::Normal,
CElementGen::EOptionalSystemFlags::One))
, x18c_particle2Obj(particle2.GetObj())
, x190_24_isNotDetonated(true)
, x190_25_beingDragged(false)
, x190_26_disableFuse(false) {
x180_particle1->SetGlobalTranslation(xf.origin);
x184_particle2->SetGlobalTranslation(xf.origin);
}
void CBomb::Accept(urde::IVisitor& visitor) { visitor.Visit(this); }
void CBomb::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) {
if (msg == EScriptObjectMessage::Registered) {
x188_lightId = mgr.AllocateUniqueId();
CGameLight* gameLight = new CGameLight(x188_lightId, GetAreaIdAlways(), false,
std::string("Bomb_PLight") + GetName().data(), GetTransform(), GetUniqueId(),
x184_particle2->GetLight(), reinterpret_cast<size_t>(x18c_particle2Obj), 1, 0.f);
mgr.AddObject(gameLight);
mgr.AddWeaponId(xec_ownerId, xf0_weaponType);
CSfxManager::AddEmitter(SFXwpn_bomb_drop, GetTranslation(), {}, true, false, 0x7f, -1);
mgr.InformListeners(GetTranslation(), EListenNoiseType::BombExplode);
return;
} else if (msg == EScriptObjectMessage::Deleted) {
if (x188_lightId != kInvalidUniqueId)
mgr.FreeScriptObject(x188_lightId);
if (x190_24_isNotDetonated)
mgr.RemoveWeaponId(xec_ownerId, xf0_weaponType);
return;
}
CActor::AcceptScriptMsg(msg, uid, mgr);
}
constexpr CMaterialFilter kSolidFilter =
CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {EMaterialTypes::Character, EMaterialTypes::Player,
EMaterialTypes::ProjectilePassthrough});
void CBomb::Think(float dt, urde::CStateManager& mgr) {
CWeapon::Think(dt, mgr);
if (x190_24_isNotDetonated) {
if (x17c_fuseTime <= 0.f) {
Explode(GetTranslation(), mgr);
if (TCastToPtr<CGameLight> light = mgr.ObjectById(x188_lightId))
light->SetActive(true);
}
if (x17c_fuseTime > 0.5f)
x180_particle1->Update(dt);
else
UpdateLight(dt, mgr);
if (!x190_26_disableFuse)
x17c_fuseTime -= dt;
} else {
UpdateLight(dt, mgr);
if (x184_particle2->IsSystemDeletable())
mgr.FreeScriptObject(GetUniqueId());
}
if (x190_24_isNotDetonated) {
if (x164_acceleration.magSquared() > 0.f)
x158_velocity += dt * x164_acceleration;
if (x158_velocity.magSquared() > 0.f) {
x170_prevLocation = GetTranslation();
CActor::SetTranslation((dt * x158_velocity) + GetTranslation());
zeus::CVector3f diffVec = (GetTranslation() - x170_prevLocation);
float diffMag = diffVec.magnitude();
if (diffMag == 0.f)
Explode(GetTranslation(), mgr);
else {
CRayCastResult res =
mgr.RayStaticIntersection(x170_prevLocation, (1.f / diffMag) * diffVec, diffMag, kSolidFilter);
if (res.IsValid())
Explode(GetTranslation(), mgr);
}
}
}
x180_particle1->SetGlobalTranslation(GetTranslation());
x184_particle2->SetGlobalTranslation(GetTranslation());
}
void CBomb::AddToRenderer(const zeus::CFrustum& frustum, const urde::CStateManager& mgr) const {
zeus::CVector3f origin = GetTranslation();
float ballRadius = mgr.GetPlayer().GetMorphBall()->GetBallRadius();
zeus::CAABox aabox(origin - (0.9f * ballRadius), origin + (0.9f * ballRadius));
zeus::CVector3f closestPoint = aabox.closestPointAlongVector(CGraphics::g_ViewMatrix.frontVector());
if (x190_24_isNotDetonated && x17c_fuseTime > 0.5f)
g_Renderer->AddParticleGen(*x180_particle1, closestPoint, aabox);
else
g_Renderer->AddParticleGen(*x184_particle2, closestPoint, aabox);
}
void CBomb::Touch(CActor&, urde::CStateManager&) {
#if 0
x190_24_isNotDetonated; /* wat? */
#endif
}
std::optional<zeus::CAABox> CBomb::GetTouchBounds() const {
float radius = (x190_24_isNotDetonated ? 0.2f : x12c_curDamageInfo.GetRadius());
float minX = (x170_prevLocation.x() >= GetTranslation().x() ? x170_prevLocation.x() : GetTranslation().x()) - radius;
float minY = (x170_prevLocation.y() >= GetTranslation().y() ? x170_prevLocation.y() : GetTranslation().y()) - radius;
float minZ = (x170_prevLocation.z() >= GetTranslation().z() ? x170_prevLocation.z() : GetTranslation().z()) - radius;
float maxX = (x170_prevLocation.x() >= GetTranslation().x() ? x170_prevLocation.x() : GetTranslation().x()) + radius;
float maxY = (x170_prevLocation.y() >= GetTranslation().y() ? x170_prevLocation.y() : GetTranslation().y()) + radius;
float maxZ = (x170_prevLocation.z() >= GetTranslation().z() ? x170_prevLocation.z() : GetTranslation().z()) + radius;
return {{minX, minY, minZ, maxX, maxY, maxZ}};
}
void CBomb::Explode(const zeus::CVector3f& pos, CStateManager& mgr) {
mgr.ApplyDamageToWorld(xec_ownerId, *this, pos, x12c_curDamageInfo, xf8_filter);
CSfxManager::AddEmitter(SFXwpn_bomb_explo, GetTranslation(), {}, true, false, 0x7f, -1);
mgr.InformListeners(pos, EListenNoiseType::BombExplode);
mgr.RemoveWeaponId(xec_ownerId, xf0_weaponType);
x190_24_isNotDetonated = false;
}
void CBomb::UpdateLight(float dt, CStateManager& mgr) {
x184_particle2->Update(dt);
if (x188_lightId == kInvalidUniqueId)
return;
if (TCastToPtr<CGameLight> light = mgr.ObjectById(x188_lightId))
if (light->GetActive())
light->SetLight(x184_particle2->GetLight());
}
} // namespace urde
<|endoftext|>
|
<commit_before>#pragma once
#include <memory>
#include <string>
#include <vector>
#include "Runtime/RetroTypes.hpp"
#include "Runtime/rstl.hpp"
#include "Runtime/Audio/CSfxManager.hpp"
#include "Runtime/AutoMapper/CMapWorld.hpp"
#include "Runtime/Graphics/CModel.hpp"
#include "Runtime/World/CEnvFxManager.hpp"
#include "Runtime/World/CGameArea.hpp"
#include "Runtime/World/ScriptObjectSupport.hpp"
namespace urde {
class CAudioGroupSet;
class CGameArea;
class CResFactory;
class IGameArea;
class IObjectStore;
class IWorld {
public:
virtual ~IWorld() = default;
virtual CAssetId IGetWorldAssetId() const = 0;
virtual CAssetId IGetStringTableAssetId() const = 0;
virtual CAssetId IGetSaveWorldAssetId() const = 0;
virtual const CMapWorld* IGetMapWorld() const = 0;
virtual CMapWorld* IGetMapWorld() = 0;
virtual const IGameArea* IGetAreaAlways(TAreaId id) const = 0;
virtual TAreaId IGetCurrentAreaId() const = 0;
virtual TAreaId IGetAreaId(CAssetId id) const = 0;
virtual bool ICheckWorldComplete() = 0;
virtual std::string IGetDefaultAudioTrack() const = 0;
virtual int IGetAreaCount() const = 0;
};
class CDummyWorld : public IWorld {
bool x4_loadMap;
enum class Phase {
Loading,
LoadingMap,
LoadingMapAreas,
Done,
} x8_phase = Phase::Loading;
CAssetId xc_mlvlId;
CAssetId x10_strgId;
CAssetId x14_savwId;
std::vector<CDummyGameArea> x18_areas;
CAssetId x28_mapWorldId;
TLockedToken<CMapWorld> x2c_mapWorld;
std::shared_ptr<IDvdRequest> x30_loadToken;
std::unique_ptr<uint8_t[]> x34_loadBuf;
u32 x38_bufSz;
TAreaId x3c_curAreaId = kInvalidAreaId;
public:
CDummyWorld(CAssetId mlvlId, bool loadMap);
~CDummyWorld() override;
CAssetId IGetWorldAssetId() const override;
CAssetId IGetStringTableAssetId() const override;
CAssetId IGetSaveWorldAssetId() const override;
const CMapWorld* IGetMapWorld() const override;
CMapWorld* IGetMapWorld() override;
const IGameArea* IGetAreaAlways(TAreaId id) const override;
TAreaId IGetCurrentAreaId() const override;
TAreaId IGetAreaId(CAssetId id) const override;
bool ICheckWorldComplete() override;
std::string IGetDefaultAudioTrack() const override;
int IGetAreaCount() const override;
};
class CWorld : public IWorld {
friend class CStateManager;
public:
class CRelay {
TEditorId x0_relay = kInvalidEditorId;
TEditorId x4_target = kInvalidEditorId;
s16 x8_msg = -1;
bool xa_active = false;
public:
CRelay() = default;
CRelay(CInputStream& in);
TEditorId GetRelayId() const { return x0_relay; }
TEditorId GetTargetId() const { return x4_target; }
s16 GetMessage() const { return x8_msg; }
bool GetActive() const { return xa_active; }
static std::vector<CWorld::CRelay> ReadMemoryRelays(athena::io::MemoryReader& r);
};
struct CSoundGroupData {
int x0_groupId;
CAssetId x4_agscId;
std::string xc_name;
TCachedToken<CAudioGroupSet> x1c_groupData;
public:
CSoundGroupData(int grpId, CAssetId agsc);
};
private:
static constexpr CGameArea* skGlobalEnd = nullptr;
static constexpr CGameArea* skGlobalNonConstEnd = nullptr;
enum class Phase {
Loading,
LoadingMap,
LoadingMapAreas,
LoadingSkyBox,
LoadingSoundGroups,
Done,
} x4_phase = Phase::Loading;
CAssetId x8_mlvlId;
CAssetId xc_strgId;
CAssetId x10_savwId;
std::vector<std::unique_ptr<CGameArea>> x18_areas;
CAssetId x24_mapwId;
TLockedToken<CMapWorld> x28_mapWorld;
std::vector<CRelay> x2c_relays;
std::shared_ptr<IDvdRequest> x3c_loadToken;
std::unique_ptr<uint8_t[]> x40_loadBuf;
u32 x44_bufSz;
u32 x48_chainCount = 0;
CGameArea* x4c_chainHeads[5] = {};
IObjectStore& x60_objectStore;
IFactory& x64_resFactory;
TAreaId x68_curAreaId = kInvalidAreaId;
u32 x6c_loadedAudioGrpCount = 0;
union {
struct {
bool x70_24_currentAreaNeedsAllocation : 1;
bool x70_25_loadPaused : 1;
bool x70_26_skyboxActive : 1;
bool x70_27_skyboxVisible : 1;
};
u32 dummy = 0;
};
std::vector<CSoundGroupData> x74_soundGroupData;
std::string x84_defAudioTrack;
std::optional<TLockedToken<CModel>> x94_skyboxWorld;
std::optional<TLockedToken<CModel>> xa4_skyboxWorldLoaded;
std::optional<TLockedToken<CModel>> xb4_skyboxOverride;
EEnvFxType xc4_neededFx = EEnvFxType::None;
rstl::reserved_vector<CSfxHandle, 10> xc8_globalSfxHandles;
void LoadSoundGroup(int groupId, CAssetId agscId, CSoundGroupData& data);
void LoadSoundGroups();
void UnloadSoundGroups();
void StopSounds();
public:
void MoveToChain(CGameArea* area, EChain chain);
void MoveAreaToAliveChain(TAreaId aid);
bool CheckWorldComplete(CStateManager* mgr, TAreaId id, CAssetId mreaId);
CGameArea::CChainIterator GetChainHead(EChain chain) { return {x4c_chainHeads[int(chain)]}; }
CGameArea::CConstChainIterator GetChainHead(EChain chain) const { return {x4c_chainHeads[int(chain)]}; }
CGameArea::CChainIterator begin() { return GetChainHead(EChain::Alive); }
CGameArea::CChainIterator end() { return AliveAreasEnd(); }
CGameArea::CConstChainIterator begin() const { return GetChainHead(EChain::Alive); }
CGameArea::CConstChainIterator end() const { return GetAliveAreasEnd(); }
bool ScheduleAreaToLoad(CGameArea* area, CStateManager& mgr);
void TravelToArea(TAreaId aid, CStateManager& mgr, bool);
void SetLoadPauseState(bool paused);
void CycleLoadPauseState();
CWorld(IObjectStore& objStore, IFactory& resFactory, CAssetId mlvlId);
~CWorld();
bool DoesAreaExist(TAreaId area) const;
const std::vector<std::unique_ptr<CGameArea>>& GetGameAreas() const { return x18_areas; }
const CMapWorld* GetMapWorld() const { return x28_mapWorld.GetObj(); }
u32 GetRelayCount() const { return x2c_relays.size(); }
CRelay GetRelay(u32 idx) const { return x2c_relays[idx]; }
CAssetId IGetWorldAssetId() const override;
CAssetId IGetStringTableAssetId() const override;
CAssetId IGetSaveWorldAssetId() const override;
const CMapWorld* IGetMapWorld() const override;
CMapWorld* IGetMapWorld() override;
const CGameArea* GetAreaAlways(TAreaId) const;
CGameArea* GetArea(TAreaId);
s32 GetNumAreas() const { return x18_areas.size(); }
const IGameArea* IGetAreaAlways(TAreaId id) const override;
TAreaId IGetCurrentAreaId() const override;
TAreaId GetCurrentAreaId() const { return x68_curAreaId; }
TAreaId IGetAreaId(CAssetId id) const override;
bool ICheckWorldComplete() override;
std::string IGetDefaultAudioTrack() const override;
int IGetAreaCount() const override;
static void PropogateAreaChain(CGameArea::EOcclusionState, CGameArea*, CWorld*);
static CGameArea::CConstChainIterator GetAliveAreasEnd() { return {skGlobalEnd}; }
static CGameArea::CChainIterator AliveAreasEnd() { return {skGlobalNonConstEnd}; }
void Update(float dt);
void PreRender();
void TouchSky();
void DrawSky(const zeus::CTransform& xf) const;
void StopGlobalSound(u16 id);
bool HasGlobalSound(u16 id) const;
void AddGlobalSound(const CSfxHandle& hnd);
EEnvFxType GetNeededEnvFx() const { return xc4_neededFx; }
CAssetId GetWorldAssetId() const { return x8_mlvlId; }
bool AreSkyNeedsMet() const;
TAreaId GetAreaIdForSaveId(s32 saveId) const;
};
struct CWorldLayers {
struct Area {
u32 m_startNameIdx;
u32 m_layerCount;
u64 m_layerBits;
};
std::vector<Area> m_areas;
std::vector<std::string> m_names;
static void ReadWorldLayers(athena::io::MemoryReader& r, int version, CAssetId mlvlId);
};
} // namespace urde
<commit_msg>CWorld: Provide parameter names for prototypes<commit_after>#pragma once
#include <memory>
#include <string>
#include <vector>
#include "Runtime/RetroTypes.hpp"
#include "Runtime/rstl.hpp"
#include "Runtime/Audio/CSfxManager.hpp"
#include "Runtime/AutoMapper/CMapWorld.hpp"
#include "Runtime/Graphics/CModel.hpp"
#include "Runtime/World/CEnvFxManager.hpp"
#include "Runtime/World/CGameArea.hpp"
#include "Runtime/World/ScriptObjectSupport.hpp"
namespace urde {
class CAudioGroupSet;
class CGameArea;
class CResFactory;
class IGameArea;
class IObjectStore;
class IWorld {
public:
virtual ~IWorld() = default;
virtual CAssetId IGetWorldAssetId() const = 0;
virtual CAssetId IGetStringTableAssetId() const = 0;
virtual CAssetId IGetSaveWorldAssetId() const = 0;
virtual const CMapWorld* IGetMapWorld() const = 0;
virtual CMapWorld* IGetMapWorld() = 0;
virtual const IGameArea* IGetAreaAlways(TAreaId id) const = 0;
virtual TAreaId IGetCurrentAreaId() const = 0;
virtual TAreaId IGetAreaId(CAssetId id) const = 0;
virtual bool ICheckWorldComplete() = 0;
virtual std::string IGetDefaultAudioTrack() const = 0;
virtual int IGetAreaCount() const = 0;
};
class CDummyWorld : public IWorld {
bool x4_loadMap;
enum class Phase {
Loading,
LoadingMap,
LoadingMapAreas,
Done,
} x8_phase = Phase::Loading;
CAssetId xc_mlvlId;
CAssetId x10_strgId;
CAssetId x14_savwId;
std::vector<CDummyGameArea> x18_areas;
CAssetId x28_mapWorldId;
TLockedToken<CMapWorld> x2c_mapWorld;
std::shared_ptr<IDvdRequest> x30_loadToken;
std::unique_ptr<uint8_t[]> x34_loadBuf;
u32 x38_bufSz;
TAreaId x3c_curAreaId = kInvalidAreaId;
public:
CDummyWorld(CAssetId mlvlId, bool loadMap);
~CDummyWorld() override;
CAssetId IGetWorldAssetId() const override;
CAssetId IGetStringTableAssetId() const override;
CAssetId IGetSaveWorldAssetId() const override;
const CMapWorld* IGetMapWorld() const override;
CMapWorld* IGetMapWorld() override;
const IGameArea* IGetAreaAlways(TAreaId id) const override;
TAreaId IGetCurrentAreaId() const override;
TAreaId IGetAreaId(CAssetId id) const override;
bool ICheckWorldComplete() override;
std::string IGetDefaultAudioTrack() const override;
int IGetAreaCount() const override;
};
class CWorld : public IWorld {
friend class CStateManager;
public:
class CRelay {
TEditorId x0_relay = kInvalidEditorId;
TEditorId x4_target = kInvalidEditorId;
s16 x8_msg = -1;
bool xa_active = false;
public:
CRelay() = default;
CRelay(CInputStream& in);
TEditorId GetRelayId() const { return x0_relay; }
TEditorId GetTargetId() const { return x4_target; }
s16 GetMessage() const { return x8_msg; }
bool GetActive() const { return xa_active; }
static std::vector<CWorld::CRelay> ReadMemoryRelays(athena::io::MemoryReader& r);
};
struct CSoundGroupData {
int x0_groupId;
CAssetId x4_agscId;
std::string xc_name;
TCachedToken<CAudioGroupSet> x1c_groupData;
public:
CSoundGroupData(int grpId, CAssetId agsc);
};
private:
static constexpr CGameArea* skGlobalEnd = nullptr;
static constexpr CGameArea* skGlobalNonConstEnd = nullptr;
enum class Phase {
Loading,
LoadingMap,
LoadingMapAreas,
LoadingSkyBox,
LoadingSoundGroups,
Done,
} x4_phase = Phase::Loading;
CAssetId x8_mlvlId;
CAssetId xc_strgId;
CAssetId x10_savwId;
std::vector<std::unique_ptr<CGameArea>> x18_areas;
CAssetId x24_mapwId;
TLockedToken<CMapWorld> x28_mapWorld;
std::vector<CRelay> x2c_relays;
std::shared_ptr<IDvdRequest> x3c_loadToken;
std::unique_ptr<uint8_t[]> x40_loadBuf;
u32 x44_bufSz;
u32 x48_chainCount = 0;
CGameArea* x4c_chainHeads[5] = {};
IObjectStore& x60_objectStore;
IFactory& x64_resFactory;
TAreaId x68_curAreaId = kInvalidAreaId;
u32 x6c_loadedAudioGrpCount = 0;
union {
struct {
bool x70_24_currentAreaNeedsAllocation : 1;
bool x70_25_loadPaused : 1;
bool x70_26_skyboxActive : 1;
bool x70_27_skyboxVisible : 1;
};
u32 dummy = 0;
};
std::vector<CSoundGroupData> x74_soundGroupData;
std::string x84_defAudioTrack;
std::optional<TLockedToken<CModel>> x94_skyboxWorld;
std::optional<TLockedToken<CModel>> xa4_skyboxWorldLoaded;
std::optional<TLockedToken<CModel>> xb4_skyboxOverride;
EEnvFxType xc4_neededFx = EEnvFxType::None;
rstl::reserved_vector<CSfxHandle, 10> xc8_globalSfxHandles;
void LoadSoundGroup(int groupId, CAssetId agscId, CSoundGroupData& data);
void LoadSoundGroups();
void UnloadSoundGroups();
void StopSounds();
public:
void MoveToChain(CGameArea* area, EChain chain);
void MoveAreaToAliveChain(TAreaId aid);
bool CheckWorldComplete(CStateManager* mgr, TAreaId id, CAssetId mreaId);
CGameArea::CChainIterator GetChainHead(EChain chain) { return {x4c_chainHeads[int(chain)]}; }
CGameArea::CConstChainIterator GetChainHead(EChain chain) const { return {x4c_chainHeads[int(chain)]}; }
CGameArea::CChainIterator begin() { return GetChainHead(EChain::Alive); }
CGameArea::CChainIterator end() { return AliveAreasEnd(); }
CGameArea::CConstChainIterator begin() const { return GetChainHead(EChain::Alive); }
CGameArea::CConstChainIterator end() const { return GetAliveAreasEnd(); }
bool ScheduleAreaToLoad(CGameArea* area, CStateManager& mgr);
void TravelToArea(TAreaId aid, CStateManager& mgr, bool skipLoadOther);
void SetLoadPauseState(bool paused);
void CycleLoadPauseState();
CWorld(IObjectStore& objStore, IFactory& resFactory, CAssetId mlvlId);
~CWorld();
bool DoesAreaExist(TAreaId area) const;
const std::vector<std::unique_ptr<CGameArea>>& GetGameAreas() const { return x18_areas; }
const CMapWorld* GetMapWorld() const { return x28_mapWorld.GetObj(); }
u32 GetRelayCount() const { return x2c_relays.size(); }
CRelay GetRelay(u32 idx) const { return x2c_relays[idx]; }
CAssetId IGetWorldAssetId() const override;
CAssetId IGetStringTableAssetId() const override;
CAssetId IGetSaveWorldAssetId() const override;
const CMapWorld* IGetMapWorld() const override;
CMapWorld* IGetMapWorld() override;
const CGameArea* GetAreaAlways(TAreaId id) const;
CGameArea* GetArea(TAreaId);
s32 GetNumAreas() const { return x18_areas.size(); }
const IGameArea* IGetAreaAlways(TAreaId id) const override;
TAreaId IGetCurrentAreaId() const override;
TAreaId GetCurrentAreaId() const { return x68_curAreaId; }
TAreaId IGetAreaId(CAssetId id) const override;
bool ICheckWorldComplete() override;
std::string IGetDefaultAudioTrack() const override;
int IGetAreaCount() const override;
static void PropogateAreaChain(CGameArea::EOcclusionState occlusionState, CGameArea* area, CWorld* world);
static CGameArea::CConstChainIterator GetAliveAreasEnd() { return {skGlobalEnd}; }
static CGameArea::CChainIterator AliveAreasEnd() { return {skGlobalNonConstEnd}; }
void Update(float dt);
void PreRender();
void TouchSky();
void DrawSky(const zeus::CTransform& xf) const;
void StopGlobalSound(u16 id);
bool HasGlobalSound(u16 id) const;
void AddGlobalSound(const CSfxHandle& hnd);
EEnvFxType GetNeededEnvFx() const { return xc4_neededFx; }
CAssetId GetWorldAssetId() const { return x8_mlvlId; }
bool AreSkyNeedsMet() const;
TAreaId GetAreaIdForSaveId(s32 saveId) const;
};
struct CWorldLayers {
struct Area {
u32 m_startNameIdx;
u32 m_layerCount;
u64 m_layerBits;
};
std::vector<Area> m_areas;
std::vector<std::string> m_names;
static void ReadWorldLayers(athena::io::MemoryReader& r, int version, CAssetId mlvlId);
};
} // namespace urde
<|endoftext|>
|
<commit_before>
// Implementation for TestArray. See TestByte.cc
//
// jhrg 1/12/95
// $Log: TestArray.cc,v $
// Revision 1.4 1995/03/04 14:38:00 jimg
// Modified these so that they fit with the changes in the DAP classes.
//
// Revision 1.3 1995/02/10 02:33:37 jimg
// Modified Test<class>.h and .cc so that they used to new definitions of
// read_val().
// Modified the classes read() so that they are more in line with the
// class library's intended use in a real subclass set.
//
// Revision 1.2 1995/01/19 21:58:50 jimg
// Added read_val from dummy_read.cc to the sample set of sub-class
// implementations.
// Changed the declaration of readVal in BaseType so that it names the
// mfunc read_val (to be consistant with the other mfunc names).
// Removed the unnecessary duplicate declaration of the abstract virtual
// mfuncs read and (now) read_val from the classes Byte, ... Grid. The
// declaration in BaseType is sufficient along with the decl and definition
// in the *.cc,h files which contain the subclasses for Byte, ..., Grid.
//
// Revision 1.1 1995/01/19 20:20:34 jimg
// Created as an example of subclassing the class hierarchy rooted at
// BaseType.
//
#ifdef __GNUG__
#pragma implementation
#endif
#include <assert.h>
#include "TestArray.h"
#include "Test.h"
String testarray = "TestArray";
Array *
NewArray(const String &n, BaseType *v)
{
return new TestArray(n, v);
}
BaseType *
TestArray::ptr_duplicate()
{
return new TestArray(*this);
}
TestArray::TestArray(const String &n, BaseType *v) : Array(n, v)
{
}
TestArray::~TestArray()
{
}
bool
TestArray::read(String dataset, String var_name, String constraint)
{
unsigned int wid = var()->width(); // size of the contained variable
// run read() on the contained variable to get, via the read() mfuncs
// defined in the other Test classes, a value in the *contained* object.
var()->read(dataset, var_name, constraint);
// OK, now make an array of those things, and copy the value length()
// times.
unsigned int len = length();
char *tmp = new char[width()];
void *elem_val = 0; // the null forces a new object to be
// allocated
var()->read_val(&elem_val);
for (int i = 0; i < len; ++i)
memcpy(tmp + i * wid, elem_val, wid);
store_val(tmp);
delete tmp;
}
<commit_msg>Fixed bugs with read()s new & delete calls.<commit_after>
// Implementation for TestArray. See TestByte.cc
//
// jhrg 1/12/95
// $Log: TestArray.cc,v $
// Revision 1.5 1995/03/16 17:32:27 jimg
// Fixed bugs with read()s new & delete calls.
//
// Revision 1.4 1995/03/04 14:38:00 jimg
// Modified these so that they fit with the changes in the DAP classes.
//
// Revision 1.3 1995/02/10 02:33:37 jimg
// Modified Test<class>.h and .cc so that they used to new definitions of
// read_val().
// Modified the classes read() so that they are more in line with the
// class library's intended use in a real subclass set.
//
// Revision 1.2 1995/01/19 21:58:50 jimg
// Added read_val from dummy_read.cc to the sample set of sub-class
// implementations.
// Changed the declaration of readVal in BaseType so that it names the
// mfunc read_val (to be consistant with the other mfunc names).
// Removed the unnecessary duplicate declaration of the abstract virtual
// mfuncs read and (now) read_val from the classes Byte, ... Grid. The
// declaration in BaseType is sufficient along with the decl and definition
// in the *.cc,h files which contain the subclasses for Byte, ..., Grid.
//
// Revision 1.1 1995/01/19 20:20:34 jimg
// Created as an example of subclassing the class hierarchy rooted at
// BaseType.
//
#ifdef __GNUG__
#pragma implementation
#endif
#include "config.h"
#include <assert.h>
#include "TestArray.h"
#ifdef TRACE_NEW
#include "trace_new.h"
#endif
Array *
NewArray(const String &n, BaseType *v)
{
return new TestArray(n, v);
}
BaseType *
TestArray::ptr_duplicate()
{
return new TestArray(*this);
}
TestArray::TestArray(const String &n, BaseType *v) : Array(n, v)
{
}
TestArray::~TestArray()
{
}
bool
TestArray::read(String dataset, String var_name, String constraint)
{
unsigned int wid = var()->width(); // size of the contained variable
// run read() on the contained variable to get, via the read() mfuncs
// defined in the other Test classes, a value in the *contained* object.
var()->read(dataset, var_name, constraint);
// OK, now make an array of those things, and copy the value length()
// times.
unsigned int len = length();
char *tmp = new char[width()];
void *elem_val = 0; // the null forces a new object to be
// allocated
var()->read_val(&elem_val); // read_val() allocates space as an array...
for (int i = 0; i < len; ++i)
memcpy(tmp + i * wid, elem_val, wid);
store_val(tmp);
delete[] elem_val;
delete[] tmp;
}
<|endoftext|>
|
<commit_before>#include "CONTROL_S.H"
#include "DRAW.H"
#include "SPECIFIC.H"
void DrawBinoculars()
{
S_Warn("[DrawBinoculars] - Unimplemented!\n");
}
int GetChange(struct ITEM_INFO* item, struct ANIM_STRUCT* anim)//7D48C
{
struct CHANGE_STRUCT* change;//$t1
struct RANGE_STRUCT* range;//$v1
int i;//$t2
int j;//$t0
if (item->current_anim_state == item->goal_anim_state)
{
//locret_7D51C
return 0;
}
change = &changes[anim->change_index];
if (anim->number_changes <= 0)
{
//locret_7D51C
return 0;
}
//loc_7D4C4
do
{
j = 0;
if (change->goal_anim_state == item->goal_anim_state && change->number_ranges > 0)
{
range = &ranges[change->range_index];
//loc_7D4E4
do
{
if (item->frame_number < range->start_frame)
{
//loc_7D4FC
j++;
if (j < change->number_ranges)
{
range++;
continue;
}
else
{
break;
}
}
else if (range->end_frame >= item->frame_number)
{
//loc_7D524
item->anim_number = range->link_anim_num;
item->frame_number = range->link_frame_num;
return 1;
}
} while (1);
}
//loc_7D50C
i++;
change++;
} while (i < anim->number_changes);
//locret_7D51C
return 0;
}
void AnimateLara(struct ITEM_INFO* item /* s1 */)//7D53C(<)
{
struct ANIM_STRUCT* anim = &anims[item->anim_number];//$s2
item->frame_number += 1;
//v0 = anim->number_changes
if (anim->number_changes > 0 && GetChange())
{
}//loc_7D5BC
#if 0
move $a0, $s1
jal sub_7D48C
move $a1, $s2
beqz $v0, loc_7D5BC
nop
lh $v1, 0x14($s1)
lw $a0, 0x202C($gp)
sll $v0, $v1, 2
addu $v0, $v1
sll $v0, 3
addu $s2, $a0, $v0
lh $v1, 6($s2)
nop
sh $v1, 0xE($s1)
loc_7D5BC:
lh $v1, 0x16($s1)
lh $v0, 0x1A($s2)
nop
slt $v0, $v1
beqz $v0, loc_7D6D4
nop
lh $s3, 0x24($s2)
lh $v0, 0x26($s2)
lw $v1, 0x2078($gp)
blez $s3, loc_7D6A4
sll $v0, 1
addu $s0, $v1, $v0
loc_7D5EC:
lhu $v0, 0($s0)
addiu $s0, 2
addiu $at, $v0, -1
beqz $at, loc_7D628
addiu $at, $v0, -2
beqz $at, loc_7D650
addiu $at, $v0, -3
beqz $at, loc_7D684
addiu $at, $v0, -5
beqz $at, loc_7D620
addiu $at, $v0, -6
bnez $at, loc_7D698
nop
loc_7D620:
j loc_7D698
addiu $s0, 4
loc_7D628:
move $a0, $s1
lh $a1, 0($s0)
lh $a2, 2($s0)
lh $a3, 4($s0)
jal sub_7D410
addiu $s0, 6
move $a0, $s1
li $a1, 0xFFFFFE83
jal sub_7C58C
addiu $ra, 0x48
loc_7D650:
lw $v1, 0x84($s1)
lhu $at, 0($s0)
lhu $v0, 2($s0)
lh $a0, 0x5232($gp)
addiu $s0, 4
ori $v1, 8
sh $at, 0x20($s1)
sh $v0, 0x1E($s1)
beqz $a0, loc_7D698
sw $v1, 0x84($s1)
sh $a0, 0x20($s1)
j loc_7D698
sh $zero, 0x5232($gp)
loc_7D684:
lh $v1, 0x522A($gp)
li $v0, 5
beq $v1, $v0, loc_7D698
nop
sh $zero, 0x522A($gp)
loc_7D698:
addiu $s3, -1
bgtz $s3, loc_7D5EC
nop
loc_7D6A4:
lh $at, 0x1C($s2)
lhu $a0, 0x1E($s2)
lw $v0, 0x202C($gp)
sh $at, 0x14($s1)
sh $a0, 0x16($s1)
sll $v1, $at, 2
addu $v1, $at
sll $v1, 3
addu $s2, $v0, $v1
lh $v0, 6($s2)
nop
sh $v0, 0xE($s1)
loc_7D6D4:
lh $s3, 0x24($s2)
lh $v0, 0x26($s2)
lw $v1, 0x2078($gp)
blez $s3, loc_7D7C8
sll $v0, 1
addu $s0, $v1, $v0
loc_7D6EC:
lhu $v0, 0($s0)
addiu $s0, 2
addiu $at, $v0, -2
beqz $at, loc_7D7B8
addiu $at, $v0, -5
beqz $at, loc_7D720
addiu $at, $v0, -6
beqz $at, loc_7D780
addiu $at, $v0, -1
bnez $at, loc_7D7BC
nop
j loc_7D7BC
addiu $s0, 6
loc_7D720:
lh $v1, 0x16($s1)
lh $v0, 0($s0)
lhu $a0, 2($s0)
bne $v1, $v0, loc_7D7B8
andi $a1, $a0, 0xC000
beqz $a1, loc_7D76C
li $v0, 0x4000
lw $v1, 0x5270($gp)
bne $a1, $v0, loc_7D754
nop
bgez $v1, loc_7D76C
li $v0, 0xFFFF8100
beq $v1, $v0, loc_7D76C
loc_7D754:
li $v0, 0x8000
bne $a1, $v0, loc_7D7B8
nop
bgez $v1, loc_7D7B8
li $v0, 0xFFFF8100
beq $v1, $v0, loc_7D7B8
loc_7D76C:
andi $a0, 0x3FFF
addiu $a1, $s1, 0x40
li $a2, 2
jal sub_91780
addiu $ra, 0x38
loc_7D780:
lh $at, 0x16($s1)
lh $v0, 0($s0)
lui $v1, 9
bne $at, $v0, loc_7D7B8
la $v1, off_92AE8
lhu $a1, 2($s0)
move $a0, $s1
andi $a3, $a1, 0x3FFF
sll $v0, $a3, 2
addu $v0, $v1
lw $a2, 0($v0)
andi $a1, 0xC000
jalr $a2
sh $a1, 0x1AAC($gp)
loc_7D7B8:
addiu $s0, 4
loc_7D7BC:
addiu $s3, -1
bgtz $s3, loc_7D6EC
nop
loc_7D7C8:
lw $a1, 0x14($s2)
lw $s0, 0x10($s2)
lh $t1, 0x16($s1)
lh $v0, 0x18($s2)
beqz $a1, loc_7D7EC
subu $t1, $v0
mult $a1, $t1
mflo $v0
addu $s0, $v0
loc_7D7EC:
lw $v0, 0x84($s1)
nop
andi $v0, 8
bnez $v0, loc_7D828
sra $s0, 16
lw $a1, 0xC($s2)
lw $a0, 8($s2)
beqz $a1, loc_7D820
sra $v0, $a0, 16
mult $a1, $t1
mflo $v0
addu $a0, $v0
sra $v0, $a0, 16
loc_7D820:
j loc_7D884
sh $v0, 0x1E($s1)
loc_7D828:
lw $a2, 0xC($s2)
addiu $v0, $t1, -1
mult $a2, $v0
lhu $a1, 0x1E($s1)
lw $v1, 8($s2)
mflo $a0
addu $a0, $v1, $a0
sra $v0, $a0, 16
subu $a1, $v0
addu $a0, $a2
sra $v0, $a0, 16
lh $a0, 0x20($s1)
addu $a1, $v0
sh $a1, 0x1E($s1)
slti $v0, $a0, 0x80
beqz $v0, loc_7D870
addiu $v0, $a0, 1
addiu $v0, $a0, 6
loc_7D870:
sh $v0, 0x20($s1)
lw $v1, 0x44($s1)
nop
addu $v1, $v0
sw $v1, 0x44($s1)
loc_7D884:
lw $v1, 0x532C($gp)
li $v0, 0xFFFFFFFF
beq $v1, $v0, loc_7D89C
nop
jal sub_4B3D8
move $a0, $s1
loc_7D89C:
lw $v0, 0x526C($gp)
lui $t0, 9
andi $v0, 0x20
bnez $v0, loc_7D934
la $t0, dword_9A8C8
lhu $a2, 0x52CE($gp)
lh $a3, 0x1E($s1)
srl $at, $a2, 2
andi $at, 0x3FFC
addu $at, $t0
lh $v0, 0($at)
lh $at, 2($at)
mult $v0, $a3
lw $t2, 0x40($s1)
lw $t3, 0x48($s1)
mflo $v0
sra $v0, 12
addu $t2, $v0
mult $at, $a3
addiu $a2, 0x4000
sra $a2, 2
andi $a2, 0x3FFC
addu $a2, $t0
lh $v1, 0($a2)
lh $a0, 2($a2)
mflo $at
sra $at, 12
addu $t3, $at
mult $v1, $s0
mflo $v1
sra $v1, $v0, 12
addu $t2, $v1
mult $a0, $s0
sw $t2, 0x40($s1)
mflo $a0
sra $a0, 12
addu $t3, $a0
sw $t3, 0x48($s1)
loc_7D934:
lw $ra, 0x24+var_4($sp)
lw $s3, 0x24+var_8($sp)
lw $s2, 0x24+var_C($sp)
lw $s1, 0x24+var_10($sp)
lw $s0, 0x24+var_14($sp)
jr $ra
addiu $sp, 0x24
#endif
UNIMPLEMENTED();
}<commit_msg>[Specific-PSXPC_N] Implement TranslateItem.<commit_after>#include "CONTROL_S.H"
#include "CAMERA.H"
#include "COLLIDE_S.H"
#include "DRAW.H"
#include "SPECIFIC.H"
void DrawBinoculars()
{
S_Warn("[DrawBinoculars] - Unimplemented!\n");
}
void TranslateItem(struct ITEM_INFO* item, unsigned short x, unsigned short y, unsigned short z)
{
short sin;//$v1
short cos;//$t0
cos = COS(item->pos.y_rot);
sin = SIN(item->pos.y_rot);
item->pos.x_pos += ((cos * x) + (sin * z)) >> W2V_SHIFT;
item->pos.y_pos += y;
item->pos.z_pos += ((-sin * x) + (cos * z)) >> W2V_SHIFT;
}
int GetChange(struct ITEM_INFO* item, struct ANIM_STRUCT* anim)//7D48C
{
struct CHANGE_STRUCT* change;//$t1
struct RANGE_STRUCT* range;//$v1
int i;//$t2
int j;//$t0
if (item->current_anim_state == item->goal_anim_state)
{
//locret_7D51C
return 0;
}
change = &changes[anim->change_index];
if (anim->number_changes <= 0)
{
//locret_7D51C
return 0;
}
//loc_7D4C4
do
{
j = 0;
if (change->goal_anim_state == item->goal_anim_state && change->number_ranges > 0)
{
range = &ranges[change->range_index];
//loc_7D4E4
do
{
if (item->frame_number < range->start_frame)
{
//loc_7D4FC
j++;
if (j < change->number_ranges)
{
range++;
continue;
}
else
{
break;
}
}
else if (range->end_frame >= item->frame_number)
{
//loc_7D524
item->anim_number = range->link_anim_num;
item->frame_number = range->link_frame_num;
return 1;
}
} while (1);
}
//loc_7D50C
i++;
change++;
} while (i < anim->number_changes);
//locret_7D51C
return 0;
}
void AnimateLara(struct ITEM_INFO* item /* s1 */)//7D53C(<)
{
struct ANIM_STRUCT* anim = &anims[item->anim_number];//$s2
unsigned short* command;//$s0
unsigned short data;//$v0
item->frame_number += 1;
//v0 = anim->number_changes
if (anim->number_changes > 0 && GetChange(item, anim))
{
//v1 = item->anim_number
//a0 = &anims[item->anim_number];
anim = &anims[item->anim_number];///@TODO Not really required
item->current_anim_state = anim->current_anim_state;
}
//loc_7D5BC
//v1 = item->frame_number
//v0 = anim->frame_end
if (anim->frame_end < item->frame_number)
{
//s3 = anim->number_commands
//v0 = anim->command_index
//v1 = commands
if (anim->number_commands > 0)
{
command = (unsigned short*)&commands[anim->command_index];
//loc_7D5EC
data = *command++;
if (data - 1 == 0)
{
//loc_7D628
TranslateItem(item, command[0], command[1], command[2]);
command += 3;
UpdateLaraRoom(item, -381);
}
else if (data - 2 == 0)
{
//loc_7D650
}
else if (data - 3 == 0)
{
//loc_7D684
}
else if (data - 5 == 0 || data - 6 == 0)
{
//loc_7D620
}
//loc_7D698
}//loc_7D6A4
}//loc_7D6D4
#if 0
addiu $at, $v0, -1
beqz $at, loc_7D628
addiu $at, $v0, -2
beqz $at, loc_7D650
addiu $at, $v0, -3
beqz $at, loc_7D684
addiu $at, $v0, -5
beqz $at, loc_7D620
addiu $at, $v0, -6
bnez $at, loc_7D698
nop
loc_7D620:
j loc_7D698
addiu $s0, 4
loc_7D650:
lw $v1, 0x84($s1)
lhu $at, 0($s0)
lhu $v0, 2($s0)
lh $a0, 0x5232($gp)
addiu $s0, 4
ori $v1, 8
sh $at, 0x20($s1)
sh $v0, 0x1E($s1)
beqz $a0, loc_7D698
sw $v1, 0x84($s1)
sh $a0, 0x20($s1)
j loc_7D698
sh $zero, 0x5232($gp)
loc_7D684:
lh $v1, 0x522A($gp)
li $v0, 5
beq $v1, $v0, loc_7D698
nop
sh $zero, 0x522A($gp)
loc_7D698:
addiu $s3, -1
bgtz $s3, loc_7D5EC
nop
loc_7D6A4:
lh $at, 0x1C($s2)
lhu $a0, 0x1E($s2)
lw $v0, 0x202C($gp)
sh $at, 0x14($s1)
sh $a0, 0x16($s1)
sll $v1, $at, 2
addu $v1, $at
sll $v1, 3
addu $s2, $v0, $v1
lh $v0, 6($s2)
nop
sh $v0, 0xE($s1)
loc_7D6D4:
lh $s3, 0x24($s2)
lh $v0, 0x26($s2)
lw $v1, 0x2078($gp)
blez $s3, loc_7D7C8
sll $v0, 1
addu $s0, $v1, $v0
loc_7D6EC:
lhu $v0, 0($s0)
addiu $s0, 2
addiu $at, $v0, -2
beqz $at, loc_7D7B8
addiu $at, $v0, -5
beqz $at, loc_7D720
addiu $at, $v0, -6
beqz $at, loc_7D780
addiu $at, $v0, -1
bnez $at, loc_7D7BC
nop
j loc_7D7BC
addiu $s0, 6
loc_7D720:
lh $v1, 0x16($s1)
lh $v0, 0($s0)
lhu $a0, 2($s0)
bne $v1, $v0, loc_7D7B8
andi $a1, $a0, 0xC000
beqz $a1, loc_7D76C
li $v0, 0x4000
lw $v1, 0x5270($gp)
bne $a1, $v0, loc_7D754
nop
bgez $v1, loc_7D76C
li $v0, 0xFFFF8100
beq $v1, $v0, loc_7D76C
loc_7D754:
li $v0, 0x8000
bne $a1, $v0, loc_7D7B8
nop
bgez $v1, loc_7D7B8
li $v0, 0xFFFF8100
beq $v1, $v0, loc_7D7B8
loc_7D76C:
andi $a0, 0x3FFF
addiu $a1, $s1, 0x40
li $a2, 2
jal sub_91780
addiu $ra, 0x38
loc_7D780:
lh $at, 0x16($s1)
lh $v0, 0($s0)
lui $v1, 9
bne $at, $v0, loc_7D7B8
la $v1, off_92AE8
lhu $a1, 2($s0)
move $a0, $s1
andi $a3, $a1, 0x3FFF
sll $v0, $a3, 2
addu $v0, $v1
lw $a2, 0($v0)
andi $a1, 0xC000
jalr $a2
sh $a1, 0x1AAC($gp)
loc_7D7B8:
addiu $s0, 4
loc_7D7BC:
addiu $s3, -1
bgtz $s3, loc_7D6EC
nop
loc_7D7C8:
lw $a1, 0x14($s2)
lw $s0, 0x10($s2)
lh $t1, 0x16($s1)
lh $v0, 0x18($s2)
beqz $a1, loc_7D7EC
subu $t1, $v0
mult $a1, $t1
mflo $v0
addu $s0, $v0
loc_7D7EC:
lw $v0, 0x84($s1)
nop
andi $v0, 8
bnez $v0, loc_7D828
sra $s0, 16
lw $a1, 0xC($s2)
lw $a0, 8($s2)
beqz $a1, loc_7D820
sra $v0, $a0, 16
mult $a1, $t1
mflo $v0
addu $a0, $v0
sra $v0, $a0, 16
loc_7D820:
j loc_7D884
sh $v0, 0x1E($s1)
loc_7D828:
lw $a2, 0xC($s2)
addiu $v0, $t1, -1
mult $a2, $v0
lhu $a1, 0x1E($s1)
lw $v1, 8($s2)
mflo $a0
addu $a0, $v1, $a0
sra $v0, $a0, 16
subu $a1, $v0
addu $a0, $a2
sra $v0, $a0, 16
lh $a0, 0x20($s1)
addu $a1, $v0
sh $a1, 0x1E($s1)
slti $v0, $a0, 0x80
beqz $v0, loc_7D870
addiu $v0, $a0, 1
addiu $v0, $a0, 6
loc_7D870:
sh $v0, 0x20($s1)
lw $v1, 0x44($s1)
nop
addu $v1, $v0
sw $v1, 0x44($s1)
loc_7D884:
lw $v1, 0x532C($gp)
li $v0, 0xFFFFFFFF
beq $v1, $v0, loc_7D89C
nop
jal sub_4B3D8
move $a0, $s1
loc_7D89C:
lw $v0, 0x526C($gp)
lui $t0, 9
andi $v0, 0x20
bnez $v0, loc_7D934
la $t0, dword_9A8C8
lhu $a2, 0x52CE($gp)
lh $a3, 0x1E($s1)
srl $at, $a2, 2
andi $at, 0x3FFC
addu $at, $t0
lh $v0, 0($at)
lh $at, 2($at)
mult $v0, $a3
lw $t2, 0x40($s1)
lw $t3, 0x48($s1)
mflo $v0
sra $v0, 12
addu $t2, $v0
mult $at, $a3
addiu $a2, 0x4000
sra $a2, 2
andi $a2, 0x3FFC
addu $a2, $t0
lh $v1, 0($a2)
lh $a0, 2($a2)
mflo $at
sra $at, 12
addu $t3, $at
mult $v1, $s0
mflo $v1
sra $v1, $v0, 12
addu $t2, $v1
mult $a0, $s0
sw $t2, 0x40($s1)
mflo $a0
sra $a0, 12
addu $t3, $a0
sw $t3, 0x48($s1)
loc_7D934:
lw $ra, 0x24+var_4($sp)
lw $s3, 0x24+var_8($sp)
lw $s2, 0x24+var_C($sp)
lw $s1, 0x24+var_10($sp)
lw $s0, 0x24+var_14($sp)
jr $ra
addiu $sp, 0x24
#endif
UNIMPLEMENTED();
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: FWS.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2003-10-06 15:43:20 $
*
* 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 _FOREIGN_WINDOW_SYSTEM_HXX
#define _FOREIGN_WINDOW_SYSTEM_HXX
#include <X11/Xlib.h>
#if defined(__cplusplus)
extern "C" {
#endif
/* Initialize our atoms and determine if the current window manager is
* providing FWS extension support.
*/
Bool
WMSupportsFWS (Display *display, int screen);
/* Send a client message to the FWS_COMM_WINDOW indicating the existance
* of a new FWS client window. Be careful to avoid BadWindow errors on
* the XSendEvent in case the FWS_COMM_WINDOW root window property had
* old/obsolete junk in it.
*/
Bool
RegisterFwsWindow (Display *display, Window window);
/* Add the FWS protocol atoms to the WMProtocols property for the window.
*/
void
AddFwsProtocols (Display *display, Window window);
#if defined(__cplusplus)
} /* extern "C" */
#endif
#endif // _FOREIGN_WINDOW_SYSTEM_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.580); FILE MERGED 2005/09/05 14:46:17 rt 1.2.580.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FWS.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 13:50:38 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FOREIGN_WINDOW_SYSTEM_HXX
#define _FOREIGN_WINDOW_SYSTEM_HXX
#include <X11/Xlib.h>
#if defined(__cplusplus)
extern "C" {
#endif
/* Initialize our atoms and determine if the current window manager is
* providing FWS extension support.
*/
Bool
WMSupportsFWS (Display *display, int screen);
/* Send a client message to the FWS_COMM_WINDOW indicating the existance
* of a new FWS client window. Be careful to avoid BadWindow errors on
* the XSendEvent in case the FWS_COMM_WINDOW root window property had
* old/obsolete junk in it.
*/
Bool
RegisterFwsWindow (Display *display, Window window);
/* Add the FWS protocol atoms to the WMProtocols property for the window.
*/
void
AddFwsProtocols (Display *display, Window window);
#if defined(__cplusplus)
} /* extern "C" */
#endif
#endif // _FOREIGN_WINDOW_SYSTEM_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wntgdi.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-19 20:01:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
// -----------------------------------------------------------------------
extern "C"
{
BOOL WINAPI WIN_Rectangle( HDC hDC, int X1, int Y1, int X2, int Y2 )
{
return Rectangle( hDC, X1, Y1, X2, Y2 );
}
}
// -----------------------------------------------------------------------
extern "C"
{
BOOL WINAPI WIN_Polygon( HDC hDC, CONST POINT * ppt, int ncnt )
{
return Polygon( hDC, ppt, ncnt );
}
}
// -----------------------------------------------------------------------
extern "C"
{
BOOL WINAPI WIN_PolyPolygon( HDC hDC, CONST POINT * ppt, LPINT npcnt, int ncnt )
{
return PolyPolygon( hDC, ppt, npcnt, ncnt );
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.112); FILE MERGED 2006/09/01 17:58:14 kaib 1.3.112.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wntgdi.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 12:46:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
// -----------------------------------------------------------------------
extern "C"
{
BOOL WINAPI WIN_Rectangle( HDC hDC, int X1, int Y1, int X2, int Y2 )
{
return Rectangle( hDC, X1, Y1, X2, Y2 );
}
}
// -----------------------------------------------------------------------
extern "C"
{
BOOL WINAPI WIN_Polygon( HDC hDC, CONST POINT * ppt, int ncnt )
{
return Polygon( hDC, ppt, ncnt );
}
}
// -----------------------------------------------------------------------
extern "C"
{
BOOL WINAPI WIN_PolyPolygon( HDC hDC, CONST POINT * ppt, LPINT npcnt, int ncnt )
{
return PolyPolygon( hDC, ppt, npcnt, ncnt );
}
}
<|endoftext|>
|
<commit_before>#ifndef __V_PLAY_HPP__
#define __V_PLAY_HPP__
#include "utility.hpp"
#include "debug.hpp"
#include "videotype.hpp"
using namespace UtilityLib;
typedef BOOL (*VPlayDataHandler)(void* pData, VideoFrame& packet);
typedef BOOL (*VPlayPBTimeCallback)(void* pData, int time);
typedef BOOL (*VPlayRawFrameHandler)(void* pData, RawFrame& frame);
typedef enum __VPlayCmd
{
VPLAY_CMD_PLAY = 1,
VPLAY_CMD_PAUSE,
VPLAY_CMD_SPEED,
VPLAY_CMD_MOVE,
VPLAY_CMD_LAST
}VPlayCmd;
typedef struct __VPlayCmdParam
{
int speed;
int moveto;
}VPlayCmdParam;
class VPlayData;
class VE_LIBRARY_API VPlay
{
public:
VPlay();
~VPlay();
public:
static BOOL SetLicense(astring &strLicense);
static BOOL GetLicenseInfo(astring &strHostId, int &ch, int &type);
public:
BOOL Init(BOOL bRealStream, string strUrl, string strUser, string strPass);
BOOL Init(string strFile);
BOOL AttachWidget(HWND hWnd, int w, int h);
BOOL UpdateWidget(HWND hWnd, int w, int h);
BOOL DetachWidget(HWND hWnd);
BOOL SetPbTimeCallback(HWND hWnd, void * pData, VPlayPBTimeCallback callback);
BOOL Control(VPlayCmd cmd, VPlayCmdParam param);
BOOL EnablePtz(HWND hWnd, bool enable);
BOOL DrawPtzDirection(HWND hWnd, int x1, int y1, int x2, int y2);
BOOL ClearPtzDirection(HWND hWnd);
BOOL StartGetData(void * pData, VPlayDataHandler callback);
BOOL StopGetData();
BOOL StartGetRawFrame(void * pData, VPlayRawFrameHandler callback);
BOOL StopGetRawFrame();
BOOL PutRawData(VideoFrame& packet);
BOOL ShowAlarm(HWND hWnd);
public:
VPlayData * m_data;
};
#endif /* __V_PLAY_HPP__ */
<commit_msg>add intel media sdk<commit_after>#ifndef __V_PLAY_HPP__
#define __V_PLAY_HPP__
#include "utility.hpp"
#include "debug.hpp"
#include "videotype.hpp"
using namespace UtilityLib;
typedef BOOL (*VPlayDataHandler)(void* pData, VideoFrame& packet);
typedef BOOL (*VPlayPBTimeCallback)(void* pData, int time);
typedef BOOL (*VPlayRawFrameHandler)(void* pData, RawFrame& frame);
typedef enum __VPlayCmd
{
VPLAY_CMD_PLAY = 1,
VPLAY_CMD_PAUSE,
VPLAY_CMD_SPEED,
VPLAY_CMD_MOVE,
VPLAY_CMD_LAST
}VPlayCmd;
typedef struct __VPlayCmdParam
{
int speed;
int moveto;
}VPlayCmdParam;
class VPlayData;
class VE_LIBRARY_API VPlay
{
public:
VPlay();
~VPlay();
public:
static BOOL SetLicense(astring &strLicense);
static BOOL GetLicenseInfo(astring &strHostId, int &ch, int &type);
public:
BOOL Init(BOOL bRealStream, string strUrl, string strUser, string strPass, BOOL bHWAccel = FALSE);
BOOL Init(string strFile, BOOL bHWAccel = FALSE);
BOOL AttachWidget(HWND hWnd, int w, int h);
BOOL UpdateWidget(HWND hWnd, int w, int h);
BOOL DetachWidget(HWND hWnd);
BOOL SetPbTimeCallback(HWND hWnd, void * pData, VPlayPBTimeCallback callback);
BOOL Control(VPlayCmd cmd, VPlayCmdParam param);
BOOL EnablePtz(HWND hWnd, bool enable);
BOOL DrawPtzDirection(HWND hWnd, int x1, int y1, int x2, int y2);
BOOL ClearPtzDirection(HWND hWnd);
BOOL StartGetData(void * pData, VPlayDataHandler callback);
BOOL StopGetData();
BOOL StartGetRawFrame(void * pData, VPlayRawFrameHandler callback);
BOOL StopGetRawFrame();
BOOL PutRawData(VideoFrame& packet);
BOOL ShowAlarm(HWND hWnd);
public:
VPlayData * m_data;
};
#endif /* __V_PLAY_HPP__ */
<|endoftext|>
|
<commit_before>#pragma once
#include "PageFrameAllocator.hpp"
#include "PageTable.hpp"
class MMU
{
public:
MMU(uint32_t mmap_addr, uint32_t mmap_length);
void *palloc(size_t numberOfPages);
int pfree(void *startOfMemoryRange, size_t numberOfPages);
void install();
private:
PageFrameAllocator _pageFrameAllocator;
PageTable _pageDirectory;
};
<commit_msg>Gave palloc()/pfree() default page count of 1.<commit_after>#pragma once
#include "PageFrameAllocator.hpp"
#include "PageTable.hpp"
class MMU
{
public:
MMU(uint32_t mmap_addr, uint32_t mmap_length);
void *palloc(size_t numberOfPages = 1);
int pfree(void *startOfMemoryRange, size_t numberOfPages = 1);
void install();
private:
PageFrameAllocator _pageFrameAllocator;
PageTable _pageDirectory;
};
<|endoftext|>
|
<commit_before>#include <QtWidgets/QHBoxLayout>
#include <QtCore/QString>
#include "gridParameters.h"
#include "../../../qrkernel/settingsManager.h"
GridParameters::GridParameters(QWidget *parent)
: QFrame(parent)
{
QHBoxLayout *layout = new QHBoxLayout(this);
mShowGridCheckBox = new QCheckBox(this);
QString const checkBoxTitle = tr("Show grid");
mShowGridCheckBox->setText(checkBoxTitle);
mShowGridCheckBox->setTristate(false);
mCellSize = new QSlider(this);
mCellSize->setOrientation(Qt::Horizontal);
mCellSize->setMinimum(50);
mCellSize->setMaximum(200);
mCellSize->setTickInterval(10);
mCellSize->setEnabled(false);
layout->addWidget(mShowGridCheckBox);
layout->addWidget(mCellSize);
layout->setContentsMargins(5, 5, 5, 5);
connect(mShowGridCheckBox, SIGNAL(toggled(bool)), mCellSize, SLOT(setEnabled(bool)));
connect(mShowGridCheckBox, SIGNAL(toggled(bool)), this, SLOT(showGrid(bool)));
connect(mCellSize, SIGNAL(valueChanged(int)), this, SLOT(setCellSize(int)));
setLayout(layout);
showGrid(qReal::SettingsManager::value("2dShowGrid").toBool());
setCellSize(qReal::SettingsManager::value("2dGridCellSize").toInt());
}
GridParameters::~GridParameters()
{
}
void GridParameters::showGrid(bool isGridEnabled)
{
qReal::SettingsManager::setValue("2dShowGrid", isGridEnabled);
emit parametersChanged();
}
void GridParameters::setCellSize(int cellSizeValue)
{
qReal::SettingsManager::setValue("2dGridCellSize", cellSizeValue);
emit parametersChanged();
}
<commit_msg>Fixed grid initialization in 2D model<commit_after>#include <QtWidgets/QHBoxLayout>
#include <QtCore/QString>
#include "gridParameters.h"
#include "../../../qrkernel/settingsManager.h"
GridParameters::GridParameters(QWidget *parent)
: QFrame(parent)
{
QHBoxLayout *layout = new QHBoxLayout(this);
mShowGridCheckBox = new QCheckBox(this);
QString const checkBoxTitle = tr("Show grid");
mShowGridCheckBox->setText(checkBoxTitle);
mShowGridCheckBox->setTristate(false);
mCellSize = new QSlider(this);
mCellSize->setOrientation(Qt::Horizontal);
mCellSize->setMinimum(50);
mCellSize->setMaximum(200);
mCellSize->setTickInterval(10);
mCellSize->setEnabled(false);
layout->addWidget(mShowGridCheckBox);
layout->addWidget(mCellSize);
layout->setContentsMargins(5, 5, 5, 5);
connect(mShowGridCheckBox, SIGNAL(toggled(bool)), mCellSize, SLOT(setEnabled(bool)));
connect(mShowGridCheckBox, SIGNAL(toggled(bool)), this, SLOT(showGrid(bool)));
connect(mCellSize, SIGNAL(valueChanged(int)), this, SLOT(setCellSize(int)));
bool const showGrid = qReal::SettingsManager::value("2dShowGrid").toBool();
int const gridSize = qReal::SettingsManager::value("2dGridCellSize").toInt();
mShowGridCheckBox->setChecked(showGrid);
mCellSize->setValue(gridSize);
setLayout(layout);
}
GridParameters::~GridParameters()
{
}
void GridParameters::showGrid(bool isGridEnabled)
{
qReal::SettingsManager::setValue("2dShowGrid", isGridEnabled);
emit parametersChanged();
}
void GridParameters::setCellSize(int cellSizeValue)
{
qReal::SettingsManager::setValue("2dGridCellSize", cellSizeValue);
emit parametersChanged();
}
<|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------
// hexanoise/generator_opencl.cpp
//
// Copyright 2014, nocte@hippie.nu Released under the MIT License.
//---------------------------------------------------------------------------
#include "generator_opencl.hpp"
#include <iostream>
#include <cmath>
#include <fstream>
#include <stdexcept>
#include "node.hpp"
#ifndef OPENCL_OCTAVES_LIMIT
# define OPENCL_OCTAVES_LIMIT 16
#endif
namespace hexa {
namespace noise {
generator_opencl::generator_opencl (const generator_context& ctx,
cl::Context& opencl_context,
cl::Device& opencl_device,
const node& n,
const std::string& opencl_file)
: generator_i(ctx)
, count_(1)
, context_(opencl_context)
, device_(opencl_device)
, queue_ (opencl_context, opencl_device)
{
std::string body (co(n));
std::ifstream file (opencl_file.c_str(), std::ios::binary);
if (!file)
throw std::runtime_error("cannot open OpenCL file " + opencl_file);
file.seekg(0, std::ios::end);
main_.resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read(&main_[0], main_.size());
file.close();
main_ += "\n";
for (auto& p : functions_)
{
main_ += p;
main_ += "\n\n";
}
main_ += "\n" \
"__kernel void noisemain(\n" \
" __global double* output, const double2 start, const double2 step)\n" \
"{\n"\
" int2 coord = (int2)(get_global_id(0), get_global_id(1));\n"\
" int sizex = get_global_size(0);\n"\
" double2 p = mad(step, (double2)(coord.x, coord.y), start);\n" \
" output[coord.y * sizex + coord.x] = ";
main_ += body;
main_ += ";\n}\n";
main_ += "\n" \
"__kernel void noisemain_int16(\n" \
" __global int16* output, const double2 start, const double2 step)\n" \
"{\n"\
" int2 coord = (int2)(get_global_id(0), get_global_id(1));\n"\
" int sizex = get_global_size(0);\n"\
" double2 p = mad(step, (double2)(coord.x, coord.y), start);\n" \
" output[coord.y * sizex + coord.x] = (int16)(";
main_ += body;
main_ += ");\n}\n";
std::vector<cl::Device> device_vec;
device_vec.emplace_back(opencl_device);
cl::Program::Sources sources (1, { main_.c_str(), main_.size() });
program_ = cl::Program(opencl_context, sources);
try
{
program_.build(device_vec, "-cl-strict-aliasing -cl-mad-enable -cl-unsafe-math-optimizations -cl-fast-relaxed-math");
}
catch (cl::Error&)
{
std::cerr << program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(opencl_device) << std::endl;
throw;
}
kernel_ = cl::Kernel(program_, "noisemain");
kernel_int16_ = cl::Kernel(program_, "noisemain_int16");
}
std::vector<double>
generator_opencl::run (const glm::dvec2& corner,
const glm::dvec2& step,
const glm::ivec2& count)
{
unsigned int width (count.x), height (count.y);
unsigned int elements (width * height);
std::vector<double> result (elements);
cl::Buffer output (context_, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR,
elements * sizeof(double),
&result[0]);
kernel_.setArg(0, output);
kernel_.setArg(1, sizeof(corner), (void*)&corner);
kernel_.setArg(2, sizeof(step), (void*)&step);
queue_.enqueueNDRangeKernel(kernel_, cl::NullRange, {width, height},
cl::NullRange);
auto memobj (queue_.enqueueMapBuffer(output, true, CL_MAP_WRITE, 0,
elements * sizeof(double)));
queue_.enqueueUnmapMemObject(output, memobj);
return result;
}
std::vector<int16_t>
generator_opencl::run_int16 (const glm::dvec2& corner,
const glm::dvec2& step,
const glm::ivec2& count)
{
unsigned int width (count.x), height (count.y);
unsigned int elements (width * height);
std::vector<int16_t> result (elements);
cl::Buffer output (context_, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR,
elements * sizeof(int16_t),
&result[0]);
kernel_int16_.setArg(0, output);
kernel_int16_.setArg(1, sizeof(corner), (void*)&corner);
kernel_int16_.setArg(2, sizeof(step), (void*)&step);
queue_.enqueueNDRangeKernel(kernel_int16_, cl::NullRange, {width, height},
cl::NullRange);
auto memobj (queue_.enqueueMapBuffer(output, true, CL_MAP_WRITE, 0,
elements * sizeof(int16_t)));
queue_.enqueueUnmapMemObject(output, memobj);
return result;
}
std::string generator_opencl::pl (const node& n)
{
std::string result ("(");
for (auto i (n.input.begin()); i != n.input.end(); )
{
result += co(*i);
++i;
if (i != n.input.end())
result.push_back(',');
}
result += ')';
return result;
}
std::string generator_opencl::co (const node& n)
{
switch (n.type)
{
case node::entry_point: return "p";
case node::const_var: return std::to_string(n.aux_var);
case node::const_bool: return std::to_string(n.aux_bool);
case node::const_str: throw std::runtime_error("string encountered");
case node::rotate: return "p_rotate" + pl(n);
case node::scale: return "("+co(n.input[0])+"/"+co(n.input[1])+")";
case node::shift: return "("+co(n.input[0])+"+"+co(n.input[1])+")";
case node::swap: return "p_swap" + pl(n);
case node::map:
{
std::string func_name ("p_map" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "inline double2 " << func_name << " (const double2 p) { return (double2)("
<< co(n.input[1]) << ", "
<< co(n.input[2]) << "); }" << std::endl;
functions_.emplace_back(func_body.str());
return func_name + "("+ co(n.input[0]) + ")";
}
case node::turbulence:
{
std::string func_name ("p_map" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "inline double2 " << func_name << " (const double2 p) { return (double2)("
<< "p.x+(" << co(n.input[1]) << "), "
<< "p.y+(" << co(n.input[2]) << ")); }" << std::endl;
functions_.emplace_back(func_body.str());
return func_name + "("+ co(n.input[0]) + ")";
}
case node::worley:
{
std::string func_name ("p_worley" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "inline double " << func_name << " (const double2 q, uint seed) { "
<< " double2 p = p_worley(q, seed);"
<< " return " << co(n.input[1]) << "; }" << std::endl;
functions_.emplace_back(func_body.str());
return func_name + "("+co(n.input[0])+ ","+co(n.input[2])+")";
}
case node::voronoi:
{
std::string func_name ("p_voronoi" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "inline double " << func_name << " (const double2 q, uint seed) { "
<< " double2 p = p_voronoi(q, seed);"
<< " return " << co(n.input[1]) << "; }" << std::endl;
functions_.emplace_back(func_body.str());
return func_name + "("+co(n.input[0])+ ","+co(n.input[2])+")";
}
case node::angle: return "p_angle" + pl(n);
case node::chebyshev: return "p_chebyshev" + pl(n);
case node::checkerboard: return "p_checkerboard" + pl(n);
case node::distance: return "length" + pl(n);
case node::manhattan: return "p_manhattan" + pl(n);
case node::perlin: return "p_perlin" + pl(n);
case node::simplex: return "p_simplex" + pl(n);
case node::x: return co(n.input[0])+".x";
case node::y: return co(n.input[0])+".y";
case node::add: return "("+co(n.input[0])+"+"+co(n.input[1])+")";
case node::sub: return "("+co(n.input[0])+"-"+co(n.input[1])+")";
case node::mul: return "("+co(n.input[0])+"*"+co(n.input[1])+")";
case node::div: return "("+co(n.input[0])+"/"+co(n.input[1])+")";
case node::abs: return "fabs" + pl(n);
case node::blend: return "p_blend" + pl(n);
case node::cos: return "cospi" + pl(n);
case node::min: return "fmin" + pl(n);
case node::max: return "fmax" + pl(n);
case node::neg: return "-" + co(n.input[0]);
case node::pow:
{
if (n.input[1].is_const)
{
double exp (std::floor(n.input[1].aux_var));
if (std::abs(exp - n.input[1].aux_var) < 1e-9)
return "pown("+co(n.input[0])+","+std::to_string((int)exp)+")";
}
return "pow"+pl(n);
}
case node::range: return "p_range" + pl(n);
case node::round: return "round" + pl(n);
case node::saw: return "p_saw" + pl(n);
case node::sin: return "sinpi" + pl(n);
case node::sqrt: return "sqrt" + pl(n);
case node::tan: return "tanpi" + pl(n);
case node::band: return co(n.input[0])+"&&"+co(n.input[1]);
case node::bor: return co(n.input[0])+"||"+co(n.input[1]);
case node::bxor: return co(n.input[0])+"^^"+co(n.input[1]);
case node::bnot: return "!"+co(n.input[0]);
case node::is_equal: return co(n.input[0])+"=="+co(n.input[1]);
case node::is_greaterthan: return co(n.input[0])+">"+co(n.input[1]);
case node::is_gte: return co(n.input[0])+">="+co(n.input[1]);
case node::is_lessthan: return co(n.input[0])+"<"+co(n.input[1]);
case node::is_lte: return co(n.input[0])+"<="+co(n.input[1]);
case node::is_in_circle: return "p_is_in_circle" + pl(n);
case node::is_in_rectangle: return "p_is_in_rectangle" + pl(n);
case node::then_else:
return "("+co(n.input[0])+")?("+co(n.input[1])+"):("+co(n.input[2])+")";
case node::fractal:
{
assert(n.input.size() == 5);
if (!n.input[2].is_const)
throw std::runtime_error("fractal octave count must be a constexpr");
int octaves (std::min<int>(n.input[2].aux_var, OPENCL_OCTAVES_LIMIT));
std::string func_name ("p_fractal_" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "double " << func_name << " (double2 p, const double lac, const double per) {"
<< "double result = 0.0; double div = 0.0; double step = 1.0;"
<< "for(int i = 0; i < " << octaves << "; ++i)"
<< "{"
<< " result += " << co(n.input[1]) << " * step;"
<< " div += step;"
<< " step *= lac;"
<< " p *= per;"
<< " p.x += 12345.0;"
<< "}"
<< "return result / div;"
<< "}";
functions_.emplace_back(func_body.str());
return func_name + "("
+ co(n.input[0]) + "," + co(n.input[3]) + ","
+ co(n.input[4]) + ")";
}
case node::lambda_:
{
assert(n.input.size() == 2);
std::string func_name ("p_lambda_" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "double " << func_name << " (double2 p) {"
<< "return " << co(n.input[1]) << ";}" << std::endl;
functions_.emplace_back(func_body.str());
return func_name +"("+ co(n.input[0])+")";
}
case node::external_:
throw std::runtime_error("OpenCL @external not implemented yet");
case node::curve_linear:
throw std::runtime_error("OpenCL curve_linear not implemented yet");
case node::curve_spline:
throw std::runtime_error("OpenCL curve_spline not implemented yet");
case node::png_lookup:
throw std::runtime_error("OpenCL png_lookup not implemented yet");
default:
throw std::runtime_error("function not implemented in OpenCL yet");
}
return std::string();
}
}} // namespace hexa::noise
<commit_msg>Fixed bug in OpenCL 'shift'<commit_after>//---------------------------------------------------------------------------
// hexanoise/generator_opencl.cpp
//
// Copyright 2014, nocte@hippie.nu Released under the MIT License.
//---------------------------------------------------------------------------
#include "generator_opencl.hpp"
#include <iostream>
#include <cmath>
#include <fstream>
#include <stdexcept>
#include "node.hpp"
#ifndef OPENCL_OCTAVES_LIMIT
# define OPENCL_OCTAVES_LIMIT 16
#endif
namespace hexa {
namespace noise {
generator_opencl::generator_opencl (const generator_context& ctx,
cl::Context& opencl_context,
cl::Device& opencl_device,
const node& n,
const std::string& opencl_file)
: generator_i(ctx)
, count_(1)
, context_(opencl_context)
, device_(opencl_device)
, queue_ (opencl_context, opencl_device)
{
std::string body (co(n));
std::ifstream file (opencl_file.c_str(), std::ios::binary);
if (!file)
throw std::runtime_error("cannot open OpenCL file " + opencl_file);
file.seekg(0, std::ios::end);
main_.resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read(&main_[0], main_.size());
file.close();
main_ += "\n";
for (auto& p : functions_)
{
main_ += p;
main_ += "\n\n";
}
main_ += "\n" \
"__kernel void noisemain(\n" \
" __global double* output, const double2 start, const double2 step)\n" \
"{\n"\
" int2 coord = (int2)(get_global_id(0), get_global_id(1));\n"\
" int sizex = get_global_size(0);\n"\
" double2 p = mad(step, (double2)(coord.x, coord.y), start);\n" \
" output[coord.y * sizex + coord.x] = ";
main_ += body;
main_ += ";\n}\n";
main_ += "\n" \
"__kernel void noisemain_int16(\n" \
" __global int16* output, const double2 start, const double2 step)\n" \
"{\n"\
" int2 coord = (int2)(get_global_id(0), get_global_id(1));\n"\
" int sizex = get_global_size(0);\n"\
" double2 p = mad(step, (double2)(coord.x, coord.y), start);\n" \
" output[coord.y * sizex + coord.x] = (int16)(";
main_ += body;
main_ += ");\n}\n";
std::vector<cl::Device> device_vec;
device_vec.emplace_back(opencl_device);
cl::Program::Sources sources (1, { main_.c_str(), main_.size() });
program_ = cl::Program(opencl_context, sources);
try
{
program_.build(device_vec, "-cl-strict-aliasing -cl-mad-enable -cl-unsafe-math-optimizations -cl-fast-relaxed-math");
}
catch (cl::Error&)
{
std::cerr << program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(opencl_device) << std::endl;
throw;
}
kernel_ = cl::Kernel(program_, "noisemain");
kernel_int16_ = cl::Kernel(program_, "noisemain_int16");
}
std::vector<double>
generator_opencl::run (const glm::dvec2& corner,
const glm::dvec2& step,
const glm::ivec2& count)
{
unsigned int width (count.x), height (count.y);
unsigned int elements (width * height);
std::vector<double> result (elements);
cl::Buffer output (context_, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR,
elements * sizeof(double),
&result[0]);
kernel_.setArg(0, output);
kernel_.setArg(1, sizeof(corner), (void*)&corner);
kernel_.setArg(2, sizeof(step), (void*)&step);
queue_.enqueueNDRangeKernel(kernel_, cl::NullRange, {width, height},
cl::NullRange);
auto memobj (queue_.enqueueMapBuffer(output, true, CL_MAP_WRITE, 0,
elements * sizeof(double)));
queue_.enqueueUnmapMemObject(output, memobj);
return result;
}
std::vector<int16_t>
generator_opencl::run_int16 (const glm::dvec2& corner,
const glm::dvec2& step,
const glm::ivec2& count)
{
unsigned int width (count.x), height (count.y);
unsigned int elements (width * height);
std::vector<int16_t> result (elements);
cl::Buffer output (context_, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR,
elements * sizeof(int16_t),
&result[0]);
kernel_int16_.setArg(0, output);
kernel_int16_.setArg(1, sizeof(corner), (void*)&corner);
kernel_int16_.setArg(2, sizeof(step), (void*)&step);
queue_.enqueueNDRangeKernel(kernel_int16_, cl::NullRange, {width, height},
cl::NullRange);
auto memobj (queue_.enqueueMapBuffer(output, true, CL_MAP_WRITE, 0,
elements * sizeof(int16_t)));
queue_.enqueueUnmapMemObject(output, memobj);
return result;
}
std::string generator_opencl::pl (const node& n)
{
std::string result ("(");
for (auto i (n.input.begin()); i != n.input.end(); )
{
result += co(*i);
++i;
if (i != n.input.end())
result.push_back(',');
}
result += ')';
return result;
}
std::string generator_opencl::co (const node& n)
{
switch (n.type)
{
case node::entry_point: return "p";
case node::const_var: return std::to_string(n.aux_var);
case node::const_bool: return std::to_string(n.aux_bool);
case node::const_str: throw std::runtime_error("string encountered");
case node::rotate: return "p_rotate" + pl(n);
case node::scale: return "("+co(n.input[0])+"/"+co(n.input[1])+")";
case node::shift: return "("+co(n.input[0])+"+(double2)("+co(n.input[1])+","+co(n.input[2])+"))";
case node::swap: return "p_swap" + pl(n);
case node::map:
{
std::string func_name ("p_map" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "inline double2 " << func_name << " (const double2 p) { return (double2)("
<< co(n.input[1]) << ", "
<< co(n.input[2]) << "); }" << std::endl;
functions_.emplace_back(func_body.str());
return func_name + "("+ co(n.input[0]) + ")";
}
case node::turbulence:
{
std::string func_name ("p_map" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "inline double2 " << func_name << " (const double2 p) { return (double2)("
<< "p.x+(" << co(n.input[1]) << "), "
<< "p.y+(" << co(n.input[2]) << ")); }" << std::endl;
functions_.emplace_back(func_body.str());
return func_name + "("+ co(n.input[0]) + ")";
}
case node::worley:
{
std::string func_name ("p_worley" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "inline double " << func_name << " (const double2 q, uint seed) { "
<< " double2 p = p_worley(q, seed);"
<< " return " << co(n.input[1]) << "; }" << std::endl;
functions_.emplace_back(func_body.str());
return func_name + "("+co(n.input[0])+ ","+co(n.input[2])+")";
}
case node::voronoi:
{
std::string func_name ("p_voronoi" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "inline double " << func_name << " (const double2 q, uint seed) { "
<< " double2 p = p_voronoi(q, seed);"
<< " return " << co(n.input[1]) << "; }" << std::endl;
functions_.emplace_back(func_body.str());
return func_name + "("+co(n.input[0])+ ","+co(n.input[2])+")";
}
case node::angle: return "p_angle" + pl(n);
case node::chebyshev: return "p_chebyshev" + pl(n);
case node::checkerboard: return "p_checkerboard" + pl(n);
case node::distance: return "length" + pl(n);
case node::manhattan: return "p_manhattan" + pl(n);
case node::perlin: return "p_perlin" + pl(n);
case node::simplex: return "p_simplex" + pl(n);
case node::x: return co(n.input[0])+".x";
case node::y: return co(n.input[0])+".y";
case node::add: return "("+co(n.input[0])+"+"+co(n.input[1])+")";
case node::sub: return "("+co(n.input[0])+"-"+co(n.input[1])+")";
case node::mul: return "("+co(n.input[0])+"*"+co(n.input[1])+")";
case node::div: return "("+co(n.input[0])+"/"+co(n.input[1])+")";
case node::abs: return "fabs" + pl(n);
case node::blend: return "p_blend" + pl(n);
case node::cos: return "cospi" + pl(n);
case node::min: return "fmin" + pl(n);
case node::max: return "fmax" + pl(n);
case node::neg: return "-" + co(n.input[0]);
case node::pow:
{
if (n.input[1].is_const)
{
double exp (std::floor(n.input[1].aux_var));
if (std::abs(exp - n.input[1].aux_var) < 1e-9)
return "pown("+co(n.input[0])+","+std::to_string((int)exp)+")";
}
return "pow"+pl(n);
}
case node::range: return "p_range" + pl(n);
case node::round: return "round" + pl(n);
case node::saw: return "p_saw" + pl(n);
case node::sin: return "sinpi" + pl(n);
case node::sqrt: return "sqrt" + pl(n);
case node::tan: return "tanpi" + pl(n);
case node::band: return co(n.input[0])+"&&"+co(n.input[1]);
case node::bor: return co(n.input[0])+"||"+co(n.input[1]);
case node::bxor: return co(n.input[0])+"^^"+co(n.input[1]);
case node::bnot: return "!"+co(n.input[0]);
case node::is_equal: return co(n.input[0])+"=="+co(n.input[1]);
case node::is_greaterthan: return co(n.input[0])+">"+co(n.input[1]);
case node::is_gte: return co(n.input[0])+">="+co(n.input[1]);
case node::is_lessthan: return co(n.input[0])+"<"+co(n.input[1]);
case node::is_lte: return co(n.input[0])+"<="+co(n.input[1]);
case node::is_in_circle: return "p_is_in_circle" + pl(n);
case node::is_in_rectangle: return "p_is_in_rectangle" + pl(n);
case node::then_else:
return "("+co(n.input[0])+")?("+co(n.input[1])+"):("+co(n.input[2])+")";
case node::fractal:
{
assert(n.input.size() == 5);
if (!n.input[2].is_const)
throw std::runtime_error("fractal octave count must be a constexpr");
int octaves (std::min<int>(n.input[2].aux_var, OPENCL_OCTAVES_LIMIT));
std::string func_name ("p_fractal_" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "double " << func_name << " (double2 p, const double lac, const double per) {"
<< "double result = 0.0; double div = 0.0; double step = 1.0;"
<< "for(int i = 0; i < " << octaves << "; ++i)"
<< "{"
<< " result += " << co(n.input[1]) << " * step;"
<< " div += step;"
<< " step *= lac;"
<< " p *= per;"
<< " p.x += 12345.0;"
<< "}"
<< "return result / div;"
<< "}";
functions_.emplace_back(func_body.str());
return func_name + "("
+ co(n.input[0]) + "," + co(n.input[3]) + ","
+ co(n.input[4]) + ")";
}
case node::lambda_:
{
assert(n.input.size() == 2);
std::string func_name ("p_lambda_" + std::to_string(count_++));
std::stringstream func_body;
func_body
<< "double " << func_name << " (double2 p) {"
<< "return " << co(n.input[1]) << ";}" << std::endl;
functions_.emplace_back(func_body.str());
return func_name +"("+ co(n.input[0])+")";
}
case node::external_:
throw std::runtime_error("OpenCL @external not implemented yet");
case node::curve_linear:
throw std::runtime_error("OpenCL curve_linear not implemented yet");
case node::curve_spline:
throw std::runtime_error("OpenCL curve_spline not implemented yet");
case node::png_lookup:
throw std::runtime_error("OpenCL png_lookup not implemented yet");
default:
throw std::runtime_error("function not implemented in OpenCL yet");
}
return std::string();
}
}} // namespace hexa::noise
<|endoftext|>
|
<commit_before>/**
* @file cache.cpp
*
*/
#include "cache.h"
#include "info.h"
#include "logger.h"
#include "plugin_factory.h"
#include <boost/lexical_cast.hpp>
#include <time.h>
using namespace std;
using namespace himan::plugin;
typedef lock_guard<mutex> Lock;
std::mutex itsCheckMutex;
cache::cache() { itsLogger = logger("cache"); }
string cache::UniqueName(const info& info)
{
string producer_id = boost::lexical_cast<string>(info.Producer().Id());
string forecast_time = info.Time().OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
string valid_time = info.Time().ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
string param = info.Param().Name();
string level_value = boost::lexical_cast<string>(info.Level().Value());
string level = HPLevelTypeToString.at(info.Level().Type());
string forecast_type = boost::lexical_cast<string>(info.ForecastType().Type());
string forecast_type_value = boost::lexical_cast<string>(info.ForecastType().Value());
return producer_id + '_' + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value + '_' +
forecast_type + '_' + forecast_type_value;
}
string cache::UniqueNameFromOptions(search_options& options)
{
ASSERT(options.configuration->DatabaseType() == kNoDatabase || options.prod.Id() != kHPMissingInt);
string producer_id = boost::lexical_cast<string>(options.prod.Id());
string forecast_time = options.time.OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
string valid_time = options.time.ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
string param = options.param.Name();
string level_value = boost::lexical_cast<string>((options.level).Value());
string level = HPLevelTypeToString.at(options.level.Type());
string forecast_type = boost::lexical_cast<string>(options.ftype.Type());
string forecast_type_value = boost::lexical_cast<string>(options.ftype.Value());
return producer_id + "_" + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value + '_' +
forecast_type + '_' + forecast_type_value;
}
void cache::Insert(info& anInfo, bool pin) { SplitToPool(anInfo, pin); }
void cache::SplitToPool(info& anInfo, bool pin)
{
auto localInfo = anInfo;
// Cached data is never replaced by another data that has
// the same uniqueName
string uniqueName = UniqueName(localInfo);
{
Lock lock(itsCheckMutex);
if (cache_pool::Instance()->Find(uniqueName))
{
// New item, but only one thread should insert it (prevent race condition)
itsLogger.Trace("Data with key " + uniqueName + " already exists at cache");
// Update timestamp of this cache item
cache_pool::Instance()->UpdateTime(uniqueName);
return;
}
}
#ifdef HAVE_CUDA
if (localInfo.Grid()->IsPackedData())
{
itsLogger.Trace("Removing packed data from cached info");
localInfo.Grid()->PackedData().Clear();
}
#endif
ASSERT(!localInfo.Grid()->IsPackedData());
vector<param> params;
vector<level> levels;
vector<forecast_time> times;
vector<forecast_type> ftype;
params.push_back(localInfo.Param());
levels.push_back(localInfo.Level());
times.push_back(localInfo.Time());
ftype.push_back(localInfo.ForecastType());
auto newInfo = make_shared<info>(localInfo);
newInfo->Params(params);
newInfo->Levels(levels);
newInfo->Times(times);
newInfo->ForecastTypes(ftype);
newInfo->Create(localInfo.Grid());
ASSERT(uniqueName == UniqueName(*newInfo));
{
Lock lock(itsCheckMutex);
cache_pool::Instance()->Insert(uniqueName, newInfo, pin);
}
}
vector<shared_ptr<himan::info>> cache::GetInfo(search_options& options)
{
string uniqueName = UniqueNameFromOptions(options);
vector<shared_ptr<himan::info>> info;
if (cache_pool::Instance()->Find(uniqueName))
{
info.push_back(cache_pool::Instance()->GetInfo(uniqueName));
itsLogger.Trace("Found matching data for " + uniqueName);
}
return info;
}
void cache::Clean() { cache_pool::Instance()->Clean(); }
size_t cache::Size() const { return cache_pool::Instance()->Size(); }
cache_pool* cache_pool::itsInstance = NULL;
cache_pool::cache_pool() : itsCacheLimit(-1) { itsLogger = logger("cache_pool"); }
cache_pool* cache_pool::Instance()
{
if (!itsInstance)
{
itsInstance = new cache_pool();
}
return itsInstance;
}
void cache_pool::CacheLimit(int theCacheLimit) { itsCacheLimit = theCacheLimit; }
bool cache_pool::Find(const string& uniqueName) { return itsCache.count(uniqueName) > 0; }
void cache_pool::Insert(const string& uniqueName, shared_ptr<himan::info> anInfo, bool pin)
{
Lock lock(itsInsertMutex);
cache_item item;
item.info = anInfo;
item.access_time = time(nullptr);
item.pinned = pin;
itsCache.insert(pair<string, cache_item>(uniqueName, item));
itsLogger.Trace("Data added to cache with name: " + uniqueName + ", pinned: " + boost::lexical_cast<string>(pin));
if (itsCacheLimit > -1 && itsCache.size() > static_cast<size_t>(itsCacheLimit))
{
Clean();
}
}
void cache_pool::UpdateTime(const std::string& uniqueName) { itsCache[uniqueName].access_time = time(nullptr); }
void cache_pool::Clean()
{
Lock lock(itsDeleteMutex);
ASSERT(itsCacheLimit > 0);
if (itsCache.size() <= static_cast<size_t>(itsCacheLimit))
{
return;
}
string oldestName;
time_t oldestTime = INT_MAX;
for (const auto& kv : itsCache)
{
if (kv.second.access_time < oldestTime && !kv.second.pinned)
{
oldestName = kv.first;
oldestTime = kv.second.access_time;
}
}
ASSERT(!oldestName.empty());
itsCache.erase(oldestName);
itsLogger.Trace("Data cleared from cache: " + oldestName +
" with time: " + boost::lexical_cast<string>(oldestTime));
itsLogger.Trace("Cache size: " + boost::lexical_cast<string>(itsCache.size()));
}
shared_ptr<himan::info> cache_pool::GetInfo(const string& uniqueName)
{
Lock lock(itsGetMutex);
return make_shared<info>(*itsCache[uniqueName].info);
}
size_t cache_pool::Size() const { return itsCache.size(); }
<commit_msg>Remove erroneous comment<commit_after>/**
* @file cache.cpp
*
*/
#include "cache.h"
#include "info.h"
#include "logger.h"
#include "plugin_factory.h"
#include <boost/lexical_cast.hpp>
#include <time.h>
using namespace std;
using namespace himan::plugin;
typedef lock_guard<mutex> Lock;
std::mutex itsCheckMutex;
cache::cache() { itsLogger = logger("cache"); }
string cache::UniqueName(const info& info)
{
string producer_id = boost::lexical_cast<string>(info.Producer().Id());
string forecast_time = info.Time().OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
string valid_time = info.Time().ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
string param = info.Param().Name();
string level_value = boost::lexical_cast<string>(info.Level().Value());
string level = HPLevelTypeToString.at(info.Level().Type());
string forecast_type = boost::lexical_cast<string>(info.ForecastType().Type());
string forecast_type_value = boost::lexical_cast<string>(info.ForecastType().Value());
return producer_id + '_' + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value + '_' +
forecast_type + '_' + forecast_type_value;
}
string cache::UniqueNameFromOptions(search_options& options)
{
ASSERT(options.configuration->DatabaseType() == kNoDatabase || options.prod.Id() != kHPMissingInt);
string producer_id = boost::lexical_cast<string>(options.prod.Id());
string forecast_time = options.time.OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
string valid_time = options.time.ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
string param = options.param.Name();
string level_value = boost::lexical_cast<string>((options.level).Value());
string level = HPLevelTypeToString.at(options.level.Type());
string forecast_type = boost::lexical_cast<string>(options.ftype.Type());
string forecast_type_value = boost::lexical_cast<string>(options.ftype.Value());
return producer_id + "_" + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value + '_' +
forecast_type + '_' + forecast_type_value;
}
void cache::Insert(info& anInfo, bool pin) { SplitToPool(anInfo, pin); }
void cache::SplitToPool(info& anInfo, bool pin)
{
auto localInfo = anInfo;
// Cached data is never replaced by another data that has
// the same uniqueName
string uniqueName = UniqueName(localInfo);
{
Lock lock(itsCheckMutex);
if (cache_pool::Instance()->Find(uniqueName))
{
itsLogger.Trace("Data with key " + uniqueName + " already exists at cache");
// Update timestamp of this cache item
cache_pool::Instance()->UpdateTime(uniqueName);
return;
}
}
#ifdef HAVE_CUDA
if (localInfo.Grid()->IsPackedData())
{
itsLogger.Trace("Removing packed data from cached info");
localInfo.Grid()->PackedData().Clear();
}
#endif
ASSERT(!localInfo.Grid()->IsPackedData());
vector<param> params;
vector<level> levels;
vector<forecast_time> times;
vector<forecast_type> ftype;
params.push_back(localInfo.Param());
levels.push_back(localInfo.Level());
times.push_back(localInfo.Time());
ftype.push_back(localInfo.ForecastType());
auto newInfo = make_shared<info>(localInfo);
newInfo->Params(params);
newInfo->Levels(levels);
newInfo->Times(times);
newInfo->ForecastTypes(ftype);
newInfo->Create(localInfo.Grid());
ASSERT(uniqueName == UniqueName(*newInfo));
{
Lock lock(itsCheckMutex);
cache_pool::Instance()->Insert(uniqueName, newInfo, pin);
}
}
vector<shared_ptr<himan::info>> cache::GetInfo(search_options& options)
{
string uniqueName = UniqueNameFromOptions(options);
vector<shared_ptr<himan::info>> info;
if (cache_pool::Instance()->Find(uniqueName))
{
info.push_back(cache_pool::Instance()->GetInfo(uniqueName));
itsLogger.Trace("Found matching data for " + uniqueName);
}
return info;
}
void cache::Clean() { cache_pool::Instance()->Clean(); }
size_t cache::Size() const { return cache_pool::Instance()->Size(); }
cache_pool* cache_pool::itsInstance = NULL;
cache_pool::cache_pool() : itsCacheLimit(-1) { itsLogger = logger("cache_pool"); }
cache_pool* cache_pool::Instance()
{
if (!itsInstance)
{
itsInstance = new cache_pool();
}
return itsInstance;
}
void cache_pool::CacheLimit(int theCacheLimit) { itsCacheLimit = theCacheLimit; }
bool cache_pool::Find(const string& uniqueName) { return itsCache.count(uniqueName) > 0; }
void cache_pool::Insert(const string& uniqueName, shared_ptr<himan::info> anInfo, bool pin)
{
Lock lock(itsInsertMutex);
cache_item item;
item.info = anInfo;
item.access_time = time(nullptr);
item.pinned = pin;
itsCache.insert(pair<string, cache_item>(uniqueName, item));
itsLogger.Trace("Data added to cache with name: " + uniqueName + ", pinned: " + boost::lexical_cast<string>(pin));
if (itsCacheLimit > -1 && itsCache.size() > static_cast<size_t>(itsCacheLimit))
{
Clean();
}
}
void cache_pool::UpdateTime(const std::string& uniqueName) { itsCache[uniqueName].access_time = time(nullptr); }
void cache_pool::Clean()
{
Lock lock(itsDeleteMutex);
ASSERT(itsCacheLimit > 0);
if (itsCache.size() <= static_cast<size_t>(itsCacheLimit))
{
return;
}
string oldestName;
time_t oldestTime = INT_MAX;
for (const auto& kv : itsCache)
{
if (kv.second.access_time < oldestTime && !kv.second.pinned)
{
oldestName = kv.first;
oldestTime = kv.second.access_time;
}
}
ASSERT(!oldestName.empty());
itsCache.erase(oldestName);
itsLogger.Trace("Data cleared from cache: " + oldestName +
" with time: " + boost::lexical_cast<string>(oldestTime));
itsLogger.Trace("Cache size: " + boost::lexical_cast<string>(itsCache.size()));
}
shared_ptr<himan::info> cache_pool::GetInfo(const string& uniqueName)
{
Lock lock(itsGetMutex);
return make_shared<info>(*itsCache[uniqueName].info);
}
size_t cache_pool::Size() const { return itsCache.size(); }
<|endoftext|>
|
<commit_before>//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
#include <stdio.h>
#include "ac/common.h"
#include "ac/display.h"
#include "ac/draw.h"
#include "ac/game.h"
#include "ac/gamesetupstruct.h"
#include "ac/gamestate.h"
#include "ac/global_drawingsurface.h"
#include "ac/global_translation.h"
#include "ac/roomstruct.h"
#include "ac/string.h"
#include "debug/debug_log.h"
#include "font/fonts.h"
#include "gui/guidefines.h"
#include "ac/spritecache.h"
#include "gfx/gfx_util.h"
using AGS::Common::Bitmap;
namespace BitmapHelper = AGS::Common::BitmapHelper;
extern Bitmap *raw_saved_screen;
extern roomstruct thisroom;
extern GameState play;
extern char lines[MAXLINE][200];
extern int numlines;
extern int spritewidth[MAX_SPRITES],spriteheight[MAX_SPRITES];
extern SpriteCache spriteset;
extern GameSetupStruct game;
extern int current_screen_resolution_multiplier;
// Raw screen writing routines - similar to old CapturedStuff
//#define RAW_START() Bitmap *oldabuf=RAW_GRAPHICS()->GetBitmap(); RAW_GRAPHICS()->GetBitmap()=thisroom.ebscene[play.bg_frame]; play.raw_modified[play.bg_frame] = 1
//#define RAW_END() RAW_GRAPHICS()->GetBitmap() = oldabuf
#define RAW_START() raw_drawing_surface = thisroom.ebscene[play.bg_frame]; play.raw_modified[play.bg_frame] = 1
#define RAW_END()
#define RAW_SURFACE() (raw_drawing_surface)
Bitmap *raw_drawing_surface;
// RawSaveScreen: copy the current screen to a backup bitmap
void RawSaveScreen () {
if (raw_saved_screen != NULL)
delete raw_saved_screen;
Bitmap *source = thisroom.ebscene[play.bg_frame];
raw_saved_screen = BitmapHelper::CreateBitmapCopy(source);
}
// RawRestoreScreen: copy backup bitmap back to screen; we
// deliberately don't free the Bitmap *cos they can multiple restore
// and it gets freed on room exit anyway
void RawRestoreScreen() {
if (raw_saved_screen == NULL) {
debug_log("RawRestoreScreen: unable to restore, since the screen hasn't been saved previously.");
return;
}
Bitmap *deston = thisroom.ebscene[play.bg_frame];
deston->Blit(raw_saved_screen, 0, 0, 0, 0, deston->GetWidth(), deston->GetHeight());
invalidate_screen();
mark_current_background_dirty();
}
// Restores the backup bitmap, but tints it to the specified level
void RawRestoreScreenTinted(int red, int green, int blue, int opacity) {
if (raw_saved_screen == NULL) {
debug_log("RawRestoreScreenTinted: unable to restore, since the screen hasn't been saved previously.");
return;
}
if ((red < 0) || (green < 0) || (blue < 0) ||
(red > 255) || (green > 255) || (blue > 255) ||
(opacity < 1) || (opacity > 100))
quit("!RawRestoreScreenTinted: invalid parameter. R,G,B must be 0-255, opacity 1-100");
DEBUG_CONSOLE("RawRestoreTinted RGB(%d,%d,%d) %d%%", red, green, blue, opacity);
Bitmap *deston = thisroom.ebscene[play.bg_frame];
tint_image(deston, raw_saved_screen, red, green, blue, opacity);
invalidate_screen();
mark_current_background_dirty();
}
void RawDrawFrameTransparent (int frame, int translev) {
if ((frame < 0) || (frame >= thisroom.num_bscenes) ||
(translev < 0) || (translev > 99))
quit("!RawDrawFrameTransparent: invalid parameter (transparency must be 0-99, frame a valid BG frame)");
if (thisroom.ebscene[frame]->GetColorDepth() <= 8)
quit("!RawDrawFrameTransparent: 256-colour backgrounds not supported");
if (frame == play.bg_frame)
quit("!RawDrawFrameTransparent: cannot draw current background onto itself");
if (translev == 0) {
// just draw it over the top, no transparency
thisroom.ebscene[play.bg_frame]->Blit(thisroom.ebscene[frame], 0, 0, 0, 0, thisroom.ebscene[frame]->GetWidth(), thisroom.ebscene[frame]->GetHeight());
play.raw_modified[play.bg_frame] = 1;
return;
}
// Draw it transparently
RAW_START();
AGS::Engine::GfxUtil::DrawSpriteWithTransparency (RAW_SURFACE(), thisroom.ebscene[frame], 0, 0,
AGS::Engine::GfxUtil::Trans100ToAlpha255(translev));
invalidate_screen();
mark_current_background_dirty();
RAW_END();
}
void RawClear (int clr) {
play.raw_modified[play.bg_frame] = 1;
clr = RAW_SURFACE()->GetCompatibleColor(clr);
thisroom.ebscene[play.bg_frame]->Clear (clr);
invalidate_screen();
mark_current_background_dirty();
}
void RawSetColor (int clr) {
//push_screen();
//SetVirtualScreen(thisroom.ebscene[play.bg_frame]);
// set the colour at the appropriate depth for the background
play.raw_color = GetVirtualScreen()->GetCompatibleColor(clr);
//pop_screen();
}
void RawSetColorRGB(int red, int grn, int blu) {
if ((red < 0) || (red > 255) || (grn < 0) || (grn > 255) ||
(blu < 0) || (blu > 255))
quit("!RawSetColorRGB: colour values must be 0-255");
play.raw_color = makecol_depth(thisroom.ebscene[play.bg_frame]->GetColorDepth(), red, grn, blu);
}
void RawPrint (int xx, int yy, const char*texx, ...) {
char displbuf[STD_BUFFER_SIZE];
va_list ap;
va_start(ap,texx);
vsprintf(displbuf, get_translation(texx), ap);
va_end(ap);
RAW_START();
// don't use wtextcolor because it will do a 16->32 conversion
color_t text_color = play.raw_color;
if ((RAW_SURFACE()->GetColorDepth() <= 8) && (play.raw_color > 255)) {
text_color = RAW_SURFACE()->GetCompatibleColor(1);
debug_log ("RawPrint: Attempted to use hi-color on 256-col background");
}
multiply_up_coordinates(&xx, &yy);
wouttext_outline(RAW_SURFACE(), xx, yy, play.normal_font, text_color, displbuf);
// we must invalidate the entire screen because these are room
// co-ordinates, not screen co-ords which it works with
invalidate_screen();
mark_current_background_dirty();
RAW_END();
}
void RawPrintMessageWrapped (int xx, int yy, int wid, int font, int msgm) {
char displbuf[3000];
int texthit = wgetfontheight(font);
multiply_up_coordinates(&xx, &yy);
wid = multiply_up_coordinate(wid);
get_message_text (msgm, displbuf);
// it's probably too late but check anyway
if (strlen(displbuf) > 2899)
quit("!RawPrintMessageWrapped: message too long");
break_up_text_into_lines (wid, font, displbuf);
RAW_START();
color_t text_color = play.raw_color;
for (int i = 0; i < numlines; i++)
wouttext_outline(RAW_SURFACE(), xx, yy + texthit*i, font, text_color, lines[i]);
invalidate_screen();
mark_current_background_dirty();
RAW_END();
}
void RawDrawImageCore(int xx, int yy, int slot, int transparency) {
if ((slot < 0) || (slot >= MAX_SPRITES) || (spriteset[slot] == NULL))
quit("!RawDrawImage: invalid sprite slot number specified");
RAW_START();
if (spriteset[slot]->GetColorDepth() != RAW_SURFACE()->GetColorDepth()) {
debug_log("RawDrawImage: Sprite %d colour depth %d-bit not same as background depth %d-bit", slot, spriteset[slot]->GetColorDepth(), RAW_SURFACE()->GetColorDepth());
}
draw_sprite_slot_support_alpha(RAW_SURFACE(), false, xx, yy, slot,
AGS::Engine::GfxUtil::Trans100ToAlpha255(transparency));
invalidate_screen();
mark_current_background_dirty();
RAW_END();
}
void RawDrawImage(int xx, int yy, int slot) {
multiply_up_coordinates(&xx, &yy);
RawDrawImageCore(xx, yy, slot);
}
void RawDrawImageTrans(int xx, int yy, int slot, int transparency) {
multiply_up_coordinates(&xx, &yy);
RawDrawImageCore(xx, yy, slot, transparency);
}
void RawDrawImageOffset(int xx, int yy, int slot) {
if ((current_screen_resolution_multiplier == 1) && (game.default_resolution >= 3)) {
// running a 640x400 game at 320x200, adjust
xx /= 2;
yy /= 2;
}
else if ((current_screen_resolution_multiplier > 1) && (game.default_resolution <= 2)) {
// running a 320x200 game at 640x400, adjust
xx *= 2;
yy *= 2;
}
RawDrawImageCore(xx, yy, slot);
}
void RawDrawImageTransparent(int xx, int yy, int slot, int trans) {
if ((trans < 0) || (trans > 100))
quit("!RawDrawImageTransparent: invalid transparency setting");
int trans_mode = (trans * 255) / 100;
RawDrawImageTrans(xx, yy, slot, trans_mode);
update_polled_stuff_if_runtime(); // this operation can be slow so stop music skipping
}
void RawDrawImageResized(int xx, int yy, int gotSlot, int width, int height) {
if ((gotSlot < 0) || (gotSlot >= MAX_SPRITES) || (spriteset[gotSlot] == NULL))
quit("!RawDrawImageResized: invalid sprite slot number specified");
// very small, don't draw it
if ((width < 1) || (height < 1))
return;
multiply_up_coordinates(&xx, &yy);
multiply_up_coordinates(&width, &height);
// resize the sprite to the requested size
Bitmap *newPic = BitmapHelper::CreateBitmap(width, height, spriteset[gotSlot]->GetColorDepth());
newPic->StretchBlt(spriteset[gotSlot],
RectWH(0, 0, spritewidth[gotSlot], spriteheight[gotSlot]),
RectWH(0, 0, width, height));
RAW_START();
if (newPic->GetColorDepth() != RAW_SURFACE()->GetColorDepth())
quit("!RawDrawImageResized: image colour depth mismatch: the background image must have the same colour depth as the sprite being drawn");
AGS::Engine::GfxUtil::DrawSpriteWithTransparency(RAW_SURFACE(), newPic, xx, yy);
delete newPic;
invalidate_screen();
mark_current_background_dirty();
update_polled_stuff_if_runtime(); // this operation can be slow so stop music skipping
RAW_END();
}
void RawDrawLine (int fromx, int fromy, int tox, int toy) {
multiply_up_coordinates(&fromx, &fromy);
multiply_up_coordinates(&tox, &toy);
play.raw_modified[play.bg_frame] = 1;
int ii,jj;
// draw a line thick enough to look the same at all resolutions
Bitmap *bg_frame = thisroom.ebscene[play.bg_frame];
color_t draw_color = play.raw_color;
for (ii = 0; ii < get_fixed_pixel_size(1); ii++) {
for (jj = 0; jj < get_fixed_pixel_size(1); jj++)
bg_frame->DrawLine (Line(fromx+ii, fromy+jj, tox+ii, toy+jj), draw_color);
}
invalidate_screen();
mark_current_background_dirty();
}
void RawDrawCircle (int xx, int yy, int rad) {
multiply_up_coordinates(&xx, &yy);
rad = multiply_up_coordinate(rad);
play.raw_modified[play.bg_frame] = 1;
Bitmap *bg_frame = thisroom.ebscene[play.bg_frame];
bg_frame->FillCircle(Circle (xx, yy, rad), play.raw_color);
invalidate_screen();
mark_current_background_dirty();
}
void RawDrawRectangle(int x1, int y1, int x2, int y2) {
play.raw_modified[play.bg_frame] = 1;
multiply_up_coordinates(&x1, &y1);
multiply_up_coordinates_round_up(&x2, &y2);
Bitmap *bg_frame = thisroom.ebscene[play.bg_frame];
bg_frame->FillRect(Rect(x1,y1,x2,y2), play.raw_color);
invalidate_screen();
mark_current_background_dirty();
}
void RawDrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
play.raw_modified[play.bg_frame] = 1;
multiply_up_coordinates(&x1, &y1);
multiply_up_coordinates(&x2, &y2);
multiply_up_coordinates(&x3, &y3);
Bitmap *bg_frame = thisroom.ebscene[play.bg_frame];
bg_frame->DrawTriangle(Triangle (x1,y1,x2,y2,x3,y3), play.raw_color);
invalidate_screen();
mark_current_background_dirty();
}
<commit_msg>Engine: fixed crash in RawClearScreen()<commit_after>//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
#include <stdio.h>
#include "ac/common.h"
#include "ac/display.h"
#include "ac/draw.h"
#include "ac/game.h"
#include "ac/gamesetupstruct.h"
#include "ac/gamestate.h"
#include "ac/global_drawingsurface.h"
#include "ac/global_translation.h"
#include "ac/roomstruct.h"
#include "ac/string.h"
#include "debug/debug_log.h"
#include "font/fonts.h"
#include "gui/guidefines.h"
#include "ac/spritecache.h"
#include "gfx/gfx_util.h"
using AGS::Common::Bitmap;
namespace BitmapHelper = AGS::Common::BitmapHelper;
extern Bitmap *raw_saved_screen;
extern roomstruct thisroom;
extern GameState play;
extern char lines[MAXLINE][200];
extern int numlines;
extern int spritewidth[MAX_SPRITES],spriteheight[MAX_SPRITES];
extern SpriteCache spriteset;
extern GameSetupStruct game;
extern int current_screen_resolution_multiplier;
// Raw screen writing routines - similar to old CapturedStuff
//#define RAW_START() Bitmap *oldabuf=RAW_GRAPHICS()->GetBitmap(); RAW_GRAPHICS()->GetBitmap()=thisroom.ebscene[play.bg_frame]; play.raw_modified[play.bg_frame] = 1
//#define RAW_END() RAW_GRAPHICS()->GetBitmap() = oldabuf
#define RAW_START() raw_drawing_surface = thisroom.ebscene[play.bg_frame]; play.raw_modified[play.bg_frame] = 1
#define RAW_END()
#define RAW_SURFACE() (raw_drawing_surface)
Bitmap *raw_drawing_surface;
// RawSaveScreen: copy the current screen to a backup bitmap
void RawSaveScreen () {
if (raw_saved_screen != NULL)
delete raw_saved_screen;
Bitmap *source = thisroom.ebscene[play.bg_frame];
raw_saved_screen = BitmapHelper::CreateBitmapCopy(source);
}
// RawRestoreScreen: copy backup bitmap back to screen; we
// deliberately don't free the Bitmap *cos they can multiple restore
// and it gets freed on room exit anyway
void RawRestoreScreen() {
if (raw_saved_screen == NULL) {
debug_log("RawRestoreScreen: unable to restore, since the screen hasn't been saved previously.");
return;
}
Bitmap *deston = thisroom.ebscene[play.bg_frame];
deston->Blit(raw_saved_screen, 0, 0, 0, 0, deston->GetWidth(), deston->GetHeight());
invalidate_screen();
mark_current_background_dirty();
}
// Restores the backup bitmap, but tints it to the specified level
void RawRestoreScreenTinted(int red, int green, int blue, int opacity) {
if (raw_saved_screen == NULL) {
debug_log("RawRestoreScreenTinted: unable to restore, since the screen hasn't been saved previously.");
return;
}
if ((red < 0) || (green < 0) || (blue < 0) ||
(red > 255) || (green > 255) || (blue > 255) ||
(opacity < 1) || (opacity > 100))
quit("!RawRestoreScreenTinted: invalid parameter. R,G,B must be 0-255, opacity 1-100");
DEBUG_CONSOLE("RawRestoreTinted RGB(%d,%d,%d) %d%%", red, green, blue, opacity);
Bitmap *deston = thisroom.ebscene[play.bg_frame];
tint_image(deston, raw_saved_screen, red, green, blue, opacity);
invalidate_screen();
mark_current_background_dirty();
}
void RawDrawFrameTransparent (int frame, int translev) {
if ((frame < 0) || (frame >= thisroom.num_bscenes) ||
(translev < 0) || (translev > 99))
quit("!RawDrawFrameTransparent: invalid parameter (transparency must be 0-99, frame a valid BG frame)");
if (thisroom.ebscene[frame]->GetColorDepth() <= 8)
quit("!RawDrawFrameTransparent: 256-colour backgrounds not supported");
if (frame == play.bg_frame)
quit("!RawDrawFrameTransparent: cannot draw current background onto itself");
RAW_START();
if (translev == 0)
{
// just draw it over the top, no transparency
RAW_SURFACE()->Blit(thisroom.ebscene[frame], 0, 0, 0, 0, thisroom.ebscene[frame]->GetWidth(), thisroom.ebscene[frame]->GetHeight());
}
else
{
// Draw it transparently
AGS::Engine::GfxUtil::DrawSpriteWithTransparency (RAW_SURFACE(), thisroom.ebscene[frame], 0, 0,
AGS::Engine::GfxUtil::Trans100ToAlpha255(translev));
}
invalidate_screen();
mark_current_background_dirty();
RAW_END();
}
void RawClear (int clr) {
RAW_START();
clr = RAW_SURFACE()->GetCompatibleColor(clr);
RAW_SURFACE()->Clear (clr);
invalidate_screen();
mark_current_background_dirty();
}
void RawSetColor (int clr) {
//push_screen();
//SetVirtualScreen(thisroom.ebscene[play.bg_frame]);
// set the colour at the appropriate depth for the background
play.raw_color = GetVirtualScreen()->GetCompatibleColor(clr);
//pop_screen();
}
void RawSetColorRGB(int red, int grn, int blu) {
if ((red < 0) || (red > 255) || (grn < 0) || (grn > 255) ||
(blu < 0) || (blu > 255))
quit("!RawSetColorRGB: colour values must be 0-255");
play.raw_color = makecol_depth(thisroom.ebscene[play.bg_frame]->GetColorDepth(), red, grn, blu);
}
void RawPrint (int xx, int yy, const char*texx, ...) {
char displbuf[STD_BUFFER_SIZE];
va_list ap;
va_start(ap,texx);
vsprintf(displbuf, get_translation(texx), ap);
va_end(ap);
RAW_START();
// don't use wtextcolor because it will do a 16->32 conversion
color_t text_color = play.raw_color;
if ((RAW_SURFACE()->GetColorDepth() <= 8) && (play.raw_color > 255)) {
text_color = RAW_SURFACE()->GetCompatibleColor(1);
debug_log ("RawPrint: Attempted to use hi-color on 256-col background");
}
multiply_up_coordinates(&xx, &yy);
wouttext_outline(RAW_SURFACE(), xx, yy, play.normal_font, text_color, displbuf);
// we must invalidate the entire screen because these are room
// co-ordinates, not screen co-ords which it works with
invalidate_screen();
mark_current_background_dirty();
RAW_END();
}
void RawPrintMessageWrapped (int xx, int yy, int wid, int font, int msgm) {
char displbuf[3000];
int texthit = wgetfontheight(font);
multiply_up_coordinates(&xx, &yy);
wid = multiply_up_coordinate(wid);
get_message_text (msgm, displbuf);
// it's probably too late but check anyway
if (strlen(displbuf) > 2899)
quit("!RawPrintMessageWrapped: message too long");
break_up_text_into_lines (wid, font, displbuf);
RAW_START();
color_t text_color = play.raw_color;
for (int i = 0; i < numlines; i++)
wouttext_outline(RAW_SURFACE(), xx, yy + texthit*i, font, text_color, lines[i]);
invalidate_screen();
mark_current_background_dirty();
RAW_END();
}
void RawDrawImageCore(int xx, int yy, int slot, int transparency) {
if ((slot < 0) || (slot >= MAX_SPRITES) || (spriteset[slot] == NULL))
quit("!RawDrawImage: invalid sprite slot number specified");
RAW_START();
if (spriteset[slot]->GetColorDepth() != RAW_SURFACE()->GetColorDepth()) {
debug_log("RawDrawImage: Sprite %d colour depth %d-bit not same as background depth %d-bit", slot, spriteset[slot]->GetColorDepth(), RAW_SURFACE()->GetColorDepth());
}
draw_sprite_slot_support_alpha(RAW_SURFACE(), false, xx, yy, slot,
AGS::Engine::GfxUtil::Trans100ToAlpha255(transparency));
invalidate_screen();
mark_current_background_dirty();
RAW_END();
}
void RawDrawImage(int xx, int yy, int slot) {
multiply_up_coordinates(&xx, &yy);
RawDrawImageCore(xx, yy, slot);
}
void RawDrawImageTrans(int xx, int yy, int slot, int transparency) {
multiply_up_coordinates(&xx, &yy);
RawDrawImageCore(xx, yy, slot, transparency);
}
void RawDrawImageOffset(int xx, int yy, int slot) {
if ((current_screen_resolution_multiplier == 1) && (game.default_resolution >= 3)) {
// running a 640x400 game at 320x200, adjust
xx /= 2;
yy /= 2;
}
else if ((current_screen_resolution_multiplier > 1) && (game.default_resolution <= 2)) {
// running a 320x200 game at 640x400, adjust
xx *= 2;
yy *= 2;
}
RawDrawImageCore(xx, yy, slot);
}
void RawDrawImageTransparent(int xx, int yy, int slot, int trans) {
if ((trans < 0) || (trans > 100))
quit("!RawDrawImageTransparent: invalid transparency setting");
int trans_mode = (trans * 255) / 100;
RawDrawImageTrans(xx, yy, slot, trans_mode);
update_polled_stuff_if_runtime(); // this operation can be slow so stop music skipping
}
void RawDrawImageResized(int xx, int yy, int gotSlot, int width, int height) {
if ((gotSlot < 0) || (gotSlot >= MAX_SPRITES) || (spriteset[gotSlot] == NULL))
quit("!RawDrawImageResized: invalid sprite slot number specified");
// very small, don't draw it
if ((width < 1) || (height < 1))
return;
multiply_up_coordinates(&xx, &yy);
multiply_up_coordinates(&width, &height);
// resize the sprite to the requested size
Bitmap *newPic = BitmapHelper::CreateBitmap(width, height, spriteset[gotSlot]->GetColorDepth());
newPic->StretchBlt(spriteset[gotSlot],
RectWH(0, 0, spritewidth[gotSlot], spriteheight[gotSlot]),
RectWH(0, 0, width, height));
RAW_START();
if (newPic->GetColorDepth() != RAW_SURFACE()->GetColorDepth())
quit("!RawDrawImageResized: image colour depth mismatch: the background image must have the same colour depth as the sprite being drawn");
AGS::Engine::GfxUtil::DrawSpriteWithTransparency(RAW_SURFACE(), newPic, xx, yy);
delete newPic;
invalidate_screen();
mark_current_background_dirty();
update_polled_stuff_if_runtime(); // this operation can be slow so stop music skipping
RAW_END();
}
void RawDrawLine (int fromx, int fromy, int tox, int toy) {
multiply_up_coordinates(&fromx, &fromy);
multiply_up_coordinates(&tox, &toy);
play.raw_modified[play.bg_frame] = 1;
int ii,jj;
// draw a line thick enough to look the same at all resolutions
Bitmap *bg_frame = thisroom.ebscene[play.bg_frame];
color_t draw_color = play.raw_color;
for (ii = 0; ii < get_fixed_pixel_size(1); ii++) {
for (jj = 0; jj < get_fixed_pixel_size(1); jj++)
bg_frame->DrawLine (Line(fromx+ii, fromy+jj, tox+ii, toy+jj), draw_color);
}
invalidate_screen();
mark_current_background_dirty();
}
void RawDrawCircle (int xx, int yy, int rad) {
multiply_up_coordinates(&xx, &yy);
rad = multiply_up_coordinate(rad);
play.raw_modified[play.bg_frame] = 1;
Bitmap *bg_frame = thisroom.ebscene[play.bg_frame];
bg_frame->FillCircle(Circle (xx, yy, rad), play.raw_color);
invalidate_screen();
mark_current_background_dirty();
}
void RawDrawRectangle(int x1, int y1, int x2, int y2) {
play.raw_modified[play.bg_frame] = 1;
multiply_up_coordinates(&x1, &y1);
multiply_up_coordinates_round_up(&x2, &y2);
Bitmap *bg_frame = thisroom.ebscene[play.bg_frame];
bg_frame->FillRect(Rect(x1,y1,x2,y2), play.raw_color);
invalidate_screen();
mark_current_background_dirty();
}
void RawDrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
play.raw_modified[play.bg_frame] = 1;
multiply_up_coordinates(&x1, &y1);
multiply_up_coordinates(&x2, &y2);
multiply_up_coordinates(&x3, &y3);
Bitmap *bg_frame = thisroom.ebscene[play.bg_frame];
bg_frame->DrawTriangle(Triangle (x1,y1,x2,y2,x3,y3), play.raw_color);
invalidate_screen();
mark_current_background_dirty();
}
<|endoftext|>
|
<commit_before>#ifndef __LIB_IMENUCONTROL_HPP__
#define __LIB_IMENUCONTROL_HPP__
#include <lib/draw/rendergroup.hpp>
#include <lib/include/key.hpp>
#include <lib/include/color.hpp>
#include "menumanager.hpp"
#include <lib/draw/scene.hpp>
namespace lib
{
namespace menu
{
class IMenuControl : public lib::draw::RenderGroup
{
public:
IMenuControl(const std::string &name) : lib::draw::RenderGroup(name) {}
virtual ~IMenuControl() {}
virtual void onKeyPressed(lib::input::Key key) = 0;
virtual void onKeyReleased(lib::input::Key key) = 0;
MenuManager * const menuManager() const
{
return dynamic_cast<MenuManager*const>(parent());
}
uptr<MenuTheme> const &menuTheme() const
{
return menuManager()->menuTheme();
}
};
}
}
#endif
<commit_msg>Manager getter<commit_after>#ifndef __LIB_IMENUCONTROL_HPP__
#define __LIB_IMENUCONTROL_HPP__
#include <lib/draw/rendergroup.hpp>
#include <lib/include/key.hpp>
#include <lib/include/color.hpp>
#include "menumanager.hpp"
#include <lib/draw/scene.hpp>
namespace lib
{
namespace menu
{
class IMenuControl : public lib::draw::RenderGroup
{
public:
IMenuControl(const std::string &name) : lib::draw::RenderGroup(name) {}
virtual ~IMenuControl() {}
virtual void onKeyPressed(lib::input::Key key) = 0;
virtual void onKeyReleased(lib::input::Key key) = 0;
MenuManager * const menuManager()
{
return dynamic_cast<MenuManager *const>(parentScene());
}
uptr<MenuTheme> const &menuTheme()
{
return menuManager()->menuTheme();
}
};
}
}
#endif
<|endoftext|>
|
<commit_before>#include "gpu_buffer.hpp"
#include "glfunctions.hpp"
#include "../base/assert.hpp"
glConst glTarget(GPUBuffer::Target t)
{
if (t == GPUBuffer::ElementBuffer)
return GLConst::GLArrayBuffer;
return GLConst::GLElementArrayBuffer;
}
GPUBuffer::GPUBuffer(Target t, uint8_t elementSize, uint16_t capacity)
: base_t(elementSize, capacity)
, m_t(t)
{
m_bufferID = GLFunctions::glGenBuffer();
Bind();
Resize(capacity);
}
GPUBuffer::~GPUBuffer()
{
GLFunctions::glDeleteBuffer(m_bufferID);
}
void GPUBuffer::UploadData(void const * data, uint16_t elementCount)
{
uint16_t currentSize = GetCurrentSize();
uint8_t elementSize = GetElementSize();
ASSERT(GetCapacity() >= elementCount + currentSize, ("Not enough memory to upload ", elementCount, " elements"));
Bind();
GLFunctions::glBufferSubData(glTarget(m_t), elementCount * elementSize, data, currentSize * elementSize);
base_t::UploadData(elementCount);
}
void GPUBuffer::Bind()
{
GLFunctions::glBindBuffer(m_bufferID, glTarget((m_t)));
}
void GPUBuffer::Resize(uint16_t elementCount)
{
base_t::Resize(elementCount);
GLFunctions::glBufferData(glTarget(m_t), GetCapacity() * GetElementSize(), NULL, GLConst::GLStaticDraw);
}
<commit_msg>[drape] on update Index buffer we must bind it as current<commit_after>#include "gpu_buffer.hpp"
#include "glfunctions.hpp"
#include "../base/assert.hpp"
glConst glTarget(GPUBuffer::Target t)
{
if (t == GPUBuffer::ElementBuffer)
return GLConst::GLArrayBuffer;
return GLConst::GLElementArrayBuffer;
}
GPUBuffer::GPUBuffer(Target t, uint8_t elementSize, uint16_t capacity)
: base_t(elementSize, capacity)
, m_t(t)
{
m_bufferID = GLFunctions::glGenBuffer();
Bind();
Resize(capacity);
}
GPUBuffer::~GPUBuffer()
{
GLFunctions::glDeleteBuffer(m_bufferID);
}
void GPUBuffer::UploadData(void const * data, uint16_t elementCount)
{
uint16_t currentSize = GetCurrentSize();
uint8_t elementSize = GetElementSize();
ASSERT(GetCapacity() >= elementCount + currentSize, ("Not enough memory to upload ", elementCount, " elements"));
Bind();
GLFunctions::glBufferSubData(glTarget(m_t), elementCount * elementSize, data, currentSize * elementSize);
base_t::UploadData(elementCount);
}
void GPUBuffer::Bind()
{
GLFunctions::glBindBuffer(m_bufferID, glTarget((m_t)));
}
void GPUBuffer::Resize(uint16_t elementCount)
{
base_t::Resize(elementCount);
Bind();
GLFunctions::glBufferData(glTarget(m_t), GetCapacity() * GetElementSize(), NULL, GLConst::GLStaticDraw);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <memory>
#include <type_traits>
#include "glog/logging.h"
// This file defines a pointer wrapper |not_null| that statically ensures
// non-nullness where possible, and performs runtime checks at the point of
// conversion otherwise.
// The point is to replace cases of undefined behaviour (dereferencing a null
// pointer) by well-defined, localized, failure.
// For instance, when dereferencing a null pointer into a reference, a segfault
// will generally not occur when the pointer is dereferenced, but where the
// reference is used instead, making it hard to track where an invariant was
// violated.
// The static typing of |not_null| also optimizes away some unneeded checks:
// a function taking a |not_null| argument will not need to check its arguments,
// the caller has to provide a |not_null| pointer instead. If the object passed
// is already a |not_null|, no check needs to be performed.
// The syntax is as follows:
// not_null<int*> p // non-null pointer to an |int|.
// not_null<std::unique_ptr<int>> p // non-null unique pointer to an |int|.
// |not_null| does not have a default constructor, since there is no non-null
// default valid pointer. The only ways to construct a |not_null| pointer,
// other than from existing instances of |not_null|, are |check_not_null| and
// |make_unique_not_null|.
//
// The following example shows uses of |not_null|:
// void Accumulate(not_null<int*> const accumulator,
// not_null<int const*> const term) {
// *accumulator += *term; // This will not dereference a null pointer.
// }
//
// void InterfaceAccumulator(int* const dubious_accumulator,
// int const* const term_of_dubious_c_provenance) {
// // The call below performs two checks. If either parameter is null, the
// // program will fail (through a glog |CHECK|) at the callsite.
// Accumulate(check_not_null(dubious_accumulator),
// check_not_null(term_of_dubious_c_provenance));
// // The call below fails to compile: we need to check the arguments.
// Accumulate(check_not_null(dubious_accumulator),
// check_not_null(term_of_dubious_c_provenance));
// }
//
// void UseAccumulator() {
// not_null<std::unique_ptr<int>> accumulator =
// make_not_null_unique<int>(0);
// not_null<int> term = // ...
// // This compiles, no check is performed.
// Accumulate(accumulator.get(), term);
// // ...
// }
//
// The following redundant checks are not performed. This is useful, since
// in a template we may not know whether a pointer is |not_null|.
// not_null<std::unique_ptr<int>> accumulator = // ...
// not_null<int> term = // ...
// |check_not_null| does not perform a check.
// Accumulate(check_not_null(accumulator.get()), check_not_null(term));
// |term == nullptr| can be expanded to false through inlining, so the branch
// will likely be optimized away.
// if(term == nullptr) // ...
// // Same as above.
// if(term) // ...
namespace principia {
namespace base {
template<typename Pointer>
class not_null;
// Type traits.
// |is_instance<T, U>::value| is true if and only if |U| is an instance of the
// template |T|. It is false otherwise.
template<template<typename...> class T, typename U>
struct is_instance_of : std::false_type {};
template<template<typename...> class T, typename U>
struct is_instance_of<T, T<U>> : std::true_type {};
// |remove_not_null<not_null<T>>::type| is |remove_not_null<T>::type|.
// The recurrence ends when |T| is not an instance of |not_null|, in which case
// |remove_not_null<T>::type| is |T|.
template<typename Pointer>
struct remove_not_null {
using type = Pointer;
};
template<typename Pointer>
struct remove_not_null<not_null<Pointer>> {
using type = typename remove_not_null<Pointer>::type;
};
// When |T| is not a reference, |_checked_not_null<T>| is |not_null<T>| if |T|
// is not already an instance of |not_null|. It fails otherwise.
// |_checked_not_null| is invariant under application of reference or rvalue
// reference to its template argument.
template<typename Pointer>
using _checked_not_null = typename std::enable_if<
!is_instance_of<not_null,
typename std::remove_reference<Pointer>::type>::value,
not_null<typename std::remove_reference<Pointer>::type>>::type;
// |not_null<Pointer>| is a wrapper for a non-null object of type |Pointer|.
// |Pointer| should be a C-style pointer or a smart pointer. |Pointer| must not
// be a const, reference, rvalue reference, or |not_null|. |not_null<Pointer>|
// is movable and may be left in an invalid state when moved, i.e., its
// |pointer_| may become null.
// |not_null<not_null<Pointer>>| and |not_null<Pointer>| are equivalent.
// This is useful when a |template<typename T>| using a |not_null<T>| is
// instanced with an instance of |not_null|.
template<typename Pointer>
class not_null {
public:
// The type of the pointer being wrapped.
// This follows the naming convention from |std::unique_ptr|.
using pointer = typename remove_not_null<Pointer>::type;
not_null() = delete;
// Copy constructor from an other |not_null<Pointer>|.
not_null(not_null const&) = default;
// Copy contructor for implicitly convertible pointers.
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null(not_null<OtherPointer> const& other);
// Move constructor from an other |not_null<Pointer>|. This constructor may
// invalidate its argument.
// NOTE(egg): We would use |= default|, but VS2013 does not implement that for
// the move constructor.
not_null(not_null&&); // NOLINT(build/c++11)
// Move contructor for implicitly convertible pointers. This constructor may
// invalidate its argument.
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null(not_null<OtherPointer>&& other); // NOLINT(build/c++11)
~not_null() = default;
// Copy assigment operators.
not_null& operator=(not_null const&) = default;
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null& operator=(not_null<OtherPointer> const& other);
// Move assignment operators.
// Implemented as a swap, so the argument remains valid.
not_null& operator=(not_null&& other); // NOLINT(build/c++11)
// This operator may invalidate its argument.
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null& operator=(not_null<OtherPointer>&& other); // NOLINT(build/c++11)
// Returns |pointer_|, by const reference to avoid a copy if |pointer| is
// |unique_ptr|.
operator pointer const&() const;
// Returns |*pointer_|.
decltype(*pointer{}) operator*() const;
decltype(std::addressof(*pointer{})) const operator->() const;
// When |pointer| has a |get()| member function, this returns
// |pointer_.get()|.
template<typename P = pointer, typename = decltype(P{}.get())>
not_null<decltype(P{}.get())> get() const;
// The following operators are redundant for valid |not_null<Pointer>|s with
// the implicit conversion to |pointer|, but they should allow some
// optimization.
// Returns |false|.
bool operator==(nullptr_t const other) const;
// Returns |true|.
bool operator!=(nullptr_t const other) const;
// Returns |true|.
operator bool() const;
private:
// Creates a |not_null<Pointer>| whose |pointer_| equals the given |pointer|,
// dawg. The constructor does *not* perform a null check. Callers must
// perform one if needed before using it.
explicit not_null(pointer const& ptr);
explicit not_null(pointer&& ptr); // NOLINT(build/c++11)
pointer pointer_;
template<typename OtherPointer>
friend class not_null;
template<typename P>
friend _checked_not_null<P> check_not_null(P pointer);
template<typename T, typename... Args>
friend not_null<std::unique_ptr<T>> make_not_null_unique(
Args&&... args); // NOLINT(build/c++11)
};
// We want only one way of doing things, and we can't make
// |not_null<Pointer> const| and |not_null<Pointer const>| etc. equivalent
// easily.
// Use |not_null<Pointer> const| instead.
template<typename Pointer>
class not_null<Pointer const>;
// Use |not_null<Pointer>&| instead.
template<typename Pointer>
class not_null<Pointer&>;
// Use |not_null<Pointer>&&| instead.
template<typename Pointer>
class not_null<Pointer&&>; // NOLINT(build/c++11)
// Factory taking advantage of template argument deduction. Returns a
// |not_null<Pointer>| to |*pointer|. |CHECK|s that |pointer| is not null.
template<typename Pointer>
_checked_not_null<Pointer> check_not_null(Pointer pointer);
// While the above factory would cover this case using the implicit
// conversion, this results in a redundant |CHECK|.
// This function returns its argument.
template<typename Pointer>
not_null<Pointer> check_not_null(not_null<Pointer> pointer);
// Factory for a |not_null<std::unique_ptr<T>>|, forwards the arguments to the
// constructor of T. |make_not_null_unique<T>(args)| is interchangeable with
// |check_not_null(make_unique<T>(args))|, but does not perform a |CHECK|, since
// the result of |make_unique| is not null.
template<typename T, typename... Args>
not_null<std::unique_ptr<T>> make_not_null_unique(
Args&&... args); // NOLINT(build/c++11)
// For logging.
template<typename Pointer>
std::ostream& operator<<(std::ostream& stream,
not_null<Pointer> const& pointer);
} // namespace base
} // namespace principia
#include "base/not_null_body.hpp"
<commit_msg>After pleroy's second review.<commit_after>#pragma once
#include <memory>
#include <type_traits>
#include "glog/logging.h"
// This file defines a pointer wrapper |not_null| that statically ensures
// non-nullness where possible, and performs runtime checks at the point of
// conversion otherwise.
// The point is to replace cases of undefined behaviour (dereferencing a null
// pointer) by well-defined, localized, failure.
// For instance, when dereferencing a null pointer into a reference, a segfault
// will generally not occur when the pointer is dereferenced, but where the
// reference is used instead, making it hard to track where an invariant was
// violated.
// The static typing of |not_null| also optimizes away some unneeded checks:
// a function taking a |not_null| argument will not need to check its arguments,
// the caller has to provide a |not_null| pointer instead. If the object passed
// is already a |not_null|, no check needs to be performed.
// The syntax is as follows:
// not_null<int*> p // non-null pointer to an |int|.
// not_null<std::unique_ptr<int>> p // non-null unique pointer to an |int|.
// |not_null| does not have a default constructor, since there is no non-null
// default valid pointer. The only ways to construct a |not_null| pointer,
// other than from existing instances of |not_null|, are |check_not_null| and
// |make_unique_not_null|.
//
// The following example shows uses of |not_null|:
// void Accumulate(not_null<int*> const accumulator,
// not_null<int const*> const term) {
// *accumulator += *term; // This will not dereference a null pointer.
// }
//
// void InterfaceAccumulator(int* const dubious_accumulator,
// int const* const term_of_dubious_c_provenance) {
// // The call below performs two checks. If either parameter is null, the
// // program will fail (through a glog |CHECK|) at the callsite.
// Accumulate(check_not_null(dubious_accumulator),
// check_not_null(term_of_dubious_c_provenance));
// // The call below fails to compile: we need to check the arguments.
// Accumulate(dubious_accumulator, term_of_dubious_c_provenance);
// }
//
// void UseAccumulator() {
// not_null<std::unique_ptr<int>> accumulator =
// make_not_null_unique<int>(0);
// not_null<int> term = // ...
// // This compiles, no check is performed.
// Accumulate(accumulator.get(), term);
// // ...
// }
//
// The following redundant checks are not performed. This is useful, since
// in a template we may not know whether a pointer is |not_null|.
// not_null<std::unique_ptr<int>> accumulator = // ...
// not_null<int> term = // ...
// |check_not_null| does not perform a check.
// Accumulate(check_not_null(accumulator.get()), check_not_null(term));
// |term == nullptr| can be expanded to false through inlining, so the branch
// will likely be optimized away.
// if (term == nullptr) // ...
// // Same as above.
// if (term) // ...
namespace principia {
namespace base {
template<typename Pointer>
class not_null;
// Type traits.
// |is_instance<T, U>::value| is true if and only if |U| is an instance of the
// template |T|. It is false otherwise.
template<template<typename...> class T, typename U>
struct is_instance_of : std::false_type {};
template<template<typename...> class T, typename U>
struct is_instance_of<T, T<U>> : std::true_type {};
// |remove_not_null<not_null<T>>::type| is |remove_not_null<T>::type|.
// The recurrence ends when |T| is not an instance of |not_null|, in which case
// |remove_not_null<T>::type| is |T|.
template<typename Pointer>
struct remove_not_null {
using type = Pointer;
};
template<typename Pointer>
struct remove_not_null<not_null<Pointer>> {
using type = typename remove_not_null<Pointer>::type;
};
// When |T| is not a reference, |_checked_not_null<T>| is |not_null<T>| if |T|
// is not already an instance of |not_null|. It fails otherwise.
// |_checked_not_null| is invariant under application of reference or rvalue
// reference to its template argument.
template<typename Pointer>
using _checked_not_null = typename std::enable_if<
!is_instance_of<not_null,
typename std::remove_reference<Pointer>::type>::value,
not_null<typename std::remove_reference<Pointer>::type>>::type;
// |not_null<Pointer>| is a wrapper for a non-null object of type |Pointer|.
// |Pointer| should be a C-style pointer or a smart pointer. |Pointer| must not
// be a const, reference, rvalue reference, or |not_null|. |not_null<Pointer>|
// is movable and may be left in an invalid state when moved, i.e., its
// |pointer_| may become null.
// |not_null<not_null<Pointer>>| and |not_null<Pointer>| are equivalent.
// This is useful when a |template<typename T>| using a |not_null<T>| is
// instanced with an instance of |not_null|.
template<typename Pointer>
class not_null {
public:
// The type of the pointer being wrapped.
// This follows the naming convention from |std::unique_ptr|.
using pointer = typename remove_not_null<Pointer>::type;
not_null() = delete;
// Copy constructor from an other |not_null<Pointer>|.
not_null(not_null const&) = default;
// Copy contructor for implicitly convertible pointers.
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null(not_null<OtherPointer> const& other);
// Move constructor from an other |not_null<Pointer>|. This constructor may
// invalidate its argument.
// NOTE(egg): We would use |= default|, but VS2013 does not implement that for
// the move constructor.
not_null(not_null&&); // NOLINT(build/c++11)
// Move contructor for implicitly convertible pointers. This constructor may
// invalidate its argument.
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null(not_null<OtherPointer>&& other); // NOLINT(build/c++11)
~not_null() = default;
// Copy assigment operators.
not_null& operator=(not_null const&) = default;
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null& operator=(not_null<OtherPointer> const& other);
// Move assignment operators.
// Implemented as a swap, so the argument remains valid.
not_null& operator=(not_null&& other); // NOLINT(build/c++11)
// This operator may invalidate its argument.
template<typename OtherPointer,
typename = typename std::enable_if<
std::is_convertible<OtherPointer, pointer>::value>::type>
not_null& operator=(not_null<OtherPointer>&& other); // NOLINT(build/c++11)
// Returns |pointer_|, by const reference to avoid a copy if |pointer| is
// |unique_ptr|.
operator pointer const&() const;
// Returns |*pointer_|.
decltype(*pointer{}) operator*() const;
decltype(std::addressof(*pointer{})) const operator->() const;
// When |pointer| has a |get()| member function, this returns
// |pointer_.get()|.
template<typename P = pointer, typename = decltype(P{}.get())>
not_null<decltype(P{}.get())> get() const;
// The following operators are redundant for valid |not_null<Pointer>|s with
// the implicit conversion to |pointer|, but they should allow some
// optimization.
// Returns |false|.
bool operator==(nullptr_t const other) const;
// Returns |true|.
bool operator!=(nullptr_t const other) const;
// Returns |true|.
operator bool() const;
private:
// Creates a |not_null<Pointer>| whose |pointer_| equals the given |pointer|,
// dawg. The constructor does *not* perform a null check. Callers must
// perform one if needed before using it.
explicit not_null(pointer const& ptr);
explicit not_null(pointer&& ptr); // NOLINT(build/c++11)
pointer pointer_;
template<typename OtherPointer>
friend class not_null;
template<typename P>
friend _checked_not_null<P> check_not_null(P pointer);
template<typename T, typename... Args>
friend not_null<std::unique_ptr<T>> make_not_null_unique(
Args&&... args); // NOLINT(build/c++11)
};
// We want only one way of doing things, and we can't make
// |not_null<Pointer> const| and |not_null<Pointer const>| etc. equivalent
// easily.
// Use |not_null<Pointer> const| instead.
template<typename Pointer>
class not_null<Pointer const>;
// Use |not_null<Pointer>&| instead.
template<typename Pointer>
class not_null<Pointer&>;
// Use |not_null<Pointer>&&| instead.
template<typename Pointer>
class not_null<Pointer&&>; // NOLINT(build/c++11)
// Factory taking advantage of template argument deduction. Returns a
// |not_null<Pointer>| to |*pointer|. |CHECK|s that |pointer| is not null.
template<typename Pointer>
_checked_not_null<Pointer> check_not_null(Pointer pointer);
// While the above factory would cover this case using the implicit
// conversion, this results in a redundant |CHECK|.
// This function returns its argument.
template<typename Pointer>
not_null<Pointer> check_not_null(not_null<Pointer> pointer);
// Factory for a |not_null<std::unique_ptr<T>>|, forwards the arguments to the
// constructor of T. |make_not_null_unique<T>(args)| is interchangeable with
// |check_not_null(make_unique<T>(args))|, but does not perform a |CHECK|, since
// the result of |make_unique| is not null.
template<typename T, typename... Args>
not_null<std::unique_ptr<T>> make_not_null_unique(
Args&&... args); // NOLINT(build/c++11)
// For logging.
template<typename Pointer>
std::ostream& operator<<(std::ostream& stream,
not_null<Pointer> const& pointer);
} // namespace base
} // namespace principia
#include "base/not_null_body.hpp"
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include "trace.hxx"
#include <tools/debug.hxx>
#if defined(DBG_UTIL)
//==============================================================================
//------------------------------------------------------------------------------
::osl::Mutex Tracer::s_aMapSafety;
::std::map< ::oslThreadIdentifier, INT32, ::std::less< ::osl::ThreadIdentifier > >
Tracer::s_aThreadIndents;
//------------------------------------------------------------------------------
Tracer::Tracer(const char* _pBlockDescription)
:m_sBlockDescription(_pBlockDescription)
{
::osl::MutexGuard aGuard(s_aMapSafety);
INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ]++;
ByteString sIndent;
while (nIndent--)
sIndent += '\t';
ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
sThread += '\t';
ByteString sMessage(sThread);
sMessage += sIndent;
sMessage += m_sBlockDescription;
sMessage += " {";
DBG_TRACE(sMessage.GetBuffer());
}
//------------------------------------------------------------------------------
Tracer::~Tracer()
{
::osl::MutexGuard aGuard(s_aMapSafety);
INT32 nIndent = --s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];
ByteString sIndent;
while (nIndent--)
sIndent += '\t';
ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
sThread += '\t';
ByteString sMessage(sThread);
sMessage += sIndent;
sMessage += "} // ";
sMessage += m_sBlockDescription;
DBG_TRACE(sMessage.GetBuffer());
}
//------------------------------------------------------------------------------
void Tracer::TraceString(const char* _pMessage)
{
::osl::MutexGuard aGuard(s_aMapSafety);
INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];
ByteString sIndent;
while (nIndent--)
sIndent += '\t';
ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
sThread += '\t';
ByteString sMessage(sThread);
sMessage += sIndent;
sMessage += m_sBlockDescription;
sMessage += ": ";
sMessage += _pMessage;
DBG_TRACE(sMessage.GetBuffer());
}
//------------------------------------------------------------------------------
void Tracer::TraceString1StringParam(const char* _pMessage, const char* _pParam)
{
::osl::MutexGuard aGuard(s_aMapSafety);
INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];
ByteString sIndent;
while (nIndent--)
sIndent += '\t';
ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
sThread += '\t';
ByteString sMessage(sThread);
sMessage += sIndent;
sMessage += m_sBlockDescription;
sMessage += ": ";
sMessage += _pMessage;
DBG_TRACE1(sMessage.GetBuffer(), _pParam);
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix breakage in dbgutil-enabled build<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include "trace.hxx"
#include <tools/debug.hxx>
#if defined(DBG_UTIL)
//==============================================================================
//------------------------------------------------------------------------------
::osl::Mutex Tracer::s_aMapSafety;
::std::map< ::oslThreadIdentifier, INT32, ::std::less< oslThreadIdentifier > >
Tracer::s_aThreadIndents;
//------------------------------------------------------------------------------
Tracer::Tracer(const char* _pBlockDescription)
:m_sBlockDescription(_pBlockDescription)
{
::osl::MutexGuard aGuard(s_aMapSafety);
INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ]++;
ByteString sIndent;
while (nIndent--)
sIndent += '\t';
ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
sThread += '\t';
ByteString sMessage(sThread);
sMessage += sIndent;
sMessage += m_sBlockDescription;
sMessage += " {";
DBG_TRACE(sMessage.GetBuffer());
}
//------------------------------------------------------------------------------
Tracer::~Tracer()
{
::osl::MutexGuard aGuard(s_aMapSafety);
INT32 nIndent = --s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];
ByteString sIndent;
while (nIndent--)
sIndent += '\t';
ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
sThread += '\t';
ByteString sMessage(sThread);
sMessage += sIndent;
sMessage += "} // ";
sMessage += m_sBlockDescription;
DBG_TRACE(sMessage.GetBuffer());
}
//------------------------------------------------------------------------------
void Tracer::TraceString(const char* _pMessage)
{
::osl::MutexGuard aGuard(s_aMapSafety);
INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];
ByteString sIndent;
while (nIndent--)
sIndent += '\t';
ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
sThread += '\t';
ByteString sMessage(sThread);
sMessage += sIndent;
sMessage += m_sBlockDescription;
sMessage += ": ";
sMessage += _pMessage;
DBG_TRACE(sMessage.GetBuffer());
}
//------------------------------------------------------------------------------
void Tracer::TraceString1StringParam(const char* _pMessage, const char* _pParam)
{
::osl::MutexGuard aGuard(s_aMapSafety);
INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];
ByteString sIndent;
while (nIndent--)
sIndent += '\t';
ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
sThread += '\t';
ByteString sMessage(sThread);
sMessage += sIndent;
sMessage += m_sBlockDescription;
sMessage += ": ";
sMessage += _pMessage;
DBG_TRACE1(sMessage.GetBuffer(), _pParam);
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include "ptk/shell.h"
#include <cctype>
#include <cstring>
#include <cstdio>
using namespace ptk;
ShellCommand::ShellCommand(const char *name) :
SubThread(),
name(name)
{
next_command = Shell::commands;
Shell::commands = this;
}
void ShellCommand::printf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
Shell::out->vprintf(fmt, args);
va_end(args);
}
void ShellCommand::help(bool brief) {
Shell::out->printf("%s ...\r\n", name);
}
DeviceInStream *Shell::in;
DeviceOutStream *Shell::out;
int Shell::argc;
const char *Shell::argv[MAX_ARGS];
ShellCommand *Shell::commands;
Shell::Shell(DeviceInStream &in, DeviceOutStream &out) :
Thread(),
line_length(0)
{
Shell::in = ∈
Shell::out = &out;
}
void Shell::run() {
PTK_BEGIN();
while (1) {
// BUG: why doesn't the first prompt appear?
out->puts("> ");
line_length = 0;
line_complete = false;
while (!line_complete) {
PTK_WAIT_EVENT(in->not_empty, TIME_INFINITE);
uint8_t c;
while (!line_complete && in->get(c)) {
if (line_length == MAX_LINE-1) {
line_complete = true;
break;
}
switch (c) {
case 0x04 : // ctrl-D
out->puts("^D");
line[line_length] = 0;
line_complete = true;
break;
case 0x7f : // delete
case 0x08 : // ctrl-H
if (line_length > 0) {
out->puts("\010 \010");
line_length--;
}
break;
case 0x15 : // ctrl-U
out->puts("^U\r\n> ");
line[line_length=0] = 0;
break;
case '\r' :
out->puts("\r\n");
line[line_length] = 0;
line_complete = true;
break;
default :
if (c < ' ' || c >= 0x80) {
continue; // unprintable
}
if (line_length >= MAX_LINE-1) continue;
out->put(c);
line[line_length++] = c;
break;
}
}
if (line_complete) {
parse_line();
if (argc > 0) {
ShellCommand *cmd = find_command(argv[0]);
if (cmd) {
PTK_WAIT_SUBTHREAD(*cmd, TIME_INFINITE);
} else {
out->printf("%s ?\r\n", argv[0]);
}
}
}
} // while (!line_complete)
} // while (1)
PTK_END();
}
void Shell::parse_line() {
unsigned int i=0;
argc = 0;
while (i < line_length && argc < MAX_ARGS) {
// start argument word
argv[argc++] = &line[i];
while (i < line_length && !std::isspace(line[i])) i++;
line[i++] = 0;
// skip whitespace
while (i < line_length && std::isspace(line[i])) i++;
}
}
int Shell::lookup_keyword(const char *str,
const keyword_t list[],
size_t size)
{
size /= sizeof(keyword_t);
for (unsigned i=0; i < size; ++i) {
if (!strcmp(str, list[i].name)) return list[i].id;
}
return -1;
}
void Shell::print_keywords(const keyword_t list[], size_t size) {
size /= sizeof(keyword_t);
for (unsigned i=0; i < size; ++i) {
out->printf(" %-8s -- %s\r\n", list[i].name, list[i].description);
}
}
ShellCommand *Shell::find_command(const char *name) {
if (!strcmp(name, "?")) name = "help";
for (ShellCommand *cmd = commands; cmd; cmd = cmd->next_command) {
if (!strcmp(name, cmd->name)) return cmd;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
class HelpCommand : public ShellCommand {
ShellCommand *cmd;
public:
HelpCommand() : ShellCommand("help") {
}
virtual void help(bool brief) {
Shell::out->printf("%-10s - %s\r\n", name, "list available commands");
}
virtual void run() {
PTK_BEGIN();
for (cmd = Shell::commands; cmd; cmd = cmd->next_command) {
PTK_WAIT_UNTIL(Shell::out->available() > 16, TIME_INFINITE);
cmd->help(true);
}
PTK_END();
}
} help_command;
class ThreadsCommand : public ShellCommand {
Thread *thread;
public:
ThreadsCommand() : ShellCommand("threads") {
}
virtual void help(bool brief) {
Shell::out->printf("%-10s - %s\r\n", name, "show active protothreads");
}
public:
virtual void run() {
PTK_BEGIN();
for (thread = all_registered_threads;
thread;
thread = thread->next_registered_thread)
{
if (thread->continuation) {
PTK_WAIT_UNTIL(Shell::out->available() > 64, TIME_INFINITE);
Shell::out->printf("[%08x] %6s %s:%d\r\n",
thread,
thread->state_name(),
thread->debug_file,
thread->debug_line);
}
}
PTK_END();
}
} threads_command;
<commit_msg>don't wait forever for buffer space<commit_after>#include "ptk/shell.h"
#include <cctype>
#include <cstring>
#include <cstdio>
using namespace ptk;
ShellCommand::ShellCommand(const char *name) :
SubThread(),
name(name)
{
next_command = Shell::commands;
Shell::commands = this;
}
void ShellCommand::printf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
Shell::out->vprintf(fmt, args);
va_end(args);
}
void ShellCommand::help(bool brief) {
Shell::out->printf("%s ...\r\n", name);
}
DeviceInStream *Shell::in;
DeviceOutStream *Shell::out;
int Shell::argc;
const char *Shell::argv[MAX_ARGS];
ShellCommand *Shell::commands;
Shell::Shell(DeviceInStream &in, DeviceOutStream &out) :
Thread(),
line_length(0)
{
Shell::in = ∈
Shell::out = &out;
}
void Shell::run() {
PTK_BEGIN();
while (1) {
// BUG: why doesn't the first prompt appear?
out->puts("> ");
line_length = 0;
line_complete = false;
while (!line_complete) {
PTK_WAIT_EVENT(in->not_empty, TIME_INFINITE);
uint8_t c;
while (!line_complete && in->get(c)) {
if (line_length == MAX_LINE-1) {
line_complete = true;
break;
}
switch (c) {
case 0x04 : // ctrl-D
out->puts("^D");
line[line_length] = 0;
line_complete = true;
break;
case 0x7f : // delete
case 0x08 : // ctrl-H
if (line_length > 0) {
out->puts("\010 \010");
line_length--;
}
break;
case 0x15 : // ctrl-U
out->puts("^U\r\n> ");
line[line_length=0] = 0;
break;
case '\r' :
out->puts("\r\n");
line[line_length] = 0;
line_complete = true;
break;
default :
if (c < ' ' || c >= 0x80) {
continue; // unprintable
}
if (line_length >= MAX_LINE-1) continue;
out->put(c);
line[line_length++] = c;
break;
}
}
if (line_complete) {
parse_line();
if (argc > 0) {
ShellCommand *cmd = find_command(argv[0]);
if (cmd) {
PTK_WAIT_SUBTHREAD(*cmd, TIME_INFINITE);
} else {
out->printf("%s ?\r\n", argv[0]);
}
}
}
} // while (!line_complete)
} // while (1)
PTK_END();
}
void Shell::parse_line() {
unsigned int i=0;
argc = 0;
while (i < line_length && argc < MAX_ARGS) {
// start argument word
argv[argc++] = &line[i];
while (i < line_length && !std::isspace(line[i])) i++;
line[i++] = 0;
// skip whitespace
while (i < line_length && std::isspace(line[i])) i++;
}
}
int Shell::lookup_keyword(const char *str,
const keyword_t list[],
size_t size)
{
size /= sizeof(keyword_t);
for (unsigned i=0; i < size; ++i) {
if (!strcmp(str, list[i].name)) return list[i].id;
}
return -1;
}
void Shell::print_keywords(const keyword_t list[], size_t size) {
size /= sizeof(keyword_t);
for (unsigned i=0; i < size; ++i) {
out->printf(" %-8s -- %s\r\n", list[i].name, list[i].description);
}
}
ShellCommand *Shell::find_command(const char *name) {
if (!strcmp(name, "?")) name = "help";
for (ShellCommand *cmd = commands; cmd; cmd = cmd->next_command) {
if (!strcmp(name, cmd->name)) return cmd;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
class HelpCommand : public ShellCommand {
ShellCommand *cmd;
public:
HelpCommand() : ShellCommand("help") {
}
virtual void help(bool brief) {
Shell::out->printf("%-10s - %s\r\n", name, "list available commands");
}
virtual void run() {
PTK_BEGIN();
for (cmd = Shell::commands; cmd; cmd = cmd->next_command) {
// wait a bit until there's (hopefully) room in the output buffer
PTK_WAIT_UNTIL(Shell::out->available() > 16, 100);
cmd->help(true);
}
PTK_END();
}
} help_command;
class ThreadsCommand : public ShellCommand {
Thread *thread;
public:
ThreadsCommand() : ShellCommand("threads") {
}
virtual void help(bool brief) {
Shell::out->printf("%-10s - %s\r\n", name, "show active protothreads");
}
public:
virtual void run() {
PTK_BEGIN();
for (thread = all_registered_threads;
thread;
thread = thread->next_registered_thread)
{
if (thread->continuation) {
// wait a bit until there's (hopefully) room in the output buffer
PTK_WAIT_UNTIL(Shell::out->available() > 64, 100);
Shell::out->printf("[%08x] %6s %s:%d\r\n",
thread,
thread->state_name(),
thread->debug_file,
thread->debug_line);
}
}
PTK_END();
}
} threads_command;
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: chrdlg.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: fme $ $Date: 2001-06-01 10:20:44 $
*
* 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 _SWCHARDLG_HXX
#define _SWCHARDLG_HXX
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
class FontList;
class SwView;
class SvxMacroItem;
/*--------------------------------------------------------------------
Beschreibung: Der Tabdialog Traeger der TabPages
--------------------------------------------------------------------*/
class SwCharDlg: public SfxTabDialog
{
SwView& rView;
BOOL bIsDrwTxtMode;
public:
SwCharDlg(Window* pParent, SwView& pVw, const SfxItemSet& rCoreSet,
const String* pFmtStr = 0, BOOL bIsDrwTxtDlg = FALSE);
~SwCharDlg();
virtual void PageCreated( USHORT nId, SfxTabPage &rPage );
};
/*-----------------14.08.96 11.03-------------------
Beschreibung: Tabpage fuer URL-Attribut
--------------------------------------------------*/
class SwCharURLPage : public SfxTabPage
{
FixedLine aURLFL;
FixedText aURLFT;
Edit aURLED;
FixedText aTextFT;
Edit aTextED;
FixedText aNameFT;
Edit aNameED;
FixedText aTargetFrmFT;
ComboBox aTargetFrmLB;
PushButton aURLPB;
PushButton aEventPB;
FixedLine aStyleFL;
FixedText aVisitedFT;
ListBox aVisitedLB;
FixedText aNotVisitedFT;
ListBox aNotVisitedLB;
SvxMacroItem* pINetItem;
BOOL bModified;
DECL_LINK( InsertFileHdl, PushButton * );
DECL_LINK( EventHdl, PushButton * );
public:
SwCharURLPage( Window* pParent,
const SfxItemSet& rSet );
~SwCharURLPage();
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet);
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1448); FILE MERGED 2005/09/05 13:45:00 rt 1.2.1448.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: chrdlg.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 09:04:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SWCHARDLG_HXX
#define _SWCHARDLG_HXX
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
class FontList;
class SwView;
class SvxMacroItem;
/*--------------------------------------------------------------------
Beschreibung: Der Tabdialog Traeger der TabPages
--------------------------------------------------------------------*/
class SwCharDlg: public SfxTabDialog
{
SwView& rView;
BOOL bIsDrwTxtMode;
public:
SwCharDlg(Window* pParent, SwView& pVw, const SfxItemSet& rCoreSet,
const String* pFmtStr = 0, BOOL bIsDrwTxtDlg = FALSE);
~SwCharDlg();
virtual void PageCreated( USHORT nId, SfxTabPage &rPage );
};
/*-----------------14.08.96 11.03-------------------
Beschreibung: Tabpage fuer URL-Attribut
--------------------------------------------------*/
class SwCharURLPage : public SfxTabPage
{
FixedLine aURLFL;
FixedText aURLFT;
Edit aURLED;
FixedText aTextFT;
Edit aTextED;
FixedText aNameFT;
Edit aNameED;
FixedText aTargetFrmFT;
ComboBox aTargetFrmLB;
PushButton aURLPB;
PushButton aEventPB;
FixedLine aStyleFL;
FixedText aVisitedFT;
ListBox aVisitedLB;
FixedText aNotVisitedFT;
ListBox aNotVisitedLB;
SvxMacroItem* pINetItem;
BOOL bModified;
DECL_LINK( InsertFileHdl, PushButton * );
DECL_LINK( EventHdl, PushButton * );
public:
SwCharURLPage( Window* pParent,
const SfxItemSet& rSet );
~SwCharURLPage();
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet);
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
#endif
<|endoftext|>
|
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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.
*
* @file HitFinderTools.h
*/
#include "HitFinderTools.h"
#include <cmath> /// std::sin(), std::cos()
#include <TMath.h> /// DegToRad()
JPetHit HitFinderTools::createDummyRefDefHit(const JPetPhysSignal& signalB,
const VelocityMap& velMap)
{
JPetHit hit;
hit.setSignalB(signalB);
hit.setTime(signalB.getTime());
hit.setQualityOfTime(-1.0);
hit.setTimeDiff(0.0);
hit.setQualityOfTimeDiff(-1.0);
hit.setEnergy(-1.0);
hit.setQualityOfEnergy(-1.0);
hit.setScintillator(signalB.getPM().getScin());
hit.setBarrelSlot(signalB.getPM().getBarrelSlot());
setHitXYPosition(hit);
auto search = velMap.find(hit.getBarrelSlot().getID());
if (search != velMap.end()) hit.setPosZ(-1000000.0);
return hit;
}
void HitFinderTools::addIfReferenceSignal(
std::vector<JPetHit>& hits,
const std::vector<JPetPhysSignal>& sideA,
const std::vector<JPetPhysSignal>& sideB,
const VelocityMap& velMap)
{
if (sideA.size() == 0 && sideB.size() > 0) {
auto scinID = sideB.at(0).getPM().getScin().getID();
auto layerID = sideB.at(0).getBarrelSlot().getLayer().getID();
if (scinID == 193 && layerID == 4) {
for (auto signalB : sideB) {
hits.push_back(createDummyRefDefHit(signalB, velMap));
}
}
}
}
void HitFinderTools::sortByTime(std::vector<JPetPhysSignal>& side)
{
std::sort(side.begin(),
side.end(),
[](const JPetPhysSignal & h1,
const JPetPhysSignal & h2) {
return h1.getTime() < h2.getTime();
});
}
void HitFinderTools::setHitZPosition(JPetHit& hit, const VelocityMap& velMap)
{
auto search = velMap.find(hit.getBarrelSlot().getID());
if (search != velMap.end()) {
double vel = search->second.first;
double position = vel * hit.getTimeDiff() / 2000.;
hit.setPosZ(position);
} else {
hit.setPosZ(-1000000.0);
}
}
void HitFinderTools::setHitXYPosition(JPetHit& hit)
{
auto radius = hit.getBarrelSlot().getLayer().getRadius();
auto theta = TMath::DegToRad() * hit.getBarrelSlot().getTheta();
hit.setPosX(radius * std::cos(theta));
hit.setPosY(radius * std::sin(theta));
}
JPetHit HitFinderTools::createHit(const JPetPhysSignal& signalA,
const JPetPhysSignal& signalB,
const VelocityMap& velMap)
{
JPetHit hit;
hit.setSignalA(signalA);
hit.setSignalB(signalB);
hit.setTime((signalA.getTime() + signalB.getTime()) / 2.0);
hit.setQualityOfTime(-1.0);
hit.setTimeDiff(signalB.getTime() - signalA.getTime());
hit.setQualityOfTimeDiff(-1.0);
hit.setEnergy(-1.0);
hit.setQualityOfEnergy(-1.0);
hit.setScintillator(signalA.getPM().getScin());
hit.setBarrelSlot(signalA.getPM().getBarrelSlot());
setHitXYPosition(hit);
setHitZPosition(hit, velMap);
return hit;
}
std::vector<JPetHit> HitFinderTools::createHits(
JPetStatistics& statistics,
const SignalsContainer& allSignalsInTimeWindow,
const double timeDifferenceWindow,
const VelocityMap& velMap)
{
std::vector<JPetHit> hits;
for (auto scintillator : allSignalsInTimeWindow) {
auto sideA = scintillator.second.first;
auto sideB = scintillator.second.second;
// Handling the special case of reference detector signals,
// which are defined as coming only from sideB,
// scintillator no. 193 in layer no. 4
// and do not correspond to a full hit
addIfReferenceSignal(hits, sideA, sideB, velMap);
if (sideA.size() > 0 && sideB.size() > 0) {
sortByTime(sideA);
sortByTime(sideB);
for (auto signalA : sideA) {
for (auto signalB : sideB) {
if ((signalB.getTime() - signalA.getTime())
> timeDifferenceWindow)
break;
if (fabs(signalA.getTime() - signalB.getTime())
< timeDifferenceWindow) {
//Creating hit for successfully matched pair of Phys singlas
//Setting meaningless parameters of Energy, Position, quality
JPetHit hit = createHit(signalA, signalB, velMap);
hits.push_back(hit);
statistics.getHisto2D("time_diff_per_scin")
->Fill(hit.getTimeDiff(),
(float)(hit.getScintillator().getID()));
statistics.getHisto2D("hit_pos_per_scin")
->Fill(hit.getPosZ(),
(float)(hit.getScintillator().getID()));
}
}
}
}
}
if (!checkIsDegreeOrRad(hits))
WARNING("ALL barrel slots have theta < then 7, check is they have correct degree theta");
return hits;
}
bool HitFinderTools::checkIsDegreeOrRad(const std::vector<JPetHit>& hits)
{
bool isDegree = false;
for (const JPetHit& hit : hits) {
if (hit.getBarrelSlot().getTheta() > 7.) {
isDegree = true;
break;
}
}
return isDegree;
}<commit_msg>Add end-of-line<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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.
*
* @file HitFinderTools.h
*/
#include "HitFinderTools.h"
#include <cmath> /// std::sin(), std::cos()
#include <TMath.h> /// DegToRad()
JPetHit HitFinderTools::createDummyRefDefHit(const JPetPhysSignal& signalB,
const VelocityMap& velMap)
{
JPetHit hit;
hit.setSignalB(signalB);
hit.setTime(signalB.getTime());
hit.setQualityOfTime(-1.0);
hit.setTimeDiff(0.0);
hit.setQualityOfTimeDiff(-1.0);
hit.setEnergy(-1.0);
hit.setQualityOfEnergy(-1.0);
hit.setScintillator(signalB.getPM().getScin());
hit.setBarrelSlot(signalB.getPM().getBarrelSlot());
setHitXYPosition(hit);
auto search = velMap.find(hit.getBarrelSlot().getID());
if (search != velMap.end()) hit.setPosZ(-1000000.0);
return hit;
}
void HitFinderTools::addIfReferenceSignal(
std::vector<JPetHit>& hits,
const std::vector<JPetPhysSignal>& sideA,
const std::vector<JPetPhysSignal>& sideB,
const VelocityMap& velMap)
{
if (sideA.size() == 0 && sideB.size() > 0) {
auto scinID = sideB.at(0).getPM().getScin().getID();
auto layerID = sideB.at(0).getBarrelSlot().getLayer().getID();
if (scinID == 193 && layerID == 4) {
for (auto signalB : sideB) {
hits.push_back(createDummyRefDefHit(signalB, velMap));
}
}
}
}
void HitFinderTools::sortByTime(std::vector<JPetPhysSignal>& side)
{
std::sort(side.begin(),
side.end(),
[](const JPetPhysSignal & h1,
const JPetPhysSignal & h2) {
return h1.getTime() < h2.getTime();
});
}
void HitFinderTools::setHitZPosition(JPetHit& hit, const VelocityMap& velMap)
{
auto search = velMap.find(hit.getBarrelSlot().getID());
if (search != velMap.end()) {
double vel = search->second.first;
double position = vel * hit.getTimeDiff() / 2000.;
hit.setPosZ(position);
} else {
hit.setPosZ(-1000000.0);
}
}
void HitFinderTools::setHitXYPosition(JPetHit& hit)
{
auto radius = hit.getBarrelSlot().getLayer().getRadius();
auto theta = TMath::DegToRad() * hit.getBarrelSlot().getTheta();
hit.setPosX(radius * std::cos(theta));
hit.setPosY(radius * std::sin(theta));
}
JPetHit HitFinderTools::createHit(const JPetPhysSignal& signalA,
const JPetPhysSignal& signalB,
const VelocityMap& velMap)
{
JPetHit hit;
hit.setSignalA(signalA);
hit.setSignalB(signalB);
hit.setTime((signalA.getTime() + signalB.getTime()) / 2.0);
hit.setQualityOfTime(-1.0);
hit.setTimeDiff(signalB.getTime() - signalA.getTime());
hit.setQualityOfTimeDiff(-1.0);
hit.setEnergy(-1.0);
hit.setQualityOfEnergy(-1.0);
hit.setScintillator(signalA.getPM().getScin());
hit.setBarrelSlot(signalA.getPM().getBarrelSlot());
setHitXYPosition(hit);
setHitZPosition(hit, velMap);
return hit;
}
std::vector<JPetHit> HitFinderTools::createHits(
JPetStatistics& statistics,
const SignalsContainer& allSignalsInTimeWindow,
const double timeDifferenceWindow,
const VelocityMap& velMap)
{
std::vector<JPetHit> hits;
for (auto scintillator : allSignalsInTimeWindow) {
auto sideA = scintillator.second.first;
auto sideB = scintillator.second.second;
// Handling the special case of reference detector signals,
// which are defined as coming only from sideB,
// scintillator no. 193 in layer no. 4
// and do not correspond to a full hit
addIfReferenceSignal(hits, sideA, sideB, velMap);
if (sideA.size() > 0 && sideB.size() > 0) {
sortByTime(sideA);
sortByTime(sideB);
for (auto signalA : sideA) {
for (auto signalB : sideB) {
if ((signalB.getTime() - signalA.getTime())
> timeDifferenceWindow)
break;
if (fabs(signalA.getTime() - signalB.getTime())
< timeDifferenceWindow) {
//Creating hit for successfully matched pair of Phys singlas
//Setting meaningless parameters of Energy, Position, quality
JPetHit hit = createHit(signalA, signalB, velMap);
hits.push_back(hit);
statistics.getHisto2D("time_diff_per_scin")
->Fill(hit.getTimeDiff(),
(float)(hit.getScintillator().getID()));
statistics.getHisto2D("hit_pos_per_scin")
->Fill(hit.getPosZ(),
(float)(hit.getScintillator().getID()));
}
}
}
}
}
if (!checkIsDegreeOrRad(hits))
WARNING("ALL barrel slots have theta < then 7, check is they have correct degree theta");
return hits;
}
bool HitFinderTools::checkIsDegreeOrRad(const std::vector<JPetHit>& hits)
{
bool isDegree = false;
for (const JPetHit& hit : hits) {
if (hit.getBarrelSlot().getTheta() > 7.) {
isDegree = true;
break;
}
}
return isDegree;
}
<|endoftext|>
|
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
void * operator new(size_t size)
{
return (void *)malloc(size);
}
void operator delete( void *to_free )
{
if( to_free ) {
(void)free( to_free );
}
}
#if defined( __GNUC__ )
# if (__GNUG__== 2 && (__GNUC_MINOR__ == 6 || __GNUC_MINOR__ == 7 || __GNUC_MINOR__ == 91))
extern "C" {
void *__builtin_new( size_t );
void __builtin_delete( void * );
void *
__builtin_vec_new (size_t sz)
{
return __builtin_new( sz );
}
void
__builtin_vec_delete( void *to_free )
{
__builtin_delete( to_free );
}
}
# endif
#endif
#if 0
/* This function is called by egcs when a pure virtual method is called.
Since the user job may not be linking with egcs libraries, we need to
provide our own version. */
#define MESSAGE "pure virtual method called\n"
extern "C" {
void
__pure_virtual()
{
write (2, MESSAGE, sizeof (MESSAGE) - 1);
_exit (1);
}
}
#endif
<commit_msg>Added a new __GNUC_MINOR__ number to support the gcc 2.95.x compilers.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
void * operator new(size_t size)
{
return (void *)malloc(size);
}
void operator delete( void *to_free )
{
if( to_free ) {
(void)free( to_free );
}
}
#if defined( __GNUC__ )
# if (__GNUG__== 2 && (__GNUC_MINOR__ == 6 || __GNUC_MINOR__ == 7 || __GNUC_MINOR__ == 91 || __GNUC_MINOR__ == 95))
extern "C" {
void *__builtin_new( size_t );
void __builtin_delete( void * );
void *
__builtin_vec_new (size_t sz)
{
return __builtin_new( sz );
}
void
__builtin_vec_delete( void *to_free )
{
__builtin_delete( to_free );
}
}
# endif
#endif
#if 0
/* This function is called by egcs when a pure virtual method is called.
Since the user job may not be linking with egcs libraries, we need to
provide our own version. */
#define MESSAGE "pure virtual method called\n"
extern "C" {
void
__pure_virtual()
{
write (2, MESSAGE, sizeof (MESSAGE) - 1);
_exit (1);
}
}
#endif
<|endoftext|>
|
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/util/buildinfo.h>
#include <inviwo/core/util/assertion.h>
#include <inviwo/core/util/filesystem.h>
#include <fstream>
#include <sstream>
#include <locale>
namespace inviwo {
namespace util {
// helper struct to define arbitrary separator characters in a locale
// usage:
// std::stringstream stream;
// stream.imbue(std::locale(stream.getloc(), new CsvWhitespace));
struct IniSeparator : std::ctype<char> {
static const mask* makeTable() {
// copy table of C locale
static std::vector<mask> m(classic_table(), classic_table() + table_size);
m[' '] &= ~space; // remove space as whitespace
m['='] |= space;
return &m[0];
}
IniSeparator(std::size_t refs = 0) : ctype(makeTable(), false, refs) {}
};
BuildInfo getBuildInfo() {
auto dir =
filesystem::getFileDirectory(filesystem::getExecutablePath()) + "/inviwo_buildinfo.ini";
LogInfoCustom("BUILDINFO", dir);
std::ifstream in(dir.c_str(), std::ios::in);
if (!in.is_open()) {
return {};
}
BuildInfo buildInfo;
std::istringstream iss;
iss.imbue(std::locale(iss.getloc(), new IniSeparator()));
enum class Section { Unknown, Date, Hashes };
std::string line;
Section currentSection = Section::Unknown;
while (std::getline(in, line)) {
line = trim(line);
// ignore comment, i.e. line starts with ';'
if (line.empty() || line[0] == ';') {
continue;
}
if (line == "[date]") {
currentSection = Section::Date;
}
else if (line == "[hashes]") {
currentSection = Section::Hashes;
}
else if (line[0] == '[') {
currentSection = Section::Unknown;
}
else {
// read in key value pairs
iss.clear();
iss.str(line);
std::string key;
std::string value;
if (!(iss >> key >> value)) {
// invalid key-value pair, ignore it
continue;
}
switch (currentSection) {
case Section::Date:
{
int valuei = std::stoi(value);
if (key == "year") {
buildInfo.year = valuei;
}
else if (key == "month") {
buildInfo.month = valuei;
}
else if (key == "day") {
buildInfo.day = valuei;
}
else if (key == "hour") {
buildInfo.hour = valuei;
}
else if (key == "minute") {
buildInfo.minute = valuei;
}
else if (key == "second") {
buildInfo.second = valuei;
}
break;
}
case Section::Hashes:
buildInfo.githashes.push_back({ key, value });
break;
case Section::Unknown:
default:
break;
}
}
}
return buildInfo;
}
} // namespace util
} // namespace inviwo
<commit_msg>Core: removed log msg<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/util/buildinfo.h>
#include <inviwo/core/util/assertion.h>
#include <inviwo/core/util/filesystem.h>
#include <fstream>
#include <sstream>
#include <locale>
namespace inviwo {
namespace util {
// helper struct to define arbitrary separator characters in a locale
// usage:
// std::stringstream stream;
// stream.imbue(std::locale(stream.getloc(), new CsvWhitespace));
struct IniSeparator : std::ctype<char> {
static const mask* makeTable() {
// copy table of C locale
static std::vector<mask> m(classic_table(), classic_table() + table_size);
m[' '] &= ~space; // remove space as whitespace
m['='] |= space;
return &m[0];
}
IniSeparator(std::size_t refs = 0) : ctype(makeTable(), false, refs) {}
};
BuildInfo getBuildInfo() {
auto dir =
filesystem::getFileDirectory(filesystem::getExecutablePath()) + "/inviwo_buildinfo.ini";
std::ifstream in(dir.c_str(), std::ios::in);
if (!in.is_open()) {
return {};
}
BuildInfo buildInfo;
std::istringstream iss;
iss.imbue(std::locale(iss.getloc(), new IniSeparator()));
enum class Section { Unknown, Date, Hashes };
std::string line;
Section currentSection = Section::Unknown;
while (std::getline(in, line)) {
line = trim(line);
// ignore comment, i.e. line starts with ';'
if (line.empty() || line[0] == ';') {
continue;
}
if (line == "[date]") {
currentSection = Section::Date;
}
else if (line == "[hashes]") {
currentSection = Section::Hashes;
}
else if (line[0] == '[') {
currentSection = Section::Unknown;
}
else {
// read in key value pairs
iss.clear();
iss.str(line);
std::string key;
std::string value;
if (!(iss >> key >> value)) {
// invalid key-value pair, ignore it
continue;
}
switch (currentSection) {
case Section::Date:
{
int valuei = std::stoi(value);
if (key == "year") {
buildInfo.year = valuei;
}
else if (key == "month") {
buildInfo.month = valuei;
}
else if (key == "day") {
buildInfo.day = valuei;
}
else if (key == "hour") {
buildInfo.hour = valuei;
}
else if (key == "minute") {
buildInfo.minute = valuei;
}
else if (key == "second") {
buildInfo.second = valuei;
}
break;
}
case Section::Hashes:
buildInfo.githashes.push_back({ key, value });
break;
case Section::Unknown:
default:
break;
}
}
}
return buildInfo;
}
} // namespace util
} // namespace inviwo
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016, Nils Asmussen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__
#define __CPU_DTU_ACCEL_SYSCALLSM_HH__
#include "cpu/dtu-accel/accelerator.hh"
#include "sim/system.hh"
class SyscallSM
{
public:
enum Operation
{
// sent by the DTU if the PF handler is not reachable
PAGEFAULT = 0,
// capability creations
CREATE_SRV,
CREATE_SESS,
CREATE_RGATE,
CREATE_SGATE,
CREATE_MGATE,
CREATE_MAP,
CREATE_VPEGRP,
CREATE_VPE,
// capability operations
ACTIVATE,
VPE_CTRL,
VPE_WAIT,
DERIVE_MEM,
OPEN_SESS,
// capability exchange
DELEGATE,
OBTAIN,
EXCHANGE,
REVOKE,
// forwarding
FORWARD_MSG,
FORWARD_MEM,
FORWARD_REPLY,
// misc
NOOP,
};
enum VPEOp
{
VCTRL_INIT,
VCTRL_START,
VCTRL_YIELD,
VCTRL_STOP,
};
enum State
{
SYSC_SEND,
SYSC_WAIT,
SYSC_FETCH,
SYSC_READ_ADDR,
SYSC_ACK,
};
explicit SyscallSM(DtuAccel *_accel)
: accel(_accel), state(), stateChanged(), waitForReply(), fetched(),
replyAddr(), syscallSize() {}
std::string stateName() const;
bool isWaiting() const { return state == SYSC_FETCH; }
bool hasStateChanged() const { return stateChanged; }
void retryFetch() { fetched = false; }
void start(Addr size, bool wait = true, bool resume = false)
{
syscallSize = size;
state = resume ? SYSC_FETCH : SYSC_SEND;
fetched = false;
waitForReply = wait;
}
PacketPtr tick();
bool handleMemResp(PacketPtr pkt);
private:
DtuAccel *accel;
State state;
bool stateChanged;
bool waitForReply;
bool fetched;
Addr replyAddr;
Addr syscallSize;
};
#endif /* __CPU_DTU_ACCEL_SYSCALLSM_HH__ */
<commit_msg>DtuAccel: updated syscalls.<commit_after>/*
* Copyright (c) 2016, Nils Asmussen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__
#define __CPU_DTU_ACCEL_SYSCALLSM_HH__
#include "cpu/dtu-accel/accelerator.hh"
#include "sim/system.hh"
class SyscallSM
{
public:
enum Operation
{
// sent by the DTU if the PF handler is not reachable
PAGEFAULT = 0,
// capability creations
CREATE_SRV,
CREATE_SESS,
CREATE_RGATE,
CREATE_SGATE,
CREATE_MGATE,
CREATE_MAP,
CREATE_VPEGRP,
CREATE_VPE,
// capability operations
ACTIVATE,
SRV_CTRL,
VPE_CTRL,
VPE_WAIT,
DERIVE_MEM,
OPEN_SESS,
// capability exchange
DELEGATE,
OBTAIN,
EXCHANGE,
REVOKE,
// forwarding
FORWARD_MSG,
FORWARD_MEM,
FORWARD_REPLY,
// misc
NOOP,
};
enum VPEOp
{
VCTRL_INIT,
VCTRL_START,
VCTRL_YIELD,
VCTRL_STOP,
};
enum State
{
SYSC_SEND,
SYSC_WAIT,
SYSC_FETCH,
SYSC_READ_ADDR,
SYSC_ACK,
};
explicit SyscallSM(DtuAccel *_accel)
: accel(_accel), state(), stateChanged(), waitForReply(), fetched(),
replyAddr(), syscallSize() {}
std::string stateName() const;
bool isWaiting() const { return state == SYSC_FETCH; }
bool hasStateChanged() const { return stateChanged; }
void retryFetch() { fetched = false; }
void start(Addr size, bool wait = true, bool resume = false)
{
syscallSize = size;
state = resume ? SYSC_FETCH : SYSC_SEND;
fetched = false;
waitForReply = wait;
}
PacketPtr tick();
bool handleMemResp(PacketPtr pkt);
private:
DtuAccel *accel;
State state;
bool stateChanged;
bool waitForReply;
bool fetched;
Addr replyAddr;
Addr syscallSize;
};
#endif /* __CPU_DTU_ACCEL_SYSCALLSM_HH__ */
<|endoftext|>
|
<commit_before>
#include <databaseImplement.h>
using std::cout;
using std::cin;
using std::endl;
void database:: add(itemInfo stuff)
{
map<string, itemInfo> :: iterator it;
static int i=0;
char c;
for (it=mymap.begin(); it!=mymap.end(); ++it)
{
if(it->second.rfid==stuff.rfid)
{
cout<<"RFID Exists do u want to rem-ove "<<it->second.getname()<<"from the list (Y OR N)";
cin>>c;
switch(c)
{
case 'Y':
it->second.Timerupdate();
mymap.erase(it);
break;
case 'N':
cout<<"try another rfid";
cin>>stuff.rfid;
add(stuff);
break;
}
}
}
//mymap.insert ( std::pair<int,itemInfo> (i,stuff) );
mymap[stuff.rfid]=stuff;
cout << "data successfully added!" <<endl;
}
void database :: find(string rfid)
{
map<string, itemInfo> :: iterator it;
for (it=mymap.begin(); it!=mymap.end(); ++it)
{
if(it->second.rfid==rfid)
it->second.statusupdate();
}
}
void database :: update(string rfid, float weight)
{
map<string, itemInfo> :: iterator it;
for (it=mymap.begin(); it!=mymap.end(); ++it)
{
if(it->second.rfid==rfid)
it->second.weightupdate(weight);
}
}
<commit_msg>Update databaseImplement.cpp<commit_after>
#include <databaseImplement.h>
using std::cout;
using std::cin;
using std::endl;
void database:: add(itemInfo stuff)
{
fstream myfile;
map<string, itemInfo> :: iterator it;
static int i=0;
char c;
for (it=mymap.begin(); it!=mymap.end(); ++it)
{
if(it->second.rfid==stuff.rfid)
{
cout<<"RFID Exists do u want to rem-ove "<<it->second.getname()<<"from the list (Y OR N)";
cin>>c;
switch(c)
{
case 'Y':
it->second.Timerupdate();
mymap.erase(it);
break;
case 'N':
cout<<"try another rfid";
cin>>stuff.rfid;
add(stuff);
break;
}
}
}
//mymap.insert ( std::pair<int,itemInfo> (i,stuff) );
mymap[stuff.rfid]=stuff;
fout.open("filename.txt", ios::app)
for (it=mymap.begin(); it!=mymap.end(); ++it)
{
fout<<it->second.name<<" "<<it->second.weight<<" "<<it->second.status<<" " <<it->second.rfid<<endl;
}
fout.close();
cout << "data successfully added!" <<endl;
}
void database :: find(string rfid)
{
map<string, itemInfo> :: iterator it;
for (it=mymap.begin(); it!=mymap.end(); ++it)
{
if(it->second.rfid==rfid)
it->second.statusupdate();
}
}
void database :: update(string rfid, float weight)
{
map<string, itemInfo> :: iterator it;
for (it=mymap.begin(); it!=mymap.end(); ++it)
{
if(it->second.rfid==rfid)
it->second.weightupdate(weight);
}
}
<|endoftext|>
|
<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "vvlog.h"
#ifdef _WIN32
#include <Windows.h>
#endif
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <iostream>
using virvo::logging::Output;
using virvo::logging::Stream;
using virvo::logging::ErrorStream;
class AutoOutput
{
Output* func;
public:
AutoOutput() : func(0) {}
~AutoOutput() { delete func; }
Output* operator ->() const { return func; }
void reset(Output* newFunc) {
delete func;
func = newFunc;
}
private:
typedef Output* AutoOutput::* bool_type;
public:
operator bool_type() const {
return func ? &AutoOutput::func : 0;
}
};
static int GetLogLevelFromEnv()
{
#ifdef _MSC_VER
#pragma warning(suppress : 4996)
#endif
if (char* env = std::getenv("VV_DEBUG"))
return std::atoi(env);
return 0;
}
// The current logging level
static int LogLevel = GetLogLevelFromEnv();
// The current logging destination
static AutoOutput LogOutput;
static void PrintMessage(int level, std::string const& str)
{
if (LogOutput)
LogOutput->message(level, str);
else
std::clog << str << std::endl;
}
int virvo::logging::getLevel()
{
return LogLevel;
}
int virvo::logging::setLevel(int level)
{
LogLevel = level;
return 0;
}
int virvo::logging::isActive(int level)
{
return level <= LogLevel;
}
int virvo::logging::setOutput(Output* func)
{
LogOutput.reset(func);
return 0;
}
Stream::Stream(int level, char const* /*file*/, int /*line*/)
: level_(level)
{
}
Stream::~Stream()
{
PrintMessage(level_, stream_.str());
}
static std::string FormatLastError()
{
#ifdef _WIN32
LPSTR buffer = 0;
// Retrieve the system error message for the last-error code
FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPSTR>(&buffer),
0,
NULL );
std::string result = buffer;
LocalFree(buffer);
return result;
#else
return std::strerror(errno);
#endif
}
ErrorStream::ErrorStream(int /*level*/, char const* /*file*/, int /*line*/)
{
}
ErrorStream::~ErrorStream()
{
stream_ << ": " << FormatLastError();
PrintMessage(-1, stream_.str());
}
<commit_msg>compile fix: it's called windows.h on mingw-cross<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "vvlog.h"
#ifdef _WIN32
#include <windows.h>
#endif
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <iostream>
using virvo::logging::Output;
using virvo::logging::Stream;
using virvo::logging::ErrorStream;
class AutoOutput
{
Output* func;
public:
AutoOutput() : func(0) {}
~AutoOutput() { delete func; }
Output* operator ->() const { return func; }
void reset(Output* newFunc) {
delete func;
func = newFunc;
}
private:
typedef Output* AutoOutput::* bool_type;
public:
operator bool_type() const {
return func ? &AutoOutput::func : 0;
}
};
static int GetLogLevelFromEnv()
{
#ifdef _MSC_VER
#pragma warning(suppress : 4996)
#endif
if (char* env = std::getenv("VV_DEBUG"))
return std::atoi(env);
return 0;
}
// The current logging level
static int LogLevel = GetLogLevelFromEnv();
// The current logging destination
static AutoOutput LogOutput;
static void PrintMessage(int level, std::string const& str)
{
if (LogOutput)
LogOutput->message(level, str);
else
std::clog << str << std::endl;
}
int virvo::logging::getLevel()
{
return LogLevel;
}
int virvo::logging::setLevel(int level)
{
LogLevel = level;
return 0;
}
int virvo::logging::isActive(int level)
{
return level <= LogLevel;
}
int virvo::logging::setOutput(Output* func)
{
LogOutput.reset(func);
return 0;
}
Stream::Stream(int level, char const* /*file*/, int /*line*/)
: level_(level)
{
}
Stream::~Stream()
{
PrintMessage(level_, stream_.str());
}
static std::string FormatLastError()
{
#ifdef _WIN32
LPSTR buffer = 0;
// Retrieve the system error message for the last-error code
FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPSTR>(&buffer),
0,
NULL );
std::string result = buffer;
LocalFree(buffer);
return result;
#else
return std::strerror(errno);
#endif
}
ErrorStream::ErrorStream(int /*level*/, char const* /*file*/, int /*line*/)
{
}
ErrorStream::~ErrorStream()
{
stream_ << ": " << FormatLastError();
PrintMessage(-1, stream_.str());
}
<|endoftext|>
|
<commit_before>/*!
*
* Copyright (C) 2012 Jolla Ltd.
*
* Contact: Mohammed Hassan <mohammed.hassan@jollamobile.com>
*
* 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
*/
#include "grilodatasource.h"
#include "grilomedia.h"
#include "grilomodel.h"
#include "griloregistry.h"
#include <QDebug>
#include <QTimerEvent>
static void fill_key_id(gpointer data, gpointer user_data) {
QVariantList *varList = static_cast<QVariantList *>(user_data);
varList->append(GriloDataSource::MetadataKeys(GRLPOINTER_TO_KEYID(data)));
}
GriloDataSource::GriloDataSource(QObject *parent) :
QObject(parent),
m_opId(0),
m_registry(0),
m_count(0),
m_skip(0),
m_insertIndex(0),
m_updateScheduled(false) {
m_metadataKeys << Title;
m_typeFilter << None;
}
GriloDataSource::~GriloDataSource() {
cancelRefresh();
m_models.clear();
}
const QList<GriloMedia *> *GriloDataSource::media() const {
return &m_media;
}
void GriloDataSource::addModel(GriloModel *model) {
if (m_models.indexOf(model) == -1) {
m_models << model;
}
}
void GriloDataSource::removeModel(GriloModel *model) {
if (int index = m_models.indexOf(model) != -1) {
m_models.removeAt(index);
}
}
void GriloDataSource::prefill(GriloModel *model) {
if (m_media.isEmpty()) {
return;
}
model->beginInsertRows(QModelIndex(), 0, m_media.size() - 1);
model->endInsertRows();
emit model->countChanged();
}
void GriloDataSource::addMedia(GrlMedia *media) {
GriloMedia *wrappedMedia = 0;
if (m_insertIndex < m_media.count()) {
wrappedMedia = m_hash.value(QString::fromUtf8(grl_media_get_id(media)), 0);
}
if (wrappedMedia) {
// If the media was already queried by a previous fetch update its position and refresh
// the data instead of creating another item.
bool dataChanged = false;
int index = m_media.indexOf(wrappedMedia);
if (index == m_insertIndex) {
dataChanged = true;
} else if (index != -1) {
dataChanged = true;
foreach (GriloModel *model, m_models) {
model->beginMoveRows(QModelIndex(), index, index, QModelIndex(), m_insertIndex);
}
m_media.move(index, m_insertIndex);
foreach (GriloModel *model, m_models) {
model->endMoveRows();
}
}
if (dataChanged) {
wrappedMedia->setMedia(media);
foreach (GriloModel *model, m_models) {
QModelIndex modelIndex = model->index(m_insertIndex, 0);
model->dataChanged(modelIndex, modelIndex);
}
++m_insertIndex;
return;
}
}
wrappedMedia = new GriloMedia(media);
foreach (GriloModel *model, m_models) {
model->beginInsertRows(QModelIndex(), m_insertIndex, m_insertIndex);
}
m_media.insert(m_insertIndex, wrappedMedia);
++m_insertIndex;
QString id = wrappedMedia->id();
if (!id.isEmpty()) {
m_hash.insert(id, wrappedMedia);
}
foreach (GriloModel *model, m_models) {
model->endInsertRows();
emit model->countChanged();
}
}
void GriloDataSource::removeMedia(GrlMedia *media) {
QString id = QString::fromUtf8(grl_media_get_id(media));
if (id.isEmpty() || !m_hash.contains(id)) {
// We really cannot do much.
return;
}
GriloMedia *wrapper = m_hash[id];
int index = m_media.indexOf(wrapper);
if (index < m_insertIndex) {
--m_insertIndex;
}
// remove from models:
foreach (GriloModel *model, m_models) {
model->beginRemoveRows(QModelIndex(), index, index);
}
// remove from hash
m_hash.take(id);
// remove from list
m_media.takeAt(index);
// destroy
wrapper->deleteLater();
foreach (GriloModel *model, m_models) {
model->endRemoveRows();
}
}
void GriloDataSource::clearMedia() {
if (m_media.isEmpty()) {
return;
}
int size = m_media.size();
foreach (GriloModel *model, m_models) {
model->beginRemoveRows(QModelIndex(), 0, size - 1);
}
qDeleteAll(m_media);
m_media.clear();
m_hash.clear();
foreach (GriloModel *model, m_models) {
model->endRemoveRows();
emit model->countChanged();
}
}
GriloRegistry *GriloDataSource::registry() const {
return m_registry;
}
void GriloDataSource::setRegistry(GriloRegistry *registry) {
// Registry change is not allowed for now.
if (!m_registry && registry != m_registry) {
m_registry = registry;
QObject::connect(m_registry, SIGNAL(availableSourcesChanged()),
this, SLOT(availableSourcesChanged()));
QObject::connect(m_registry, SIGNAL(contentChanged(QString,GrlSourceChangeType,GPtrArray*)),
this, SLOT(contentChanged(QString,GrlSourceChangeType,GPtrArray*)));
emit registryChanged();
}
}
int GriloDataSource::count() const {
return m_count;
}
void GriloDataSource::setCount(int count) {
if (m_count != count) {
m_count = count;
emit countChanged();
}
}
int GriloDataSource::skip() const {
return m_skip;
}
void GriloDataSource::setSkip(int skip) {
if (m_skip != skip) {
m_skip = skip;
emit skipChanged();
}
}
QVariantList GriloDataSource::metadataKeys() const {
return m_metadataKeys;
}
void GriloDataSource::setMetadataKeys(const QVariantList& keys) {
if (m_metadataKeys != keys) {
m_metadataKeys = keys;
emit metadataKeysChanged();
}
}
QVariantList GriloDataSource::typeFilter() const {
return m_typeFilter;
}
void GriloDataSource::setTypeFilter(const QVariantList& filter) {
if (m_typeFilter != filter) {
m_typeFilter = filter;
emit typeFilterChanged();
}
}
GrlOperationOptions *GriloDataSource::operationOptions(GrlSource *src, const OperationType& type) {
GrlCaps *caps = NULL;
if (src) {
caps = grl_source_get_caps(src, (GrlSupportedOps)type);
}
GrlOperationOptions *options = grl_operation_options_new(caps);
grl_operation_options_set_flags(options, GRL_RESOLVE_IDLE_RELAY); // TODO: hardcoded
grl_operation_options_set_skip(options, m_skip);
if (m_count != 0) {
grl_operation_options_set_count(options, m_count);
}
int typeFilter = 0;
foreach (const QVariant& var, m_typeFilter) {
if (var.canConvert<int>()) {
typeFilter |= var.toInt();
}
}
grl_operation_options_set_type_filter(options, (GrlTypeFilter)typeFilter);
return options;
}
GList *GriloDataSource::keysAsList() {
// TODO: Check why using grl_metadata_key_list_new() produces a symbol error.
GList *keys = NULL;
foreach (const QVariant& var, m_metadataKeys) {
if (var.canConvert<int>()) {
keys = g_list_append(keys, GRLKEYID_TO_POINTER(var.toInt()));
}
}
return keys;
}
void GriloDataSource::cancelRefresh() {
if (m_opId != 0) {
grl_operation_cancel(m_opId);
m_opId = 0;
}
m_insertIndex = 0;
m_updateScheduled = false;
m_updateTimer.stop();
}
void GriloDataSource::grilo_source_result_cb(GrlSource *source, guint op_id,
GrlMedia *media, guint remaining,
gpointer user_data, const GError *error) {
Q_UNUSED(source);
// We get an error if the operation has been canceled:
if (error) {
if (error->domain != GRL_CORE_ERROR || error->code != GRL_CORE_ERROR_OPERATION_CANCELLED) {
// TODO: error reporting?
qCritical() << "Operation failed" << error->message;
}
}
GriloDataSource *that = static_cast<GriloDataSource *>(user_data);
if (that->m_opId != op_id) {
qWarning() << "Got results belonging to an unknown browse id";
if (media) {
g_object_unref(media);
}
return;
}
if (media) {
that->addMedia(media);
}
if (remaining == 0) {
emit that->finished();
that->m_opId = 0;
if (that->m_updateScheduled) {
that->m_updateTimer.start(100, that);
}
// If there are items from a previous fetch still remaining remove them.
if (that->m_insertIndex < that->m_media.count()) {
foreach (GriloModel *model, that->m_models) {
model->beginRemoveRows(QModelIndex(), that->m_insertIndex, that->m_media.count() - 1);
}
while (that->m_media.count() > that->m_insertIndex) {
GriloMedia *media = that->m_media.takeLast();
that->m_hash.remove(media->id());
delete media;
}
foreach (GriloModel *model, that->m_models) {
model->endRemoveRows();
emit model->countChanged();
}
}
}
}
void GriloDataSource::contentChanged(const QString &source, GrlSourceChangeType change_type,
GPtrArray *changed_media)
{
Q_UNUSED(source);
Q_UNUSED(change_type);
Q_UNUSED(changed_media);
}
void GriloDataSource::updateContent(GrlSourceChangeType change_type, GPtrArray *changed_media)
{
switch (change_type) {
case GRL_CONTENT_CHANGED:
case GRL_CONTENT_ADDED:
if (!m_updateScheduled) {
m_updateScheduled = true;
if (m_opId == 0) {
m_updateTimer.start(100, this);
}
}
break;
case GRL_CONTENT_REMOVED:
for (uint i = 0; i < changed_media->len; ++i) {
removeMedia((GrlMedia *)g_ptr_array_index(changed_media, i));
}
break;
default:
break;
}
}
QVariantList GriloDataSource::listToVariantList(const GList *keys) const {
QVariantList varList;
g_list_foreach(const_cast<GList *>(keys), fill_key_id, &varList);
return varList;
}
void GriloDataSource::timerEvent(QTimerEvent *event) {
if (event->timerId() == m_updateTimer.timerId()) {
m_updateTimer.stop();
emit contentUpdated();
}
}
<commit_msg>[datasource] Corrected emitting countChanged when removing rows<commit_after>/*!
*
* Copyright (C) 2012 Jolla Ltd.
*
* Contact: Mohammed Hassan <mohammed.hassan@jollamobile.com>
*
* 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
*/
#include "grilodatasource.h"
#include "grilomedia.h"
#include "grilomodel.h"
#include "griloregistry.h"
#include <QDebug>
#include <QTimerEvent>
static void fill_key_id(gpointer data, gpointer user_data) {
QVariantList *varList = static_cast<QVariantList *>(user_data);
varList->append(GriloDataSource::MetadataKeys(GRLPOINTER_TO_KEYID(data)));
}
GriloDataSource::GriloDataSource(QObject *parent) :
QObject(parent),
m_opId(0),
m_registry(0),
m_count(0),
m_skip(0),
m_insertIndex(0),
m_updateScheduled(false) {
m_metadataKeys << Title;
m_typeFilter << None;
}
GriloDataSource::~GriloDataSource() {
cancelRefresh();
m_models.clear();
}
const QList<GriloMedia *> *GriloDataSource::media() const {
return &m_media;
}
void GriloDataSource::addModel(GriloModel *model) {
if (m_models.indexOf(model) == -1) {
m_models << model;
}
}
void GriloDataSource::removeModel(GriloModel *model) {
if (int index = m_models.indexOf(model) != -1) {
m_models.removeAt(index);
}
}
void GriloDataSource::prefill(GriloModel *model) {
if (m_media.isEmpty()) {
return;
}
model->beginInsertRows(QModelIndex(), 0, m_media.size() - 1);
model->endInsertRows();
emit model->countChanged();
}
void GriloDataSource::addMedia(GrlMedia *media) {
GriloMedia *wrappedMedia = 0;
if (m_insertIndex < m_media.count()) {
wrappedMedia = m_hash.value(QString::fromUtf8(grl_media_get_id(media)), 0);
}
if (wrappedMedia) {
// If the media was already queried by a previous fetch update its position and refresh
// the data instead of creating another item.
bool dataChanged = false;
int index = m_media.indexOf(wrappedMedia);
if (index == m_insertIndex) {
dataChanged = true;
} else if (index != -1) {
dataChanged = true;
foreach (GriloModel *model, m_models) {
model->beginMoveRows(QModelIndex(), index, index, QModelIndex(), m_insertIndex);
}
m_media.move(index, m_insertIndex);
foreach (GriloModel *model, m_models) {
model->endMoveRows();
}
}
if (dataChanged) {
wrappedMedia->setMedia(media);
foreach (GriloModel *model, m_models) {
QModelIndex modelIndex = model->index(m_insertIndex, 0);
model->dataChanged(modelIndex, modelIndex);
}
++m_insertIndex;
return;
}
}
wrappedMedia = new GriloMedia(media);
foreach (GriloModel *model, m_models) {
model->beginInsertRows(QModelIndex(), m_insertIndex, m_insertIndex);
}
m_media.insert(m_insertIndex, wrappedMedia);
++m_insertIndex;
QString id = wrappedMedia->id();
if (!id.isEmpty()) {
m_hash.insert(id, wrappedMedia);
}
foreach (GriloModel *model, m_models) {
model->endInsertRows();
emit model->countChanged();
}
}
void GriloDataSource::removeMedia(GrlMedia *media) {
QString id = QString::fromUtf8(grl_media_get_id(media));
if (id.isEmpty() || !m_hash.contains(id)) {
// We really cannot do much.
return;
}
GriloMedia *wrapper = m_hash[id];
int index = m_media.indexOf(wrapper);
if (index < m_insertIndex) {
--m_insertIndex;
}
// remove from models:
foreach (GriloModel *model, m_models) {
model->beginRemoveRows(QModelIndex(), index, index);
}
// remove from hash
m_hash.take(id);
// remove from list
m_media.takeAt(index);
// destroy
wrapper->deleteLater();
foreach (GriloModel *model, m_models) {
model->endRemoveRows();
emit model->countChanged();
}
}
void GriloDataSource::clearMedia() {
if (m_media.isEmpty()) {
return;
}
int size = m_media.size();
foreach (GriloModel *model, m_models) {
model->beginRemoveRows(QModelIndex(), 0, size - 1);
}
qDeleteAll(m_media);
m_media.clear();
m_hash.clear();
foreach (GriloModel *model, m_models) {
model->endRemoveRows();
emit model->countChanged();
}
}
GriloRegistry *GriloDataSource::registry() const {
return m_registry;
}
void GriloDataSource::setRegistry(GriloRegistry *registry) {
// Registry change is not allowed for now.
if (!m_registry && registry != m_registry) {
m_registry = registry;
QObject::connect(m_registry, SIGNAL(availableSourcesChanged()),
this, SLOT(availableSourcesChanged()));
QObject::connect(m_registry, SIGNAL(contentChanged(QString,GrlSourceChangeType,GPtrArray*)),
this, SLOT(contentChanged(QString,GrlSourceChangeType,GPtrArray*)));
emit registryChanged();
}
}
int GriloDataSource::count() const {
return m_count;
}
void GriloDataSource::setCount(int count) {
if (m_count != count) {
m_count = count;
emit countChanged();
}
}
int GriloDataSource::skip() const {
return m_skip;
}
void GriloDataSource::setSkip(int skip) {
if (m_skip != skip) {
m_skip = skip;
emit skipChanged();
}
}
QVariantList GriloDataSource::metadataKeys() const {
return m_metadataKeys;
}
void GriloDataSource::setMetadataKeys(const QVariantList& keys) {
if (m_metadataKeys != keys) {
m_metadataKeys = keys;
emit metadataKeysChanged();
}
}
QVariantList GriloDataSource::typeFilter() const {
return m_typeFilter;
}
void GriloDataSource::setTypeFilter(const QVariantList& filter) {
if (m_typeFilter != filter) {
m_typeFilter = filter;
emit typeFilterChanged();
}
}
GrlOperationOptions *GriloDataSource::operationOptions(GrlSource *src, const OperationType& type) {
GrlCaps *caps = NULL;
if (src) {
caps = grl_source_get_caps(src, (GrlSupportedOps)type);
}
GrlOperationOptions *options = grl_operation_options_new(caps);
grl_operation_options_set_flags(options, GRL_RESOLVE_IDLE_RELAY); // TODO: hardcoded
grl_operation_options_set_skip(options, m_skip);
if (m_count != 0) {
grl_operation_options_set_count(options, m_count);
}
int typeFilter = 0;
foreach (const QVariant& var, m_typeFilter) {
if (var.canConvert<int>()) {
typeFilter |= var.toInt();
}
}
grl_operation_options_set_type_filter(options, (GrlTypeFilter)typeFilter);
return options;
}
GList *GriloDataSource::keysAsList() {
// TODO: Check why using grl_metadata_key_list_new() produces a symbol error.
GList *keys = NULL;
foreach (const QVariant& var, m_metadataKeys) {
if (var.canConvert<int>()) {
keys = g_list_append(keys, GRLKEYID_TO_POINTER(var.toInt()));
}
}
return keys;
}
void GriloDataSource::cancelRefresh() {
if (m_opId != 0) {
grl_operation_cancel(m_opId);
m_opId = 0;
}
m_insertIndex = 0;
m_updateScheduled = false;
m_updateTimer.stop();
}
void GriloDataSource::grilo_source_result_cb(GrlSource *source, guint op_id,
GrlMedia *media, guint remaining,
gpointer user_data, const GError *error) {
Q_UNUSED(source);
// We get an error if the operation has been canceled:
if (error) {
if (error->domain != GRL_CORE_ERROR || error->code != GRL_CORE_ERROR_OPERATION_CANCELLED) {
// TODO: error reporting?
qCritical() << "Operation failed" << error->message;
}
}
GriloDataSource *that = static_cast<GriloDataSource *>(user_data);
if (that->m_opId != op_id) {
qWarning() << "Got results belonging to an unknown browse id";
if (media) {
g_object_unref(media);
}
return;
}
if (media) {
that->addMedia(media);
}
if (remaining == 0) {
emit that->finished();
that->m_opId = 0;
if (that->m_updateScheduled) {
that->m_updateTimer.start(100, that);
}
// If there are items from a previous fetch still remaining remove them.
if (that->m_insertIndex < that->m_media.count()) {
foreach (GriloModel *model, that->m_models) {
model->beginRemoveRows(QModelIndex(), that->m_insertIndex, that->m_media.count() - 1);
}
while (that->m_media.count() > that->m_insertIndex) {
GriloMedia *media = that->m_media.takeLast();
that->m_hash.remove(media->id());
delete media;
}
foreach (GriloModel *model, that->m_models) {
model->endRemoveRows();
emit model->countChanged();
}
}
}
}
void GriloDataSource::contentChanged(const QString &source, GrlSourceChangeType change_type,
GPtrArray *changed_media)
{
Q_UNUSED(source);
Q_UNUSED(change_type);
Q_UNUSED(changed_media);
}
void GriloDataSource::updateContent(GrlSourceChangeType change_type, GPtrArray *changed_media)
{
switch (change_type) {
case GRL_CONTENT_CHANGED:
case GRL_CONTENT_ADDED:
if (!m_updateScheduled) {
m_updateScheduled = true;
if (m_opId == 0) {
m_updateTimer.start(100, this);
}
}
break;
case GRL_CONTENT_REMOVED:
for (uint i = 0; i < changed_media->len; ++i) {
removeMedia((GrlMedia *)g_ptr_array_index(changed_media, i));
}
break;
default:
break;
}
}
QVariantList GriloDataSource::listToVariantList(const GList *keys) const {
QVariantList varList;
g_list_foreach(const_cast<GList *>(keys), fill_key_id, &varList);
return varList;
}
void GriloDataSource::timerEvent(QTimerEvent *event) {
if (event->timerId() == m_updateTimer.timerId()) {
m_updateTimer.stop();
emit contentUpdated();
}
}
<|endoftext|>
|
<commit_before>#include "dynet/hsm-builder.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include "dynet/param-init.h"
using namespace std;
namespace dynet {
Cluster::Cluster() {}
void Cluster::new_graph(ComputationGraph& cg) {
for (Cluster* child : children) {
child->new_graph(cg);
}
bias.pg = NULL;
weights.pg = NULL;
}
Cluster* Cluster::add_child(unsigned sym) {
auto it = word2ind.find(sym);
unsigned i;
if (it == word2ind.end()) {
Cluster* c = new Cluster();
c->rep_dim = rep_dim;
c->path = path;
c->path.push_back(sym);
i = children.size();
word2ind.insert(make_pair(sym, i));
children.push_back(c);
}
else {
i = it->second;
}
return children[i];
}
void Cluster::add_word(unsigned word) {
word2ind[word] = terminals.size();
terminals.push_back(word);
}
void Cluster::initialize(unsigned rep_dim, ParameterCollection& model) {
this->rep_dim = rep_dim;
initialize(model);
}
void Cluster::initialize(ParameterCollection& model) {
output_size = (children.size() > 0) ? children.size() : terminals.size();
if (output_size == 1) {
}
else if (output_size == 2) {
p_weights = model.add_parameters({1, rep_dim});
p_bias = model.add_parameters({1}, ParameterInitConst(0.f));
}
else {
p_weights = model.add_parameters({output_size, rep_dim});
p_bias = model.add_parameters({output_size}, ParameterInitConst(0.f));
}
for (Cluster* child : children) {
child->initialize(model);
}
}
unsigned Cluster::num_children() const {
return children.size();
}
const Cluster* Cluster::get_child(unsigned i) const {
return children[i];
}
const vector<unsigned>& Cluster::get_path() const { return path; }
unsigned Cluster::get_index(unsigned word) const { return word2ind.find(word)->second; }
unsigned Cluster::get_word(unsigned index) const { return terminals[index]; }
Expression Cluster::predict(Expression h, ComputationGraph& cg) const {
if (output_size == 1) {
return input(cg, 1.0f);
}
else {
Expression b = get_bias(cg);
Expression w = get_weights(cg);
return affine_transform({b, w, h});
}
}
Expression Cluster::neg_log_softmax(Expression h, unsigned r, ComputationGraph& cg) const {
if (output_size == 1) {
return input(cg, 0.0f);
}
else if (output_size == 2) {
Expression p = logistic(predict(h, cg));
if (r == 1) {
p = 1 - p;
}
return -log(p);
}
else {
Expression dist = predict(h, cg);
return pickneglogsoftmax(dist, r);
}
}
unsigned Cluster::sample(Expression h, ComputationGraph& cg) const {
if (output_size == 1) {
return 0;
}
else if (output_size == 2) {
Expression prob0_expr = logistic(predict(h, cg));
double prob0 = as_scalar(cg.incremental_forward(prob0_expr));
double p = rand01();
if (p < prob0) {
return 0;
}
else {
return 1;
}
}
else {
Expression dist_expr = softmax(predict(h, cg));
vector<float> dist = as_vector(cg.incremental_forward(dist_expr));
unsigned c = 0;
double p = rand01();
for (; c < dist.size(); ++c) {
p -= dist[c];
if (p < 0.0) { break; }
}
if (c == dist.size()) {
--c;
}
return c;
}
}
Expression Cluster::get_weights(ComputationGraph& cg) const {
if (weights.pg != &cg) {
weights = parameter(cg, p_weights);
}
return weights;
}
Expression Cluster::get_bias(ComputationGraph& cg) const {
if (bias.pg != &cg) {
bias = parameter(cg, p_bias);
}
return bias;
}
string Cluster::toString() const {
stringstream ss;
for (unsigned i = 0; i < path.size(); ++i) {
if (i != 0) {
ss << " ";
}
ss << path[i];
}
return ss.str();
}
HierarchicalSoftmaxBuilder::HierarchicalSoftmaxBuilder(unsigned rep_dim,
const std::string& cluster_file,
Dict& word_dict,
ParameterCollection& model) {
local_model = model.add_subcollection("hsm-builder");
root = read_cluster_file(cluster_file, word_dict);
root->initialize(rep_dim, local_model);
}
HierarchicalSoftmaxBuilder::~HierarchicalSoftmaxBuilder() {
}
void HierarchicalSoftmaxBuilder::initialize(ParameterCollection& model) {
root->initialize(model);
}
void HierarchicalSoftmaxBuilder::new_graph(ComputationGraph& cg) {
pcg = &cg;
root->new_graph(cg);
}
Expression HierarchicalSoftmaxBuilder::neg_log_softmax(const Expression& rep, unsigned wordidx) {
if(pcg != NULL)
DYNET_INVALID_ARG("In HierarchicalSoftmaxBuilder, you must call new_graph before calling neg_log_softmax!");
Cluster* path = widx2path[wordidx];
unsigned i = 0;
const Cluster* node = root;
DYNET_ASSERT(root != NULL, "Null root in HierarchicalSoftmaxBuilder");
vector<Expression> log_probs;
Expression lp;
unsigned r;
while (node->num_children() > 0) {
r = node->get_index(path->get_path()[i]);
lp = node->neg_log_softmax(rep, r, *pcg);
log_probs.push_back(lp);
node = node->get_child(r);
DYNET_ASSERT(node != NULL, "Null node in HierarchicalSoftmaxBuilder");
i += 1;
}
r = path->get_index(wordidx);
lp = node->neg_log_softmax(rep, r, *pcg);
log_probs.push_back(lp);
return sum(log_probs);
}
unsigned HierarchicalSoftmaxBuilder::sample(const Expression& rep) {
if(pcg != NULL)
DYNET_INVALID_ARG("In HierarchicalSoftmaxBuilder, you must call new_graph before calling sample!");
const Cluster* node = root;
vector<float> dist;
unsigned c;
while (node->num_children() > 0) {
c = node->sample(rep, *pcg);
node = node->get_child(c);
}
c = node->sample(rep, *pcg);
return node->get_word(c);
}
Expression HierarchicalSoftmaxBuilder::full_log_distribution(const Expression& rep) {
DYNET_RUNTIME_ERR("full_distribution not implemented for HierarchicalSoftmaxBuilder");
return dynet::Expression();
}
inline bool is_ws(char x) { return (x == ' ' || x == '\t'); }
inline bool not_ws(char x) { return (x != ' ' && x != '\t'); }
Cluster* HierarchicalSoftmaxBuilder::read_cluster_file(const std::string& cluster_file, Dict& word_dict) {
cerr << "Reading clusters from " << cluster_file << " ...\n";
ifstream in(cluster_file);
if(!in)
DYNET_INVALID_ARG("HierarchicalSoftmaxBuilder couldn't read clusters from " << cluster_file);
int wc = 0;
string line;
vector<unsigned> path;
Cluster* root = new Cluster();
while(getline(in, line)) {
path.clear();
++wc;
const unsigned len = line.size();
unsigned startp = 0;
unsigned endp = 0;
while (startp < len) {
while (is_ws(line[startp]) && startp < len) { ++startp; }
endp = startp;
while (not_ws(line[endp]) && endp < len) { ++endp; }
string symbol = line.substr(startp, endp - startp);
path.push_back(path_symbols.convert(symbol));
if (line[endp] == ' ') {
startp = endp + 1;
continue;
}
else {
break;
}
}
Cluster* node = root;
for (unsigned symbol : path) {
node = node->add_child(symbol);
}
unsigned startw = endp;
while (is_ws(line[startw]) && startw < len) { ++startw; }
unsigned endw = startw;
while (not_ws(line[endw]) && endw < len) { ++endw; }
if(endp <= startp || startw <= endp || endw <= startw)
DYNET_INVALID_ARG("File formatting error in HierarchicalSoftmaxBuilder");
string word = line.substr(startw, endw - startw);
unsigned widx = word_dict.convert(word);
node->add_word(widx);
if (widx2path.size() <= widx) {
widx2path.resize(widx + 1);
}
widx2path[widx] = node;
}
cerr << "Done reading clusters.\n";
return root;
}
} // namespace dynet
<commit_msg>In hsm-builder.cc: (1) fix the bug on checking whether new_graph is called; (2) pass the rep_dim explicitly to the cluster children nodes<commit_after>#include "dynet/hsm-builder.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include "dynet/param-init.h"
using namespace std;
namespace dynet {
Cluster::Cluster() {}
void Cluster::new_graph(ComputationGraph& cg) {
for (Cluster* child : children) {
child->new_graph(cg);
}
bias.pg = NULL;
weights.pg = NULL;
}
Cluster* Cluster::add_child(unsigned sym) {
auto it = word2ind.find(sym);
unsigned i;
if (it == word2ind.end()) {
Cluster* c = new Cluster();
c->rep_dim = rep_dim;
c->path = path;
c->path.push_back(sym);
i = children.size();
word2ind.insert(make_pair(sym, i));
children.push_back(c);
}
else {
i = it->second;
}
return children[i];
}
void Cluster::add_word(unsigned word) {
word2ind[word] = terminals.size();
terminals.push_back(word);
}
void Cluster::initialize(unsigned rep_dim, ParameterCollection& model) {
this->rep_dim = rep_dim;
initialize(model);
}
void Cluster::initialize(ParameterCollection& model) {
output_size = (children.size() > 0) ? children.size() : terminals.size();
if (output_size == 1) {
}
else if (output_size == 2) {
p_weights = model.add_parameters({1, rep_dim});
p_bias = model.add_parameters({1}, ParameterInitConst(0.f));
}
else {
p_weights = model.add_parameters({output_size, rep_dim});
p_bias = model.add_parameters({output_size}, ParameterInitConst(0.f));
}
for (Cluster* child : children) {
child->rep_dim = this->rep_dim;
child->initialize(model);
}
}
unsigned Cluster::num_children() const {
return children.size();
}
const Cluster* Cluster::get_child(unsigned i) const {
return children[i];
}
const vector<unsigned>& Cluster::get_path() const { return path; }
unsigned Cluster::get_index(unsigned word) const { return word2ind.find(word)->second; }
unsigned Cluster::get_word(unsigned index) const { return terminals[index]; }
Expression Cluster::predict(Expression h, ComputationGraph& cg) const {
if (output_size == 1) {
return input(cg, 1.0f);
} else {
Expression b = get_bias(cg);
Expression w = get_weights(cg);
return affine_transform({b, w, h});
}
}
Expression Cluster::neg_log_softmax(Expression h, unsigned r, ComputationGraph& cg) const {
if (output_size == 1) {
return input(cg, 0.0f);
}
else if (output_size == 2) {
Expression p = logistic(predict(h, cg));
if (r == 1) {
p = 1 - p;
}
return -log(p);
}
else {
Expression dist = predict(h, cg);
return pickneglogsoftmax(dist, r);
}
}
unsigned Cluster::sample(Expression h, ComputationGraph& cg) const {
if (output_size == 1) {
return 0;
}
else if (output_size == 2) {
Expression prob0_expr = logistic(predict(h, cg));
double prob0 = as_scalar(cg.incremental_forward(prob0_expr));
double p = rand01();
if (p < prob0) {
return 0;
}
else {
return 1;
}
}
else {
Expression dist_expr = softmax(predict(h, cg));
vector<float> dist = as_vector(cg.incremental_forward(dist_expr));
unsigned c = 0;
double p = rand01();
for (; c < dist.size(); ++c) {
p -= dist[c];
if (p < 0.0) { break; }
}
if (c == dist.size()) {
--c;
}
return c;
}
}
Expression Cluster::get_weights(ComputationGraph& cg) const {
if (weights.pg != &cg) {
weights = parameter(cg, p_weights);
}
return weights;
}
Expression Cluster::get_bias(ComputationGraph& cg) const {
if (bias.pg != &cg) {
bias = parameter(cg, p_bias);
}
return bias;
}
string Cluster::toString() const {
stringstream ss;
for (unsigned i = 0; i < path.size(); ++i) {
if (i != 0) {
ss << " ";
}
ss << path[i];
}
return ss.str();
}
HierarchicalSoftmaxBuilder::HierarchicalSoftmaxBuilder(unsigned rep_dim,
const std::string& cluster_file,
Dict& word_dict,
ParameterCollection& model) {
local_model = model.add_subcollection("hsm-builder");
root = read_cluster_file(cluster_file, word_dict);
root->initialize(rep_dim, local_model);
}
HierarchicalSoftmaxBuilder::~HierarchicalSoftmaxBuilder() {
}
void HierarchicalSoftmaxBuilder::initialize(ParameterCollection& model) {
root->initialize(model);
}
void HierarchicalSoftmaxBuilder::new_graph(ComputationGraph& cg) {
pcg = &cg;
root->new_graph(cg);
}
Expression HierarchicalSoftmaxBuilder::neg_log_softmax(const Expression& rep, unsigned wordidx) {
if(pcg == NULL)
DYNET_INVALID_ARG("In HierarchicalSoftmaxBuilder, you must call new_graph before calling neg_log_softmax!");
Cluster* path = widx2path[wordidx];
unsigned i = 0;
const Cluster* node = root;
DYNET_ASSERT(root != NULL, "Null root in HierarchicalSoftmaxBuilder");
vector<Expression> log_probs;
Expression lp;
unsigned r;
while (node->num_children() > 0) {
r = node->get_index(path->get_path()[i]);
lp = node->neg_log_softmax(rep, r, *pcg);
log_probs.push_back(lp);
node = node->get_child(r);
DYNET_ASSERT(node != NULL, "Null node in HierarchicalSoftmaxBuilder");
i += 1;
}
r = path->get_index(wordidx);
lp = node->neg_log_softmax(rep, r, *pcg);
log_probs.push_back(lp);
return sum(log_probs);
}
unsigned HierarchicalSoftmaxBuilder::sample(const Expression& rep) {
if(pcg == NULL)
DYNET_INVALID_ARG("In HierarchicalSoftmaxBuilder, you must call new_graph before calling sample!");
const Cluster* node = root;
vector<float> dist;
unsigned c;
while (node->num_children() > 0) {
c = node->sample(rep, *pcg);
node = node->get_child(c);
}
c = node->sample(rep, *pcg);
return node->get_word(c);
}
Expression HierarchicalSoftmaxBuilder::full_log_distribution(const Expression& rep) {
DYNET_RUNTIME_ERR("full_distribution not implemented for HierarchicalSoftmaxBuilder");
return dynet::Expression();
}
inline bool is_ws(char x) { return (x == ' ' || x == '\t'); }
inline bool not_ws(char x) { return (x != ' ' && x != '\t'); }
Cluster* HierarchicalSoftmaxBuilder::read_cluster_file(const std::string& cluster_file, Dict& word_dict) {
cerr << "Reading clusters from " << cluster_file << " ...\n";
ifstream in(cluster_file);
if(!in)
DYNET_INVALID_ARG("HierarchicalSoftmaxBuilder couldn't read clusters from " << cluster_file);
int wc = 0;
string line;
vector<unsigned> path;
Cluster* root = new Cluster();
while(getline(in, line)) {
path.clear();
++wc;
const unsigned len = line.size();
unsigned startp = 0;
unsigned endp = 0;
while (startp < len) {
while (is_ws(line[startp]) && startp < len) { ++startp; }
endp = startp;
while (not_ws(line[endp]) && endp < len) { ++endp; }
string symbol = line.substr(startp, endp - startp);
path.push_back(path_symbols.convert(symbol));
if (line[endp] == ' ') {
startp = endp + 1;
continue;
}
else {
break;
}
}
Cluster* node = root;
for (unsigned symbol : path) {
node = node->add_child(symbol);
}
unsigned startw = endp;
while (is_ws(line[startw]) && startw < len) { ++startw; }
unsigned endw = startw;
while (not_ws(line[endw]) && endw < len) { ++endw; }
if(endp <= startp || startw <= endp || endw <= startw)
DYNET_INVALID_ARG("File formatting error in HierarchicalSoftmaxBuilder");
string word = line.substr(startw, endw - startw);
unsigned widx = word_dict.convert(word);
node->add_word(widx);
if (widx2path.size() <= widx) {
widx2path.resize(widx + 1);
}
widx2path[widx] = node;
}
cerr << "Done reading clusters.\n";
return root;
}
} // namespace dynet
<|endoftext|>
|
<commit_before>/* Copyright 2017 Google Inc. 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 "deepmath/guidance/vocabulary.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
namespace deepmath {
using tensorflow::StringPiece;
static bool is_variable(const StringPiece word) {
return !word.empty() && isupper(word[0]);
}
// Add variables, functions, and numbers from a file
void Vocabulary::Initialize(tensorflow::StringPiece path) {
QCHECK(id_to_vocab_.empty()) << "Initialize called twice";
// Remove flags from path
bool one_variable = false;
const auto slash = path.rfind('/');
const auto colon = path.rfind(':');
if (colon != string::npos && (slash == string::npos || slash < colon)) {
for (const auto& flag :
tensorflow::str_util::Split(path.substr(colon + 1), ',')) {
if (flag == "one_variable") {
one_variable = true;
} else if (flag == "map_unknown") {
map_unknown_ = true;
} else {
LOG(FATAL) << "Invalid vocabulary flag '" << flag << "'";
}
}
path = path.substr(0, colon);
}
// A few symbols are used in string form by the weaver
id_to_vocab_.resize(kStart);
id_to_vocab_[kEqual] = "=";
id_to_vocab_[kFalse] = "$false";
id_to_vocab_[kTrue] = "$true";
// Load vocabulary
{
string all_vocab;
TF_CHECK_OK(tensorflow::ReadFileToString(
tensorflow::Env::Default(), path.ToString(), &all_vocab));
for (const auto& raw_word : tensorflow::str_util::Split(all_vocab, '\n')) {
tensorflow::StringPiece word = raw_word;
tensorflow::str_util::RemoveWhitespaceContext(&word);
if (word.empty()) continue;
for (const auto c : word) {
QCHECK(isalnum(c) || c == '_') << "Nonalphanumeric vocab word '"
<< tensorflow::str_util::CEscape(word) << " in " << path;
}
if (one_variable && is_variable(word)) {
if (variable_id_ < 0) {
variable_id_ = id_to_vocab_.size();
id_to_vocab_.push_back("X");
}
} else {
id_to_vocab_.push_back(word.ToString());
}
}
}
// Invert id_to_vocab_
for (int i = 0; i < id_to_vocab_.size(); i++) {
if (!id_to_vocab_[i].empty()) {
vocab_to_id_.emplace(id_to_vocab_[i], i);
}
}
}
// Lookup the id of a vocabulary word
int32 Vocabulary::Word(const string& word) const {
if (variable_id_ >= 0 && is_variable(word)) return variable_id_;
auto it = vocab_to_id_.find(word);
if (it == vocab_to_id_.end() && map_unknown_) {
if (variable_id_ >= 0)
return variable_id_;
else
it = vocab_to_id_.find("X49");
}
QCHECK(it != vocab_to_id_.end()) << "Unknown vocabulary word: " << word;
return it->second;
}
} // namespace deepmath
<commit_msg>Internal changes<commit_after>/* Copyright 2017 Google Inc. 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 "deepmath/guidance/vocabulary.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
namespace deepmath {
using tensorflow::StringPiece;
static bool is_variable(const StringPiece word) {
return !word.empty() && isupper(word[0]);
}
// Add variables, functions, and numbers from a file
void Vocabulary::Initialize(tensorflow::StringPiece path) {
QCHECK(id_to_vocab_.empty()) << "Initialize called twice";
// Remove flags from path
bool one_variable = false;
const auto slash = path.rfind('/');
const auto colon = path.rfind(':');
if (colon != string::npos && (slash == string::npos || slash < colon)) {
for (const auto& flag :
tensorflow::str_util::Split(path.substr(colon + 1), ',')) {
if (flag == "one_variable") {
one_variable = true;
} else if (flag == "map_unknown") {
map_unknown_ = true;
} else {
LOG(FATAL) << "Invalid vocabulary flag '" << flag << "'";
}
}
path = path.substr(0, colon);
}
// A few symbols are used in string form by the weaver
id_to_vocab_.resize(kStart);
id_to_vocab_[kEqual] = "=";
id_to_vocab_[kFalse] = "$false";
id_to_vocab_[kTrue] = "$true";
// Load vocabulary
{
string all_vocab;
TF_CHECK_OK(tensorflow::ReadFileToString(tensorflow::Env::Default(),
std::string(path), &all_vocab));
for (const auto& raw_word : tensorflow::str_util::Split(all_vocab, '\n')) {
tensorflow::StringPiece word = raw_word;
tensorflow::str_util::RemoveWhitespaceContext(&word);
if (word.empty()) continue;
for (const auto c : word) {
QCHECK(isalnum(c) || c == '_') << "Nonalphanumeric vocab word '"
<< tensorflow::str_util::CEscape(word) << " in " << path;
}
if (one_variable && is_variable(word)) {
if (variable_id_ < 0) {
variable_id_ = id_to_vocab_.size();
id_to_vocab_.push_back("X");
}
} else {
id_to_vocab_.push_back(std::string(word));
}
}
}
// Invert id_to_vocab_
for (int i = 0; i < id_to_vocab_.size(); i++) {
if (!id_to_vocab_[i].empty()) {
vocab_to_id_.emplace(id_to_vocab_[i], i);
}
}
}
// Lookup the id of a vocabulary word
int32 Vocabulary::Word(const string& word) const {
if (variable_id_ >= 0 && is_variable(word)) return variable_id_;
auto it = vocab_to_id_.find(word);
if (it == vocab_to_id_.end() && map_unknown_) {
if (variable_id_ >= 0)
return variable_id_;
else
it = vocab_to_id_.find("X49");
}
QCHECK(it != vocab_to_id_.end()) << "Unknown vocabulary word: " << word;
return it->second;
}
} // namespace deepmath
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: memory.cc,v 1.58 2006/09/02 12:08:28 vruppert Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// 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
#include "bochs.h"
#include "cpu/cpu.h"
#include "iodev/iodev.h"
#define LOG_THIS BX_MEM_THIS
#if BX_PROVIDE_CPU_MEMORY
//
// Memory map inside the 1st megabyte:
//
// 0x00000 - 0x7ffff DOS area (512K)
// 0x80000 - 0x9ffff Optional fixed memory hole (128K)
// 0xa0000 - 0xbffff Standard PCI/ISA Video Mem / SMMRAM (128K)
// 0xc0000 - 0xdffff Expansion Card BIOS and Buffer Area (128K)
// 0xe0000 - 0xeffff Lower BIOS Area (64K)
// 0xf0000 - 0xfffff Upper BIOS Area (64K)
//
void BX_CPP_AttrRegparmN(3)
BX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data)
{
Bit8u *data_ptr;
bx_phy_address a20addr = A20ADDR(addr);
struct memory_handler_struct *memory_handler = NULL;
// Note: accesses should always be contained within a single page now
if (cpu != NULL) {
#if BX_SUPPORT_IODEBUG
bx_iodebug_c::mem_write(cpu, a20addr, len, data);
#endif
BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len);
#if BX_DEBUGGER
// (mch) Check for physical write break points, TODO
// (bbd) Each breakpoint should have an associated CPU#, TODO
for (int i = 0; i < num_write_watchpoints; i++) {
if (write_watchpoint[i] == a20addr) {
BX_CPU(0)->watchpoint = a20addr;
BX_CPU(0)->break_point = BREAK_POINT_WRITE;
break;
}
}
#endif
#if BX_SUPPORT_APIC
bx_generic_apic_c *local_apic = &cpu->local_apic;
if (local_apic->is_selected(a20addr, len)) {
local_apic->write(a20addr, (Bit32u *)data, len);
return;
}
#endif
if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available))
{
// SMRAM memory space
if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted))
goto mem_write;
}
}
memory_handler = BX_MEM_THIS memory_handlers[a20addr >> 20];
while (memory_handler) {
if (memory_handler->begin <= a20addr &&
memory_handler->end >= a20addr &&
memory_handler->write_handler(a20addr, len, data, memory_handler->param))
{
return;
}
memory_handler = memory_handler->next;
}
mem_write:
// all memory access feets in single 4K page
if (a20addr < BX_MEM_THIS len) {
#if BX_SUPPORT_ICACHE
pageWriteStampTable.decWriteStamp(a20addr);
#endif
// all of data is within limits of physical memory
if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))
{
if (len == 8) {
WriteHostQWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit64u*)data);
BX_DBG_DIRTY_PAGE(a20addr >> 12);
return;
}
if (len == 4) {
WriteHostDWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit32u*)data);
BX_DBG_DIRTY_PAGE(a20addr >> 12);
return;
}
if (len == 2) {
WriteHostWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit16u*)data);
BX_DBG_DIRTY_PAGE(a20addr >> 12);
return;
}
if (len == 1) {
* ((Bit8u *) (&BX_MEM_THIS vector[a20addr])) = * (Bit8u *) data;
BX_DBG_DIRTY_PAGE(a20addr >> 12);
return;
}
// len == other, just fall thru to special cases handling
}
#ifdef BX_LITTLE_ENDIAN
data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
data_ptr = (Bit8u *) data + (len - 1);
#endif
write_one:
if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))
{
// addr *not* in range 000A0000 .. 000FFFFF
BX_MEM_THIS vector[a20addr] = *data_ptr;
BX_DBG_DIRTY_PAGE(a20addr >> 12);
inc_one:
if (len == 1) return;
len--;
a20addr++;
#ifdef BX_LITTLE_ENDIAN
data_ptr++;
#else // BX_BIG_ENDIAN
data_ptr--;
#endif
goto write_one;
}
// addr must be in range 000A0000 .. 000FFFFF
// SMMRAM
if (a20addr <= 0x000bffff) {
// devices are not allowed to access SMMRAM under VGA memory
if (cpu) {
BX_MEM_THIS vector[a20addr] = *data_ptr;
BX_DBG_DIRTY_PAGE(a20addr >> 12);
}
goto inc_one;
}
// adapter ROM C0000 .. DFFFF
// ROM BIOS memory E0000 .. FFFFF
#if BX_SUPPORT_PCI == 0
// ignore write to ROM
#else
// Write Based on 440fx Programming
if (BX_MEM_THIS pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000))
{
switch (DEV_pci_wr_memtype(a20addr)) {
case 0x1: // Writes to ShadowRAM
BX_DEBUG(("Writing to ShadowRAM: address %08x, data %02x", (unsigned) a20addr, *data_ptr));
BX_MEM_THIS vector[a20addr] = *data_ptr;
BX_DBG_DIRTY_PAGE(a20addr >> 12);
goto inc_one;
case 0x0: // Writes to ROM, Inhibit
BX_DEBUG(("Write to ROM ignored: address %08x, data %02x", (unsigned) a20addr, *data_ptr));
goto inc_one;
default:
BX_PANIC(("writePhysicalPage: default case"));
goto inc_one;
}
}
#endif
goto inc_one;
}
else {
// access outside limits of physical memory, ignore
BX_DEBUG(("Write outside the limits of physical memory (ignore)"));
}
}
void BX_CPP_AttrRegparmN(3)
BX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data)
{
Bit8u *data_ptr;
bx_phy_address a20addr = A20ADDR(addr);
struct memory_handler_struct *memory_handler = NULL;
// Note: accesses should always be contained within a single page now
if (cpu != NULL) {
#if BX_SUPPORT_IODEBUG
bx_iodebug_c::mem_read(cpu, a20addr, len, data);
#endif
BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len);
#if BX_DEBUGGER
// (mch) Check for physical read break points, TODO
// (bbd) Each breakpoint should have an associated CPU#, TODO
for (int i = 0; i < num_read_watchpoints; i++) {
if (read_watchpoint[i] == a20addr) {
BX_CPU(0)->watchpoint = a20addr;
BX_CPU(0)->break_point = BREAK_POINT_READ;
break;
}
}
#endif
#if BX_SUPPORT_APIC
bx_generic_apic_c *local_apic = &cpu->local_apic;
if (local_apic->is_selected (a20addr, len)) {
local_apic->read(a20addr, data, len);
return;
}
#endif
if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available))
{
// SMRAM memory space
if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted))
goto mem_read;
}
}
memory_handler = BX_MEM_THIS memory_handlers[a20addr >> 20];
while (memory_handler) {
if (memory_handler->begin <= a20addr &&
memory_handler->end >= a20addr &&
memory_handler->read_handler(a20addr, len, data, memory_handler->param))
{
return;
}
memory_handler = memory_handler->next;
}
mem_read:
if (a20addr <= BX_MEM_THIS len) {
// all of data is within limits of physical memory
if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))
{
if (len == 8) {
ReadHostQWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit64u*) data);
return;
}
if (len == 4) {
ReadHostDWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit32u*) data);
return;
}
if (len == 2) {
ReadHostWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit16u*) data);
return;
}
if (len == 1) {
* (Bit8u *) data = * ((Bit8u *) (&BX_MEM_THIS vector[a20addr]));
return;
}
// len == other case can just fall thru to special cases handling
}
#ifdef BX_LITTLE_ENDIAN
data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
data_ptr = (Bit8u *) data + (len - 1);
#endif
read_one:
if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))
{
// addr *not* in range 00080000 .. 000FFFFF
*data_ptr = BX_MEM_THIS vector[a20addr];
inc_one:
if (len == 1) return;
len--;
a20addr++;
#ifdef BX_LITTLE_ENDIAN
data_ptr++;
#else // BX_BIG_ENDIAN
data_ptr--;
#endif
goto read_one;
}
// addr must be in range 000A0000 .. 000FFFFF
// SMMRAM
if (a20addr <= 0x000bffff) {
// devices are not allowed to access SMMRAM under VGA memory
if (cpu) *data_ptr = BX_MEM_THIS vector[a20addr];
goto inc_one;
}
#if BX_SUPPORT_PCI
if (BX_MEM_THIS pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000))
{
switch (DEV_pci_rd_memtype(a20addr)) {
case 0x0: // Read from ROM
if ((a20addr & 0xfffe0000) == 0x000e0000)
{
*data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK];
}
else
{
*data_ptr = BX_MEM_THIS rom[(a20addr & EXROM_MASK) + BIOSROMSZ];
}
goto inc_one;
case 0x1: // Read from ShadowRAM
*data_ptr = BX_MEM_THIS vector[a20addr];
goto inc_one;
default:
BX_PANIC(("readPhysicalPage: default case"));
}
goto inc_one;
}
else
#endif // #if BX_SUPPORT_PCI
{
if ((a20addr & 0xfffc0000) != 0x000c0000) {
*data_ptr = BX_MEM_THIS vector[a20addr];
}
else if ((a20addr & 0xfffe0000) == 0x000e0000)
{
*data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK];
}
else
{
*data_ptr = BX_MEM_THIS rom[(a20addr & EXROM_MASK) + BIOSROMSZ];
}
goto inc_one;
}
}
else
{ // access outside limits of physical memory
#ifdef BX_LITTLE_ENDIAN
data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
data_ptr = (Bit8u *) data + (len - 1);
#endif
for (unsigned i = 0; i < len; i++) {
if (a20addr >= (bx_phy_address)~BIOS_MASK)
*data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK];
else
*data_ptr = 0xff;
addr++;
a20addr = (addr);
#ifdef BX_LITTLE_ENDIAN
data_ptr++;
#else // BX_BIG_ENDIAN
data_ptr--;
#endif
}
}
}
#endif // #if BX_PROVIDE_CPU_MEMORY
<commit_msg>Bochs website tracker patch shows where write outside of memory occurred<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: memory.cc,v 1.59 2006/12/29 08:02:35 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// 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
#include "bochs.h"
#include "cpu/cpu.h"
#include "iodev/iodev.h"
#define LOG_THIS BX_MEM_THIS
#if BX_PROVIDE_CPU_MEMORY
//
// Memory map inside the 1st megabyte:
//
// 0x00000 - 0x7ffff DOS area (512K)
// 0x80000 - 0x9ffff Optional fixed memory hole (128K)
// 0xa0000 - 0xbffff Standard PCI/ISA Video Mem / SMMRAM (128K)
// 0xc0000 - 0xdffff Expansion Card BIOS and Buffer Area (128K)
// 0xe0000 - 0xeffff Lower BIOS Area (64K)
// 0xf0000 - 0xfffff Upper BIOS Area (64K)
//
void BX_CPP_AttrRegparmN(3)
BX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data)
{
Bit8u *data_ptr;
bx_phy_address a20addr = A20ADDR(addr);
struct memory_handler_struct *memory_handler = NULL;
// Note: accesses should always be contained within a single page now
if (cpu != NULL) {
#if BX_SUPPORT_IODEBUG
bx_iodebug_c::mem_write(cpu, a20addr, len, data);
#endif
BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len);
#if BX_DEBUGGER
// (mch) Check for physical write break points, TODO
// (bbd) Each breakpoint should have an associated CPU#, TODO
for (int i = 0; i < num_write_watchpoints; i++) {
if (write_watchpoint[i] == a20addr) {
BX_CPU(0)->watchpoint = a20addr;
BX_CPU(0)->break_point = BREAK_POINT_WRITE;
break;
}
}
#endif
#if BX_SUPPORT_APIC
bx_generic_apic_c *local_apic = &cpu->local_apic;
if (local_apic->is_selected(a20addr, len)) {
local_apic->write(a20addr, (Bit32u *)data, len);
return;
}
#endif
if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available))
{
// SMRAM memory space
if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted))
goto mem_write;
}
}
memory_handler = BX_MEM_THIS memory_handlers[a20addr >> 20];
while (memory_handler) {
if (memory_handler->begin <= a20addr &&
memory_handler->end >= a20addr &&
memory_handler->write_handler(a20addr, len, data, memory_handler->param))
{
return;
}
memory_handler = memory_handler->next;
}
mem_write:
// all memory access feets in single 4K page
if (a20addr < BX_MEM_THIS len) {
#if BX_SUPPORT_ICACHE
pageWriteStampTable.decWriteStamp(a20addr);
#endif
// all of data is within limits of physical memory
if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))
{
if (len == 8) {
WriteHostQWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit64u*)data);
BX_DBG_DIRTY_PAGE(a20addr >> 12);
return;
}
if (len == 4) {
WriteHostDWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit32u*)data);
BX_DBG_DIRTY_PAGE(a20addr >> 12);
return;
}
if (len == 2) {
WriteHostWordToLittleEndian(&BX_MEM_THIS vector[a20addr], *(Bit16u*)data);
BX_DBG_DIRTY_PAGE(a20addr >> 12);
return;
}
if (len == 1) {
* ((Bit8u *) (&BX_MEM_THIS vector[a20addr])) = * (Bit8u *) data;
BX_DBG_DIRTY_PAGE(a20addr >> 12);
return;
}
// len == other, just fall thru to special cases handling
}
#ifdef BX_LITTLE_ENDIAN
data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
data_ptr = (Bit8u *) data + (len - 1);
#endif
write_one:
if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))
{
// addr *not* in range 000A0000 .. 000FFFFF
BX_MEM_THIS vector[a20addr] = *data_ptr;
BX_DBG_DIRTY_PAGE(a20addr >> 12);
inc_one:
if (len == 1) return;
len--;
a20addr++;
#ifdef BX_LITTLE_ENDIAN
data_ptr++;
#else // BX_BIG_ENDIAN
data_ptr--;
#endif
goto write_one;
}
// addr must be in range 000A0000 .. 000FFFFF
// SMMRAM
if (a20addr <= 0x000bffff) {
// devices are not allowed to access SMMRAM under VGA memory
if (cpu) {
BX_MEM_THIS vector[a20addr] = *data_ptr;
BX_DBG_DIRTY_PAGE(a20addr >> 12);
}
goto inc_one;
}
// adapter ROM C0000 .. DFFFF
// ROM BIOS memory E0000 .. FFFFF
#if BX_SUPPORT_PCI == 0
// ignore write to ROM
#else
// Write Based on 440fx Programming
if (BX_MEM_THIS pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000))
{
switch (DEV_pci_wr_memtype(a20addr)) {
case 0x1: // Writes to ShadowRAM
BX_DEBUG(("Writing to ShadowRAM: address %08x, data %02x", (unsigned) a20addr, *data_ptr));
BX_MEM_THIS vector[a20addr] = *data_ptr;
BX_DBG_DIRTY_PAGE(a20addr >> 12);
goto inc_one;
case 0x0: // Writes to ROM, Inhibit
BX_DEBUG(("Write to ROM ignored: address %08x, data %02x", (unsigned) a20addr, *data_ptr));
goto inc_one;
default:
BX_PANIC(("writePhysicalPage: default case"));
goto inc_one;
}
}
#endif
goto inc_one;
}
else {
// access outside limits of physical memory, ignore
BX_DEBUG(("Write outside the limits of physical memory (0x%08x) (ignore)", a20addr));
}
}
void BX_CPP_AttrRegparmN(3)
BX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data)
{
Bit8u *data_ptr;
bx_phy_address a20addr = A20ADDR(addr);
struct memory_handler_struct *memory_handler = NULL;
// Note: accesses should always be contained within a single page now
if (cpu != NULL) {
#if BX_SUPPORT_IODEBUG
bx_iodebug_c::mem_read(cpu, a20addr, len, data);
#endif
BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len);
#if BX_DEBUGGER
// (mch) Check for physical read break points, TODO
// (bbd) Each breakpoint should have an associated CPU#, TODO
for (int i = 0; i < num_read_watchpoints; i++) {
if (read_watchpoint[i] == a20addr) {
BX_CPU(0)->watchpoint = a20addr;
BX_CPU(0)->break_point = BREAK_POINT_READ;
break;
}
}
#endif
#if BX_SUPPORT_APIC
bx_generic_apic_c *local_apic = &cpu->local_apic;
if (local_apic->is_selected (a20addr, len)) {
local_apic->read(a20addr, data, len);
return;
}
#endif
if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available))
{
// SMRAM memory space
if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted))
goto mem_read;
}
}
memory_handler = BX_MEM_THIS memory_handlers[a20addr >> 20];
while (memory_handler) {
if (memory_handler->begin <= a20addr &&
memory_handler->end >= a20addr &&
memory_handler->read_handler(a20addr, len, data, memory_handler->param))
{
return;
}
memory_handler = memory_handler->next;
}
mem_read:
if (a20addr <= BX_MEM_THIS len) {
// all of data is within limits of physical memory
if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))
{
if (len == 8) {
ReadHostQWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit64u*) data);
return;
}
if (len == 4) {
ReadHostDWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit32u*) data);
return;
}
if (len == 2) {
ReadHostWordFromLittleEndian(&BX_MEM_THIS vector[a20addr], * (Bit16u*) data);
return;
}
if (len == 1) {
* (Bit8u *) data = * ((Bit8u *) (&BX_MEM_THIS vector[a20addr]));
return;
}
// len == other case can just fall thru to special cases handling
}
#ifdef BX_LITTLE_ENDIAN
data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
data_ptr = (Bit8u *) data + (len - 1);
#endif
read_one:
if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))
{
// addr *not* in range 00080000 .. 000FFFFF
*data_ptr = BX_MEM_THIS vector[a20addr];
inc_one:
if (len == 1) return;
len--;
a20addr++;
#ifdef BX_LITTLE_ENDIAN
data_ptr++;
#else // BX_BIG_ENDIAN
data_ptr--;
#endif
goto read_one;
}
// addr must be in range 000A0000 .. 000FFFFF
// SMMRAM
if (a20addr <= 0x000bffff) {
// devices are not allowed to access SMMRAM under VGA memory
if (cpu) *data_ptr = BX_MEM_THIS vector[a20addr];
goto inc_one;
}
#if BX_SUPPORT_PCI
if (BX_MEM_THIS pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000))
{
switch (DEV_pci_rd_memtype(a20addr)) {
case 0x0: // Read from ROM
if ((a20addr & 0xfffe0000) == 0x000e0000)
{
*data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK];
}
else
{
*data_ptr = BX_MEM_THIS rom[(a20addr & EXROM_MASK) + BIOSROMSZ];
}
goto inc_one;
case 0x1: // Read from ShadowRAM
*data_ptr = BX_MEM_THIS vector[a20addr];
goto inc_one;
default:
BX_PANIC(("readPhysicalPage: default case"));
}
goto inc_one;
}
else
#endif // #if BX_SUPPORT_PCI
{
if ((a20addr & 0xfffc0000) != 0x000c0000) {
*data_ptr = BX_MEM_THIS vector[a20addr];
}
else if ((a20addr & 0xfffe0000) == 0x000e0000)
{
*data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK];
}
else
{
*data_ptr = BX_MEM_THIS rom[(a20addr & EXROM_MASK) + BIOSROMSZ];
}
goto inc_one;
}
}
else
{ // access outside limits of physical memory
#ifdef BX_LITTLE_ENDIAN
data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
data_ptr = (Bit8u *) data + (len - 1);
#endif
for (unsigned i = 0; i < len; i++) {
if (a20addr >= (bx_phy_address)~BIOS_MASK)
*data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK];
else
*data_ptr = 0xff;
addr++;
a20addr = (addr);
#ifdef BX_LITTLE_ENDIAN
data_ptr++;
#else // BX_BIG_ENDIAN
data_ptr--;
#endif
}
}
}
#endif // #if BX_PROVIDE_CPU_MEMORY
<|endoftext|>
|
<commit_before>#include <iostream>
#include <boost/variant.hpp>
using std::nullptr_t;
using std::pair;
using std::make_pair;
using std::move;
template <typename T, typename F, typename BaseInner, typename ArgsT>
struct ComposeVariantVisitor
{
struct Inner : BaseInner
{
Inner(ArgsT&& a) : BaseInner(std::move(a.second)), f_(std::move(a.first)) {}
void operator()(const T& t) const { f_(t); }
private:
F f_;
};
ComposeVariantVisitor(ArgsT&& args) : m_args(move(args))
{
}
template<typename Tadd, typename Fadd>
auto on(Fadd&& f)
{
return ComposeVariantVisitor<Tadd, Fadd, Inner, std::pair<Fadd, ArgsT>>(
make_pair(move(f), move(m_args)));
}
auto end_variant_visitor()
{
return Inner(move(m_args));
}
ArgsT m_args;
};
struct EmptyVariantVisitor
{
struct Inner : public boost::static_visitor<>
{
Inner(nullptr_t)
{
}
};
template <typename Tadd, typename Fadd>
auto on(Fadd&& f)
{
return ComposeVariantVisitor<Tadd, Fadd, Inner, pair<Fadd, nullptr_t>>(
make_pair(move(f), nullptr));
}
};
EmptyVariantVisitor begin_variant_visitor()
{
return EmptyVariantVisitor();
}
int main(int argc, char* argv[])
{
boost::variant<int,double,char> v;
/////////////////////////////////////////////////////////////
struct printer : boost::static_visitor<>
{
void operator()(const int i) const { std::cout << i << "\n"; }
void operator()(const double d) const { std::cout << d << "\n"; }
void operator()(const char c) const { std::cout << c << "\n"; }
};
v = 7;
boost::apply_visitor(printer(), v);
v = 3.14159;
boost::apply_visitor(printer(), v);
v = 'p';
boost::apply_visitor(printer(), v);
/////////////////////////////////////////////////////////////
auto inline_printer = begin_variant_visitor()
.on<int>([](const int i) { std::cout << i << "\n";})
.on<double>([](const double d) { std::cout << d << "\n";})
.on<char>([](const char c) { std::cout << c << "\n";})
.end_variant_visitor();
v = 7;
boost::apply_visitor(inline_printer, v);
v = 3.14159;
boost::apply_visitor(inline_printer, v);
v = 'p';
boost::apply_visitor(inline_printer, v);
}
<commit_msg>Inline variant visitor fails for class types<commit_after>#include <iostream>
#include <boost/variant.hpp>
using std::nullptr_t;
using std::pair;
using std::make_pair;
using std::move;
template <typename T, typename F, typename BaseInner, typename ArgsT>
struct ComposeVariantVisitor
{
struct Inner : BaseInner
{
Inner(ArgsT&& a) : BaseInner(std::move(a.second)), f_(std::move(a.first)) {}
void operator()(T& t) const { f_(t); }
private:
F f_;
};
ComposeVariantVisitor(ArgsT&& args) : m_args(move(args))
{
}
template<typename Tadd, typename Fadd>
auto on(Fadd&& f)
{
return ComposeVariantVisitor<Tadd, Fadd, Inner, std::pair<Fadd, ArgsT>>(
make_pair(move(f), move(m_args)));
}
auto end_variant_visitor()
{
return Inner(move(m_args));
}
ArgsT m_args;
};
struct EmptyVariantVisitor
{
struct Inner : public boost::static_visitor<>
{
Inner(nullptr_t)
{
}
};
template <typename Tadd, typename Fadd>
auto on(Fadd&& f)
{
return ComposeVariantVisitor<Tadd, Fadd, Inner, pair<Fadd, nullptr_t>>(
make_pair(move(f), nullptr));
}
};
EmptyVariantVisitor begin_variant_visitor()
{
return EmptyVariantVisitor();
}
class A{};
class B{};
class C{};
int main(int argc, char* argv[])
{
boost::variant<A,B,C> v;
/////////////////////////////////////////////////////////////
struct printer : boost::static_visitor<>
{
void operator()(A&) const { std::cout << "A\n"; }
void operator()(B&) const { std::cout << "B\n"; }
void operator()(C&) const { std::cout << "C\n"; }
};
v = A();
boost::apply_visitor(printer(), v);
v = B();
boost::apply_visitor(printer(), v);
v = C();
boost::apply_visitor(printer(), v);
/////////////////////////////////////////////////////////////
auto inline_printer = begin_variant_visitor()
.on<A>([](A&) { std::cout << "A\n";})
.on<B>([](B&) { std::cout << "B\n";})
.on<C>([](C&) { std::cout << "C\n";})
.end_variant_visitor();
v = A();
boost::apply_visitor(inline_printer, v);
v = B();
boost::apply_visitor(inline_printer, v);
v = C();
boost::apply_visitor(inline_printer, v);
}
<|endoftext|>
|
<commit_before>/**
@file Data/Metadata.hpp
@brief Metadata classes.
@author Timothy Howard
@copyright 2013-2014 Timothy Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_DATA_METADATA_HPP_
#define HORD_DATA_METADATA_HPP_
#include <Hord/config.hpp>
#include <Hord/aux.hpp>
#include <Hord/String.hpp>
#include <Hord/serialization.hpp>
#include <Hord/Data/Defs.hpp>
#include <Hord/IO/PropStream.hpp>
#include <duct/cc_unique_ptr.hpp>
namespace Hord {
namespace Data {
// Forward declarations
class MetaField;
class StringMetaField;
class Int32MetaField;
class Int64MetaField;
class BoolMetaField;
struct Metadata;
/**
@addtogroup data
@{
*/
/**
@addtogroup metadata
@{
*/
/**
Base Metadata field.
@note read() and write() will serialize base properties;
implementations shall serialize only their own properties.
*/
class MetaField {
public:
/**
Type info.
*/
struct type_info final {
/** Type. */
MetaFieldType const type;
/**
Default-construct field of this type.
@returns Pointer to field, or @c nullptr if allocation
failed.
*/
MetaField*
(&construct)() noexcept;
};
/** @name Properties */ /// @{
/**
Name.
@warning This field will be truncated to 255 code units
when serializing.
*/
String name{};
/// @}
private:
MetaField(MetaField const&) = delete;
MetaField& operator=(MetaField const&) = delete;
protected:
/** @name Implementation */ /// @{
/**
get_type_info() implementation.
*/
virtual type_info const&
get_type_info_impl() const noexcept = 0;
/**
read() implementation.
@throws SerializerError{..}
*/
virtual ser_result_type
read_impl(
InputSerializer& ser
) = 0;
/**
write() implementation.
@throws SerializerError{..}
*/
virtual ser_result_type
write_impl(
OutputSerializer& ser
) const = 0;
/// @}
public:
/** @name Special member functions */ /// @{
/** Destructor. */
virtual
~MetaField() noexcept = 0;
/** Default constructor. */
MetaField() = default;
/** Move constructor. */
MetaField(MetaField&&) = default;
/** Move assignment operator. */
MetaField& operator=(MetaField&&) = default;
/**
Constructor with name.
*/
explicit
MetaField(
String name
) noexcept
: name(std::move(name))
{}
/// @}
public:
/** @name Properties */ /// @{
/**
Get type info.
*/
type_info const&
get_type_info() const noexcept {
return get_type_info_impl();
}
/**
Set name.
*/
void
set_name(
String new_name
) noexcept {
this->name.assign(std::move(new_name));
if (0xFF < this->name.size()) {
this->name.resize(0xFF);
// TODO: Truncate invalid unit sequence (if any) after resize
}
}
/// @}
/** @name Serialization */ /// @{
/**
Read from input serializer.
@throws SerializerError{..}
If a serialization operation failed.
*/
ser_result_type
read(
ser_tag_read,
InputSerializer& ser
) {
ser(Cacophony::make_string_cfg<std::uint8_t>(this->name));
read_impl(ser);
}
/**
Write to output serializer.
@throws SerializerError{..}
If a serialization operation failed.
*/
ser_result_type
write(
ser_tag_write,
OutputSerializer& ser
) const {
ser(Cacophony::make_string_cfg<std::uint8_t>(this->name));
write_impl(ser);
}
/// @}
};
inline MetaField::~MetaField() noexcept = default;
/**
String MetaField.
*/
class StringMetaField final
: public MetaField
{
public:
/** @name Properties */ /// @{
/** Value. */
String value{};
/// @}
private:
StringMetaField(StringMetaField const&) = delete;
StringMetaField& operator=(StringMetaField const&) = delete;
MetaField::type_info const&
get_type_info_impl() const noexcept override;
ser_result_type
read_impl(
InputSerializer& ser
) override {
ser(this->value);
}
ser_result_type
write_impl(
OutputSerializer& ser
) const override {
ser(this->value);
}
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~StringMetaField() noexcept override = default;
/** Default constructor. */
StringMetaField() = default;
/** Move constructor. */
StringMetaField(StringMetaField&&) = default;
/** Move assignment operator. */
StringMetaField& operator=(StringMetaField&&) = default;
/**
Constructor with name and value.
*/
StringMetaField(
String name,
String value
) noexcept
: MetaField(std::move(name))
, value(std::move(value))
{}
/// @}
};
/**
Int32 MetaField.
*/
class Int32MetaField final
: public MetaField
{
public:
/** @name Properties */ /// @{
/** Value. */
std::int32_t value{0};
/// @}
private:
Int32MetaField(Int32MetaField const&) = delete;
Int32MetaField& operator=(Int32MetaField const&) = delete;
MetaField::type_info const&
get_type_info_impl() const noexcept override;
ser_result_type
read_impl(
InputSerializer& ser
) override {
ser(this->value);
}
ser_result_type
write_impl(
OutputSerializer& ser
) const override {
ser(this->value);
}
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~Int32MetaField() noexcept override = default;
/** Default constructor. */
Int32MetaField() = default;
/** Move constructor. */
Int32MetaField(Int32MetaField&&) = default;
/** Move assignment operator. */
Int32MetaField& operator=(Int32MetaField&&) = default;
/**
Constructor with name and value.
*/
Int32MetaField(
String name,
std::int32_t value
) noexcept
: MetaField(std::move(name))
, value(value)
{}
/// @}
};
/**
Int64 MetaField.
*/
class Int64MetaField final
: public MetaField
{
public:
/** @name Properties */ /// @{
/** Value. */
std::int64_t value{0};
/// @}
private:
Int64MetaField(Int64MetaField const&) = delete;
Int64MetaField& operator=(Int64MetaField const&) = delete;
MetaField::type_info const&
get_type_info_impl() const noexcept override;
ser_result_type
read_impl(
InputSerializer& ser
) override {
ser(this->value);
}
ser_result_type
write_impl(
OutputSerializer& ser
) const override {
ser(this->value);
}
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~Int64MetaField() noexcept override = default;
/** Default constructor. */
Int64MetaField() = default;
/** Move constructor. */
Int64MetaField(Int64MetaField&&) = default;
/** Move assignment operator. */
Int64MetaField& operator=(Int64MetaField&&) = default;
/**
Constructor with name and value.
*/
Int64MetaField(
String name,
std::int64_t value
) noexcept
: MetaField(std::move(name))
, value(value)
{}
/// @}
};
/**
Bool MetaField.
*/
class BoolMetaField final
: public MetaField
{
public:
/** @name Properties */ /// @{
/** Value. */
bool value{false};
/// @}
private:
BoolMetaField(BoolMetaField const&) = delete;
BoolMetaField& operator=(BoolMetaField const&) = delete;
MetaField::type_info const&
get_type_info_impl() const noexcept override;
ser_result_type
read_impl(
InputSerializer& ser
) override {
std::uint8_t boolu8 = 0;
ser(boolu8);
this->value = static_cast<bool>(boolu8);
}
ser_result_type
write_impl(
OutputSerializer& ser
) const override {
ser(static_cast<std::uint8_t>(this->value));
}
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~BoolMetaField() noexcept override = default;
/** Default constructor. */
BoolMetaField() = default;
/** Move constructor. */
BoolMetaField(BoolMetaField&&) = default;
/** Move assignment operator. */
BoolMetaField& operator=(BoolMetaField&&) = default;
/**
Constructor with name and value.
*/
BoolMetaField(
String name,
bool value
) noexcept
: MetaField(std::move(name))
, value(value)
{}
/// @}
};
/**
Metadata.
@sa IO::PropType::metadata
*/
struct Metadata final {
public:
/** MetaField vector. */
using field_vector_type
= aux::vector<
duct::cc_unique_ptr<MetaField>
>;
/** @name Properties */ /// @{
/** Fields. */
field_vector_type fields{};
/// @}
private:
Metadata(Metadata const&) = delete;
Metadata& operator=(Metadata const&) = delete;
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~Metadata() noexcept = default;
/** Default constructor. */
Metadata() = default;
/** Move constructor. */
Metadata(Metadata&&) = default;
/** Move assignment operator. */
Metadata& operator=(Metadata&&) = default;
/// @}
/** @name Serialization */ /// @{
/**
Deserialize from prop stream.
@note State will be retained if an exception is thrown.
@pre @code
IO::PropType::metadata == prop_stream.get_type()
@endcode
@throws Error{ErrorCode::serialization_io_failed}
If an input operation failed.
@throws Error{ErrorCode::serialization_data_malformed}
If an invalid field type is encountered in the prop stream.
@param prop_stream %Prop stream.
*/
void
deserialize(
IO::InputPropStream& prop_stream
);
/**
Serialize to prop stream.
@note State will be retained if an exception is thrown.
@pre @code
IO::PropType::metadata == prop_stream.get_type()
@endcode
@throws Error{ErrorCode::serialization_io_failed}
If an output operation failed.
@param prop_stream %Prop stream.
*/
void
serialize(
IO::OutputPropStream& prop_stream
) const;
/// @}
};
/** @} */ // end of doc-group metadata
/** @} */ // end of doc-group data
} // namespace Data
} // namespace Hord
#endif // HORD_DATA_METADATA_HPP_
<commit_msg>:Data::MetaField: constified non-moved values in ctors.<commit_after>/**
@file Data/Metadata.hpp
@brief Metadata classes.
@author Timothy Howard
@copyright 2013-2014 Timothy Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_DATA_METADATA_HPP_
#define HORD_DATA_METADATA_HPP_
#include <Hord/config.hpp>
#include <Hord/aux.hpp>
#include <Hord/String.hpp>
#include <Hord/serialization.hpp>
#include <Hord/Data/Defs.hpp>
#include <Hord/IO/PropStream.hpp>
#include <duct/cc_unique_ptr.hpp>
namespace Hord {
namespace Data {
// Forward declarations
class MetaField;
class StringMetaField;
class Int32MetaField;
class Int64MetaField;
class BoolMetaField;
struct Metadata;
/**
@addtogroup data
@{
*/
/**
@addtogroup metadata
@{
*/
/**
Base Metadata field.
@note read() and write() will serialize base properties;
implementations shall serialize only their own properties.
*/
class MetaField {
public:
/**
Type info.
*/
struct type_info final {
/** Type. */
MetaFieldType const type;
/**
Default-construct field of this type.
@returns Pointer to field, or @c nullptr if allocation
failed.
*/
MetaField*
(&construct)() noexcept;
};
/** @name Properties */ /// @{
/**
Name.
@warning This field will be truncated to 255 code units
when serializing.
*/
String name{};
/// @}
private:
MetaField(MetaField const&) = delete;
MetaField& operator=(MetaField const&) = delete;
protected:
/** @name Implementation */ /// @{
/**
get_type_info() implementation.
*/
virtual type_info const&
get_type_info_impl() const noexcept = 0;
/**
read() implementation.
@throws SerializerError{..}
*/
virtual ser_result_type
read_impl(
InputSerializer& ser
) = 0;
/**
write() implementation.
@throws SerializerError{..}
*/
virtual ser_result_type
write_impl(
OutputSerializer& ser
) const = 0;
/// @}
public:
/** @name Special member functions */ /// @{
/** Destructor. */
virtual
~MetaField() noexcept = 0;
/** Default constructor. */
MetaField() = default;
/** Move constructor. */
MetaField(MetaField&&) = default;
/** Move assignment operator. */
MetaField& operator=(MetaField&&) = default;
/**
Constructor with name.
*/
explicit
MetaField(
String name
) noexcept
: name(std::move(name))
{}
/// @}
public:
/** @name Properties */ /// @{
/**
Get type info.
*/
type_info const&
get_type_info() const noexcept {
return get_type_info_impl();
}
/**
Set name.
*/
void
set_name(
String new_name
) noexcept {
this->name.assign(std::move(new_name));
if (0xFF < this->name.size()) {
this->name.resize(0xFF);
// TODO: Truncate invalid unit sequence (if any) after resize
}
}
/// @}
/** @name Serialization */ /// @{
/**
Read from input serializer.
@throws SerializerError{..}
If a serialization operation failed.
*/
ser_result_type
read(
ser_tag_read,
InputSerializer& ser
) {
ser(Cacophony::make_string_cfg<std::uint8_t>(this->name));
read_impl(ser);
}
/**
Write to output serializer.
@throws SerializerError{..}
If a serialization operation failed.
*/
ser_result_type
write(
ser_tag_write,
OutputSerializer& ser
) const {
ser(Cacophony::make_string_cfg<std::uint8_t>(this->name));
write_impl(ser);
}
/// @}
};
inline MetaField::~MetaField() noexcept = default;
/**
String MetaField.
*/
class StringMetaField final
: public MetaField
{
public:
/** @name Properties */ /// @{
/** Value. */
String value{};
/// @}
private:
StringMetaField(StringMetaField const&) = delete;
StringMetaField& operator=(StringMetaField const&) = delete;
MetaField::type_info const&
get_type_info_impl() const noexcept override;
ser_result_type
read_impl(
InputSerializer& ser
) override {
ser(this->value);
}
ser_result_type
write_impl(
OutputSerializer& ser
) const override {
ser(this->value);
}
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~StringMetaField() noexcept override = default;
/** Default constructor. */
StringMetaField() = default;
/** Move constructor. */
StringMetaField(StringMetaField&&) = default;
/** Move assignment operator. */
StringMetaField& operator=(StringMetaField&&) = default;
/**
Constructor with name and value.
*/
StringMetaField(
String name,
String value
) noexcept
: MetaField(std::move(name))
, value(std::move(value))
{}
/// @}
};
/**
Int32 MetaField.
*/
class Int32MetaField final
: public MetaField
{
public:
/** @name Properties */ /// @{
/** Value. */
std::int32_t value{0};
/// @}
private:
Int32MetaField(Int32MetaField const&) = delete;
Int32MetaField& operator=(Int32MetaField const&) = delete;
MetaField::type_info const&
get_type_info_impl() const noexcept override;
ser_result_type
read_impl(
InputSerializer& ser
) override {
ser(this->value);
}
ser_result_type
write_impl(
OutputSerializer& ser
) const override {
ser(this->value);
}
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~Int32MetaField() noexcept override = default;
/** Default constructor. */
Int32MetaField() = default;
/** Move constructor. */
Int32MetaField(Int32MetaField&&) = default;
/** Move assignment operator. */
Int32MetaField& operator=(Int32MetaField&&) = default;
/**
Constructor with name and value.
*/
Int32MetaField(
String name,
std::int32_t const value
) noexcept
: MetaField(std::move(name))
, value(value)
{}
/// @}
};
/**
Int64 MetaField.
*/
class Int64MetaField final
: public MetaField
{
public:
/** @name Properties */ /// @{
/** Value. */
std::int64_t value{0};
/// @}
private:
Int64MetaField(Int64MetaField const&) = delete;
Int64MetaField& operator=(Int64MetaField const&) = delete;
MetaField::type_info const&
get_type_info_impl() const noexcept override;
ser_result_type
read_impl(
InputSerializer& ser
) override {
ser(this->value);
}
ser_result_type
write_impl(
OutputSerializer& ser
) const override {
ser(this->value);
}
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~Int64MetaField() noexcept override = default;
/** Default constructor. */
Int64MetaField() = default;
/** Move constructor. */
Int64MetaField(Int64MetaField&&) = default;
/** Move assignment operator. */
Int64MetaField& operator=(Int64MetaField&&) = default;
/**
Constructor with name and value.
*/
Int64MetaField(
String name,
std::int64_t const value
) noexcept
: MetaField(std::move(name))
, value(value)
{}
/// @}
};
/**
Bool MetaField.
*/
class BoolMetaField final
: public MetaField
{
public:
/** @name Properties */ /// @{
/** Value. */
bool value{false};
/// @}
private:
BoolMetaField(BoolMetaField const&) = delete;
BoolMetaField& operator=(BoolMetaField const&) = delete;
MetaField::type_info const&
get_type_info_impl() const noexcept override;
ser_result_type
read_impl(
InputSerializer& ser
) override {
std::uint8_t boolu8 = 0;
ser(boolu8);
this->value = static_cast<bool>(boolu8);
}
ser_result_type
write_impl(
OutputSerializer& ser
) const override {
ser(static_cast<std::uint8_t>(this->value));
}
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~BoolMetaField() noexcept override = default;
/** Default constructor. */
BoolMetaField() = default;
/** Move constructor. */
BoolMetaField(BoolMetaField&&) = default;
/** Move assignment operator. */
BoolMetaField& operator=(BoolMetaField&&) = default;
/**
Constructor with name and value.
*/
BoolMetaField(
String name,
bool const value
) noexcept
: MetaField(std::move(name))
, value(value)
{}
/// @}
};
/**
Metadata.
@sa IO::PropType::metadata
*/
struct Metadata final {
public:
/** MetaField vector. */
using field_vector_type
= aux::vector<
duct::cc_unique_ptr<MetaField>
>;
/** @name Properties */ /// @{
/** Fields. */
field_vector_type fields{};
/// @}
private:
Metadata(Metadata const&) = delete;
Metadata& operator=(Metadata const&) = delete;
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~Metadata() noexcept = default;
/** Default constructor. */
Metadata() = default;
/** Move constructor. */
Metadata(Metadata&&) = default;
/** Move assignment operator. */
Metadata& operator=(Metadata&&) = default;
/// @}
/** @name Serialization */ /// @{
/**
Deserialize from prop stream.
@note State will be retained if an exception is thrown.
@pre @code
IO::PropType::metadata == prop_stream.get_type()
@endcode
@throws Error{ErrorCode::serialization_io_failed}
If an input operation failed.
@throws Error{ErrorCode::serialization_data_malformed}
If an invalid field type is encountered in the prop stream.
@param prop_stream %Prop stream.
*/
void
deserialize(
IO::InputPropStream& prop_stream
);
/**
Serialize to prop stream.
@note State will be retained if an exception is thrown.
@pre @code
IO::PropType::metadata == prop_stream.get_type()
@endcode
@throws Error{ErrorCode::serialization_io_failed}
If an output operation failed.
@param prop_stream %Prop stream.
*/
void
serialize(
IO::OutputPropStream& prop_stream
) const;
/// @}
};
/** @} */ // end of doc-group metadata
/** @} */ // end of doc-group data
} // namespace Data
} // namespace Hord
#endif // HORD_DATA_METADATA_HPP_
<|endoftext|>
|
<commit_before>/**
@file serialization.hpp
@brief Serialization definitions.
@author Timothy Howard
@copyright 2013-2014 Timothy Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_SERIALIZATION_HPP_
#define HORD_SERIALIZATION_HPP_
#include <Hord/config.hpp>
#include <Cacophony/types.hpp>
#include <Cacophony/traits.hpp>
#include <Cacophony/utility.hpp>
#include <Cacophony/ErrorCode.hpp>
#include <Cacophony/Error.hpp>
#include <Cacophony/BinarySerializer.hpp>
#include <Cacophony/support/binary_blob.hpp>
#include <Cacophony/support/sequence.hpp>
#include <Cacophony/support/string_cfg.hpp>
#include <Cacophony/support/vector_cfg.hpp>
#include <Cacophony/support/std_string.hpp>
#include <Cacophony/support/std_vector.hpp>
#include <duct/EndianUtils.hpp>
namespace Hord {
// Forward declarations
/**
@addtogroup serialization
@{
*/
using Cacophony::const_safe;
/**
Serializer error code type.
*/
using SerializerErrorCode = Cacophony::ErrorCode;
/**
Serializer error type.
*/
using SerializerError = Cacophony::Error;
/**
Data input serializer.
*/
using InputSerializer = Cacophony::BinaryInputSerializer;
/**
Data output serializer.
*/
using OutputSerializer = Cacophony::BinaryOutputSerializer;
/**
Serialization function result type.
*/
using ser_result_type = Cacophony::ser_result_type;
/**
Serialization function tags for Cacophony.
These should come first in the serialization function parameter
list.
@{
*/
using ser_tag_serialize = Cacophony::tag_serialize;
using ser_tag_read = Cacophony::tag_read;
using ser_tag_write = Cacophony::tag_write;
/** @} */
/**
Get the name of a serializer error.
@returns C-string containing the name of @a error_code or
"INVALID" if somehow @a error_code is not actually a
SerializerErrorCode.
*/
inline char const*
get_ser_error_name(
SerializerErrorCode const error_code
) noexcept {
return Cacophony::get_error_name(error_code);
}
/**
Make input serializer.
*/
inline InputSerializer
make_input_serializer(
std::istream& stream
) noexcept {
return InputSerializer{stream, HORD_DATA_ENDIAN};
}
/**
Make output serializer.
*/
inline OutputSerializer
make_output_serializer(
std::ostream& stream
) noexcept {
return OutputSerializer{stream, HORD_DATA_ENDIAN};
}
/** @cond INTERNAL */
#define HORD_SER_ERR_MSG_IO_GENERIC(skind_) \
"failed to " skind_ ":" \
" serialization error: \n {%s} %s"
#define HORD_SER_ERR_MSG_IO_PROP(skind_) \
"failed to " skind_ " prop %08x -> %s:" \
" serialization error: \n {%s} %s"
#define HORD_THROW_SER_FMT(efmt_, serr_) \
HORD_THROW_FMT( \
ErrorCode::serialization_io_failed, \
efmt_, \
get_ser_error_name(serr_.get_code()), \
serr_.get_message() \
)
//
#define HORD_THROW_SER_PROP(efmt_, serr_, objid_, pkind_) \
HORD_THROW_FMT( \
Hord::ErrorCode::serialization_io_failed, \
efmt_, \
objid_, \
pkind_, \
Hord::get_ser_error_name(serr_.get_code()), \
serr_.get_message() \
)
//
/** @endcond */ // INTERNAL
/** @} */ // end of doc-group serialization
} // namespace Hord
#endif // HORD_SERIALIZATION_HPP_
<commit_msg>serialization: included Cacophony::enum_cfg.<commit_after>/**
@file serialization.hpp
@brief Serialization definitions.
@author Timothy Howard
@copyright 2013-2014 Timothy Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_SERIALIZATION_HPP_
#define HORD_SERIALIZATION_HPP_
#include <Hord/config.hpp>
#include <Cacophony/types.hpp>
#include <Cacophony/traits.hpp>
#include <Cacophony/utility.hpp>
#include <Cacophony/ErrorCode.hpp>
#include <Cacophony/Error.hpp>
#include <Cacophony/BinarySerializer.hpp>
#include <Cacophony/support/binary_blob.hpp>
#include <Cacophony/support/sequence.hpp>
#include <Cacophony/support/enum_cfg.hpp>
#include <Cacophony/support/string_cfg.hpp>
#include <Cacophony/support/vector_cfg.hpp>
#include <Cacophony/support/std_string.hpp>
#include <Cacophony/support/std_vector.hpp>
#include <duct/EndianUtils.hpp>
namespace Hord {
// Forward declarations
/**
@addtogroup serialization
@{
*/
using Cacophony::const_safe;
/**
Serializer error code type.
*/
using SerializerErrorCode = Cacophony::ErrorCode;
/**
Serializer error type.
*/
using SerializerError = Cacophony::Error;
/**
Data input serializer.
*/
using InputSerializer = Cacophony::BinaryInputSerializer;
/**
Data output serializer.
*/
using OutputSerializer = Cacophony::BinaryOutputSerializer;
/**
Serialization function result type.
*/
using ser_result_type = Cacophony::ser_result_type;
/**
Serialization function tags for Cacophony.
These should come first in the serialization function parameter
list.
@{
*/
using ser_tag_serialize = Cacophony::tag_serialize;
using ser_tag_read = Cacophony::tag_read;
using ser_tag_write = Cacophony::tag_write;
/** @} */
/**
Get the name of a serializer error.
@returns C-string containing the name of @a error_code or
"INVALID" if somehow @a error_code is not actually a
SerializerErrorCode.
*/
inline char const*
get_ser_error_name(
SerializerErrorCode const error_code
) noexcept {
return Cacophony::get_error_name(error_code);
}
/**
Make input serializer.
*/
inline InputSerializer
make_input_serializer(
std::istream& stream
) noexcept {
return InputSerializer{stream, HORD_DATA_ENDIAN};
}
/**
Make output serializer.
*/
inline OutputSerializer
make_output_serializer(
std::ostream& stream
) noexcept {
return OutputSerializer{stream, HORD_DATA_ENDIAN};
}
/** @cond INTERNAL */
#define HORD_SER_ERR_MSG_IO_GENERIC(skind_) \
"failed to " skind_ ":" \
" serialization error: \n {%s} %s"
#define HORD_SER_ERR_MSG_IO_PROP(skind_) \
"failed to " skind_ " prop %08x -> %s:" \
" serialization error: \n {%s} %s"
#define HORD_THROW_SER_FMT(efmt_, serr_) \
HORD_THROW_FMT( \
ErrorCode::serialization_io_failed, \
efmt_, \
get_ser_error_name(serr_.get_code()), \
serr_.get_message() \
)
//
#define HORD_THROW_SER_PROP(efmt_, serr_, objid_, pkind_) \
HORD_THROW_FMT( \
Hord::ErrorCode::serialization_io_failed, \
efmt_, \
objid_, \
pkind_, \
Hord::get_ser_error_name(serr_.get_code()), \
serr_.get_message() \
)
//
/** @endcond */ // INTERNAL
/** @} */ // end of doc-group serialization
} // namespace Hord
#endif // HORD_SERIALIZATION_HPP_
<|endoftext|>
|
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#ifndef _ABACLADE_COROUTINE_HXX
#define _ABACLADE_COROUTINE_HXX
#ifndef _ABACLADE_HXX
#error "Please #include <abaclade.hxx> before this file"
#endif
#ifdef ABC_CXX_PRAGMA_ONCE
#pragma once
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::coroutine
namespace abc {
/*! Subroutine for use in non-preemptive multitasking, enabling asynchronous I/O in most abc::io
classes. */
class ABACLADE_SYM coroutine : public noncopyable {
private:
friend class coroutine_scheduler;
public:
//! OS-dependent execution context for the coroutine.
class context;
public:
/*! Constructor.
@param fnMain
Function to invoke once the coroutine is first scheduled.
@param coro
Source object.
*/
coroutine();
explicit coroutine(std::function<void ()> fnMain);
coroutine(coroutine && coro) :
m_pctx(std::move(coro.m_pctx)) {
}
//! Destructor.
~coroutine();
private:
//! Pointer to the coroutine’s execution context.
std::shared_ptr<context> m_pctx;
};
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::coroutine_scheduler
namespace abc {
//! Schedules coroutine execution.
class ABACLADE_SYM coroutine_scheduler : public noncopyable {
public:
//! Constructor.
coroutine_scheduler();
//! Destructor.
virtual ~coroutine_scheduler();
void add(coroutine const & coro);
static std::shared_ptr<coroutine_scheduler> const & attach_to_this_thread(
std::shared_ptr<coroutine_scheduler> pcorosched = nullptr
);
static std::shared_ptr<coroutine_scheduler> const & get_for_current_thread() {
return sm_pcorosched;
}
/*! Begins scheduling and running coroutines on the current thread. Only returns after every
coroutine added with add_coroutine() returns. */
virtual void run() = 0;
/*! Allows other coroutines to run while the asynchronous I/O operation completes, as an
alternative to blocking while waiting for its completion.
@param fd
File descriptor that the calling coroutine is waiting for I/O on.
@param bWrite
true if the coroutine is waiting to write to fd, or false if it’s waiting to read from it.
*/
virtual void yield_while_async_pending(io::filedesc const & fd, bool bWrite) = 0;
protected:
//! Pointer to the active (current) coroutine, or nullptr if none is active.
std::shared_ptr<coroutine::context> m_pcoroctxActive;
//! List of coroutines that have been scheduled, but have not been started yet.
collections::list<std::shared_ptr<coroutine::context>> m_listStartingCoros;
//! Pointer to the coroutine_scheduler for the current thread.
static thread_local_value<std::shared_ptr<coroutine_scheduler>> sm_pcorosched;
};
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //ifndef _ABACLADE_COROUTINE_HXX
<commit_msg>Make abc::coroutine_scheduler::coroutine_scheduler() protected<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#ifndef _ABACLADE_COROUTINE_HXX
#define _ABACLADE_COROUTINE_HXX
#ifndef _ABACLADE_HXX
#error "Please #include <abaclade.hxx> before this file"
#endif
#ifdef ABC_CXX_PRAGMA_ONCE
#pragma once
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::coroutine
namespace abc {
/*! Subroutine for use in non-preemptive multitasking, enabling asynchronous I/O in most abc::io
classes. */
class ABACLADE_SYM coroutine : public noncopyable {
private:
friend class coroutine_scheduler;
public:
//! OS-dependent execution context for the coroutine.
class context;
public:
/*! Constructor.
@param fnMain
Function to invoke once the coroutine is first scheduled.
@param coro
Source object.
*/
coroutine();
explicit coroutine(std::function<void ()> fnMain);
coroutine(coroutine && coro) :
m_pctx(std::move(coro.m_pctx)) {
}
//! Destructor.
~coroutine();
private:
//! Pointer to the coroutine’s execution context.
std::shared_ptr<context> m_pctx;
};
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::coroutine_scheduler
namespace abc {
//! Schedules coroutine execution.
class ABACLADE_SYM coroutine_scheduler : public noncopyable {
public:
//! Destructor.
virtual ~coroutine_scheduler();
void add(coroutine const & coro);
static std::shared_ptr<coroutine_scheduler> const & attach_to_this_thread(
std::shared_ptr<coroutine_scheduler> pcorosched = nullptr
);
static std::shared_ptr<coroutine_scheduler> const & get_for_current_thread() {
return sm_pcorosched;
}
/*! Begins scheduling and running coroutines on the current thread. Only returns after every
coroutine added with add_coroutine() returns. */
virtual void run() = 0;
/*! Allows other coroutines to run while the asynchronous I/O operation completes, as an
alternative to blocking while waiting for its completion.
@param fd
File descriptor that the calling coroutine is waiting for I/O on.
@param bWrite
true if the coroutine is waiting to write to fd, or false if it’s waiting to read from it.
*/
virtual void yield_while_async_pending(io::filedesc const & fd, bool bWrite) = 0;
protected:
//! Constructor.
coroutine_scheduler();
protected:
//! Pointer to the active (current) coroutine, or nullptr if none is active.
std::shared_ptr<coroutine::context> m_pcoroctxActive;
//! List of coroutines that have been scheduled, but have not been started yet.
collections::list<std::shared_ptr<coroutine::context>> m_listStartingCoros;
//! Pointer to the coroutine_scheduler for the current thread.
static thread_local_value<std::shared_ptr<coroutine_scheduler>> sm_pcorosched;
};
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //ifndef _ABACLADE_COROUTINE_HXX
<|endoftext|>
|
<commit_before>/*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/render/normals.hpp
*
* Copyright 2014-2019 Patrik Huber
*
* 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.
*/
#pragma once
#ifndef EOS_RENDER_NORMALS_HPP
#define EOS_RENDER_NORMALS_HPP
#include "glm/vec3.hpp"
#include "glm/geometric.hpp"
#include "Eigen/Core"
namespace eos {
namespace render {
/**
* Computes the normal of a face (triangle), i.e. the per-face normal. Returned normal will be unit length.
*
* Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are
* front-facing.
*
* @param[in] v0 First vertex.
* @param[in] v1 Second vertex.
* @param[in] v2 Third vertex.
* @return The unit-length normal of the given triangle.
*/
inline Eigen::Vector3f compute_face_normal(const Eigen::Vector3f& v0, const Eigen::Vector3f& v1,
const Eigen::Vector3f& v2)
{
Eigen::Vector3f n = (v1 - v0).cross(v2 - v0); // v0-to-v1 x v0-to-v2
return n.normalized();
};
/**
* Computes the normal of a face (triangle), i.e. the per-face normal. Returned normal will be unit length.
*
* Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are
* front-facing.
*
* @param[in] v0 First vertex.
* @param[in] v1 Second vertex.
* @param[in] v2 Third vertex.
* @return The unit-length normal of the given triangle.
*/
inline Eigen::Vector3f compute_face_normal(const Eigen::Vector4f& v0, const Eigen::Vector4f& v1,
const Eigen::Vector4f& v2)
{
Eigen::Vector4f n = (v1 - v0).cross3(v2 - v0); // v0-to-v1 x v0-to-v2
return n.head<3>().normalized();
};
/**
* Computes the normal of a face (triangle), i.e. the per-face normal. Returned normal will be unit length.
*
* Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are
* front-facing.
*
* @param[in] v0 First vertex.
* @param[in] v1 Second vertex.
* @param[in] v2 Third vertex.
* @return The unit-length normal of the given triangle.
*/
inline glm::vec3 compute_face_normal(const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2)
{
glm::vec3 n = glm::cross(v1 - v0, v2 - v0); // v0-to-v1 x v0-to-v2
n = glm::normalize(n);
return n;
};
} /* namespace render */
} /* namespace eos */
#endif /* EOS_RENDER_NORMALS_HPP */
<commit_msg>Add functions to compute face and vertex normals of a mesh<commit_after>/*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/render/normals.hpp
*
* Copyright 2014-2019 Patrik Huber
*
* 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.
*/
#pragma once
#ifndef EOS_RENDER_NORMALS_HPP
#define EOS_RENDER_NORMALS_HPP
#include "glm/vec3.hpp"
#include "glm/geometric.hpp"
#include "Eigen/Core"
#include <vector>
namespace eos {
namespace render {
/**
* Computes the normal of a face (triangle), i.e. the per-face normal. Returned normal will be unit length.
*
* Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are
* front-facing.
*
* @param[in] v0 First vertex.
* @param[in] v1 Second vertex.
* @param[in] v2 Third vertex.
* @return The unit-length normal of the given triangle.
*/
inline Eigen::Vector3f compute_face_normal(const Eigen::Vector3f& v0, const Eigen::Vector3f& v1,
const Eigen::Vector3f& v2)
{
Eigen::Vector3f n = (v1 - v0).cross(v2 - v0); // v0-to-v1 x v0-to-v2
return n.normalized();
};
/**
* Computes the normal of a face (triangle), i.e. the per-face normal. Returned normal will be unit length.
*
* Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are
* front-facing.
*
* @param[in] v0 First vertex.
* @param[in] v1 Second vertex.
* @param[in] v2 Third vertex.
* @return The unit-length normal of the given triangle.
*/
inline Eigen::Vector3f compute_face_normal(const Eigen::Vector4f& v0, const Eigen::Vector4f& v1,
const Eigen::Vector4f& v2)
{
Eigen::Vector4f n = (v1 - v0).cross3(v2 - v0); // v0-to-v1 x v0-to-v2
return n.head<3>().normalized();
};
/**
* Computes the normal of a face (triangle), i.e. the per-face normal. Returned normal will be unit length.
*
* Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are
* front-facing.
*
* @param[in] v0 First vertex.
* @param[in] v1 Second vertex.
* @param[in] v2 Third vertex.
* @return The unit-length normal of the given triangle.
*/
inline glm::vec3 compute_face_normal(const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2)
{
glm::vec3 n = glm::cross(v1 - v0, v2 - v0); // v0-to-v1 x v0-to-v2
n = glm::normalize(n);
return n;
};
/**
* Computes the per-face (per-triangle) normals of all triangles of the given mesh. Returned normals will be unit length.
*
* Assumes triangles are given in CCW order, i.e. vertices in counterclockwise order on the screen are front-facing.
*
* @param[in] vertices A list of vertices.
* @param[in] triangle_vertex_indices Triangle list for the given vertices.
* @return The unit-length per-face normals.
*/
inline std::vector<Eigen::Vector3f>
compute_face_normals(const std::vector<Eigen::Vector3f>& vertices,
const std::vector<std::array<int, 3>>& triangle_vertex_indices)
{
std::vector<Eigen::Vector3f> face_normals;
for (const auto& tvi : triangle_vertex_indices)
{
const auto face_normal = compute_face_normal(vertices[tvi[0]], vertices[tvi[1]], vertices[tvi[2]]);
face_normals.push_back(face_normal);
}
return face_normals;
};
/**
* Computes the per-vertex normals of all vertices of the given mesh. Returned normals will be unit length.
*
* Assumes triangles are given in CCW order, i.e. vertices in counterclockwise order on the screen are
* front-facing.
*
* @param[in] vertices A list of vertices.
* @param[in] triangle_vertex_indices Triangle list for the given vertices.
* @param[in] face_normals Per-face normals for all triangles.
* @return The unit-length per-vertex normals.
*/
inline std::vector<Eigen::Vector3f>
compute_vertex_normals(const std::vector<Eigen::Vector3f>& vertices,
const std::vector<std::array<int, 3>>& triangle_vertex_indices,
const std::vector<Eigen::Vector3f>& face_normals)
{
std::vector<Eigen::Vector3f> per_vertex_normals;
// Initialise with zeros:
for (int i = 0; i < vertices.size(); ++i)
{
per_vertex_normals.emplace_back(Eigen::Vector3f(0.0f, 0.0f, 0.0f));
}
// Loop over the faces again:
for (int i = 0; i < triangle_vertex_indices.size(); ++i)
{
const auto& tvi = triangle_vertex_indices[i];
// Throw normal at each corner:
per_vertex_normals[tvi[0]] += face_normals[i];
per_vertex_normals[tvi[1]] += face_normals[i];
per_vertex_normals[tvi[2]] += face_normals[i];
}
// Take average via normalization:
for (auto& n : per_vertex_normals)
{
n.normalize();
}
return per_vertex_normals;
};
} /* namespace render */
} /* namespace eos */
#endif /* EOS_RENDER_NORMALS_HPP */
<|endoftext|>
|
<commit_before>#pragma once
#include <string>
#include <engine/gfx/shapes.hpp>
#include <stlw/result.hpp>
#include <stlw/type_ctors.hpp>
namespace game
{
namespace boomhs
{
template <typename L>
class boomhs_game
{
L &logger_;
boomhs_game(L &l)
: logger_(l)
{
}
friend struct boomhs_library;
inline static bool is_quit_event(SDL_Event &event)
{
bool is_quit = false;
switch (event.type) {
case SDL_QUIT: {
is_quit = true;
break;
}
case SDL_KEYDOWN: {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE: {
is_quit = true;
break;
}
}
}
}
return is_quit;
}
public:
NO_COPY(boomhs_game);
MOVE_DEFAULT(boomhs_game);
template <typename R>
stlw::result<stlw::empty_type, std::string> init(R &renderer)
{
// nothing to do for now
return stlw::make_empty();
}
template <typename R>
void game_loop(R &renderer)
{
// Set up vertex data (and buffer(s)) and attribute pointers
constexpr float Wcoord = 1.0f;
// clang-format off
constexpr std::array<float, 12> v0 =
{
-0.5f , -0.5f, 0.0f, Wcoord, // bottom left
0.0f , -0.5f, 0.0f, Wcoord, // bottom right
-0.25f, 0.5f , 0.0f, Wcoord // top middle
};
constexpr std::array<float, 12> v1 =
{
0.5f , 0.0f, 0.0f, Wcoord, // bottom left
1.00f , 0.0f, 0.0f, Wcoord, // bottom right
0.75f , 1.0f, 0.0f, Wcoord // top middle
};
constexpr std::array<float, 12> c0 =
{
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
};
// clang-format on
using namespace engine::gfx;
constexpr triangle t0 = make_triangle(v0, c0);
constexpr triangle t1 = make_triangle(v1, c0);
renderer.draw(this->logger_, t0, t1);
}
bool process_event(SDL_Event &event) { return is_quit_event(event); }
};
struct boomhs_library {
boomhs_library() = delete;
DEFINE_STATIC_WRAPPER_FUNCTION(make_game, boomhs_game<P...>);
};
} // ns boomhs
} // ns game
<commit_msg>Inject triangle's initial position<commit_after>#pragma once
#include <string>
#include <engine/gfx/shapes.hpp>
#include <stlw/result.hpp>
#include <stlw/type_ctors.hpp>
namespace game
{
namespace boomhs
{
template <typename L>
class boomhs_game
{
L &logger_;
engine::gfx::triangle t0_;
engine::gfx::triangle t1_;
boomhs_game(L &l, engine::gfx::triangle const& t0, engine::gfx::triangle const& t1)
: logger_(l)
, t0_(std::move(t0))
, t1_(std::move(t1))
{
}
friend struct boomhs_library;
inline static bool is_quit_event(SDL_Event &event)
{
bool is_quit = false;
switch (event.type) {
case SDL_QUIT: {
is_quit = true;
break;
}
case SDL_KEYDOWN: {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE: {
is_quit = true;
break;
}
}
}
}
return is_quit;
}
public:
NO_COPY(boomhs_game);
MOVE_DEFAULT(boomhs_game);
template <typename R>
stlw::result<stlw::empty_type, std::string> init(R &renderer)
{
// nothing to do for now
return stlw::make_empty();
}
template <typename R>
void game_loop(R &renderer)
{
renderer.draw(this->logger_, this->t0_, this->t1_);
}
bool process_event(SDL_Event &event) { return is_quit_event(event); }
};
struct boomhs_library {
boomhs_library() = delete;
template<typename L>
static inline auto
make_game(L &logger)
{
// Set up vertex data (and buffer(s)) and attribute pointers
constexpr float Wcoord = 1.0f;
// clang-format off
constexpr std::array<float, 12> v0 =
{
-0.5f , -0.5f, 0.0f, Wcoord, // bottom left
0.0f , -0.5f, 0.0f, Wcoord, // bottom right
-0.25f, 0.5f , 0.0f, Wcoord // top middle
};
constexpr std::array<float, 12> v1 =
{
0.5f , 0.0f, 0.0f, Wcoord, // bottom left
1.00f , 0.0f, 0.0f, Wcoord, // bottom right
0.75f , 1.0f, 0.0f, Wcoord // top middle
};
constexpr std::array<float, 12> c0 =
{
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
};
// clang-format on
using namespace engine::gfx;
triangle t0 = make_triangle(v0, c0);
triangle t1 = make_triangle(v1, c0);
return boomhs_game<L>{logger, t0, t1};
}
};
} // ns boomhs
} // ns game
<|endoftext|>
|
<commit_before>//
// DemoFog.cpp
// IcEngDemo
//
// Created by Sherman Chen on 3/22/17.
// Copyright (c) 2017 Simviu Technology Inc.
// All rights reserved.
// http://www.simviu.com/dev
//
#include "DemoScene.h"
using namespace std;
using namespace ctl;
using namespace Ic3d;
static const string K_sModel = "IcDemo/MixShapes/MixShapes.obj";
static const int K_objAry_N = 10; // NxNxN of objs
static const int K_objAry_W = 10.0; // Width of objs
static const int K_objAry_H = 20.0; // Height of objs
//----------------------------------------------
// onInit
//----------------------------------------------
void DemoFog::onInit()
{
//--- Always call parent class onInit()
IcScene::onInit();
//--- Init Fog
//--- Load Scene
loadScene();
}
//----------------------------------------------
// loadScene
//----------------------------------------------
void DemoFog::loadScene()
{
//--- Load Object
const auto& cfg = IcApp::getInstance()->m_cfg;
string sPathRes = cfg.m_sPathRes;
string sFile = sPathRes + K_sModel;
auto pModel = ctl::makeSp<IcModel>(sFile);
// Add array of objs to Scene
int N = K_objAry_N;
float w = K_objAry_W;
float h = K_objAry_H;
for(int y=0;y<N;y++)
for(int x=0;x<N;x++)
for(int z=0;z<N;z++)
{
auto pObj = ctl::makeSp<IcObject>(pModel);
TVec3 pos((x-N/2)*w, (y-N/2)*h, (z-N/2)*w);
pObj->setPos(pos);
addObj(pObj);
}
}
<commit_msg>FogDemo added.<commit_after>//
// DemoFog.cpp
// IcEngDemo
//
// Created by Sherman Chen on 3/22/17.
// Copyright (c) 2017 Simviu Technology Inc.
// All rights reserved.
// http://www.simviu.com/dev
//
#include "DemoScene.h"
using namespace std;
using namespace ctl;
using namespace Ic3d;
static const string K_sModel = "IcDemo/MixShapes/MixShapes.obj";
static const int K_objAry_N = 10; // NxNxN of objs
static const int K_objAry_W = 10.0; // Width of objs
static const int K_objAry_H = 20.0; // Height of objs
//----------------------------------------------
// onInit
//----------------------------------------------
void DemoFog::onInit()
{
//--- Always call parent class onInit()
IcScene::onInit();
//--- Init Fog
m_cfg.m_fogPara.m_color = TColor(1,1,1,1);
m_cfg.m_fogPara.m_K_linear = 0.1;
//--- Load Scene
loadScene();
}
//----------------------------------------------
// loadScene
//----------------------------------------------
void DemoFog::loadScene()
{
//--- Load Object
const auto& cfg = IcApp::getInstance()->m_cfg;
string sPathRes = cfg.m_sPathRes;
string sFile = sPathRes + K_sModel;
auto pModel = ctl::makeSp<IcModel>(sFile);
// Add array of objs to Scene
int N = K_objAry_N;
float w = K_objAry_W;
float h = K_objAry_H;
for(int y=0;y<N;y++)
for(int x=0;x<N;x++)
for(int z=0;z<N;z++)
{
auto pObj = ctl::makeSp<IcObject>(pModel);
TVec3 pos((x-N/2)*w, (y-N/2)*h, (z-N/2)*w);
pObj->setPos(pos);
addObj(pObj);
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016-present, Facebook, Inc.
*
* 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 <condition_variable>
#include <mutex>
#include <stack>
#if !defined(_MSC_VER) && !defined(__APPLE__)
#include <sched.h>
#endif
#include "caffe2/core/context_gpu.h"
#include "caffe2/core/net_simple.h"
#include "caffe2/core/operator.h"
#include "caffe2/proto/caffe2.pb.h"
namespace caffe2 {
namespace gpu_single_thread {
struct Task {
std::vector<std::unique_ptr<OperatorBase>>* ops_;
std::condition_variable* cv_;
std::mutex* mtx_;
int stream_id_;
bool done_ = false;
};
class GPUExecutor {
public:
explicit GPUExecutor(int gpu_id) : gpu_id_(gpu_id) {}
~GPUExecutor() {
queue_.NoMoreJobs();
thread_.join();
}
void RunJob(Task* task) {
queue_.Push(task);
}
void start() {
thread_ = std::thread(&GPUExecutor::WorkerFunction, this);
}
static std::shared_ptr<GPUExecutor> Get(int gpu);
static void Release(int gpu);
private:
void set_affinity();
void WorkerFunction();
std::thread thread_;
int gpu_id_;
SimpleQueue<Task*> queue_;
static std::shared_ptr<GPUExecutor> executors_[CAFFE2_COMPILE_TIME_MAX_GPUS];
static std::mutex gpu_mtx_[CAFFE2_COMPILE_TIME_MAX_GPUS];
};
std::shared_ptr<GPUExecutor>
GPUExecutor::executors_[CAFFE2_COMPILE_TIME_MAX_GPUS];
std::mutex GPUExecutor::gpu_mtx_[CAFFE2_COMPILE_TIME_MAX_GPUS];
std::shared_ptr<GPUExecutor> GPUExecutor::Get(int gpu) {
std::lock_guard<std::mutex> grd(gpu_mtx_[gpu]);
if (!executors_[gpu].get()) {
executors_[gpu].reset(new GPUExecutor(gpu));
executors_[gpu].get()->start();
}
return executors_[gpu];
}
void GPUExecutor::Release(int gpu) {
std::lock_guard<std::mutex> grd(gpu_mtx_[gpu]);
if (executors_[gpu].use_count() == 1) {
executors_[gpu].reset();
}
}
void GPUExecutor::set_affinity() {
// TODO: find a Windows-compatible affinity setting approach.
// Currently, set_affinity has no effect in Windows. The code is still
// correct with possible slowdowns.
#if !defined(_MSC_VER) && !defined(__APPLE__)
/* Set CPU affinity */
int num_cores = std::thread::hardware_concurrency();
if (num_cores > 0) {
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(gpu_id_ % num_cores, &mask);
if (sched_setaffinity(0, sizeof(cpu_set_t), &mask)) {
LOG(WARNING) << "Could not set CPU affinity";
}
}
#endif
}
// Worker that takes list of operators from the queue
// and executes them.
void GPUExecutor::WorkerFunction() {
int stream_id_seq = 0;
std::stack<int> streams;
set_affinity();
while (true) {
Task* task = nullptr;
vector<Task*> task_batch;
if (!queue_.Pop(&task)) {
return;
}
int num_tasks = 1 + queue_.size();
// Grab all tasks currently in queue so we can run them in parallel
// Since we have only one producer, we know this does not block
// TODO: launch ops in "zig-zag" manner so that we can start multiple
// streams as simultaneously as possible
for (int i = num_tasks - 1; i >= 0; i--) {
assert(task != nullptr);
if (streams.empty()) {
task->stream_id_ = stream_id_seq++;
} else {
task->stream_id_ = streams.top();
streams.pop();
}
for (auto& op : *task->ops_) {
op->RunAsync(task->stream_id_);
}
task_batch.push_back(task);
// Get the next one
if (i > 0) {
if (!queue_.Pop(&task)) {
return;
}
}
}
// Wait for the currently executing streams
for (auto& pendtask : task_batch) {
cudaStream_t stream =
CUDAContext::cuda_stream(gpu_id_, pendtask->stream_id_);
CUDA_ENFORCE(cudaStreamSynchronize(stream));
streams.push(pendtask->stream_id_);
std::unique_lock<std::mutex> lk(*pendtask->mtx_);
pendtask->done_ = true;
pendtask->cv_->notify_one();
}
}
}
class SingleThreadAsyncNet : public SimpleNet {
public:
using SimpleNet::SimpleNet;
~SingleThreadAsyncNet() {
if (executor_.get()) {
// Explicitly reset my holding of the exeuctor so it can be
// killed.
executor_.reset();
GPUExecutor::Release(gpu_id_);
}
}
bool Run() {
if (!executor_.get()) {
initialize();
}
// Dispatch jobs to the gpu-specific executor thread
std::unique_lock<std::mutex> lk(mutex_);
Task t;
t.ops_ = &operators_;
t.cv_ = &cv_;
t.mtx_ = &mutex_;
t.done_ = false;
executor_.get()->RunJob(&t);
while (!t.done_) {
cv_.wait(lk);
}
return true;
}
private:
std::condition_variable cv_;
std::mutex mutex_;
void initialize() {
std::lock_guard<std::mutex> grd(mutex_);
/* Check the gpu id of this net and check that only one
GPU has operators on this net */
gpu_id_ = (-1);
for (auto& op : operators_) {
if (op->device_option().device_type() == CUDA) {
if (gpu_id_ < 0) {
gpu_id_ = op->device_option().cuda_gpu_id();
} else {
CAFFE_ENFORCE_EQ(
gpu_id_,
op->device_option().cuda_gpu_id(),
"One net can only have operators for one GPU");
}
}
}
executor_ = GPUExecutor::Get(gpu_id_);
}
int gpu_id_;
std::shared_ptr<GPUExecutor> executor_;
};
REGISTER_NET(singlethread_async, SingleThreadAsyncNet)
} // namespace gpu_single_thread
} // namespace caffe2
<commit_msg>Update SingleThreadAsyncNet<commit_after>/**
* Copyright (c) 2016-present, Facebook, Inc.
*
* 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 <condition_variable>
#include <mutex>
#include <stack>
#if !defined(_MSC_VER) && !defined(__APPLE__)
#include <sched.h>
#endif
#include "caffe2/core/context_gpu.h"
#include "caffe2/core/net_simple.h"
#include "caffe2/core/operator.h"
#include "caffe2/proto/caffe2.pb.h"
namespace caffe2 {
namespace gpu_single_thread {
struct Task {
std::vector<std::unique_ptr<OperatorBase>>* ops_;
std::condition_variable* cv_;
std::mutex* mtx_;
int stream_id_;
bool done_ = false;
};
class GPUExecutor {
public:
explicit GPUExecutor(int gpu_id) : gpu_id_(gpu_id) {}
~GPUExecutor() {
queue_.NoMoreJobs();
thread_.join();
}
void RunJob(Task* task) {
queue_.Push(task);
}
void start() {
thread_ = std::thread(&GPUExecutor::WorkerFunction, this);
}
static std::shared_ptr<GPUExecutor> Get(int gpu);
static void Release(int gpu);
private:
void set_affinity();
void WorkerFunction();
std::thread thread_;
int gpu_id_;
SimpleQueue<Task*> queue_;
static std::shared_ptr<GPUExecutor> executors_[CAFFE2_COMPILE_TIME_MAX_GPUS];
static std::mutex gpu_mtx_[CAFFE2_COMPILE_TIME_MAX_GPUS];
};
std::shared_ptr<GPUExecutor>
GPUExecutor::executors_[CAFFE2_COMPILE_TIME_MAX_GPUS];
std::mutex GPUExecutor::gpu_mtx_[CAFFE2_COMPILE_TIME_MAX_GPUS];
std::shared_ptr<GPUExecutor> GPUExecutor::Get(int gpu) {
std::lock_guard<std::mutex> grd(gpu_mtx_[gpu]);
if (!executors_[gpu].get()) {
executors_[gpu].reset(new GPUExecutor(gpu));
executors_[gpu].get()->start();
}
return executors_[gpu];
}
void GPUExecutor::Release(int gpu) {
std::lock_guard<std::mutex> grd(gpu_mtx_[gpu]);
if (executors_[gpu].use_count() == 1) {
executors_[gpu].reset();
}
}
void GPUExecutor::set_affinity() {
// TODO: find a Windows-compatible affinity setting approach.
// Currently, set_affinity has no effect in Windows. The code is still
// correct with possible slowdowns.
#if !defined(_MSC_VER) && !defined(__APPLE__)
/* Set CPU affinity */
int num_cores = std::thread::hardware_concurrency();
if (num_cores > 0) {
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(gpu_id_ % num_cores, &mask);
if (sched_setaffinity(0, sizeof(cpu_set_t), &mask)) {
LOG(WARNING) << "Could not set CPU affinity";
}
}
#endif
}
// Worker that takes list of operators from the queue
// and executes them.
void GPUExecutor::WorkerFunction() {
int stream_id_seq = 0;
std::stack<int> streams;
set_affinity();
while (true) {
Task* task = nullptr;
vector<Task*> task_batch;
if (!queue_.Pop(&task)) {
return;
}
int num_tasks = 1 + queue_.size();
// Grab all tasks currently in queue so we can run them in parallel
// Since we have only one producer, we know this does not block
// TODO: launch ops in "zig-zag" manner so that we can start multiple
// streams as simultaneously as possible
for (int i = num_tasks - 1; i >= 0; i--) {
assert(task != nullptr);
if (streams.empty()) {
task->stream_id_ = stream_id_seq++;
} else {
task->stream_id_ = streams.top();
streams.pop();
}
for (auto& op : *task->ops_) {
op->RunAsync(task->stream_id_);
}
task_batch.push_back(task);
// Get the next one
if (i > 0) {
if (!queue_.Pop(&task)) {
return;
}
}
}
// Wait for the currently executing streams
for (auto& pendtask : task_batch) {
cudaStream_t stream =
CUDAContext::cuda_stream(gpu_id_, pendtask->stream_id_);
CUDA_ENFORCE(cudaStreamSynchronize(stream));
streams.push(pendtask->stream_id_);
std::unique_lock<std::mutex> lk(*pendtask->mtx_);
pendtask->done_ = true;
pendtask->cv_->notify_one();
}
}
}
class SingleThreadAsyncNet : public SimpleNet {
public:
using SimpleNet::SimpleNet;
~SingleThreadAsyncNet() {
if (executor_.get()) {
// Explicitly reset my holding of the exeuctor so it can be
// killed.
executor_.reset();
GPUExecutor::Release(gpu_id_);
}
}
bool DoRunAsync() override {
if (!executor_.get()) {
initialize();
}
// Dispatch jobs to the gpu-specific executor thread
std::unique_lock<std::mutex> lk(mutex_);
Task t;
t.ops_ = &operators_;
t.cv_ = &cv_;
t.mtx_ = &mutex_;
t.done_ = false;
executor_.get()->RunJob(&t);
while (!t.done_) {
cv_.wait(lk);
}
return true;
}
private:
std::condition_variable cv_;
std::mutex mutex_;
void initialize() {
std::lock_guard<std::mutex> grd(mutex_);
/* Check the gpu id of this net and check that only one
GPU has operators on this net */
gpu_id_ = (-1);
for (auto& op : operators_) {
if (op->device_option().device_type() == CUDA) {
if (gpu_id_ < 0) {
gpu_id_ = op->device_option().cuda_gpu_id();
} else {
CAFFE_ENFORCE_EQ(
gpu_id_,
op->device_option().cuda_gpu_id(),
"One net can only have operators for one GPU");
}
}
}
executor_ = GPUExecutor::Get(gpu_id_);
}
int gpu_id_;
std::shared_ptr<GPUExecutor> executor_;
};
REGISTER_NET(singlethread_async, SingleThreadAsyncNet)
} // namespace gpu_single_thread
} // namespace caffe2
<|endoftext|>
|
<commit_before>/*******************************************************************************
* BAREFOOT NETWORKS CONFIDENTIAL & PROPRIETARY
*
* Copyright (c) 2017-2021 Barefoot Networks, Inc.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains the property of
* Barefoot Networks, Inc. and its suppliers, if any. The intellectual and
* technical concepts contained herein are proprietary to Barefoot Networks,
* Inc.
* and its suppliers and may be covered by U.S. and Foreign Patents, patents in
* process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material is
* strictly forbidden unless prior written permission is obtained from
* Barefoot Networks, Inc.
*
* No warranty, explicit or implicit is provided, unless granted under a
* written agreement with Barefoot Networks, Inc.
*
* $Id: $
*
******************************************************************************/
/** @file tdi_rt_init.hpp
*
* @brief Contains TDI Dev Manager APIs. These APIs help manage TdiInfo
* \n objects with respect to the devices and programs in the ecosystem.
*
* \n Contains DevMgr, Device, Target, Flags
*/
#ifndef _TDI_RT_INIT_HPP_
#define _TDI_RT_INIT_HPP_
#include <functional>
#include <memory>
#include <mutex>
// tdi includes
//#include <tdi/common/tdi_target.hpp>
//#include <tdi/common/tdi_info.hpp>
//#include <tdi/common/tdi_session.hpp>
// pna includes
#include <tdi/arch/pna/pna_init.hpp>
// local includes
#ifdef __cplusplus
extern "C" {
#endif
#include <dvm/bf_drv_intf.h>
#ifdef __cplusplus
}
#endif
namespace tdi {
namespace pna {
namespace rt {
/**
* @brief Class which encapsulates static info of a device eg.
* Arch type,
* Mgrs it was started with, State information, TdiInfo of all
* programs, Pipeline profile information.
*
* Static info means that none of this can be changed after
* device add happens.
*/
class Device : public tdi::pna::Device {
public:
Device(const tdi_dev_id_t &device_id,
const tdi_arch_type_e &arch_type,
const std::vector<tdi::ProgramConfig> &device_config,
const std::vector<tdi_mgr_type_e> mgr_type_list,
void *cookie);
virtual tdi_status_t createSession(
std::shared_ptr<tdi::Session> * /*session*/) const override final {
return TDI_SUCCESS;
}
virtual tdi_status_t createTarget(
std::unique_ptr<tdi::Target> * target) const override final {
*target=std::unique_ptr<tdi::Target>(new tdi::pna::Target(this->device_id_, 0, PNA_DIRECTION_ALL));
return TDI_SUCCESS;
}
virtual tdi_status_t createFlags(
const uint64_t & /*flags_val*/,
std::unique_ptr<tdi::Flags> * /*flags*/) const override final {
return TDI_SUCCESS;
}
private:
// This is where the real state map wil go
// std::map<std::string, std::shared_ptr<DeviceState>> tdi_dev_state_map_;
};
/**
* @brief Class to manage initialization of TDI <br>
* <B>Creation: </B> Cannot be created
*/
class Init : public tdi::Init {
public:
/**
* @brief Bf Rt Module Init API. This function needs to be called to
* initialize TDI. Some specific managers can be specified to be skipped
* TDI initialization. This allows TDI session layer to not know about these
* managers. By default, no mgr initialization is skipped if empty vector is
* passed
*
* @param[in] mgr_type_list vector of mgrs to skip initializing. If
* empty, don't skip anything
* @return Status of the API call
*/
static tdi_status_t tdiModuleInit(
const std::vector<tdi_mgr_type_e> mgr_type_list);
static std::string tdi_module_name;
static bf_drv_client_handle_t tdi_drv_hdl;
}; // Init
} // namespace rt
} // namespace pna
} // namespace tdi
#endif
<commit_msg>need to include the proper path for tdi_defs.h.<commit_after>/*******************************************************************************
* BAREFOOT NETWORKS CONFIDENTIAL & PROPRIETARY
*
* Copyright (c) 2017-2021 Barefoot Networks, Inc.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains the property of
* Barefoot Networks, Inc. and its suppliers, if any. The intellectual and
* technical concepts contained herein are proprietary to Barefoot Networks,
* Inc.
* and its suppliers and may be covered by U.S. and Foreign Patents, patents in
* process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material is
* strictly forbidden unless prior written permission is obtained from
* Barefoot Networks, Inc.
*
* No warranty, explicit or implicit is provided, unless granted under a
* written agreement with Barefoot Networks, Inc.
*
* $Id: $
*
******************************************************************************/
/** @file tdi_rt_init.hpp
*
* @brief Contains TDI Dev Manager APIs. These APIs help manage TdiInfo
* \n objects with respect to the devices and programs in the ecosystem.
*
* \n Contains DevMgr, Device, Target, Flags
*/
#ifndef _TDI_RT_INIT_HPP_
#define _TDI_RT_INIT_HPP_
#include <functional>
#include <memory>
#include <mutex>
// tdi includes
//#include <tdi/common/tdi_target.hpp>
//#include <tdi/common/tdi_info.hpp>
//#include <tdi/common/tdi_session.hpp>
// pna includes
#include <tdi/arch/pna/pna_init.hpp>
// local includes
#ifdef __cplusplus
extern "C" {
#endif
#include <tdi/common/tdi_defs.h>
#include <dvm/bf_drv_intf.h>
#ifdef __cplusplus
}
#endif
namespace tdi {
namespace pna {
namespace rt {
/**
* @brief Class which encapsulates static info of a device eg.
* Arch type,
* Mgrs it was started with, State information, TdiInfo of all
* programs, Pipeline profile information.
*
* Static info means that none of this can be changed after
* device add happens.
*/
class Device : public tdi::pna::Device {
public:
Device(const tdi_dev_id_t &device_id,
const tdi_arch_type_e &arch_type,
const std::vector<tdi::ProgramConfig> &device_config,
const std::vector<tdi_mgr_type_e> mgr_type_list,
void *cookie);
virtual tdi_status_t createSession(
std::shared_ptr<tdi::Session> * /*session*/) const override final {
return TDI_SUCCESS;
}
virtual tdi_status_t createTarget(
std::unique_ptr<tdi::Target> * target) const override final {
*target=std::unique_ptr<tdi::Target>(new tdi::pna::Target(this->device_id_, 0, PNA_DIRECTION_ALL));
return TDI_SUCCESS;
}
virtual tdi_status_t createFlags(
const uint64_t & /*flags_val*/,
std::unique_ptr<tdi::Flags> * /*flags*/) const override final {
return TDI_SUCCESS;
}
private:
// This is where the real state map wil go
// std::map<std::string, std::shared_ptr<DeviceState>> tdi_dev_state_map_;
};
/**
* @brief Class to manage initialization of TDI <br>
* <B>Creation: </B> Cannot be created
*/
class Init : public tdi::Init {
public:
/**
* @brief Bf Rt Module Init API. This function needs to be called to
* initialize TDI. Some specific managers can be specified to be skipped
* TDI initialization. This allows TDI session layer to not know about these
* managers. By default, no mgr initialization is skipped if empty vector is
* passed
*
* @param[in] mgr_type_list vector of mgrs to skip initializing. If
* empty, don't skip anything
* @return Status of the API call
*/
static tdi_status_t tdiModuleInit(
const std::vector<tdi_mgr_type_e> mgr_type_list);
static std::string tdi_module_name;
static bf_drv_client_handle_t tdi_drv_hdl;
}; // Init
} // namespace rt
} // namespace pna
} // namespace tdi
#endif
<|endoftext|>
|
<commit_before>#ifndef V_SMC_CORE_PARTICLE_HPP
#define V_SMC_CORE_PARTICLE_HPP
#include <vector>
#include <cmath>
#include <cstddef>
#include <boost/function.hpp>
#include <boost/random/binomial_distribution.hpp>
#include <boost/random/uniform_01.hpp>
#include <Eigen/Dense>
#include <vSMC/internal/rng.hpp>
#include <vSMC/internal/version.hpp>
namespace vSMC {
/// Resample scheme
enum ResampleScheme {
MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC, RESIDUAL_STRATIFIED};
/// \brief Particle class
///
/// Particle class store the particle set and arrays of weights and log
/// weights. It provides access to particle values as well as weights. It
/// computes and manages resources for ESS, resampling, etc, tasks unique to
/// each iteration.
template <typename T>
class Particle
{
public :
typedef V_SMC_RNG_TYPE rng_type;
/// \brief Construct a Particle object with given number of particles
///
/// \param N The number of particles
/// \param seed The seed to the parallel RNG system
Particle (std::size_t N, rng_type::seed_type seed = V_SMC_RNG_SEED) :
size_(N), value_(N),
weight_(N), log_weight_(N), inc_weight_(N), replication_(N),
ess_(0), resampled_(false), zconst_(0), prng_(N)
{
rng_type rng(seed);
rng.step_size(size_);
for (std::size_t i = 0; i != size_; ++i) {
rng.advance_ctr(i);
prng_[i] = rng;
}
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
/// \brief Size of the particle set
///
/// \return The number of particles
std::size_t size () const
{
return size_;
}
/// \brief Read and write access to particle values
///
/// \return A reference to the particle values, type (T &)
///
/// \note The Particle class guarantee that during the life type of the
/// object, the reference returned by this member will no be a dangle
/// handler.
T &value ()
{
return value_;
}
/// \brief Read only access to particle values
///
/// \return A const reference to the particle values
const T &value () const
{
return value_;
}
/// \brief Read only access to the weights
///
/// \return A const pointer to the weights
///
/// \note The Particle class guarantee that during the life type of the
/// object, the pointer returned by this always valid and point to the
/// same address
const double *weight_ptr () const
{
return weight_.data();
}
/// \brief Read only access to the log weights
///
/// \return A const pointer to the log weights
const double *log_weight_ptr () const
{
return log_weight_.data();
}
const Eigen::VectorXd &weight () const
{
return weight_;
}
const Eigen::VectorXd &log_weight () const
{
return log_weight_;
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const double *new_weight, double delta = 1)
{
Eigen::Map<const Eigen::VectorXd> w(new_weight, size_);
log_weight_ = delta * w;
set_weight();
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const double *inc_weight, double delta = 1,
bool add_zconst = true)
{
Eigen::Map<const Eigen::VectorXd> w(inc_weight, size_);
if (add_zconst) {
inc_weight_ = (delta * w).array().exp();
zconst_ += std::log(weight_.dot(inc_weight_));
}
log_weight_ += delta * w;
set_weight();
}
/// \brief The ESS (Effective Sample Size)
///
/// \return The value of ESS for current particle set
double ess () const
{
return ess_;
}
/// \brief Get indicator of resampling
///
/// \return A bool value, \b true if the current iteration was resampled
bool resampled () const
{
return resampled_;
}
/// \brief Set indicator of resampling
///
/// \param resampled \b true if the current iteration was resampled
void resampled (bool resampled)
{
resampled_ = resampled;
}
/// \brief Get the value of SMC normalizing constant
///
/// \return SMC normalizng constant estimate
double zconst () const
{
return zconst_;
}
/// \brief Reset the value of SMC normalizing constant
void reset_zconst ()
{
zconst_ = 0;
}
/// \brief Perform resampling
///
/// \param scheme The resampling scheme, see ResamplingScheme
void resample (ResampleScheme scheme)
{
switch (scheme) {
case MULTINOMIAL :
resample_multinomial();
break;
case RESIDUAL :
resample_residual();
break;
case STRATIFIED :
resample_stratified();
break;
case SYSTEMATIC :
resample_systematic();
break;
case RESIDUAL_STRATIFIED :
resample_residual_stratified ();
break;
default :
throw std::runtime_error(
"ERROR: vSMC::Particle::resample: "
"Unknown Resample Scheme");
}
}
rng_type &prng (std::size_t id)
{
return prng_[id];
}
private :
std::size_t size_;
T value_;
Eigen::VectorXd weight_;
Eigen::VectorXd log_weight_;
Eigen::VectorXd inc_weight_;
Eigen::VectorXi replication_;
double ess_;
bool resampled_;
double zconst_;
std::vector<rng_type> prng_;
typedef boost::random::binomial_distribution<> binom_type;
binom_type binom_;
void set_weight ()
{
double max_weight = log_weight_.maxCoeff();
log_weight_ = log_weight_.array() - max_weight;
weight_ = log_weight_.array().exp();
double sum = weight_.sum();
weight_ *= 1 / sum;
ess_ = 1 / weight_.squaredNorm();
}
void resample_multinomial ()
{
weight2replication(size_);
resample_do();
}
void resample_residual ()
{
// Reuse weight and log_weight. weight: act as the fractional part of
// N * weight. log_weight: act as the integral part of N * weight.
// They all will be reset to equal weights after resampling. So it is
// safe to modify them here.
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
std::size_t size = size_ - log_weight_.sum();
weight2replication(size);
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
resample_do();
}
void resample_stratified ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
boost::random::uniform_01<> unif;
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
u = unif(prng_[j++]);
}
cw += weight_[++k];
}
resample_do();
}
void resample_systematic ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
boost::random::uniform_01<> unif;
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
++j;
}
cw += weight_[++k];
}
resample_do();
}
void resample_residual_stratified ()
{
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
resample_stratified();
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
resample_do();
}
void weight2replication (std::size_t size)
{
double tp = weight_.sum();
double sum_p = 0;
std::size_t sum_n = 0;
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i) {
if (sum_n < size && weight_[i] > 0) {
binom_type::param_type
param(size - sum_n, weight_[i] / (tp - sum_p));
replication_[i] = binom_(prng_[i], param);
}
sum_p += weight_[i];
sum_n += replication_[i];
}
}
void resample_do ()
{
std::size_t from = 0;
std::size_t time = 0;
for (std::size_t to = 0; to != size_; ++to) {
if (!replication_[to]) {
// replication_[to] has zero child, copy from elsewhere
if (replication_[from] - time <= 1) {
// only 1 child left on replication_[from]
time = 0;
do // move from to some position with at least 2 children
++from;
while (replication_[from] < 2);
}
value_.copy(from, to);
++time;
}
}
ess_ = size_;
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
}; // class Particle
} // namespace vSMC
#endif // V_SMC_CORE_PARTICLE_HPP
<commit_msg>restore the check of case where replication does not sum up to number of particles<commit_after>#ifndef V_SMC_CORE_PARTICLE_HPP
#define V_SMC_CORE_PARTICLE_HPP
#include <vector>
#include <cmath>
#include <cstddef>
#include <boost/function.hpp>
#include <boost/random/binomial_distribution.hpp>
#include <boost/random/uniform_01.hpp>
#include <Eigen/Dense>
#include <vSMC/internal/rng.hpp>
#include <vSMC/internal/version.hpp>
namespace vSMC {
/// Resample scheme
enum ResampleScheme {
MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC, RESIDUAL_STRATIFIED};
/// \brief Particle class
///
/// Particle class store the particle set and arrays of weights and log
/// weights. It provides access to particle values as well as weights. It
/// computes and manages resources for ESS, resampling, etc, tasks unique to
/// each iteration.
template <typename T>
class Particle
{
public :
typedef V_SMC_RNG_TYPE rng_type;
/// \brief Construct a Particle object with given number of particles
///
/// \param N The number of particles
/// \param seed The seed to the parallel RNG system
Particle (std::size_t N, rng_type::seed_type seed = V_SMC_RNG_SEED) :
size_(N), value_(N),
weight_(N), log_weight_(N), inc_weight_(N), replication_(N),
ess_(0), resampled_(false), zconst_(0), prng_(N)
{
rng_type rng(seed);
rng.step_size(size_);
for (std::size_t i = 0; i != size_; ++i) {
rng.advance_ctr(i);
prng_[i] = rng;
}
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
/// \brief Size of the particle set
///
/// \return The number of particles
std::size_t size () const
{
return size_;
}
/// \brief Read and write access to particle values
///
/// \return A reference to the particle values, type (T &)
///
/// \note The Particle class guarantee that during the life type of the
/// object, the reference returned by this member will no be a dangle
/// handler.
T &value ()
{
return value_;
}
/// \brief Read only access to particle values
///
/// \return A const reference to the particle values
const T &value () const
{
return value_;
}
/// \brief Read only access to the weights
///
/// \return A const pointer to the weights
///
/// \note The Particle class guarantee that during the life type of the
/// object, the pointer returned by this always valid and point to the
/// same address
const double *weight_ptr () const
{
return weight_.data();
}
/// \brief Read only access to the log weights
///
/// \return A const pointer to the log weights
const double *log_weight_ptr () const
{
return log_weight_.data();
}
const Eigen::VectorXd &weight () const
{
return weight_;
}
const Eigen::VectorXd &log_weight () const
{
return log_weight_;
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const double *new_weight, double delta = 1)
{
Eigen::Map<const Eigen::VectorXd> w(new_weight, size_);
log_weight_ = delta * w;
set_weight();
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const double *inc_weight, double delta = 1,
bool add_zconst = true)
{
Eigen::Map<const Eigen::VectorXd> w(inc_weight, size_);
if (add_zconst) {
inc_weight_ = (delta * w).array().exp();
zconst_ += std::log(weight_.dot(inc_weight_));
}
log_weight_ += delta * w;
set_weight();
}
/// \brief The ESS (Effective Sample Size)
///
/// \return The value of ESS for current particle set
double ess () const
{
return ess_;
}
/// \brief Get indicator of resampling
///
/// \return A bool value, \b true if the current iteration was resampled
bool resampled () const
{
return resampled_;
}
/// \brief Set indicator of resampling
///
/// \param resampled \b true if the current iteration was resampled
void resampled (bool resampled)
{
resampled_ = resampled;
}
/// \brief Get the value of SMC normalizing constant
///
/// \return SMC normalizng constant estimate
double zconst () const
{
return zconst_;
}
/// \brief Reset the value of SMC normalizing constant
void reset_zconst ()
{
zconst_ = 0;
}
/// \brief Perform resampling
///
/// \param scheme The resampling scheme, see ResamplingScheme
void resample (ResampleScheme scheme)
{
switch (scheme) {
case MULTINOMIAL :
resample_multinomial();
break;
case RESIDUAL :
resample_residual();
break;
case STRATIFIED :
resample_stratified();
break;
case SYSTEMATIC :
resample_systematic();
break;
case RESIDUAL_STRATIFIED :
resample_residual_stratified ();
break;
default :
throw std::runtime_error(
"ERROR: vSMC::Particle::resample: "
"Unknown Resample Scheme");
}
}
rng_type &prng (std::size_t id)
{
return prng_[id];
}
private :
std::size_t size_;
T value_;
Eigen::VectorXd weight_;
Eigen::VectorXd log_weight_;
Eigen::VectorXd inc_weight_;
Eigen::VectorXi replication_;
double ess_;
bool resampled_;
double zconst_;
std::vector<rng_type> prng_;
typedef boost::random::binomial_distribution<> binom_type;
binom_type binom_;
void set_weight ()
{
double max_weight = log_weight_.maxCoeff();
log_weight_ = log_weight_.array() - max_weight;
weight_ = log_weight_.array().exp();
double sum = weight_.sum();
weight_ *= 1 / sum;
ess_ = 1 / weight_.squaredNorm();
}
void resample_multinomial ()
{
weight2replication(size_);
resample_do();
}
void resample_residual ()
{
// Reuse weight and log_weight. weight: act as the fractional part of
// N * weight. log_weight: act as the integral part of N * weight.
// They all will be reset to equal weights after resampling. So it is
// safe to modify them here.
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
std::size_t size = size_ - log_weight_.sum();
weight2replication(size);
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
resample_do();
}
void resample_stratified ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
boost::random::uniform_01<> unif;
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
u = unif(prng_[j++]);
}
cw += weight_[++k];
}
resample_do();
}
void resample_systematic ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
boost::random::uniform_01<> unif;
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
++j;
}
cw += weight_[++k];
}
resample_do();
}
void resample_residual_stratified ()
{
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
resample_stratified();
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
resample_do();
}
void weight2replication (std::size_t size)
{
double tp = weight_.sum();
double sum_p = 0;
std::size_t sum_n = 0;
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i) {
if (sum_n < size && weight_[i] > 0) {
binom_type::param_type
param(size - sum_n, weight_[i] / (tp - sum_p));
replication_[i] = binom_(prng_[i], param);
}
sum_p += weight_[i];
sum_n += replication_[i];
}
}
void resample_do ()
{
// Some times the nuemrical round error can cause the total childs
// differ from number of particles
std::size_t sum = replication_.sum();
if (sum != size_) {
Eigen::VectorXd::Index id_max;
replication_.maxCoeff(&id_max);
replication_[id_max] += size_ - sum;
}
std::size_t from = 0;
std::size_t time = 0;
for (std::size_t to = 0; to != size_; ++to) {
if (!replication_[to]) {
// replication_[to] has zero child, copy from elsewhere
if (replication_[from] - time <= 1) {
// only 1 child left on replication_[from]
time = 0;
do // move from to some position with at least 2 children
++from;
while (replication_[from] < 2);
}
value_.copy(from, to);
++time;
}
}
ess_ = size_;
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
}; // class Particle
} // namespace vSMC
#endif // V_SMC_CORE_PARTICLE_HPP
<|endoftext|>
|
<commit_before>#ifndef VSMC_CORE_PARTICLE_HPP
#define VSMC_CORE_PARTICLE_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/internal/resampling.hpp>
namespace vsmc {
/// \brief Particle class representing the whole particle set
/// \ingroup Core
///
/// \tparam T Requirement:
/// \li Constructor compatible with
/// \code T(Particle<T>::size_type N) \endcode
/// \li member function copy method compatible with
/// \code copy(Particle<T>::size_type from, Particle<T>::size_type to) \endcode
template <typename T>
class Particle
{
public :
/// The type of the size of the particle set
typedef VSMC_INDEX_TYPE size_type;
/// The type of the particle values
typedef T value_type;
#ifdef VSMC_USE_SEQUENTIAL_RNG
/// The type of the Counter-based random number generator C++11 engine
typedef VSMC_SEQRNG_TYPE rng_type;
#else
/// The type of the Counter-based random number generator
typedef VSMC_CBRNG_TYPE cbrng_type;
/// The type of the Counter-based random number generator C++11 engine
typedef rng::Engine<cbrng_type> rng_type;
#endif
/// The integer type of the seed
typedef rng_type::result_type seed_type;
/// The type of the weight and log weight vector
typedef Eigen::VectorXd weight_type;
/// \brief Construct a Particle object with a given number of particles
///
/// \param N The number of particles
/// \param seed The seed to the parallel RNG system
///
/// \post All weights are initialized to be euqal to each other
explicit Particle (size_type N, seed_type seed = VSMC_RNG_SEED) :
size_(N), value_(N),
weight_(N), log_weight_(N), inc_weight_(N), replication_(N),
ess_(N), resampled_(false), zconst_(0), seed_(seed)
#ifndef VSMC_USE_SEQUENTIAL_RNG
, prng_(N)
#endif
{
reset_rng();
set_equal_weight();
}
/// \brief Size of the particle set
///
/// \return The number of particles
size_type size () const
{
return size_;
}
/// \brief Read and write access to particle values
///
/// \return A reference to the particle values
value_type &value ()
{
return value_;
}
/// \brief Read only access to particle values
///
/// \return A const reference to the particle values
const value_type &value () const
{
return value_;
}
/// \brief Get the weight of a single particle
///
/// \param id The position of the particle, 0 to size() - 1
///
/// \return The weight of the particle at position id
double weight (size_type id) const
{
return weight_[id];
}
/// \brief Read only access to the weights through pointer
///
/// \return A const pointer to the weight array
const double *weight_ptr () const
{
return weight_.data();
}
/// \brief Read only access to the weights through Eigen vector
///
/// \return A const reference to the weight vector
const weight_type &weight () const
{
return weight_;
}
/// \brief Get the log weight of a single particle
///
/// \param id The position of the particle, 0 to size() - 1
///
/// \return The log weight of the particle at position id
double log_weight (size_type id) const
{
return log_weight_[id];
}
/// \brief Read only access to the log weights through pointer
///
/// \return A const pointer to the log weight array
const double *log_weight_ptr () const
{
return log_weight_.data();
}
/// \brief Read only access to the log weights through Eigen vector
///
/// \return A const reference to the log weight vector
const weight_type &log_weight () const
{
return log_weight_;
}
/// \brief Set equal weights for all particles
void set_equal_weight ()
{
ess_ = size_;
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const double *new_weight, double delta = 1)
{
Eigen::Map<const weight_type> w(new_weight, size_);
set_log_weight(w, delta);
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const weight_type &new_weight, double delta = 1)
{
log_weight_ = delta * new_weight.head(size_);
set_weight();
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const double *inc_weight, double delta = 1,
bool add_zconst = true)
{
Eigen::Map<const weight_type> w(inc_weight, size_);
add_log_weight(w, delta, add_zconst);
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const weight_type &inc_weight, double delta = 1,
bool add_zconst = true)
{
using std::log;
if (add_zconst) {
inc_weight_ = (delta * inc_weight.head(size_)).array().exp();
zconst_ += log(weight_.dot(inc_weight_.head(size_)));
}
log_weight_ += delta * inc_weight.head(size_);
set_weight();
}
/// \brief The ESS (Effective Sample Size)
///
/// \return The value of ESS for current particle set
double ess () const
{
return ess_;
}
/// \brief Get indicator of resampling
///
/// \return \b true if the current iteration was resampled
bool resampled () const
{
return resampled_;
}
/// \brief Get the value of SMC normalizing constant
///
/// \return Log of SMC normalizng constant estimate
double zconst () const
{
return zconst_;
}
/// \brief Reset the value of SMC normalizing constant
void reset_zconst ()
{
zconst_ = 0;
}
/// \brief Perform resampling
///
/// \param scheme The resampling scheme, see ResamplingScheme
/// \param threshold The threshold for resampling
void resample (ResampleScheme scheme, double threshold)
{
resampled_ = ess_ < threshold * size_;
if (resampled_) {
internal::pre_resampling(value_);
switch (scheme) {
case MULTINOMIAL :
resample_multinomial();
break;
case RESIDUAL :
resample_residual();
break;
case STRATIFIED :
resample_stratified();
break;
case SYSTEMATIC :
resample_systematic();
break;
case RESIDUAL_STRATIFIED :
resample_residual_stratified ();
break;
default :
resample_stratified();
break;
}
resample_do();
internal::post_resampling(value_);
}
}
/// \brief Get a C++11 RNG engine
///
/// \param id The position of the particle, 0 to size() - 1
///
/// \return A reference to a C++11 RNG engine unique to particle at
/// position id, and independent of others if \c VSMC_USE_SEQUENTIAL_RNG is
/// not defined. Otherwise, it is the same pseudo RNG for any value of \c
/// id
rng_type &rng (size_type id)
{
#ifdef VSMC_USE_SEQUENTIAL_RNG
return srng_;
#else
return prng_[id];
#endif
}
/// \brief Reset the parallel RNG system
///
/// \param seed The new seed to the system
void reset_rng (seed_type seed)
{
seed_ = seed;
reset_rng();
}
/// \brief Reset the parallel RNG system using last time used seed
void reset_rng ()
{
#ifdef VSMC_USE_SEQUENTIAL_RNG
srng_ = rng_type(seed_);
#else
for (size_type i = 0; i != size_; ++i)
prng_[i] = rng_type(seed_ + i);
#endif
}
private :
typedef Eigen::Matrix<size_type, Eigen::Dynamic, 1> replication_type;
size_type size_;
value_type value_;
weight_type weight_;
weight_type log_weight_;
weight_type inc_weight_;
replication_type replication_;
double ess_;
bool resampled_;
double zconst_;
seed_type seed_;
#ifdef VSMC_USE_SEQUENTIAL_RNG
rng_type srng_;
#else
std::deque<rng_type> prng_;
#endif
void set_weight ()
{
double max_weight = log_weight_.maxCoeff();
log_weight_ = log_weight_.array() - max_weight;
weight_ = log_weight_.array().exp();
double sum = weight_.sum();
weight_ *= 1 / sum;
ess_ = 1 / weight_.squaredNorm();
}
void resample_multinomial ()
{
weight2replication(size_);
}
void resample_residual ()
{
/// \internal Reuse weight and log_weight. weight: act as the
/// fractional part of N * weight. log_weight: act as the integral
/// part of N * weight. They all will be reset to equal weights after
/// resampling. So it is safe to modify them here.
using std::modf;
for (size_type i = 0; i != size_; ++i)
weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i);
weight2replication(weight_.sum());
for (size_type i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_stratified ()
{
replication_.setConstant(0);
size_type j = 0;
size_type k = 0;
rng::uniform_real_distribution<double> unif(0,1);
double u = unif(rng(0));
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
u = unif(rng(j));
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
}
void resample_systematic ()
{
replication_.setConstant(0);
size_type j = 0;
size_type k = 0;
rng::uniform_real_distribution<double> unif(0,1);
double u = unif(rng(0));
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
}
void resample_residual_stratified ()
{
using std::modf;
replication_.setConstant(0);
for (size_type i = 0; i != size_; ++i)
weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i);
size_type size = weight_.sum();
weight_ /= size;
size_type j = 0;
size_type k = 0;
rng::uniform_real_distribution<double> unif(0,1);
double u = unif(rng(0));
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
u = unif(rng(j));
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
for (size_type i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_residual_systematic ()
{
using std::modf;
replication_.setConstant(0);
for (size_type i = 0; i != size_; ++i)
weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i);
size_type size = weight_.sum();
weight_ /= size;
size_type j = 0;
size_type k = 0;
rng::uniform_real_distribution<double> unif(0,1);
double u = unif(rng(0));
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
for (size_type i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void weight2replication (size_type size)
{
double tp = weight_.sum();
double sum_p = 0;
size_type sum_n = 0;
replication_.setConstant(0);
for (size_type i = 0; i != size_; ++i) {
if (sum_n < size && weight_[i] > 0) {
rng::binomial_distribution<size_type> binom(
size - sum_n, weight_[i] / (tp - sum_p));
replication_[i] = binom(rng(i));
}
sum_p += weight_[i];
sum_n += replication_[i];
}
}
void resample_do ()
{
// Some times the nuemrical round error can cause the total childs
// differ from number of particles
size_type sum = replication_.sum();
if (sum != size_) {
size_type id_max;
replication_.maxCoeff(&id_max);
replication_[id_max] += size_ - sum;
}
size_type from = 0;
size_type time = 0;
for (size_type to = 0; to != size_; ++to) {
if (!replication_[to]) {
// replication_[to] has zero child, copy from elsewhere
if (replication_[from] - time <= 1) {
// only 1 child left on replication_[from]
time = 0;
do // move from to some position with at least 2 children
++from;
while (replication_[from] < 2);
}
value_.copy(from, to);
++time;
}
}
set_equal_weight();
}
}; // class Particle
} // namespace vsmc
#endif // VSMC_CORE_PARTICLE_HPP
<commit_msg>cache ESS and normalized weight computation<commit_after>#ifndef VSMC_CORE_PARTICLE_HPP
#define VSMC_CORE_PARTICLE_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/internal/resampling.hpp>
namespace vsmc {
/// \brief Particle class representing the whole particle set
/// \ingroup Core
///
/// \tparam T Requirement:
/// \li Constructor compatible with
/// \code T(Particle<T>::size_type N) \endcode
/// \li member function copy method compatible with
/// \code copy(Particle<T>::size_type from, Particle<T>::size_type to) \endcode
template <typename T>
class Particle
{
public :
/// The type of the size of the particle set
typedef VSMC_INDEX_TYPE size_type;
/// The type of the particle values
typedef T value_type;
#ifdef VSMC_USE_SEQUENTIAL_RNG
/// The type of the Counter-based random number generator C++11 engine
typedef VSMC_SEQRNG_TYPE rng_type;
#else
/// The type of the Counter-based random number generator
typedef VSMC_CBRNG_TYPE cbrng_type;
/// The type of the Counter-based random number generator C++11 engine
typedef rng::Engine<cbrng_type> rng_type;
#endif
/// The integer type of the seed
typedef rng_type::result_type seed_type;
/// The type of the weight and log weight vector
typedef Eigen::VectorXd weight_type;
/// \brief Construct a Particle object with a given number of particles
///
/// \param N The number of particles
/// \param seed The seed to the parallel RNG system
///
/// \post All weights are initialized to be euqal to each other
explicit Particle (size_type N, seed_type seed = VSMC_RNG_SEED) :
size_(N), value_(N), log_weight_(N), replication_(N),
weight_(N), weight_cached_(false), inc_weight_(N),
ess_(N), ess_cached_(false), resampled_(false), zconst_(0), seed_(seed)
#ifndef VSMC_USE_SEQUENTIAL_RNG
, prng_(N)
#endif
{
reset_rng();
set_equal_weight();
}
/// \brief Size of the particle set
///
/// \return The number of particles
size_type size () const
{
return size_;
}
/// \brief Read and write access to particle values
///
/// \return A reference to the particle values
value_type &value ()
{
return value_;
}
/// \brief Read only access to particle values
///
/// \return A const reference to the particle values
const value_type &value () const
{
return value_;
}
/// \brief Get the weight of a single particle
///
/// \param id The position of the particle, 0 to size() - 1
///
/// \return The weight of the particle at position id
double weight (size_type id) const
{
return weight()[id];
}
/// \brief Read only access to the weights through pointer
///
/// \return A const pointer to the weight array
const double *weight_ptr () const
{
return weight().data();
}
/// \brief Read only access to the weights through Eigen vector
///
/// \return A const reference to the weight vector
const weight_type &weight () const
{
if (!weight_cached_) {
weight_ = log_weight_.array().exp();
double sum = weight_.sum();
weight_ *= 1 / sum;
weight_cached_ = true;
}
return weight_;
}
/// \brief Get the log weight of a single particle
///
/// \param id The position of the particle, 0 to size() - 1
///
/// \return The log weight of the particle at position id
double log_weight (size_type id) const
{
return log_weight()[id];
}
/// \brief Read only access to the log weights through pointer
///
/// \return A const pointer to the log weight array
const double *log_weight_ptr () const
{
return log_weight().data();
}
/// \brief Read only access to the log weights through Eigen vector
///
/// \return A const reference to the log weight vector
const weight_type &log_weight () const
{
return log_weight_;
}
/// \brief Set equal weights for all particles
void set_equal_weight ()
{
log_weight_.setConstant(0);
weight_.setConstant(1.0 / size_);
weight_cached_ = true;
ess_ = size_;
ess_cached_ = true;
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const double *new_weight, double delta = 1)
{
Eigen::Map<const weight_type> w(new_weight, size_);
set_log_weight(w, delta);
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const weight_type &new_weight, double delta = 1)
{
log_weight_ = delta * new_weight.head(size_);
set_log_weight();
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const double *inc_weight, double delta = 1,
bool add_zconst = true)
{
Eigen::Map<const weight_type> w(inc_weight, size_);
add_log_weight(w, delta, add_zconst);
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const weight_type &inc_weight, double delta = 1,
bool add_zconst = true)
{
using std::log;
if (add_zconst) {
inc_weight_ = (delta * inc_weight.head(size_)).array().exp();
zconst_ += log(weight_.dot(inc_weight_.head(size_)));
}
log_weight_ += delta * inc_weight.head(size_);
set_log_weight();
}
/// \brief The ESS (Effective Sample Size)
///
/// \return The value of ESS for current particle set
double ess () const
{
if (!ess_cached_) {
ess_ = 1 / weight().squaredNorm();
ess_cached_ = true;
}
return ess_;
}
/// \brief Get indicator of resampling
///
/// \return \b true if the current iteration was resampled
bool resampled () const
{
return resampled_;
}
/// \brief Get the value of SMC normalizing constant
///
/// \return Log of SMC normalizng constant estimate
double zconst () const
{
return zconst_;
}
/// \brief Reset the value of SMC normalizing constant
void reset_zconst ()
{
zconst_ = 0;
}
/// \brief Perform resampling
///
/// \param scheme The resampling scheme, see ResamplingScheme
/// \param threshold The threshold for resampling
void resample (ResampleScheme scheme, double threshold)
{
resampled_ = ess() < threshold * size_;
if (resampled_) {
internal::pre_resampling(value_);
switch (scheme) {
case MULTINOMIAL :
resample_multinomial();
break;
case RESIDUAL :
resample_residual();
break;
case STRATIFIED :
resample_stratified();
break;
case SYSTEMATIC :
resample_systematic();
break;
case RESIDUAL_STRATIFIED :
resample_residual_stratified ();
break;
default :
resample_stratified();
break;
}
resample_do();
internal::post_resampling(value_);
}
}
/// \brief Get a C++11 RNG engine
///
/// \param id The position of the particle, 0 to size() - 1
///
/// \return A reference to a C++11 RNG engine unique to particle at
/// position id, and independent of others if \c VSMC_USE_SEQUENTIAL_RNG is
/// not defined. Otherwise, it is the same pseudo RNG for any value of \c
/// id
rng_type &rng (size_type id)
{
#ifdef VSMC_USE_SEQUENTIAL_RNG
return srng_;
#else
return prng_[id];
#endif
}
/// \brief Reset the parallel RNG system
///
/// \param seed The new seed to the system
void reset_rng (seed_type seed)
{
seed_ = seed;
reset_rng();
}
/// \brief Reset the parallel RNG system using last time used seed
void reset_rng ()
{
#ifdef VSMC_USE_SEQUENTIAL_RNG
srng_ = rng_type(seed_);
#else
for (size_type i = 0; i != size_; ++i)
prng_[i] = rng_type(seed_ + i);
#endif
}
private :
typedef Eigen::Matrix<size_type, Eigen::Dynamic, 1> replication_type;
size_type size_;
value_type value_;
weight_type log_weight_;
replication_type replication_;
mutable weight_type weight_;
mutable bool weight_cached_;
weight_type inc_weight_;
mutable double ess_;
mutable bool ess_cached_;
bool resampled_;
double zconst_;
seed_type seed_;
#ifdef VSMC_USE_SEQUENTIAL_RNG
rng_type srng_;
#else
std::deque<rng_type> prng_;
#endif
void set_log_weight ()
{
double max_weight = log_weight_.maxCoeff();
log_weight_ = log_weight_.array() - max_weight;
weight_cached_ = false;
ess_cached_ = false;
}
void resample_multinomial ()
{
weight2replication(size_);
}
void resample_residual ()
{
/// \internal Reuse weight and log_weight. weight: act as the
/// fractional part of N * weight. log_weight: act as the integral
/// part of N * weight. They all will be reset to equal weights after
/// resampling. So it is safe to modify them here.
using std::modf;
for (size_type i = 0; i != size_; ++i)
weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i);
weight2replication(weight_.sum());
for (size_type i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_stratified ()
{
replication_.setConstant(0);
size_type j = 0;
size_type k = 0;
rng::uniform_real_distribution<double> unif(0,1);
double u = unif(rng(0));
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
u = unif(rng(j));
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
}
void resample_systematic ()
{
replication_.setConstant(0);
size_type j = 0;
size_type k = 0;
rng::uniform_real_distribution<double> unif(0,1);
double u = unif(rng(0));
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
}
void resample_residual_stratified ()
{
using std::modf;
replication_.setConstant(0);
for (size_type i = 0; i != size_; ++i)
weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i);
size_type size = weight_.sum();
weight_ /= size;
size_type j = 0;
size_type k = 0;
rng::uniform_real_distribution<double> unif(0,1);
double u = unif(rng(0));
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
u = unif(rng(j));
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
for (size_type i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_residual_systematic ()
{
using std::modf;
replication_.setConstant(0);
for (size_type i = 0; i != size_; ++i)
weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i);
size_type size = weight_.sum();
weight_ /= size;
size_type j = 0;
size_type k = 0;
rng::uniform_real_distribution<double> unif(0,1);
double u = unif(rng(0));
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
for (size_type i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void weight2replication (size_type size)
{
double tp = weight_.sum();
double sum_p = 0;
size_type sum_n = 0;
replication_.setConstant(0);
for (size_type i = 0; i != size_; ++i) {
if (sum_n < size && weight_[i] > 0) {
rng::binomial_distribution<size_type> binom(
size - sum_n, weight_[i] / (tp - sum_p));
replication_[i] = binom(rng(i));
}
sum_p += weight_[i];
sum_n += replication_[i];
}
}
void resample_do ()
{
// Some times the nuemrical round error can cause the total childs
// differ from number of particles
size_type sum = replication_.sum();
if (sum != size_) {
size_type id_max;
replication_.maxCoeff(&id_max);
replication_[id_max] += size_ - sum;
}
size_type from = 0;
size_type time = 0;
for (size_type to = 0; to != size_; ++to) {
if (!replication_[to]) {
// replication_[to] has zero child, copy from elsewhere
if (replication_[from] - time <= 1) {
// only 1 child left on replication_[from]
time = 0;
do // move from to some position with at least 2 children
++from;
while (replication_[from] < 2);
}
value_.copy(from, to);
++time;
}
}
set_equal_weight();
}
}; // class Particle
} // namespace vsmc
#endif // VSMC_CORE_PARTICLE_HPP
<|endoftext|>
|
<commit_before>#ifndef VSMC_CORE_RESAMPLE_HPP
#define VSMC_CORE_RESAMPLE_HPP
#include <vsmc/internal/common.hpp>
namespace vsmc {
namespace internal {
template <typename SizeType, typename RngSetType>
inline void weight2replication (SizeType N, SizeType S, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
double sum_w = 0;
double acc_w = 0;
SizeType acc_s = 0;
for (SizeType i = 0; i != N; ++i) {
replication[i] = 0;
sum_w += weight[i];
}
for (SizeType i = 0; i != N; ++i) {
if (acc_s < S && weight[i] > 0) {
typedef typename cxx11::make_signed<SizeType>::type s_t;
s_t s = S - acc_s;
double p = weight[i] / (sum_w - acc_w);
if (p < 0) {
p = 0;
assert(p > -1e-6);
}
if (p > 1) {
p = 1;
assert(p - 1 < 1e-6);
}
cxx11::binomial_distribution<s_t> binom(s, p);
replication[i] = binom(rng_set.rng(i));
}
acc_w += weight[i];
acc_s += replication[i];
}
}
} // namespace vsmc::internal
/// \brief Resample scheme
/// \ingroup Core
enum ResampleScheme {
MULTINOMIAL, ///< Multinomial resampling
RESIDUAL, ///< Reisudal resampling
STRATIFIED, ///< Startified resampling
SYSTEMATIC, ///< Systematic resampling
RESIDUAL_STRATIFIED, ///< Stratified resampling on the residuals
RESIDUAL_SYSTEMATIC ///< Systematic resampling on the residuals
}; // enum ResamleScheme
/// \brief Int-to-Type struct template for resampling scheme
/// \ingroup Core
template <typename EnumType, EnumType S> struct ResampleType {};
/// \brief Resample class template
/// \ingroup Core
template <typename ResType, typename SizeType, typename RngSetType>
class Resample {};
/// \brief Multinomial resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, MULTINOMIAL>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
internal::weight2replication(N, N, rng_set, weight, replication);
}
}; // Mulitnomial resampling
/// \brief Residual resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, RESIDUAL>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
using std::modf;
residual_.resize(N);
integral_.resize(N);
for (SizeType i = 0; i != N; ++i)
residual_[i] = modf(N * weight[i], &integral_[i]);
double dsize = residual_.sum();
SizeType size = static_cast<SizeType>(dsize);
residual_ /= dsize;
internal::weight2replication(N, size, rng_set, residual_.data(),
replication);
for (SizeType i = 0; i != N; ++i)
replication[i] += static_cast<SizeType>(integral_[i]);
}
private :
Eigen::VectorXd residual_;
Eigen::VectorXd integral_;
}; // Residual resampling
/// \brief Stratified resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, STRATIFIED>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
for (SizeType i = 0; i != N; ++i)
replication[i] = 0;
SizeType j = 0;
SizeType k = 0;
cxx11::uniform_real_distribution<double> unif(0,1);
double u = unif(rng_set.rng(0));
double cw = weight[0];
while (j != N) {
while (j < cw * N - u && j != N) {
++replication[k];
u = unif(rng_set.rng(j));
++j;
}
if (k == N - 1)
break;
cw += weight[++k];
}
}
}; // Stratified resampling
/// \brief Systematic resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, SYSTEMATIC>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
for (SizeType i = 0; i != N; ++i)
replication[i] = 0;
SizeType j = 0;
SizeType k = 0;
cxx11::uniform_real_distribution<double> unif(0,1);
double u = unif(rng_set.rng(0));
double cw = weight[0];
while (j != N) {
while (j < cw * N - u && j != N) {
++replication[k];
++j;
}
if (k == N - 1)
break;
cw += weight[++k];
}
}
}; // Systematic resampling
/// \brief Residual stratified resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, RESIDUAL_STRATIFIED>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
using std::modf;
residual_.resize(N);
integral_.resize(N);
for (SizeType i = 0; i != N; ++i) {
replication[i] = 0;
residual_[i] = modf(N * weight[i], &integral_[i]);
}
double dsize = (residual_.sum());
SizeType size = static_cast<SizeType>(dsize);
residual_ /= dsize;
SizeType j = 0;
SizeType k = 0;
cxx11::uniform_real_distribution<double> unif(0,1);
double u = unif(rng_set.rng(0));
double cw = residual_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication[k];
u = unif(rng_set.rng(j));
++j;
}
if (k == N - 1)
break;
cw += residual_[++k];
}
for (SizeType i = 0; i != N; ++i)
replication[i] += static_cast<SizeType>(integral_[i]);
}
private :
Eigen::VectorXd residual_;
Eigen::VectorXd integral_;
}; // Residual stratified resampling
/// \brief Residual systematic resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, RESIDUAL_SYSTEMATIC>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
using std::modf;
residual_.resize(N);
integral_.resize(N);
for (SizeType i = 0; i != N; ++i) {
replication[i] = 0;
residual_[i] = modf(N * weight[i], &integral_[i]);
}
double dsize = (residual_.sum());
SizeType size = static_cast<SizeType>(dsize);
residual_ /= dsize;
SizeType j = 0;
SizeType k = 0;
cxx11::uniform_real_distribution<double> unif(0,1);
double u = unif(rng_set.rng(0));
double cw = residual_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication[k];
++j;
}
if (k == N - 1)
break;
cw += residual_[++k];
}
for (SizeType i = 0; i != N; ++i)
replication[i] += static_cast<SizeType>(integral_[i]);
}
private :
Eigen::VectorXd residual_;
Eigen::VectorXd integral_;
}; // Residual systematic resampling
} // namespace vsmc
#endif // VSMC_CORE_RESAMPLE_HPP
<commit_msg>rename weight2replicaiton with multinomial<commit_after>#ifndef VSMC_CORE_RESAMPLE_HPP
#define VSMC_CORE_RESAMPLE_HPP
#include <vsmc/internal/common.hpp>
namespace vsmc {
namespace internal {
template <typename SizeType, typename RngSetType>
inline void multinomial (SizeType N, SizeType S, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
double sum_w = 0;
double acc_w = 0;
SizeType acc_s = 0;
for (SizeType i = 0; i != N; ++i) {
replication[i] = 0;
sum_w += weight[i];
}
for (SizeType i = 0; i != N; ++i) {
if (acc_s < S && weight[i] > 0) {
typedef typename cxx11::make_signed<SizeType>::type s_t;
s_t s = S - acc_s;
double p = weight[i] / (sum_w - acc_w);
if (p < 0) {
p = 0;
assert(p > -1e-6);
}
if (p > 1) {
p = 1;
assert(p - 1 < 1e-6);
}
cxx11::binomial_distribution<s_t> binom(s, p);
replication[i] = binom(rng_set.rng(i));
}
acc_w += weight[i];
acc_s += replication[i];
}
}
} // namespace vsmc::internal
/// \brief Resample scheme
/// \ingroup Core
enum ResampleScheme {
MULTINOMIAL, ///< Multinomial resampling
RESIDUAL, ///< Reisudal resampling
STRATIFIED, ///< Startified resampling
SYSTEMATIC, ///< Systematic resampling
RESIDUAL_STRATIFIED, ///< Stratified resampling on the residuals
RESIDUAL_SYSTEMATIC ///< Systematic resampling on the residuals
}; // enum ResamleScheme
/// \brief Int-to-Type struct template for resampling scheme
/// \ingroup Core
template <typename EnumType, EnumType S> struct ResampleType {};
/// \brief Resample class template
/// \ingroup Core
template <typename ResType, typename SizeType, typename RngSetType>
class Resample {};
/// \brief Multinomial resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, MULTINOMIAL>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
internal::multinomial(N, N, rng_set, weight, replication);
}
}; // Mulitnomial resampling
/// \brief Residual resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, RESIDUAL>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
using std::modf;
residual_.resize(N);
integral_.resize(N);
for (SizeType i = 0; i != N; ++i)
residual_[i] = modf(N * weight[i], &integral_[i]);
double dsize = residual_.sum();
SizeType size = static_cast<SizeType>(dsize);
residual_ /= dsize;
internal::multinomial(N, size, rng_set, residual_.data(), replication);
for (SizeType i = 0; i != N; ++i)
replication[i] += static_cast<SizeType>(integral_[i]);
}
private :
Eigen::VectorXd residual_;
Eigen::VectorXd integral_;
}; // Residual resampling
/// \brief Stratified resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, STRATIFIED>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
for (SizeType i = 0; i != N; ++i)
replication[i] = 0;
SizeType j = 0;
SizeType k = 0;
cxx11::uniform_real_distribution<double> unif(0,1);
double u = unif(rng_set.rng(0));
double cw = weight[0];
while (j != N) {
while (j < cw * N - u && j != N) {
++replication[k];
u = unif(rng_set.rng(j));
++j;
}
if (k == N - 1)
break;
cw += weight[++k];
}
}
}; // Stratified resampling
/// \brief Systematic resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, SYSTEMATIC>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
for (SizeType i = 0; i != N; ++i)
replication[i] = 0;
SizeType j = 0;
SizeType k = 0;
cxx11::uniform_real_distribution<double> unif(0,1);
double u = unif(rng_set.rng(0));
double cw = weight[0];
while (j != N) {
while (j < cw * N - u && j != N) {
++replication[k];
++j;
}
if (k == N - 1)
break;
cw += weight[++k];
}
}
}; // Systematic resampling
/// \brief Residual stratified resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, RESIDUAL_STRATIFIED>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
using std::modf;
residual_.resize(N);
integral_.resize(N);
for (SizeType i = 0; i != N; ++i) {
replication[i] = 0;
residual_[i] = modf(N * weight[i], &integral_[i]);
}
double dsize = (residual_.sum());
SizeType size = static_cast<SizeType>(dsize);
residual_ /= dsize;
SizeType j = 0;
SizeType k = 0;
cxx11::uniform_real_distribution<double> unif(0,1);
double u = unif(rng_set.rng(0));
double cw = residual_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication[k];
u = unif(rng_set.rng(j));
++j;
}
if (k == N - 1)
break;
cw += residual_[++k];
}
for (SizeType i = 0; i != N; ++i)
replication[i] += static_cast<SizeType>(integral_[i]);
}
private :
Eigen::VectorXd residual_;
Eigen::VectorXd integral_;
}; // Residual stratified resampling
/// \brief Residual systematic resampling
/// \ingroup Core
template <typename SizeType, typename RngSetType>
class Resample<ResampleType<ResampleScheme, RESIDUAL_SYSTEMATIC>,
SizeType, RngSetType>
{
public :
void operator() (SizeType N, RngSetType &rng_set,
const double *weight, SizeType *replication)
{
using std::modf;
residual_.resize(N);
integral_.resize(N);
for (SizeType i = 0; i != N; ++i) {
replication[i] = 0;
residual_[i] = modf(N * weight[i], &integral_[i]);
}
double dsize = (residual_.sum());
SizeType size = static_cast<SizeType>(dsize);
residual_ /= dsize;
SizeType j = 0;
SizeType k = 0;
cxx11::uniform_real_distribution<double> unif(0,1);
double u = unif(rng_set.rng(0));
double cw = residual_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication[k];
++j;
}
if (k == N - 1)
break;
cw += residual_[++k];
}
for (SizeType i = 0; i != N; ++i)
replication[i] += static_cast<SizeType>(integral_[i]);
}
private :
Eigen::VectorXd residual_;
Eigen::VectorXd integral_;
}; // Residual systematic resampling
} // namespace vsmc
#endif // VSMC_CORE_RESAMPLE_HPP
<|endoftext|>
|
<commit_before>#include "Player.h"
#include <SFML/Graphics.hpp>
#include <iostream>
#include <sstream>
#include <iomanip>
#include "../World/World.h"
#include "../Renderer/RenderMaster.h"
sf::Font f;
Player::Player()
: Entity ({2500, 125, 2500}, {0, 0, 0}, {0.3, 1.0, 0.3})
, m_itemDown (sf::Keyboard::Down)
, m_itemUp (sf::Keyboard::Up)
, m_flyKey (sf::Keyboard::F)
{
for (int i = 0; i < 5; i++)
{
m_inventoryJumps.emplace_back
((sf::Keyboard::Key(sf::Keyboard::Num1 + i)));
}
f.loadFromFile("Res/Fonts/rs.ttf");
for (int i = 0; i < 5; i++)
{
m_items.emplace_back(Material::NOTHING, 0);
}
for (float i = 0; i < 5; i++)
{
sf::Text t;
t.setFont(f);
t.setOutlineColor(sf::Color::Black);
t.setCharacterSize(25);
t.setPosition({20.0f, 20.0f * i + 100.0f});
m_itemText.push_back(t);
}
m_posPrint.setFont(f);
m_posPrint.setOutlineColor(sf::Color::Black);
m_posPrint.setCharacterSize(25);
m_posPrint.setPosition(20.0f, 20.0f * 6.0f + 100.0f);
}
void Player::addItem(const Material& material)
{
Material::ID id = material.id;
for (unsigned i = 0; i < m_items.size(); i++)
{
if (m_items[i].getMaterial().id == id)
{
/*int leftOver =*/ m_items[i].add(1);
return;
}
else if (m_items[i].getMaterial().id == Material::ID::Nothing)
{
m_items[i] = {material, 1};
return;
}
}
}
ItemStack& Player::getHeldItems()
{
return m_items[m_heldItem];
}
void Player::handleInput(const sf::RenderWindow& window)
{
keyboardInput();
mouseInput(window);
if(m_itemDown.isKeyPressed())
{
m_heldItem++;
if (m_heldItem == (int)m_items.size())
{
m_heldItem = 0;
}
}
else if (m_itemUp.isKeyPressed())
{
m_heldItem--;
if (m_heldItem == -1)
{
m_heldItem = m_items.size() - 1;
}
}
for (int i = 0; i < 5; i++)
{
if(m_inventoryJumps[i].isKeyPressed())
{
m_heldItem = i;
}
}
if (m_flyKey.isKeyPressed())
{
m_isFlying = !m_isFlying;
}
}
void Player::update(float dt, World& world)
{
velocity += m_acceleation;
m_acceleation = {0, 0, 0};
if (!m_isFlying)
{
if (!m_isOnGround)
{
velocity.y -= 40 * dt;
}
m_isOnGround = false;
}
position.x += velocity.x * dt;
collide (world, {velocity.x, 0, 0}, dt);
position.y += velocity.y * dt;
collide (world, {0, velocity.y, 0}, dt);
position.z += velocity.z * dt;
collide (world, {0, 0, velocity.z}, dt);
box.update(position);
velocity.x *= 0.95;
velocity.z *= 0.95;
if (m_isFlying)
{
velocity.y *= 0.95;
}
}
void Player::collide(World& world, const glm::vec3& vel, float dt)
{
for (int x = position.x - box.dimensions.x; x < position.x + box.dimensions.x; x++)
for (int y = position.y - box.dimensions.y; y < position.y + 0.7 ; y++)
for (int z = position.z - box.dimensions.z; z < position.z + box.dimensions.z; z++)
{
auto block = world.getBlock(x, y, z);
if (block != 0 && block.getData().isCollidable)
{
if (vel.y > 0)
{
position.y = y - box.dimensions.y;
velocity.y = 0;
}
else if (vel.y < 0)
{
m_isOnGround = true;
position.y = y + box.dimensions.y + 1;
velocity.y = 0;
}
if (vel.x > 0)
{
position.x = x - box.dimensions.x;
}
else if (vel.x < 0)
{
position.x = x + box.dimensions.x + 1;
}
if (vel.z > 0)
{
position.z = z - box.dimensions.z;
}
else if (vel.z < 0)
{
position.z = z + box.dimensions.z + 1;
}
}
}
}
///@TODO Move this
float speed = 0.2f;
void Player::keyboardInput()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
float s = speed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::LControl)) s *= 5;
m_acceleation.x += -glm::cos(glm::radians(rotation.y + 90)) * s;
m_acceleation.z += -glm::sin(glm::radians(rotation.y + 90)) * s;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
m_acceleation.x += glm::cos(glm::radians(rotation.y + 90)) * speed;
m_acceleation.z += glm::sin(glm::radians(rotation.y + 90)) * speed;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
m_acceleation.x += -glm::cos(glm::radians(rotation.y)) * speed;
m_acceleation.z += -glm::sin(glm::radians(rotation.y)) * speed;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
m_acceleation.x += glm::cos(glm::radians(rotation.y)) * speed;
m_acceleation.z += glm::sin(glm::radians(rotation.y)) * speed;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
{
jump();
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift) && m_isFlying)
{
m_acceleation.y -= speed * 3;
}
}
void Player::mouseInput(const sf::RenderWindow& window)
{
static bool useMouse = true;
static ToggleKey useMouseKey (sf::Keyboard::L);
if (useMouseKey.isKeyPressed())
{
useMouse = !useMouse;
}
if (!useMouse)
{
return;
}
static sf::Vector2i center = {
static_cast<int>(window.getSize().x / 2),
static_cast<int>(window.getSize().y / 2)
};
static auto const BOUND = 89.9999;
static auto lastMousePosition = sf::Mouse::getPosition(window);
auto change = sf::Mouse::getPosition(window) - lastMousePosition;
rotation.y += change.x * 0.05;
rotation.x += change.y * 0.05;
if (rotation.x > BOUND) rotation.x = BOUND;
else if (rotation.x < -BOUND) rotation.x = -BOUND;
if (rotation.y > 360) rotation.y = 0;
else if (rotation.y < 0) rotation.y = 360;
lastMousePosition = sf::Mouse::getPosition(window);
if(lastMousePosition.x < 10 || lastMousePosition.x > window.getSize().x - 10 || lastMousePosition.y < 10 || lastMousePosition.y > window.getSize().y - 10 ) {
sf::Mouse::setPosition( center );
lastMousePosition = center;
}
}
void Player::draw(RenderMaster& master)
{
for (unsigned i = 0; i < m_items.size(); i++)
{
sf::Text& t = m_itemText[i];
if (i == (unsigned)m_heldItem)
{
t.setFillColor(sf::Color::Red);
}
else
{
t.setFillColor(sf::Color::White);
}
t.setString((m_items[i].getMaterial().name) + " " + std::to_string(m_items[i].getNumInStack()) + " ");
master.drawSFML(t);
}
std::ostringstream stream;
stream << " X: " << position.x
<< " Y: " << position.y
<< " Z: " << position.z
<< " Grounded " << std::boolalpha << m_isOnGround;
m_posPrint.setString(stream.str());
master.drawSFML(m_posPrint);
}
void Player::jump()
{
if (!m_isFlying)
{
if (m_isOnGround)
{
m_isOnGround = false;
m_acceleation.y += speed * 50;
}
}
else
{
m_acceleation.y += speed * 3;
}
}
<commit_msg>Added in-water physics<commit_after>#include "Player.h"
#include <SFML/Graphics.hpp>
#include <iostream>
#include <sstream>
#include <iomanip>
#include "../World/World.h"
#include "../Renderer/RenderMaster.h"
sf::Font f;
Player::Player()
: Entity ({2500, 125, 2500}, {0, 0, 0}, {0.3, 1.0, 0.3})
, m_itemDown (sf::Keyboard::Down)
, m_itemUp (sf::Keyboard::Up)
, m_flyKey (sf::Keyboard::F)
{
for (int i = 0; i < 5; i++)
{
m_inventoryJumps.emplace_back
((sf::Keyboard::Key(sf::Keyboard::Num1 + i)));
}
f.loadFromFile("Res/Fonts/rs.ttf");
for (int i = 0; i < 5; i++)
{
m_items.emplace_back(Material::NOTHING, 0);
}
for (float i = 0; i < 5; i++)
{
sf::Text t;
t.setFont(f);
t.setOutlineColor(sf::Color::Black);
t.setCharacterSize(25);
t.setPosition({20.0f, 20.0f * i + 100.0f});
m_itemText.push_back(t);
}
m_posPrint.setFont(f);
m_posPrint.setOutlineColor(sf::Color::Black);
m_posPrint.setCharacterSize(25);
m_posPrint.setPosition(20.0f, 20.0f * 6.0f + 100.0f);
}
void Player::addItem(const Material& material)
{
Material::ID id = material.id;
for (unsigned i = 0; i < m_items.size(); i++)
{
if (m_items[i].getMaterial().id == id)
{
/*int leftOver =*/ m_items[i].add(1);
return;
}
else if (m_items[i].getMaterial().id == Material::ID::Nothing)
{
m_items[i] = {material, 1};
return;
}
}
}
ItemStack& Player::getHeldItems()
{
return m_items[m_heldItem];
}
void Player::handleInput(const sf::RenderWindow& window)
{
keyboardInput();
mouseInput(window);
if(m_itemDown.isKeyPressed())
{
m_heldItem++;
if (m_heldItem == (int)m_items.size())
{
m_heldItem = 0;
}
}
else if (m_itemUp.isKeyPressed())
{
m_heldItem--;
if (m_heldItem == -1)
{
m_heldItem = m_items.size() - 1;
}
}
for (int i = 0; i < 5; i++)
{
if(m_inventoryJumps[i].isKeyPressed())
{
m_heldItem = i;
}
}
if (m_flyKey.isKeyPressed())
{
m_isFlying = !m_isFlying;
}
}
void Player::update(float dt, World& world)
{
velocity += m_acceleation;
m_acceleation = {0, 0, 0};
if (!m_isFlying)
{
if (!m_isOnGround)
{
if (m_isInWater)
{
velocity.y -= 8 * dt;
}
else
{
velocity.y -= 40 * dt;
}
}
m_isOnGround = false;
}
position.x += velocity.x * dt;
collide (world, {velocity.x, 0, 0}, dt);
position.y += velocity.y * dt;
collide (world, {0, velocity.y, 0}, dt);
position.z += velocity.z * dt;
collide (world, {0, 0, velocity.z}, dt);
box.update(position);
velocity.x *= 0.95;
velocity.z *= 0.95;
if (m_isFlying)
{
velocity.y *= 0.95;
}
}
void Player::collide(World& world, const glm::vec3& vel, float dt)
{
bool isTouching_Water = false;
for (int x = position.x - box.dimensions.x; x < position.x + box.dimensions.x; x++)
for (int y = position.y - box.dimensions.y; y < position.y + 0.7 ; y++)
for (int z = position.z - box.dimensions.z; z < position.z + box.dimensions.z; z++)
{
auto block = world.getBlock(x, y, z);
if (block == 0)
{
return;
}
if (block.getData().id == 7)
{
isTouchingWater = true;
}
if (block.getData().isCollidable)
{
if (vel.y > 0)
{
position.y = y - box.dimensions.y;
velocity.y = 0;
}
else if (vel.y < 0)
{
m_isOnGround = true;
position.y = y + box.dimensions.y + 1;
velocity.y = 0;
}
if (vel.x > 0)
{
position.x = x - box.dimensions.x;
}
else if (vel.x < 0)
{
position.x = x + box.dimensions.x + 1;
}
if (vel.z > 0)
{
position.z = z - box.dimensions.z;
}
else if (vel.z < 0)
{
position.z = z + box.dimensions.z + 1;
}
}
}
m_isInWater = isTouchinWater;
isTouchinWater = false;
}
///@TODO Move this
float speed = 0.2f;
void Player::keyboardInput()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
float s = speed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::LControl)) s *= 5;
m_acceleation.x += -glm::cos(glm::radians(rotation.y + 90)) * s;
m_acceleation.z += -glm::sin(glm::radians(rotation.y + 90)) * s;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
m_acceleation.x += glm::cos(glm::radians(rotation.y + 90)) * speed;
m_acceleation.z += glm::sin(glm::radians(rotation.y + 90)) * speed;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
m_acceleation.x += -glm::cos(glm::radians(rotation.y)) * speed;
m_acceleation.z += -glm::sin(glm::radians(rotation.y)) * speed;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
m_acceleation.x += glm::cos(glm::radians(rotation.y)) * speed;
m_acceleation.z += glm::sin(glm::radians(rotation.y)) * speed;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
{
jump();
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift) && m_isFlying)
{
m_acceleation.y -= speed * 3;
}
}
void Player::mouseInput(const sf::RenderWindow& window)
{
static bool useMouse = true;
static ToggleKey useMouseKey (sf::Keyboard::L);
if (useMouseKey.isKeyPressed())
{
useMouse = !useMouse;
}
if (!useMouse)
{
return;
}
static sf::Vector2i center = {
static_cast<int>(window.getSize().x / 2),
static_cast<int>(window.getSize().y / 2)
};
static auto const BOUND = 89.9999;
static auto lastMousePosition = sf::Mouse::getPosition(window);
auto change = sf::Mouse::getPosition(window) - lastMousePosition;
rotation.y += change.x * 0.05;
rotation.x += change.y * 0.05;
if (rotation.x > BOUND) rotation.x = BOUND;
else if (rotation.x < -BOUND) rotation.x = -BOUND;
if (rotation.y > 360) rotation.y = 0;
else if (rotation.y < 0) rotation.y = 360;
lastMousePosition = sf::Mouse::getPosition(window);
if(lastMousePosition.x < 10 || lastMousePosition.x > window.getSize().x - 10 || lastMousePosition.y < 10 || lastMousePosition.y > window.getSize().y - 10 ) {
sf::Mouse::setPosition( center );
lastMousePosition = center;
}
}
void Player::draw(RenderMaster& master)
{
for (unsigned i = 0; i < m_items.size(); i++)
{
sf::Text& t = m_itemText[i];
if (i == (unsigned)m_heldItem)
{
t.setFillColor(sf::Color::Red);
}
else
{
t.setFillColor(sf::Color::White);
}
t.setString((m_items[i].getMaterial().name) + " " + std::to_string(m_items[i].getNumInStack()) + " ");
master.drawSFML(t);
}
std::ostringstream stream;
stream << " X: " << position.x
<< " Y: " << position.y
<< " Z: " << position.z
<< " Grounded " << std::boolalpha << m_isOnGround;
m_posPrint.setString(stream.str());
master.drawSFML(m_posPrint);
}
void Player::jump()
{
if (!m_isFlying)
{
if (m_isOnGround)
{
m_isOnGround = false;
m_acceleation.y += speed * 50;
}
}
else
{
m_acceleation.y += speed * 3;
}
}
<|endoftext|>
|
<commit_before>/**
* @file fsradarentry.cpp
* @brief Firestorm radar entry implementation
*
* $LicenseInfo:firstyear=2013&license=viewerlgpl$
* Copyright (c) 2013 Ansariel Hiller @ Second Life
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* The Phoenix Firestorm Project, Inc., 1831 Oakwood Drive, Fairmont, Minnesota 56031-3225 USA
* http://www.firestormviewer.org
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "fsradarentry.h"
#include <boost/algorithm/string.hpp>
#include "fscommon.h"
#include "fsradar.h"
#include "rlvhandler.h"
using namespace boost;
FSRadarEntry::FSRadarEntry(const LLUUID& avid)
: mID(avid),
mName(avid.asString()),
mUserName(LLStringUtil::null),
mDisplayName(LLStringUtil::null),
mRange(0.f),
mFirstSeen(time(NULL)),
mGlobalPos(LLVector3d(0.0f,0.0f,0.0f)),
mRegion(LLUUID::null),
mStatus(0),
mZOffset(0.f),
mLastZOffsetTime(time(NULL)),
mAge(-1),
mIsLinden(false),
mAvatarNameCallbackConnection()
{
if (mID.notNull())
{
// NOTE: typically we request these once on creation to avoid excess traffic/processing.
//This means updates to these properties won't typically be seen while target is in nearby range.
LLAvatarPropertiesProcessor* processor = LLAvatarPropertiesProcessor::getInstance();
processor->addObserver(mID, this);
processor->sendAvatarPropertiesRequest(mID);
}
updateName();
}
FSRadarEntry::~FSRadarEntry()
{
if (mID.notNull())
{
LLAvatarPropertiesProcessor::getInstance()->removeObserver(mID, this); // may try to remove null observer
}
if (mAvatarNameCallbackConnection.connected())
{
mAvatarNameCallbackConnection.disconnect();
}
}
void FSRadarEntry::updateName()
{
if (mAvatarNameCallbackConnection.connected())
{
mAvatarNameCallbackConnection.disconnect();
}
mAvatarNameCallbackConnection = LLAvatarNameCache::get(mID, boost::bind(&FSRadarEntry::onAvatarNameCache, this, _1, _2));
}
void FSRadarEntry::onAvatarNameCache(const LLUUID& av_id, const LLAvatarName& av_name)
{
if (!gRlvHandler.hasBehaviour(RLV_BHVR_SHOWNAMES))
{
mUserName = av_name.getUserName();
mDisplayName = av_name.getDisplayName();
mName = getRadarName(av_name);
mIsLinden = FSCommon::isLinden(av_id);
}
else
{
std::string name = getRadarName(av_name);
mUserName = name;
mDisplayName = name;
mName = name;
mIsLinden = false;
}
}
void FSRadarEntry::processProperties(void* data, EAvatarProcessorType type)
{
if (data && type == APT_PROPERTIES)
{
LLAvatarData* avatar_data = static_cast<LLAvatarData*>(data);
mAge = ((LLDate::now().secondsSinceEpoch() - (avatar_data->born_on).secondsSinceEpoch()) / 86400);
mStatus = avatar_data->flags;
}
}
// static
std::string FSRadarEntry::getRadarName(const LLAvatarName& av_name)
{
// [RLVa:KB-FS] - Checked: 2011-06-11 (RLVa-1.3.1) | Added: RLVa-1.3.1
if (gRlvHandler.hasBehaviour(RLV_BHVR_SHOWNAMES))
{
return RlvStrings::getAnonym(av_name);
}
// [/RLVa:KB-FS]
U32 fmt = gSavedSettings.getU32("RadarNameFormat");
// if display names are enabled, allow a variety of formatting options, depending on menu selection
if (gSavedSettings.getBOOL("UseDisplayNames"))
{
if (fmt == FSRADAR_NAMEFORMAT_DISPLAYNAME)
{
return av_name.getDisplayName();
}
else if (fmt == FSRADAR_NAMEFORMAT_USERNAME)
{
return av_name.getUserName();
}
else if (fmt == FSRADAR_NAMEFORMAT_DISPLAYNAME_USERNAME)
{
std::string s1 = av_name.getDisplayName();
to_lower(s1);
std::string s2 = av_name.getUserName();
replace_all(s2, ".", " ");
if (s1.compare(s2) == 0)
{
return av_name.getDisplayName();
}
else
{
return llformat("%s (%s)", av_name.getDisplayName().c_str(), av_name.getUserName().c_str());
}
}
else if (fmt == FSRADAR_NAMEFORMAT_USERNAME_DISPLAYNAME)
{
std::string s1 = av_name.getDisplayName();
to_lower(s1);
std::string s2 = av_name.getUserName();
replace_all(s2, ".", " ");
if (s1.compare(s2) == 0)
{
return av_name.getDisplayName();
}
else
{
return llformat("%s (%s)", av_name.getUserName().c_str(), av_name.getDisplayName().c_str());
}
}
}
// else use legacy name lookups
return av_name.getDisplayName(); // will be mapped to legacyname automatically by the name cache
}
<commit_msg>Fixed names being shown in radar<commit_after>/**
* @file fsradarentry.cpp
* @brief Firestorm radar entry implementation
*
* $LicenseInfo:firstyear=2013&license=viewerlgpl$
* Copyright (c) 2013 Ansariel Hiller @ Second Life
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* The Phoenix Firestorm Project, Inc., 1831 Oakwood Drive, Fairmont, Minnesota 56031-3225 USA
* http://www.firestormviewer.org
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "fsradarentry.h"
#include <boost/algorithm/string.hpp>
#include "fscommon.h"
#include "fsradar.h"
#include "rlvhandler.h"
using namespace boost;
FSRadarEntry::FSRadarEntry(const LLUUID& avid)
: mID(avid),
mName(avid.asString()),
mUserName(LLStringUtil::null),
mDisplayName(LLStringUtil::null),
mRange(0.f),
mFirstSeen(time(NULL)),
mGlobalPos(LLVector3d(0.0f,0.0f,0.0f)),
mRegion(LLUUID::null),
mStatus(0),
mZOffset(0.f),
mLastZOffsetTime(time(NULL)),
mAge(-1),
mIsLinden(false),
mAvatarNameCallbackConnection()
{
if (mID.notNull())
{
// NOTE: typically we request these once on creation to avoid excess traffic/processing.
//This means updates to these properties won't typically be seen while target is in nearby range.
LLAvatarPropertiesProcessor* processor = LLAvatarPropertiesProcessor::getInstance();
processor->addObserver(mID, this);
processor->sendAvatarPropertiesRequest(mID);
}
updateName();
}
FSRadarEntry::~FSRadarEntry()
{
if (mID.notNull())
{
LLAvatarPropertiesProcessor::getInstance()->removeObserver(mID, this); // may try to remove null observer
}
if (mAvatarNameCallbackConnection.connected())
{
mAvatarNameCallbackConnection.disconnect();
}
}
void FSRadarEntry::updateName()
{
if (mAvatarNameCallbackConnection.connected())
{
mAvatarNameCallbackConnection.disconnect();
}
mAvatarNameCallbackConnection = LLAvatarNameCache::get(mID, boost::bind(&FSRadarEntry::onAvatarNameCache, this, _1, _2));
}
void FSRadarEntry::onAvatarNameCache(const LLUUID& av_id, const LLAvatarName& av_name)
{
if (!gRlvHandler.hasBehaviour(RLV_BHVR_SHOWNAMES))
{
mUserName = av_name.getUserName();
mDisplayName = av_name.getDisplayName();
mName = getRadarName(av_name);
mIsLinden = FSCommon::isLinden(av_id);
}
else
{
std::string name = getRadarName(av_name);
mUserName = name;
mDisplayName = name;
mName = name;
mIsLinden = false;
}
}
void FSRadarEntry::processProperties(void* data, EAvatarProcessorType type)
{
if (data && type == APT_PROPERTIES)
{
LLAvatarData* avatar_data = static_cast<LLAvatarData*>(data);
mAge = ((LLDate::now().secondsSinceEpoch() - (avatar_data->born_on).secondsSinceEpoch()) / 86400);
mStatus = avatar_data->flags;
}
}
// static
std::string FSRadarEntry::getRadarName(const LLAvatarName& av_name)
{
// [RLVa:KB-FS] - Checked: 2011-06-11 (RLVa-1.3.1) | Added: RLVa-1.3.1
if (gRlvHandler.hasBehaviour(RLV_BHVR_SHOWNAMES))
{
return RlvStrings::getAnonym(av_name);
}
// [/RLVa:KB-FS]
U32 fmt = gSavedSettings.getU32("RadarNameFormat");
// if display names are enabled, allow a variety of formatting options, depending on menu selection
if (gSavedSettings.getBOOL("UseDisplayNames"))
{
if (fmt == FSRADAR_NAMEFORMAT_DISPLAYNAME)
{
return av_name.getDisplayName();
}
else if (fmt == FSRADAR_NAMEFORMAT_USERNAME)
{
return av_name.getUserName();
}
else if (fmt == FSRADAR_NAMEFORMAT_DISPLAYNAME_USERNAME)
{
if (av_name.isDisplayNameDefault())
{
return av_name.getDisplayName();
}
else
{
return llformat("%s (%s)", av_name.getDisplayName().c_str(), av_name.getUserName().c_str());
}
}
else if (fmt == FSRADAR_NAMEFORMAT_USERNAME_DISPLAYNAME)
{
if (av_name.isDisplayNameDefault())
{
return av_name.getDisplayName();
}
else
{
return llformat("%s (%s)", av_name.getUserName().c_str(), av_name.getDisplayName().c_str());
}
}
}
// else use legacy name lookups
return av_name.getDisplayName(); // will be mapped to legacyname automatically by the name cache
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkScalarsToColors.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 <math.h>
#include "vtkScalarsToColors.h"
#include "vtkScalars.h"
// do not use SetMacro() because we do not the table to rebuild.
void vtkScalarsToColors::SetAlpha(float alpha)
{
this->Alpha = (alpha < 0.0 ? 0.0 : (alpha > 1.0 ? 1.0 : alpha));
}
vtkUnsignedCharArray *vtkScalarsToColors::MapScalars(vtkDataArray *scalars,
int colorMode, int comp)
{
vtkUnsignedCharArray *newColors;
vtkUnsignedCharArray *colors;
// map scalars through lookup table only if needed
if ( colorMode == VTK_COLOR_MODE_DEFAULT &&
(colors=vtkUnsignedCharArray::SafeDownCast(scalars)) != NULL )
{
newColors = this->
ConvertUnsignedCharToRGBA(colors, colors->GetNumberOfComponents(),
scalars->GetNumberOfTuples());
}
else
{
newColors = vtkUnsignedCharArray::New();
newColors->SetNumberOfComponents(4);
newColors->SetNumberOfTuples(scalars->GetNumberOfTuples());
this->
MapScalarsThroughTable2(scalars->GetVoidPointer(comp),
newColors->GetPointer(0),
scalars->GetDataType(),
scalars->GetNumberOfTuples(),
scalars->GetNumberOfComponents(),
VTK_RGBA);
}//need to map
return newColors;
}
// Map a set of scalar values through the table
void vtkScalarsToColors::MapScalarsThroughTable(vtkScalars *scalars,
unsigned char *output,
int outputFormat)
{
switch (outputFormat)
{
case VTK_RGBA:
case VTK_RGB:
case VTK_LUMINANCE_ALPHA:
case VTK_LUMINANCE:
break;
default:
vtkErrorMacro(<< "MapScalarsThroughTable: unrecognized color format");
break;
}
this->MapScalarsThroughTable2(scalars->GetVoidPointer(0),
output,
scalars->GetDataType(),
scalars->GetNumberOfScalars(),
scalars->GetNumberOfComponents(),
outputFormat);
}
vtkUnsignedCharArray *vtkScalarsToColors::ConvertUnsignedCharToRGBA(
vtkUnsignedCharArray *colors, int numComp, int numTuples)
{
unsigned char *cptr = colors->GetPointer(0);
vtkUnsignedCharArray *newColors = vtkUnsignedCharArray::New();
if ( numComp == 4 && this->Alpha >= 1.0 )
{
newColors->SetArray(cptr, numTuples, 0);
return newColors;
}
newColors->SetNumberOfComponents(4);
newColors->SetNumberOfTuples(numTuples);
unsigned char *nptr = newColors->GetPointer(0);
int i;
if ( this->Alpha >= 1.0 )
{
switch (numComp)
{
case 1:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = 255;
}
break;
case 2:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
}
break;
case 3:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = 255;
}
break;
default:
vtkErrorMacro(<<"Cannot convert colors");
return NULL;
}
}
else //blending required
{
unsigned char alpha;
switch (numComp)
{
case 1:
alpha = (unsigned char)(this->Alpha*255);
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = alpha;
}
break;
case 2:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = (unsigned char) ((*cptr)*this->Alpha); cptr++;
}
break;
case 3:
alpha = (unsigned char)(this->Alpha*255);
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = alpha;
}
break;
case 4:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = (unsigned char)((*cptr)*this->Alpha); cptr++;
}
break;
default:
vtkErrorMacro(<<"Cannot convert colors");
return NULL;
}
}
return newColors;
}
<commit_msg>ERR:Purify memory problem<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkScalarsToColors.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 <math.h>
#include "vtkScalarsToColors.h"
#include "vtkScalars.h"
// do not use SetMacro() because we do not the table to rebuild.
void vtkScalarsToColors::SetAlpha(float alpha)
{
this->Alpha = (alpha < 0.0 ? 0.0 : (alpha > 1.0 ? 1.0 : alpha));
}
vtkUnsignedCharArray *vtkScalarsToColors::MapScalars(vtkDataArray *scalars,
int colorMode, int comp)
{
vtkUnsignedCharArray *newColors;
vtkUnsignedCharArray *colors;
// map scalars through lookup table only if needed
if ( colorMode == VTK_COLOR_MODE_DEFAULT &&
(colors=vtkUnsignedCharArray::SafeDownCast(scalars)) != NULL )
{
newColors = this->
ConvertUnsignedCharToRGBA(colors, colors->GetNumberOfComponents(),
scalars->GetNumberOfTuples());
}
else
{
newColors = vtkUnsignedCharArray::New();
newColors->SetNumberOfComponents(4);
newColors->SetNumberOfTuples(scalars->GetNumberOfTuples());
this->
MapScalarsThroughTable2(scalars->GetVoidPointer(comp),
newColors->GetPointer(0),
scalars->GetDataType(),
scalars->GetNumberOfTuples(),
scalars->GetNumberOfComponents(),
VTK_RGBA);
}//need to map
return newColors;
}
// Map a set of scalar values through the table
void vtkScalarsToColors::MapScalarsThroughTable(vtkScalars *scalars,
unsigned char *output,
int outputFormat)
{
switch (outputFormat)
{
case VTK_RGBA:
case VTK_RGB:
case VTK_LUMINANCE_ALPHA:
case VTK_LUMINANCE:
break;
default:
vtkErrorMacro(<< "MapScalarsThroughTable: unrecognized color format");
break;
}
this->MapScalarsThroughTable2(scalars->GetVoidPointer(0),
output,
scalars->GetDataType(),
scalars->GetNumberOfScalars(),
scalars->GetNumberOfComponents(),
outputFormat);
}
vtkUnsignedCharArray *vtkScalarsToColors::ConvertUnsignedCharToRGBA(
vtkUnsignedCharArray *colors, int numComp, int numTuples)
{
if ( numComp == 4 && this->Alpha >= 1.0 )
{
colors->Register(this);
return colors;
}
unsigned char *cptr = colors->GetPointer(0);
vtkUnsignedCharArray *newColors = vtkUnsignedCharArray::New();
newColors->SetNumberOfComponents(4);
newColors->SetNumberOfTuples(numTuples);
unsigned char *nptr = newColors->GetPointer(0);
int i;
if ( this->Alpha >= 1.0 )
{
switch (numComp)
{
case 1:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = 255;
}
break;
case 2:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
}
break;
case 3:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = 255;
}
break;
default:
vtkErrorMacro(<<"Cannot convert colors");
return NULL;
}
}
else //blending required
{
unsigned char alpha;
switch (numComp)
{
case 1:
alpha = (unsigned char)(this->Alpha*255);
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = alpha;
}
break;
case 2:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr;
*nptr++ = *cptr;
*nptr++ = *cptr++;
*nptr++ = (unsigned char) ((*cptr)*this->Alpha); cptr++;
}
break;
case 3:
alpha = (unsigned char)(this->Alpha*255);
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = alpha;
}
break;
case 4:
for (i=0; i<numTuples; i++)
{
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = *cptr++;
*nptr++ = (unsigned char)((*cptr)*this->Alpha); cptr++;
}
break;
default:
vtkErrorMacro(<<"Cannot convert colors");
return NULL;
}
}
return newColors;
}
<|endoftext|>
|
<commit_before>#include "Explorer.h"
#include "imgui.h"
#include "imgui_docking.h"
#include "App.h"
#include "ModuleFileSystem.h"
#include "ModuleRenderer3D.h"
#include "JSONLoader.h"
#include "Functions.h"
#include "ResourceTextureLoader.h"
#include "ResourceManager.h"
Explorer::Explorer(bool start_enabled)
{
}
Explorer::~Explorer()
{
}
void Explorer::Start()
{
ResourceTextureLoader loader;
fbx_icon = loader.LoadTexture("UI/FBX_icon.png");
png_icon = loader.LoadTexture("UI/PNG_icon.png");
tga_icon = loader.LoadTexture("UI/TGA_icon.png");
folder_icon = loader.LoadTexture("UI/FOLDER_icon.png");
App->file_system->SetLookingPath(App->file_system->GetAssetsPath().c_str());
}
void Explorer::Draw()
{
igBeginDock("Explorer", &visible, ImGuiWindowFlags_MenuBar);
if (visible)
{
string looking_path = App->file_system->GetLookingPath();
ImGui::BeginMenuBar();
if (ImGui::MenuItem("Back"))
{
if (looking_path != App->file_system->GetAssetsPath())
App->file_system->SetLookingPath(GetParentDirectory(looking_path));
}
ImGui::EndMenuBar();
vector<string> files = App->file_system->GetFilesInPath(looking_path.c_str());
files = OrderFiles(files);
int i = 0;
for (vector<string>::iterator it = files.begin(); it != files.end(); ++it)
{
string path = App->file_system->GetPathFromFilePath((*it).c_str());
string filename = App->file_system->GetFileNameFromFilePath((*it).c_str());
string extension = App->file_system->GetFileExtension(filename.c_str());
extension = ToLowerCase(extension);
string name = App->file_system->GetFilenameWithoutExtension(filename.c_str(), false);
if (TextCmp(filename.c_str(), ".") || TextCmp(filename.c_str(), ".."))
continue;
if (TextCmp(extension.c_str(), "meta") || TextCmp(extension.c_str(), "prefab"))
continue;
if (TextCmp(extension.c_str(), "fbx")) {
ImGui::ImageButtonWithTextDOWN((ImTextureID*)fbx_icon, filename.c_str(), ImVec2(50, 50), ImVec2(-1, 1), ImVec2(0, 0), 10);
if (ImGui::IsMouseDoubleClicked(0) && ImGui::IsMouseHoveringRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()))
App->resource_manager->LoadFileIntoScene((*it).c_str());
}
else if (TextCmp(extension.c_str(), "png"))
{
ImGui::ImageButtonWithTextDOWN((ImTextureID*)png_icon, filename.c_str(), ImVec2(50, 50), ImVec2(-1, 1), ImVec2(0, 0), 10);
}
else if (TextCmp(extension.c_str(), "tga"))
{
ImGui::ImageButtonWithTextDOWN((ImTextureID*)tga_icon, filename.c_str(), ImVec2(50, 50), ImVec2(-1, 1), ImVec2(0, 0), 10);
}
else if (TextCmp(extension.c_str(), ""))
{
ImGui::ImageButtonWithTextDOWN((ImTextureID*)folder_icon, name.c_str(), ImVec2(50, 50), ImVec2(-1, 1), ImVec2(0, 0), 10);
if (ImGui::IsMouseDoubleClicked(0) && ImGui::IsMouseHoveringRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()))
{
App->file_system->SetLookingPath(path + filename + "\\");
}
}
//ImGui::SameLine();
//ImGui::Text(filename.c_str());
if (i < MAX_FILES_HORIZONTAL)
ImGui::SameLine();
else
i = -1;
}
}
igEndDock();
}
void Explorer::CleanUp()
{
ResourceTextureLoader loader;
loader.UnloadTexture(fbx_icon);
loader.UnloadTexture(png_icon);
loader.UnloadTexture(tga_icon);
loader.UnloadTexture(folder_icon);
}
vector<string> Explorer::OrderFiles(vector<string> files)
{
int size = files.size();
vector<string> tmp;
int i = 0;
while (i <= NUM_EXTENSIONS)
{
for (vector<string>::iterator it = files.begin(); it != files.end();)
{
string filename = App->file_system->GetFileNameFromFilePath((*it).c_str());
string extension = App->file_system->GetFileExtension(filename.c_str());
extension = ToLowerCase(extension);
if (i != NUM_EXTENSIONS && (TextCmp(filename.c_str(), ".") || TextCmp(filename.c_str(), "..")))
{
it++;
continue;
}
switch (i)
{
case 0: // Folders
if (!TextCmp(extension.c_str(), ""))
{
it++;
continue;
}
break;
case 1: // Fbx
if (!TextCmp(extension.c_str(), "fbx"))
{
it++;
continue;
}
break;
case 2: // Png
if (!TextCmp(extension.c_str(), "png"))
{
it++;
continue;
}
break;
case 3: // Png
if (!TextCmp(extension.c_str(), "tga"))
{
it++;
continue;
}
break;
case 4: // Others
break;
}
tmp.push_back(*it);
it = files.erase(it);
}
i++;
}
return tmp;
}
string Explorer::GetParentDirectory(string child)
{
string parent;
parent = child.substr(0, child.find_last_of("\\"));
parent = parent.substr(0, parent.find_last_of("\\"));
parent += "\\";
return parent;
}<commit_msg>Code left from last commit<commit_after>#include "Explorer.h"
#include "imgui.h"
#include "imgui_docking.h"
#include "App.h"
#include "ModuleFileSystem.h"
#include "ModuleRenderer3D.h"
#include "JSONLoader.h"
#include "Functions.h"
#include "ResourceTextureLoader.h"
#include "ResourceManager.h"
Explorer::Explorer(bool start_enabled)
{
}
Explorer::~Explorer()
{
}
void Explorer::Start()
{
ResourceTextureLoader loader;
fbx_icon = loader.LoadTexture("UI/FBX_icon.png");
png_icon = loader.LoadTexture("UI/PNG_icon.png");
tga_icon = loader.LoadTexture("UI/TGA_icon.png");
folder_icon = loader.LoadTexture("UI/FOLDER_icon.png");
App->file_system->SetLookingPath(App->file_system->GetAssetsPath().c_str());
}
void Explorer::Draw()
{
igBeginDock("Explorer", &visible, ImGuiWindowFlags_MenuBar);
if (visible)
{
string looking_path = App->file_system->GetLookingPath();
ImGui::BeginMenuBar();
if (ImGui::MenuItem("Back"))
{
if (looking_path != App->file_system->GetAssetsPath())
App->file_system->SetLookingPath(GetParentDirectory(looking_path));
}
if (ImGui::MenuItem("New Folder"))
{
App->file_system->CreateFolder(looking_path.c_str(), "new_folder");
}
ImGui::EndMenuBar();
vector<string> files = App->file_system->GetFilesInPath(looking_path.c_str());
files = OrderFiles(files);
int i = 0;
for (vector<string>::iterator it = files.begin(); it != files.end(); ++it)
{
string path = App->file_system->GetPathFromFilePath((*it).c_str());
string filename = App->file_system->GetFileNameFromFilePath((*it).c_str());
string extension = App->file_system->GetFileExtension(filename.c_str());
extension = ToLowerCase(extension);
string name = App->file_system->GetFilenameWithoutExtension(filename.c_str(), false);
if (TextCmp(filename.c_str(), ".") || TextCmp(filename.c_str(), ".."))
continue;
if (TextCmp(extension.c_str(), "meta") || TextCmp(extension.c_str(), "prefab"))
continue;
if (TextCmp(extension.c_str(), "fbx")) {
ImGui::ImageButtonWithTextDOWN((ImTextureID*)fbx_icon, filename.c_str(), ImVec2(50, 50), ImVec2(-1, 1), ImVec2(0, 0), 10);
if (ImGui::IsMouseDoubleClicked(0) && ImGui::IsMouseHoveringRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()))
App->resource_manager->LoadFileIntoScene((*it).c_str());
}
else if (TextCmp(extension.c_str(), "png"))
{
ImGui::ImageButtonWithTextDOWN((ImTextureID*)png_icon, filename.c_str(), ImVec2(50, 50), ImVec2(-1, 1), ImVec2(0, 0), 10);
}
else if (TextCmp(extension.c_str(), "tga"))
{
ImGui::ImageButtonWithTextDOWN((ImTextureID*)tga_icon, filename.c_str(), ImVec2(50, 50), ImVec2(-1, 1), ImVec2(0, 0), 10);
}
else if (TextCmp(extension.c_str(), ""))
{
ImGui::ImageButtonWithTextDOWN((ImTextureID*)folder_icon, name.c_str(), ImVec2(50, 50), ImVec2(-1, 1), ImVec2(0, 0), 10);
if (ImGui::IsMouseDoubleClicked(0) && ImGui::IsMouseHoveringRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()))
{
App->file_system->SetLookingPath(path + filename + "\\");
}
}
//ImGui::SameLine();
//ImGui::Text(filename.c_str());
if (i < MAX_FILES_HORIZONTAL)
ImGui::SameLine();
else
i = -1;
}
}
igEndDock();
}
void Explorer::CleanUp()
{
ResourceTextureLoader loader;
loader.UnloadTexture(fbx_icon);
loader.UnloadTexture(png_icon);
loader.UnloadTexture(tga_icon);
loader.UnloadTexture(folder_icon);
}
vector<string> Explorer::OrderFiles(vector<string> files)
{
int size = files.size();
vector<string> tmp;
int i = 0;
while (i <= NUM_EXTENSIONS)
{
for (vector<string>::iterator it = files.begin(); it != files.end();)
{
string filename = App->file_system->GetFileNameFromFilePath((*it).c_str());
string extension = App->file_system->GetFileExtension(filename.c_str());
extension = ToLowerCase(extension);
if (i != NUM_EXTENSIONS && (TextCmp(filename.c_str(), ".") || TextCmp(filename.c_str(), "..")))
{
it++;
continue;
}
switch (i)
{
case 0: // Folders
if (!TextCmp(extension.c_str(), ""))
{
it++;
continue;
}
break;
case 1: // Fbx
if (!TextCmp(extension.c_str(), "fbx"))
{
it++;
continue;
}
break;
case 2: // Png
if (!TextCmp(extension.c_str(), "png"))
{
it++;
continue;
}
break;
case 3: // Png
if (!TextCmp(extension.c_str(), "tga"))
{
it++;
continue;
}
break;
case 4: // Others
break;
}
tmp.push_back(*it);
it = files.erase(it);
}
i++;
}
return tmp;
}
string Explorer::GetParentDirectory(string child)
{
string parent;
parent = child.substr(0, child.find_last_of("\\"));
parent = parent.substr(0, parent.find_last_of("\\"));
parent += "\\";
return parent;
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <dali/internal/network/common/network-performance-server.h>
// INTERNAL INCLUDES
#include <dali/internal/system/common/performance-marker.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace // un-named namespace
{
const unsigned int SERVER_PORT = 3031;
const unsigned int MAXIMUM_PORTS_TO_TRY = 10; ///< if port in use, try up to SERVER_PORT + 10
const unsigned int CONNECTION_BACKLOG = 2; ///< maximum length of the queue of pending connections.
const unsigned int SOCKET_READ_BUFFER_SIZE = 4096;
typedef Vector<NetworkPerformanceClient*> ClientList;
/**
* POD passed to client thread on startup
*/
struct ClientThreadInfo
{
NetworkPerformanceServer* server;
NetworkPerformanceClient* client;
};
} // namespace
NetworkPerformanceServer::NetworkPerformanceServer(AdaptorInternalServices& adaptorServices,
const EnvironmentOptions& logOptions)
: mSocketFactory(adaptorServices.GetSocketFactoryInterface()),
mLogOptions(logOptions),
mServerThread(0),
mListeningSocket(NULL),
mClientUniqueId(0),
mClientCount(0),
mLogFunctionInstalled(false)
{
}
NetworkPerformanceServer::~NetworkPerformanceServer()
{
Stop();
if(mLogFunctionInstalled)
{
mLogOptions.UnInstallLogFunction();
}
}
void NetworkPerformanceServer::Start()
{
// start a thread to listen for incoming connection requests
if(!mServerThread)
{
if(mListeningSocket)
{
mSocketFactory.DestroySocket(mListeningSocket);
}
mListeningSocket = mSocketFactory.NewSocket(SocketInterface::TCP);
mListeningSocket->ReuseAddress(true);
bool bound = false;
unsigned int basePort = 0;
// try a small range of ports, so if multiple Dali apps are running you can select
// which one to connect to
while(!bound && (basePort < MAXIMUM_PORTS_TO_TRY))
{
bound = mListeningSocket->Bind(SERVER_PORT + basePort);
if(!bound)
{
basePort++;
}
}
if(!bound)
{
DALI_LOG_ERROR("Failed to bind to a port \n");
return;
}
mListeningSocket->Listen(CONNECTION_BACKLOG);
// start a thread which will block waiting for new connections
int error = pthread_create(&mServerThread, NULL, ConnectionListenerFunc, this);
DALI_ASSERT_ALWAYS(!error && "pthread create failed");
Dali::Integration::Log::LogMessage(Integration::Log::DebugInfo, "~~~ NetworkPerformanceServer started on port %d ~~~ \n", SERVER_PORT + basePort);
}
}
void NetworkPerformanceServer::Stop()
{
if(!mServerThread)
{
return;
}
if(mListeningSocket)
{
// close the server thread to prevent any new connections
mListeningSocket->ExitSelect();
}
// wait for the thread to exit.
void* exitValue;
pthread_join(mServerThread, &exitValue);
if(mListeningSocket)
{
// close the socket
mListeningSocket->CloseSocket();
}
mSocketFactory.DestroySocket(mListeningSocket);
mListeningSocket = NULL;
// this will tell all client threads to quit
StopClients();
}
bool NetworkPerformanceServer::IsRunning() const
{
if(mServerThread)
{
return true;
}
return false;
}
void NetworkPerformanceServer::ClientThread(NetworkPerformanceClient* client)
{
mClientCount++;
SocketInterface& socket(client->GetSocket());
for(;;)
{
SocketInterface::SelectReturn ret = socket.Select();
if(ret == SocketInterface::DATA_AVAILABLE)
{
// Read
char buffer[SOCKET_READ_BUFFER_SIZE];
unsigned int bytesRead;
bool ok = socket.Read(buffer, sizeof(buffer), bytesRead);
if(ok && (bytesRead > 0))
{
client->ProcessCommand(buffer, bytesRead);
}
else // if bytesRead == 0, then client closed connection, if ok == false then an error
{
DeleteClient(client);
return;
}
}
else // ret == QUIT or ERROR
{
DeleteClient(client);
return;
}
}
}
void NetworkPerformanceServer::ConnectionListener()
{
// install Dali logging function for this thread
if(!mLogFunctionInstalled)
{
mLogOptions.InstallLogFunction();
mLogFunctionInstalled = true;
}
for(;;)
{
// this will block, waiting for a client to connect
// or for mListeningSocket->ExitSelect() to be called
SocketInterface::SelectReturn ret = mListeningSocket->Select();
if(ret == SocketInterface::DATA_AVAILABLE)
{
SocketInterface* clientSocket = mListeningSocket->Accept();
// new connection made, spawn a thread to handle it
pthread_t* clientThread = new pthread_t();
NetworkPerformanceClient* client = AddClient(clientSocket, clientThread);
ClientThreadInfo* info = new ClientThreadInfo;
info->client = client;
info->server = this;
int error = pthread_create(clientThread, NULL, ClientThreadFunc, info);
DALI_ASSERT_ALWAYS(!error && "pthread create failed");
}
else // ret == SocketInterface::QUIT or SocketInterface::ERROR
{
return;
}
}
}
void* NetworkPerformanceServer::ClientThreadFunc(void* data)
{
ClientThreadInfo* info = static_cast<ClientThreadInfo*>(data);
info->server->ClientThread(info->client);
delete info;
return NULL;
}
NetworkPerformanceClient* NetworkPerformanceServer::AddClient(SocketInterface* clientSocket, pthread_t* clientThread)
{
// This function is only called from the listening thread
NetworkPerformanceClient* client = new NetworkPerformanceClient(clientThread,
clientSocket,
mClientUniqueId++,
*this,
mSocketFactory);
// protect the mClients list which can be accessed from multiple threads.
Mutex::ScopedLock lock(mClientListMutex);
mClients.PushBack(client);
return client;
}
void NetworkPerformanceServer::DeleteClient(NetworkPerformanceClient* client)
{
// protect the mClients list while modifying
Mutex::ScopedLock lock(mClientListMutex);
// remove from the list, and delete it
for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter)
{
if((*iter) == client)
{
mClients.Erase(iter);
delete client;
// if there server is shutting down, it waits for client count to hit zero
mClientCount--;
return;
}
}
}
void NetworkPerformanceServer::SendData(const char* const data, unsigned int bufferSizeInBytes, unsigned int clientId)
{
if(!mClientCount)
{
return;
}
// prevent clients been added / deleted while transmiting data
Mutex::ScopedLock lock(mClientListMutex);
for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter)
{
NetworkPerformanceClient* client = (*iter);
if(client->GetId() == clientId)
{
client->WriteSocket(data, bufferSizeInBytes);
return;
}
}
}
void NetworkPerformanceServer::TransmitMarker(const PerformanceMarker& marker, const char* const description)
{
if(!IsRunning())
{
return;
}
// prevent clients been added / deleted while transmiting data
Mutex::ScopedLock lock(mClientListMutex);
for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter)
{
NetworkPerformanceClient* client = (*iter);
client->TransmitMarker(marker, description);
}
}
void NetworkPerformanceServer::StopClients()
{
// prevent clients been added / deleted while stopping all clients
Mutex::ScopedLock lock(mClientListMutex);
for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter)
{
NetworkPerformanceClient* client = (*iter);
// stop the client from waiting for new commands, and exit from it's thread
client->ExitSelect();
}
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
<commit_msg>Fix the buffer overflow issue when reading socket data<commit_after>/*
* Copyright (c) 2022 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <dali/internal/network/common/network-performance-server.h>
// INTERNAL INCLUDES
#include <dali/internal/system/common/performance-marker.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace // un-named namespace
{
const unsigned int SERVER_PORT = 3031;
const unsigned int MAXIMUM_PORTS_TO_TRY = 10; ///< if port in use, try up to SERVER_PORT + 10
const unsigned int CONNECTION_BACKLOG = 2; ///< maximum length of the queue of pending connections.
const unsigned int SOCKET_READ_BUFFER_SIZE = 4096;
typedef Vector<NetworkPerformanceClient*> ClientList;
/**
* POD passed to client thread on startup
*/
struct ClientThreadInfo
{
NetworkPerformanceServer* server;
NetworkPerformanceClient* client;
};
} // namespace
NetworkPerformanceServer::NetworkPerformanceServer(AdaptorInternalServices& adaptorServices,
const EnvironmentOptions& logOptions)
: mSocketFactory(adaptorServices.GetSocketFactoryInterface()),
mLogOptions(logOptions),
mServerThread(0),
mListeningSocket(NULL),
mClientUniqueId(0),
mClientCount(0),
mLogFunctionInstalled(false)
{
}
NetworkPerformanceServer::~NetworkPerformanceServer()
{
Stop();
if(mLogFunctionInstalled)
{
mLogOptions.UnInstallLogFunction();
}
}
void NetworkPerformanceServer::Start()
{
// start a thread to listen for incoming connection requests
if(!mServerThread)
{
if(mListeningSocket)
{
mSocketFactory.DestroySocket(mListeningSocket);
}
mListeningSocket = mSocketFactory.NewSocket(SocketInterface::TCP);
mListeningSocket->ReuseAddress(true);
bool bound = false;
unsigned int basePort = 0;
// try a small range of ports, so if multiple Dali apps are running you can select
// which one to connect to
while(!bound && (basePort < MAXIMUM_PORTS_TO_TRY))
{
bound = mListeningSocket->Bind(SERVER_PORT + basePort);
if(!bound)
{
basePort++;
}
}
if(!bound)
{
DALI_LOG_ERROR("Failed to bind to a port \n");
return;
}
mListeningSocket->Listen(CONNECTION_BACKLOG);
// start a thread which will block waiting for new connections
int error = pthread_create(&mServerThread, NULL, ConnectionListenerFunc, this);
DALI_ASSERT_ALWAYS(!error && "pthread create failed");
Dali::Integration::Log::LogMessage(Integration::Log::DebugInfo, "~~~ NetworkPerformanceServer started on port %d ~~~ \n", SERVER_PORT + basePort);
}
}
void NetworkPerformanceServer::Stop()
{
if(!mServerThread)
{
return;
}
if(mListeningSocket)
{
// close the server thread to prevent any new connections
mListeningSocket->ExitSelect();
}
// wait for the thread to exit.
void* exitValue;
pthread_join(mServerThread, &exitValue);
if(mListeningSocket)
{
// close the socket
mListeningSocket->CloseSocket();
}
mSocketFactory.DestroySocket(mListeningSocket);
mListeningSocket = NULL;
// this will tell all client threads to quit
StopClients();
}
bool NetworkPerformanceServer::IsRunning() const
{
if(mServerThread)
{
return true;
}
return false;
}
void NetworkPerformanceServer::ClientThread(NetworkPerformanceClient* client)
{
mClientCount++;
SocketInterface& socket(client->GetSocket());
for(;;)
{
SocketInterface::SelectReturn ret = socket.Select();
if(ret == SocketInterface::DATA_AVAILABLE)
{
// Read
char buffer[SOCKET_READ_BUFFER_SIZE];
unsigned int bytesRead;
bool ok = socket.Read(buffer, sizeof(buffer), bytesRead);
if(ok && (bytesRead > 0) && (bytesRead <= SOCKET_READ_BUFFER_SIZE))
{
client->ProcessCommand(buffer, bytesRead);
}
else // if bytesRead == 0, then client closed connection, if ok == false then an error
{
DeleteClient(client);
return;
}
}
else // ret == QUIT or ERROR
{
DeleteClient(client);
return;
}
}
}
void NetworkPerformanceServer::ConnectionListener()
{
// install Dali logging function for this thread
if(!mLogFunctionInstalled)
{
mLogOptions.InstallLogFunction();
mLogFunctionInstalled = true;
}
for(;;)
{
// this will block, waiting for a client to connect
// or for mListeningSocket->ExitSelect() to be called
SocketInterface::SelectReturn ret = mListeningSocket->Select();
if(ret == SocketInterface::DATA_AVAILABLE)
{
SocketInterface* clientSocket = mListeningSocket->Accept();
// new connection made, spawn a thread to handle it
pthread_t* clientThread = new pthread_t();
NetworkPerformanceClient* client = AddClient(clientSocket, clientThread);
ClientThreadInfo* info = new ClientThreadInfo;
info->client = client;
info->server = this;
int error = pthread_create(clientThread, NULL, ClientThreadFunc, info);
DALI_ASSERT_ALWAYS(!error && "pthread create failed");
}
else // ret == SocketInterface::QUIT or SocketInterface::ERROR
{
return;
}
}
}
void* NetworkPerformanceServer::ClientThreadFunc(void* data)
{
ClientThreadInfo* info = static_cast<ClientThreadInfo*>(data);
info->server->ClientThread(info->client);
delete info;
return NULL;
}
NetworkPerformanceClient* NetworkPerformanceServer::AddClient(SocketInterface* clientSocket, pthread_t* clientThread)
{
// This function is only called from the listening thread
NetworkPerformanceClient* client = new NetworkPerformanceClient(clientThread,
clientSocket,
mClientUniqueId++,
*this,
mSocketFactory);
// protect the mClients list which can be accessed from multiple threads.
Mutex::ScopedLock lock(mClientListMutex);
mClients.PushBack(client);
return client;
}
void NetworkPerformanceServer::DeleteClient(NetworkPerformanceClient* client)
{
// protect the mClients list while modifying
Mutex::ScopedLock lock(mClientListMutex);
// remove from the list, and delete it
for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter)
{
if((*iter) == client)
{
mClients.Erase(iter);
delete client;
// if there server is shutting down, it waits for client count to hit zero
mClientCount--;
return;
}
}
}
void NetworkPerformanceServer::SendData(const char* const data, unsigned int bufferSizeInBytes, unsigned int clientId)
{
if(!mClientCount)
{
return;
}
// prevent clients been added / deleted while transmiting data
Mutex::ScopedLock lock(mClientListMutex);
for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter)
{
NetworkPerformanceClient* client = (*iter);
if(client->GetId() == clientId)
{
client->WriteSocket(data, bufferSizeInBytes);
return;
}
}
}
void NetworkPerformanceServer::TransmitMarker(const PerformanceMarker& marker, const char* const description)
{
if(!IsRunning())
{
return;
}
// prevent clients been added / deleted while transmiting data
Mutex::ScopedLock lock(mClientListMutex);
for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter)
{
NetworkPerformanceClient* client = (*iter);
client->TransmitMarker(marker, description);
}
}
void NetworkPerformanceServer::StopClients()
{
// prevent clients been added / deleted while stopping all clients
Mutex::ScopedLock lock(mClientListMutex);
for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter)
{
NetworkPerformanceClient* client = (*iter);
// stop the client from waiting for new commands, and exit from it's thread
client->ExitSelect();
}
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
<|endoftext|>
|
<commit_before><commit_msg>Reopen RenderDoc UI if closed on capture<commit_after><|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: Mace.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkActor.h"
#include "vtkConeSource.h"
#include "vtkDebugLeaks.h"
#include "vtkGlyph3D.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkRenderer.h"
#include "vtkSphereSource.h"
int Mace( int argc, char *argv[] )
{
vtkRenderer *renderer = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(renderer);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
vtkSphereSource *sphere = vtkSphereSource::New();
sphere->SetThetaResolution(8); sphere->SetPhiResolution(8);
vtkPolyDataMapper *sphereMapper = vtkPolyDataMapper::New();
sphereMapper->SetInputConnection(sphere->GetOutputPort());
vtkActor *sphereActor = vtkActor::New();
sphereActor->SetMapper(sphereMapper);
vtkConeSource *cone = vtkConeSource::New();
cone->SetResolution(6);
vtkGlyph3D *glyph = vtkGlyph3D::New();
glyph->SetInputConnection(sphere->GetOutputPort());
glyph->SetSource(cone->GetOutput());
glyph->SetVectorModeToUseNormal();
glyph->SetScaleModeToScaleByVector();
glyph->SetScaleFactor(0.25);
vtkPolyDataMapper *spikeMapper = vtkPolyDataMapper::New();
spikeMapper->SetInputConnection(glyph->GetOutputPort());
vtkActor *spikeActor = vtkActor::New();
spikeActor->SetMapper(spikeMapper);
renderer->AddActor(sphereActor);
renderer->AddActor(spikeActor);
renderer->SetBackground(1,1,1);
renWin->SetSize(300,300);
// interact with data
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Clean up
renderer->Delete();
renWin->Delete();
iren->Delete();
sphere->Delete();
sphereMapper->Delete();
sphereActor->Delete();
cone->Delete();
glyph->Delete();
spikeMapper->Delete();
spikeActor->Delete();
return !retVal;
}
<commit_msg>ENH: SetSource -> SetSourceConnection<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: Mace.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkActor.h"
#include "vtkConeSource.h"
#include "vtkDebugLeaks.h"
#include "vtkGlyph3D.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkRenderer.h"
#include "vtkSphereSource.h"
int Mace( int argc, char *argv[] )
{
vtkRenderer *renderer = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(renderer);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
vtkSphereSource *sphere = vtkSphereSource::New();
sphere->SetThetaResolution(8); sphere->SetPhiResolution(8);
vtkPolyDataMapper *sphereMapper = vtkPolyDataMapper::New();
sphereMapper->SetInputConnection(sphere->GetOutputPort());
vtkActor *sphereActor = vtkActor::New();
sphereActor->SetMapper(sphereMapper);
vtkConeSource *cone = vtkConeSource::New();
cone->SetResolution(6);
vtkGlyph3D *glyph = vtkGlyph3D::New();
glyph->SetInputConnection(sphere->GetOutputPort());
glyph->SetSourceConnection(cone->GetOutputPort());
glyph->SetVectorModeToUseNormal();
glyph->SetScaleModeToScaleByVector();
glyph->SetScaleFactor(0.25);
vtkPolyDataMapper *spikeMapper = vtkPolyDataMapper::New();
spikeMapper->SetInputConnection(glyph->GetOutputPort());
vtkActor *spikeActor = vtkActor::New();
spikeActor->SetMapper(spikeMapper);
renderer->AddActor(sphereActor);
renderer->AddActor(spikeActor);
renderer->SetBackground(1,1,1);
renWin->SetSize(300,300);
// interact with data
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Clean up
renderer->Delete();
renWin->Delete();
iren->Delete();
sphere->Delete();
sphereMapper->Delete();
sphereActor->Delete();
cone->Delete();
glyph->Delete();
spikeMapper->Delete();
spikeActor->Delete();
return !retVal;
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////
// Author: Henrik Tydesjo //
// Preprocessor Class for the SPD //
// //
///////////////////////////////////////////////
#include "AliITSPreprocessorSPD.h"
#include "AliITSCalibrationSPD.h"
#include "AliITSOnlineCalibrationSPD.h"
#include "AliITSOnlineCalibrationSPDhandler.h"
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#include "AliCDBEntry.h"
#include "AliCDBMetaData.h"
#include "AliShuttleInterface.h"
#include "AliLog.h"
#include <TTimeStamp.h>
#include <TObjString.h>
#include <TSystem.h>
ClassImp(AliITSPreprocessorSPD)
//______________________________________________________________________________________________
AliITSPreprocessorSPD::AliITSPreprocessorSPD(AliShuttleInterface* shuttle) :
AliPreprocessor("SPD", shuttle)
{
// constructor
}
//______________________________________________________________________________________________
AliITSPreprocessorSPD::~AliITSPreprocessorSPD()
{
// destructor
}
//______________________________________________________________________________________________
void AliITSPreprocessorSPD::Initialize(Int_t run, UInt_t startTime,
UInt_t endTime)
{
// initialize
AliPreprocessor::Initialize(run, startTime, endTime);
AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run,
TTimeStamp(startTime).AsString(),
TTimeStamp(endTime).AsString()));
}
//______________________________________________________________________________________________
UInt_t AliITSPreprocessorSPD::Process(TMap* dcsAliasMap)
{
// Do the actual preprocessing
UInt_t result = 1;
// // *** REFERENCE DATA ***
// // Store the container files as reference data (one for each equipment)
// for (UInt_t eq=0; eq<20; eq++) {
// Char_t id[20];
// sprintf(id,"SPDref%d",eq);
// TList* list = GetFileSources(kDAQ,id); // (the id is actually unique, so always 1 file)
// if (list) {
// TObjString* fileNameEntry = (TObjString*) list->First();
// Char_t* fileName = (Char_t*) GetFile(kDAQ, id, fileNameEntry->GetString().Data());
// AliITSOnlineSPDscan *scan = new AliITSOnlineSPDscan((Char_t*)fileName);
// TObjArray* arr = scan->GetAsTObjArray();
// Char_t refCAT[10];
// sprintf(refCAT,"Ref%d",eq);
// StoreReferenceData("SHUTTLE", refCAT, arr, &metaData, 0, 0);
// }
// }
// *** NOISY DATA ***
// Read old calibration
TString runStr = GetRunParameter("run");
Int_t run = atoi(runStr);
AliCDBStorage* storage = AliCDBManager::Instance()->GetStorage(AliShuttleInterface::GetMainCDB());
if(!storage) return 0;
AliCDBEntry* cdbEntry = storage->Get("ITS/Calib/SPDNoisy", run);
TObjArray* spdEntry;
if(cdbEntry) {
spdEntry = (TObjArray*)cdbEntry->GetObject();
if(!spdEntry) return 0;
}
else {
Log(Form("Old calibration not found in database. A fresh one will be created."));
// Create fresh calibration
spdEntry = new TObjArray(240);
for(Int_t module=0;module<240;module++){
AliITSCalibrationSPD* cal = new AliITSCalibrationSPD();
spdEntry->Add(cal);
}
spdEntry->SetOwner(kTRUE);
}
TString pwd = gSystem->pwd(); // remember the working directory, to cd back later
TString tempDir = Form("%s",AliShuttleInterface::GetShuttleTempDir());
// Retrieve and unpack tared calibration files from FXS
TList* list = GetFileSources(kDAQ,"SPD_noisy");
if (list) {
UInt_t index = 0;
while (list->At(index)!=NULL) {
TObjString* fileNameEntry = (TObjString*) list->At(index);
TString fileName = GetFile(kDAQ, "SPD_noisy", fileNameEntry->GetString().Data());
gSystem->cd(tempDir.Data());
Char_t command[100];
sprintf(command,"tar -xf %s",fileName.Data());
gSystem->Exec(command);
index++;
}
}
gSystem->cd(pwd.Data());
// Update the database entries
UInt_t nrUpdatedMods = 0;
AliITSOnlineCalibrationSPDhandler* handler = new AliITSOnlineCalibrationSPDhandler();
Char_t fileLoc[100];
sprintf(fileLoc,"%s",AliShuttleInterface::GetShuttleTempDir());
handler->SetFileLocation(fileLoc);
for (Int_t module=0; module<240; module++) {
handler->SetModuleNr(module);
if (handler->ReadFromFile()) {
((AliITSCalibrationSPD*) spdEntry->At(module)) -> SetNrNoisy( handler->GetNrNoisy() );
((AliITSCalibrationSPD*) spdEntry->At(module)) -> SetNoisyList( handler->GetNoisyArray() );
nrUpdatedMods++;
}
}
delete handler;
if (nrUpdatedMods>0) {
Log(Form("Noisy lists for %d modules updated.",nrUpdatedMods));
// Store the cdb entry
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Henrik Tydesjo");
metaData.SetComment("Preprocessor test for SPD.");
result = Store("Calib", "SPDNoisy", spdEntry, &metaData, 0, kTRUE);
delete spdEntry;
Log("Database updated.");
}
return result;
}
<commit_msg>SPD pre-processor update (H. Tydesjo)<commit_after>///////////////////////////////////////////////
// Author: Henrik Tydesjo //
// Preprocessor Class for the SPD //
// //
///////////////////////////////////////////////
#include "AliITSPreprocessorSPD.h"
#include "AliITSCalibrationSPD.h"
#include "AliITSOnlineCalibrationSPD.h"
#include "AliITSOnlineCalibrationSPDhandler.h"
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#include "AliCDBEntry.h"
#include "AliCDBMetaData.h"
#include "AliShuttleInterface.h"
#include "AliLog.h"
#include <TTimeStamp.h>
#include <TObjString.h>
#include <TSystem.h>
ClassImp(AliITSPreprocessorSPD)
//______________________________________________________________________________________________
AliITSPreprocessorSPD::AliITSPreprocessorSPD(AliShuttleInterface* shuttle) :
AliPreprocessor("SPD", shuttle)
{
// constructor
}
//______________________________________________________________________________________________
AliITSPreprocessorSPD::~AliITSPreprocessorSPD()
{
// destructor
}
//______________________________________________________________________________________________
void AliITSPreprocessorSPD::Initialize(Int_t run, UInt_t startTime,
UInt_t endTime)
{
// initialize
AliPreprocessor::Initialize(run, startTime, endTime);
AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run,
TTimeStamp(startTime).AsString(),
TTimeStamp(endTime).AsString()));
}
//______________________________________________________________________________________________
UInt_t AliITSPreprocessorSPD::Process(TMap* /*dcsAliasMap*/)
{
// Do the actual preprocessing
// *** REFERENCE DATA ***
// OLD algorithm (commented out)!!!
// ***********************************************************
// // Store the container files as reference data (one for each equipment)
// for (UInt_t eq=0; eq<20; eq++) {
// Char_t id[20];
// sprintf(id,"SPDref%d",eq);
// TList* list = GetFileSources(kDAQ,id); // (the id is actually unique, so always 1 file)
// if (list) {
// TObjString* fileNameEntry = (TObjString*) list->First();
// Char_t* fileName = (Char_t*) GetFile(kDAQ, id, fileNameEntry->GetString().Data());
// AliITSOnlineSPDscan *scan = new AliITSOnlineSPDscan((Char_t*)fileName);
// TObjArray* arr = scan->GetAsTObjArray();
// Char_t refCAT[10];
// sprintf(refCAT,"Ref%d",eq);
// StoreReferenceData("SHUTTLE", refCAT, arr, &metaData, 0, 0);
// }
// }
// ***********************************************************
// Store the container files as reference data (one file for each equipment)
for (UInt_t eq=0; eq<20; eq++) {
Char_t id[20];
sprintf(id,"SPD_reference_%d",eq);
TList* list = GetFileSources(kDAQ,id); // (the id should be unique, so always 1 file)
if (list) {
TObjString* fileNameEntry = (TObjString*) list->First();
if (fileNameEntry!=NULL) {
TString fileName = GetFile(kDAQ, id, fileNameEntry->GetString().Data());
Char_t refCAT[10];
sprintf(refCAT,"SPDref_eq_%d.root",eq);
if (!StoreReferenceFile(fileName.Data(),refCAT)) {
return 1;
}
}
}
}
// *** NOISY DATA ***
// OLD algorithm (commented out)!!!
// ***********************************************************
// // Read old calibration
// AliCDBEntry* cdbEntry = GetFromOCDB("Calib", "SPDNoisy");
// TObjArray* spdEntry;
// if(cdbEntry) {
// spdEntry = (TObjArray*)cdbEntry->GetObject();
// if(!spdEntry) return 0;
// }
// else {
// Log(Form("Old calibration not found in database. A fresh one will be created."));
// // Create fresh calibration
// spdEntry = new TObjArray(240);
// for(Int_t module=0;module<240;module++){
// AliITSCalibrationSPD* cal = new AliITSCalibrationSPD();
// spdEntry->Add(cal);
// }
// spdEntry->SetOwner(kTRUE);
// }
// ***********************************************************
// Read old calibration
AliCDBEntry* cdbEntry = GetFromOCDB("Calib", "SPDNoisy");
TObjArray* spdEntry;
if(cdbEntry) {
spdEntry = (TObjArray*)cdbEntry->GetObject();
if(!spdEntry) return 1;
}
else {
Log("Old calibration not found in database. This is required for further processing.");
return 1;
}
TString pwd = gSystem->pwd(); // remember the working directory, to cd back later
TString tempDir = Form("%s",AliShuttleInterface::GetShuttleTempDir());
// Retrieve and unpack tared calibration files from FXS
TList* list = GetFileSources(kDAQ,"SPD_noisy");
if (list) {
UInt_t index = 0;
while (list->At(index)!=NULL) {
TObjString* fileNameEntry = (TObjString*) list->At(index);
TString fileName = GetFile(kDAQ, "SPD_noisy", fileNameEntry->GetString().Data());
gSystem->cd(tempDir.Data());
Char_t command[100];
sprintf(command,"tar -xf %s",fileName.Data());
gSystem->Exec(command);
index++;
}
}
gSystem->cd(pwd.Data());
// Update the database entries if needed
UInt_t nrUpdatedMods = 0;
AliITSOnlineCalibrationSPDhandler* handler = new AliITSOnlineCalibrationSPDhandler();
Char_t fileLoc[100];
sprintf(fileLoc,"%s",AliShuttleInterface::GetShuttleTempDir());
handler->SetFileLocation(fileLoc);
for (Int_t module=0; module<240; module++) {
handler->SetModuleNr(module);
if (handler->ReadFromFile()) {
((AliITSCalibrationSPD*) spdEntry->At(module)) -> SetNrNoisy( handler->GetNrNoisy() );
((AliITSCalibrationSPD*) spdEntry->At(module)) -> SetNoisyList( handler->GetNoisyArray() );
nrUpdatedMods++;
}
}
delete handler;
if (nrUpdatedMods>0) {
Log(Form("Noisy lists for %d modules will be updated and stored...",nrUpdatedMods));
// Store the cdb entry
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Henrik Tydesjo");
metaData.SetComment("Preprocessor test for SPD.");
if (!Store("Calib", "SPDNoisy", spdEntry, &metaData, 0, kTRUE)) {
return 1;
}
// delete spdEntry;
Log("Database updated.");
}
return 0; // 0 means success
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-2007, 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. *
**************************************************************************/
#include <TClonesArray.h>
#include "AliLog.h"
#include "AliESDVertex.h"
#include "AliRunLoader.h"
#include "AliITSLoader.h"
#include "AliITSgeom.h"
#include "AliITSRecPoint.h"
#include "AliITSVertexerCosmics.h"
#include "AliStrLine.h"
//------------------------------------------------------------------------
// This class implements a method to construct a "fake" primary
// vertex for cosmic events in which the muon crosses the SPD inner
// layer (SPD1). A fake primary vertex is needed for the reconstruction,
// with e.g. AliITStrackerSA, of the two tracks produced by the muon
// in the ITS.
// We build pairs of clusters on SPD1 and define the fake vertex as
// the mid-point of the straight line joining the two clusters.
// We reject the backgroung by requiring at least one clusters on SPD2
// closer than fMaxDistOnSPD2 to the tracklet prolongation.
// We can reject (potentially pathological) events with the muon track
// tangential to the SPD1 layer by the requiring the radial position of
// the vertex to be smaller than fMaxVtxRadius.
// Due to background clusters, more than one vertex per event can
// be found. We consider the first found.
// The number of contributors set in the AliESDVertex object is the
// number of vertices found in the event; if this number is <1,
// the procedure could not find a vertex position and by default
// the vertex coordinates are set to (0,0,0) with large errors (100,100,100)
// Number of contributors = 0 --> No SPD1 tracklets matching criteria
// Number of contributors = -1 --> No SPD1 recpoints
//
// Origin: A.Dainese, andrea.dainese@lnl.infn.it
//-------------------------------------------------------------------------
ClassImp(AliITSVertexerCosmics)
//-------------------------------------------------------------------------
AliITSVertexerCosmics::AliITSVertexerCosmics():AliITSVertexer(),
fFirstSPD1(0),
fLastSPD1(0),
fFirstSPD2(0),
fLastSPD2(0),
fMaxDistOnSPD2(0),
fMaxVtxRadius(0),
fMinDist2Vtxs(0)
{
// Default constructor
SetSPD1Modules();
SetSPD2Modules();
SetMaxDistOnSPD2();
SetMaxVtxRadius();
SetMinDist2Vtxs();
}
//--------------------------------------------------------------------------
AliESDVertex* AliITSVertexerCosmics::FindVertexForCurrentEvent(Int_t evnumber)
{
// Defines the AliESDVertex for the current event
fCurrentVertex = 0;
AliRunLoader *rl =AliRunLoader::GetRunLoader();
AliITSLoader* itsLoader = (AliITSLoader*)rl->GetLoader("ITSLoader");
AliITSgeom* geom = itsLoader->GetITSgeom();
itsLoader->LoadRecPoints();
rl->GetEvent(evnumber);
TTree *rpTree = itsLoader->TreeR();
TClonesArray *recpoints=new TClonesArray("AliITSRecPoint",10000);
rpTree->SetBranchAddress("ITSRecPoints",&recpoints);
Double_t xclspd1[100],yclspd1[100],zclspd1[100],modclspd1[100];
Int_t nclspd1stored=0;
Double_t xclspd2[100],yclspd2[100],zclspd2[100],modclspd2[100];
Int_t nclspd2stored=0;
Int_t nrecpoints,nrecpointsSPD1=0;
Double_t gc[3]={0.,0.,0.};
Double_t lc[3]={0.,0.,0.};
Int_t lay,lad,det;
Double_t x[100],y[100],z[100],p1[3],p2[3],p3[3];
Int_t nvtxs;
Bool_t good,matchtospd2;
Double_t xvtx,yvtx,zvtx,rvtx;
for(Int_t imodule=fFirstSPD1; imodule<fLastSPD2; imodule++) { // SPD
rpTree->GetEvent(imodule);
geom->GetModuleId(imodule,lay,lad,det);
nrecpoints=recpoints->GetEntriesFast();
if(imodule<fLastSPD1) nrecpointsSPD1 += nrecpoints;
//printf("cosmics: module %d clusters %d\n",imodule,nrecpoints);
for(Int_t irp=0; irp<nrecpoints; irp++) {
AliITSRecPoint *rp=(AliITSRecPoint*)recpoints->UncheckedAt(irp);
// Local coordinates of this recpoint
lc[0]=rp->GetDetLocalX();
lc[2]=rp->GetDetLocalZ();
geom->LtoG(imodule,lc,gc); // global coordinates
if(lay==1) { // store SPD1 clusters
xclspd1[nclspd1stored]=gc[0];
yclspd1[nclspd1stored]=gc[1];
zclspd1[nclspd1stored]=gc[2];
modclspd1[nclspd1stored]=imodule;
nclspd1stored++;
}
if(lay==2) { // store SPD2 clusters
xclspd2[nclspd2stored]=gc[0];
yclspd2[nclspd2stored]=gc[1];
zclspd2[nclspd2stored]=gc[2];
modclspd2[nclspd2stored]=imodule;
nclspd2stored++;
}
if(nclspd1stored>100 || nclspd2stored>100)
AliFatal("More than 100 clusters per layer in SPD");
}// end clusters in a module
}// end SPD modules for a given event
// build fake vertices
nvtxs=0;
// SPD1 - first cluster
for(Int_t i1spd1=0; i1spd1<nclspd1stored; i1spd1++) {
p1[0]=xclspd1[i1spd1]; p1[1]=yclspd1[i1spd1]; p1[2]=zclspd1[i1spd1];
// SPD1 - second cluster
for(Int_t i2spd1=i1spd1+1; i2spd1<nclspd1stored; i2spd1++) {
if(modclspd1[i1spd1]==modclspd1[i2spd1]) continue;
p2[0]=xclspd1[i2spd1]; p2[1]=yclspd1[i2spd1]; p2[2]=zclspd1[i2spd1];
// look for point on SPD2
AliStrLine spd1line(p1,p2,kTRUE);
matchtospd2 = kFALSE;
for(Int_t ispd2=0; ispd2<nclspd2stored; ispd2++) {
p3[0]=xclspd2[ispd2]; p3[1]=yclspd2[ispd2]; p3[2]=zclspd2[ispd2];
//printf(" %f\n",spd1line.GetDistFromPoint(p3));
if(spd1line.GetDistFromPoint(p3)<fMaxDistOnSPD2)
{ matchtospd2 = kTRUE; break; }
}
if(!matchtospd2) continue;
xvtx = 0.5*(xclspd1[i1spd1]+xclspd1[i2spd1]);
yvtx = 0.5*(yclspd1[i1spd1]+yclspd1[i2spd1]);
zvtx = 0.5*(zclspd1[i1spd1]+zclspd1[i2spd1]);
rvtx = TMath::Sqrt(xvtx*xvtx+yvtx*yvtx);
if(rvtx>fMaxVtxRadius) continue;
good = kTRUE;
for(Int_t iv=0; iv<nvtxs; iv++) {
if(TMath::Sqrt((xvtx- x[iv])*(xvtx- x[iv])+
(yvtx- y[iv])*(yvtx- y[iv])+
(zvtx- z[iv])*(zvtx- z[iv])) < fMinDist2Vtxs)
good = kFALSE;
}
if(good) {
x[nvtxs]=xvtx;
y[nvtxs]=yvtx;
z[nvtxs]=zvtx;
nvtxs++;
}
} // SPD1 - second cluster
} // SPD1 - first cluster
Double_t pos[3]={0.,0.,0.};
Double_t err[3]={100.,100.,100.};
if(nvtxs) {
pos[0]=x[0];
pos[1]=y[0];
pos[2]=z[0];
err[0]=0.1;
err[1]=0.1;
err[2]=0.1;
}
if(!nrecpointsSPD1) nvtxs=-1;
fCurrentVertex = new AliESDVertex(pos,err,"cosmics");
fCurrentVertex->SetNContributors(nvtxs);
fCurrentVertex->SetTitle("cosmics fake vertex");
//if(nvtxs>0) fCurrentVertex->Print();
delete recpoints;
itsLoader->UnloadRecPoints();
return fCurrentVertex;
}
//-------------------------------------------------------------------------
void AliITSVertexerCosmics::FindVertices()
{
// computes the vertices of the events in the range FirstEvent - LastEvent
AliRunLoader *rl = AliRunLoader::GetRunLoader();
AliITSLoader* itsLoader = (AliITSLoader*) rl->GetLoader("ITSLoader");
itsLoader->ReloadRecPoints();
for(Int_t i=fFirstEvent;i<=fLastEvent;i++){
// printf("Processing event %d\n",i);
rl->GetEvent(i);
FindVertexForCurrentEvent(i);
if(fCurrentVertex){
WriteCurrentVertex();
}
}
}
//-------------------------------------------------------------------------
void AliITSVertexerCosmics::PrintStatus() const
{
// Print current status
printf("=======================================================\n");
printf(" fMaxDistOnSPD2: %f\n",fMaxDistOnSPD2);
printf(" fMaxVtxRadius: %f\n",fMaxVtxRadius);
printf(" fMinDist2Vtxs: %f\n",fMinDist2Vtxs);
printf(" First layer first and last modules: %d, %d\n",fFirstSPD1,fLastSPD1);
printf(" Second layer first and last modules: %d, %d\n",fFirstSPD2,fLastSPD2);
printf("=======================================================\n");
}
//-------------------------------------------------------------------------
<commit_msg>Access to the geometry via AliITSgeomTGeo<commit_after>/**************************************************************************
* Copyright(c) 1998-2007, 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. *
**************************************************************************/
#include <TClonesArray.h>
#include "AliLog.h"
#include "AliESDVertex.h"
#include "AliRunLoader.h"
#include "AliITSLoader.h"
#include "AliITSgeomTGeo.h"
#include "AliITSRecPoint.h"
#include "AliITSVertexerCosmics.h"
#include "AliStrLine.h"
//------------------------------------------------------------------------
// This class implements a method to construct a "fake" primary
// vertex for cosmic events in which the muon crosses the SPD inner
// layer (SPD1). A fake primary vertex is needed for the reconstruction,
// with e.g. AliITStrackerSA, of the two tracks produced by the muon
// in the ITS.
// We build pairs of clusters on SPD1 and define the fake vertex as
// the mid-point of the straight line joining the two clusters.
// We reject the backgroung by requiring at least one clusters on SPD2
// closer than fMaxDistOnSPD2 to the tracklet prolongation.
// We can reject (potentially pathological) events with the muon track
// tangential to the SPD1 layer by the requiring the radial position of
// the vertex to be smaller than fMaxVtxRadius.
// Due to background clusters, more than one vertex per event can
// be found. We consider the first found.
// The number of contributors set in the AliESDVertex object is the
// number of vertices found in the event; if this number is <1,
// the procedure could not find a vertex position and by default
// the vertex coordinates are set to (0,0,0) with large errors (100,100,100)
// Number of contributors = 0 --> No SPD1 tracklets matching criteria
// Number of contributors = -1 --> No SPD1 recpoints
//
// Origin: A.Dainese, andrea.dainese@lnl.infn.it
//-------------------------------------------------------------------------
ClassImp(AliITSVertexerCosmics)
//-------------------------------------------------------------------------
AliITSVertexerCosmics::AliITSVertexerCosmics():AliITSVertexer(),
fFirstSPD1(0),
fLastSPD1(0),
fFirstSPD2(0),
fLastSPD2(0),
fMaxDistOnSPD2(0),
fMaxVtxRadius(0),
fMinDist2Vtxs(0)
{
// Default constructor
SetSPD1Modules();
SetSPD2Modules();
SetMaxDistOnSPD2();
SetMaxVtxRadius();
SetMinDist2Vtxs();
}
//--------------------------------------------------------------------------
AliESDVertex* AliITSVertexerCosmics::FindVertexForCurrentEvent(Int_t evnumber)
{
// Defines the AliESDVertex for the current event
fCurrentVertex = 0;
AliRunLoader *rl =AliRunLoader::GetRunLoader();
AliITSLoader* itsLoader = (AliITSLoader*)rl->GetLoader("ITSLoader");
itsLoader->LoadRecPoints();
rl->GetEvent(evnumber);
TTree *rpTree = itsLoader->TreeR();
TClonesArray *recpoints=new TClonesArray("AliITSRecPoint",10000);
rpTree->SetBranchAddress("ITSRecPoints",&recpoints);
Double_t xclspd1[100],yclspd1[100],zclspd1[100],modclspd1[100];
Int_t nclspd1stored=0;
Double_t xclspd2[100],yclspd2[100],zclspd2[100],modclspd2[100];
Int_t nclspd2stored=0;
Int_t nrecpoints,nrecpointsSPD1=0;
Double_t gc[3]={0.,0.,0.};
Double_t lc[3]={0.,0.,0.};
Int_t lay,lad,det;
Double_t x[100],y[100],z[100],p1[3],p2[3],p3[3];
Int_t nvtxs;
Bool_t good,matchtospd2;
Double_t xvtx,yvtx,zvtx,rvtx;
for(Int_t imodule=fFirstSPD1; imodule<fLastSPD2; imodule++) { // SPD
rpTree->GetEvent(imodule);
AliITSgeomTGeo::GetModuleId(imodule,lay,lad,det);
nrecpoints=recpoints->GetEntriesFast();
if(imodule<fLastSPD1) nrecpointsSPD1 += nrecpoints;
//printf("cosmics: module %d clusters %d\n",imodule,nrecpoints);
for(Int_t irp=0; irp<nrecpoints; irp++) {
AliITSRecPoint *rp=(AliITSRecPoint*)recpoints->UncheckedAt(irp);
// Local coordinates of this recpoint
lc[0]=rp->GetDetLocalX();
lc[2]=rp->GetDetLocalZ();
AliITSgeomTGeo::LocalToGlobal(imodule,lc,gc); // global coordinates
if(lay==1) { // store SPD1 clusters
xclspd1[nclspd1stored]=gc[0];
yclspd1[nclspd1stored]=gc[1];
zclspd1[nclspd1stored]=gc[2];
modclspd1[nclspd1stored]=imodule;
nclspd1stored++;
}
if(lay==2) { // store SPD2 clusters
xclspd2[nclspd2stored]=gc[0];
yclspd2[nclspd2stored]=gc[1];
zclspd2[nclspd2stored]=gc[2];
modclspd2[nclspd2stored]=imodule;
nclspd2stored++;
}
if(nclspd1stored>100 || nclspd2stored>100)
AliFatal("More than 100 clusters per layer in SPD");
}// end clusters in a module
}// end SPD modules for a given event
// build fake vertices
nvtxs=0;
// SPD1 - first cluster
for(Int_t i1spd1=0; i1spd1<nclspd1stored; i1spd1++) {
p1[0]=xclspd1[i1spd1]; p1[1]=yclspd1[i1spd1]; p1[2]=zclspd1[i1spd1];
// SPD1 - second cluster
for(Int_t i2spd1=i1spd1+1; i2spd1<nclspd1stored; i2spd1++) {
if(modclspd1[i1spd1]==modclspd1[i2spd1]) continue;
p2[0]=xclspd1[i2spd1]; p2[1]=yclspd1[i2spd1]; p2[2]=zclspd1[i2spd1];
// look for point on SPD2
AliStrLine spd1line(p1,p2,kTRUE);
matchtospd2 = kFALSE;
for(Int_t ispd2=0; ispd2<nclspd2stored; ispd2++) {
p3[0]=xclspd2[ispd2]; p3[1]=yclspd2[ispd2]; p3[2]=zclspd2[ispd2];
//printf(" %f\n",spd1line.GetDistFromPoint(p3));
if(spd1line.GetDistFromPoint(p3)<fMaxDistOnSPD2)
{ matchtospd2 = kTRUE; break; }
}
if(!matchtospd2) continue;
xvtx = 0.5*(xclspd1[i1spd1]+xclspd1[i2spd1]);
yvtx = 0.5*(yclspd1[i1spd1]+yclspd1[i2spd1]);
zvtx = 0.5*(zclspd1[i1spd1]+zclspd1[i2spd1]);
rvtx = TMath::Sqrt(xvtx*xvtx+yvtx*yvtx);
if(rvtx>fMaxVtxRadius) continue;
good = kTRUE;
for(Int_t iv=0; iv<nvtxs; iv++) {
if(TMath::Sqrt((xvtx- x[iv])*(xvtx- x[iv])+
(yvtx- y[iv])*(yvtx- y[iv])+
(zvtx- z[iv])*(zvtx- z[iv])) < fMinDist2Vtxs)
good = kFALSE;
}
if(good) {
x[nvtxs]=xvtx;
y[nvtxs]=yvtx;
z[nvtxs]=zvtx;
nvtxs++;
}
} // SPD1 - second cluster
} // SPD1 - first cluster
Double_t pos[3]={0.,0.,0.};
Double_t err[3]={100.,100.,100.};
if(nvtxs) {
pos[0]=x[0];
pos[1]=y[0];
pos[2]=z[0];
err[0]=0.1;
err[1]=0.1;
err[2]=0.1;
}
if(!nrecpointsSPD1) nvtxs=-1;
fCurrentVertex = new AliESDVertex(pos,err,"cosmics");
fCurrentVertex->SetNContributors(nvtxs);
fCurrentVertex->SetTitle("cosmics fake vertex");
//if(nvtxs>0) fCurrentVertex->Print();
delete recpoints;
itsLoader->UnloadRecPoints();
return fCurrentVertex;
}
//-------------------------------------------------------------------------
void AliITSVertexerCosmics::FindVertices()
{
// computes the vertices of the events in the range FirstEvent - LastEvent
AliRunLoader *rl = AliRunLoader::GetRunLoader();
AliITSLoader* itsLoader = (AliITSLoader*) rl->GetLoader("ITSLoader");
itsLoader->ReloadRecPoints();
for(Int_t i=fFirstEvent;i<=fLastEvent;i++){
// printf("Processing event %d\n",i);
rl->GetEvent(i);
FindVertexForCurrentEvent(i);
if(fCurrentVertex){
WriteCurrentVertex();
}
}
}
//-------------------------------------------------------------------------
void AliITSVertexerCosmics::PrintStatus() const
{
// Print current status
printf("=======================================================\n");
printf(" fMaxDistOnSPD2: %f\n",fMaxDistOnSPD2);
printf(" fMaxVtxRadius: %f\n",fMaxVtxRadius);
printf(" fMinDist2Vtxs: %f\n",fMinDist2Vtxs);
printf(" First layer first and last modules: %d, %d\n",fFirstSPD1,fLastSPD1);
printf(" Second layer first and last modules: %d, %d\n",fFirstSPD2,fLastSPD2);
printf("=======================================================\n");
}
//-------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <bh_component.hpp>
#include "kernel.hpp"
#include "block.hpp"
#include "instruction.hpp"
#include "type.hpp"
#include "store.hpp"
using namespace bohrium;
using namespace component;
using namespace std;
namespace {
class Impl : public ComponentImpl {
private:
Store _store;
public:
Impl(int stack_level) : ComponentImpl(stack_level), _store(config) {}
~Impl() {}; // NB: a destructor implementation must exist
void execute(bh_ir *bhir);
void extmethod(const string &name, bh_opcode opcode) {}
};
}
extern "C" ComponentImpl* create(int stack_level) {
return new Impl(stack_level);
}
extern "C" void destroy(ComponentImpl* self) {
delete self;
}
// Returns the views with the greatest number of dimensions
vector<const bh_view*> max_ndim_views(int64_t nviews, const bh_view view_list[]) {
// Find the max ndim
int64_t ndim = 0;
for (int64_t i=0; i < nviews; ++i) {
const bh_view *view = &view_list[i];
if (not bh_is_constant(view)) {
if (view->ndim > ndim)
ndim = view->ndim;
}
}
vector<const bh_view*> ret;
for (int64_t i=0; i < nviews; ++i) {
const bh_view *view = &view_list[i];
if (not bh_is_constant(view)) {
if (view->ndim == ndim) {
ret.push_back(view);
}
}
}
return ret;
}
// Returns the shape of the view with the greatest number of dimensions
// if equal, the greatest shape is returned
vector<int64_t> shape_of_views(int64_t nviews, const bh_view *view_list) {
vector<const bh_view*> views = max_ndim_views(nviews, view_list);
vector<int64_t > shape;
for(const bh_view *view: views) {
for (int64_t j=0; j < view->ndim; ++j) {
if (shape.size() > (size_t)j) {
if (shape[j] < view->shape[j])
shape[j] = view->shape[j];
} else {
shape.push_back(view->shape[j]);
}
}
}
return shape;
}
namespace {
void spaces(stringstream &out, int num) {
for (int i = 0; i < num; ++i) {
out << " ";
}
}
}
void write_block(const map<const bh_base*, size_t> &base_ids, const Block &block, stringstream &out) {
spaces(out, 4 + block.rank*4);
if (block._instr != NULL) {
write_instr(base_ids, *block._instr, out);
} else {
// If this block is sweeped, we will "peel" the for-loop such that the
// sweep instruction is replaced with BH_IDENTITY in the first iteration
if (block._sweeps.size() > 0) {
Block peeled_block(block);
vector<bh_instruction> sweep_instr_list(block._sweeps.size());
{
size_t i = 0;
for (const bh_instruction *instr: block._sweeps) {
Block *sweep_instr_block = peeled_block.findInstrBlock(instr);
assert(sweep_instr_block != NULL);
bh_instruction *sweep_instr = &sweep_instr_list[i++];
sweep_instr->opcode = BH_IDENTITY;
sweep_instr->operand[1] = instr->operand[1]; // The input is the same as in the sweep
sweep_instr->operand[0] = instr->operand[0];
// But the output needs an extra dimension when we are reducing to a non-scalar
if (bh_opcode_is_reduction(instr->opcode) and instr->operand[1].ndim > 1) {
sweep_instr->operand[0].insert_dim(instr->constant.get_int64(), 1, 0);
}
sweep_instr_block->_instr = sweep_instr;
}
}
string itername;
{stringstream t; t << "i" << block.rank; itername = t.str();}
out << "{ // Peeled loop, 1. iteration" << endl;
spaces(out, 8 + block.rank*4);
out << "uint64_t " << itername << " = 0;" << endl;
for (const Block &b: peeled_block._block_list) {
write_block(base_ids, b, out);
}
spaces(out, 4 + block.rank*4);
out << "}" << endl;
spaces(out, 4 + block.rank*4);
}
string itername;
{stringstream t; t << "i" << block.rank; itername = t.str();}
out << "for(uint64_t " << itername;
if (block._sweeps.size() > 0) // If the for-loop has been peeled, we should that at 1
out << "=1; ";
else
out << "=0; ";
out << itername << " < " << block.size << "; ++" << itername << ") {" << endl;
for (const Block &b: block._block_list) {
write_block(base_ids, b, out);
}
spaces(out, 4 + block.rank*4);
out << "}" << endl;
}
}
Kernel fuser_singleton(vector<bh_instruction> &instr_list) {
// Creates the block_list based on the instr_list
Kernel ret;
for(const bh_instruction &instr: instr_list) {
int nop = bh_noperands(instr.opcode);
if (nop == 0)
continue; // Ignore noop instructions such as BH_NONE or BH_TALLY
if (bh_opcode_is_system(instr.opcode)) {
continue; // Ignore system instructions, we will have BH_FREE later
}
int sweep_rank = sweep_axis(instr);
vector<int64_t> shape = shape_of_views(nop, instr.operand);
Block root;
if (sweep_rank == 0) {
root._sweeps.insert(&instr);
}
root.rank = 0;
root.size = shape[0];
Block *parent = &root;
Block *bottom = &root;
for(int i=1; i < (int)shape.size(); ++i) {
Block b;
if (sweep_rank == i) {
b._sweeps.insert(&instr);
shape_of_views(nop, instr.operand);
}
b.rank = i;
b.size = shape[i];
parent->_block_list.push_back(b);
bottom = &parent->_block_list[0];
parent = bottom;
}
Block instr_block;
instr_block._instr = &instr;
instr_block.rank = (int)shape.size();
bottom->_block_list.push_back(instr_block);
ret.block_list.push_back(root);
}
// Find all used array bases and kernel flags such as 'useRandom'
for(bh_instruction &instr: instr_list) {
set<bh_base*> b = instr.get_bases();
ret.bases.insert(b.begin(), b.end());
if (instr.opcode == BH_RANDOM) {
ret.useRandom = true;
} else if (instr.opcode == BH_FREE) {
ret.frees.insert(instr.operand[0].base);
}
}
return ret;
}
void Impl::execute(bh_ir *bhir) {
Kernel kernel = fuser_singleton(bhir->instr_list);
// Do we have anything to do?
if (kernel.bases.size() == 0)
return;
// Assign an id to all array bases
map<const bh_base*, size_t> base_ids;
{
size_t i = 0;
for(const bh_base *base: kernel.bases) {
base_ids[base] = i++;
}
}
// Debug print
//cout << block_list;
// Code generation
stringstream ss;
// Make sure all arrays are allocated
for(bh_base *base: kernel.bases) {
bh_data_malloc(base);
}
// Write the need includes
ss << "#include <stdint.h>" << endl;
ss << "#include <stdlib.h>" << endl;
ss << "#include <stdbool.h>" << endl;
ss << "#include <complex.h>" << endl;
ss << "#include <tgmath.h>" << endl;
ss << "#include <math.h>" << endl;
ss << "#include <bh_memory.h>" << endl;
ss << "#include <bh_type.h>" << endl;
ss << endl;
if (kernel.useRandom) { // Write the random function
ss << "#include <Random123/philox.h>" << endl;
ss << "uint64_t random123(uint64_t start, uint64_t key, uint64_t index) {" << endl;
ss << " union {philox2x32_ctr_t c; uint64_t ul;} ctr, res; " << endl;
ss << " ctr.ul = start + index; " << endl;
ss << " res.c = philox2x32(ctr.c, (philox2x32_key_t){{key}}); " << endl;
ss << " return res.ul; " << endl;
ss << "} " << endl;
}
ss << endl;
// Write the header of the execute function
ss << "void execute(";
if (kernel.bases.size() > 0) {
for (auto it = kernel.bases.begin(); ;) {
const bh_base *b = *it;
ss << write_type(b->type) << " a" << base_ids.at(b) << "[]";
if (++it != kernel.bases.end()) {
ss << ", ";
} else {
break;
}
}
}
ss << ") {" << endl;
// Write the blocks that makes up the body of 'execute()'
for(const Block &block: kernel.block_list) {
write_block(base_ids, block, ss);
}
ss << "}" << endl << endl;
// Write the launcher function, which will convert the data_list of void pointers
// to typed arrays and call the execute function
{
ss << "void launcher(void* data_list[]) {" << endl;
size_t i=0;
for (const bh_base *b: kernel.bases) {
spaces(ss, 4);
ss << write_type(b->type) << " *a" << base_ids.at(b)
<< " = data_list[" << i << "];" << endl;
++i;
}
spaces(ss, 4);
ss << "execute(";
for (auto it = kernel.bases.begin(); ;) {
const bh_base *b = *it;
ss << "a" << base_ids.at(b);
if (++it != kernel.bases.end()) {
ss << ", ";
} else {
break;
}
}
ss << ");" << endl;
ss << "}" << endl;
}
// cout << ss.str();
KernelFunction func = _store.getFunction(ss.str());
assert(func != NULL);
// Create a 'data_list' of data pointers
vector<void*> data_list;
data_list.reserve(kernel.bases.size());
for(bh_base *base: kernel.bases) {
assert(base->data != NULL);
data_list.push_back(base->data);
}
// Call the launcher function with the 'data_list', which will execute the kernel
func(&data_list[0]);
// Finally, let's cleanup
for(bh_base *base: kernel.frees) {
bh_data_free(base);
}
}
<commit_msg>uni: now register new extmethods<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <bh_component.hpp>
#include <bh_extmethod.hpp>
#include "kernel.hpp"
#include "block.hpp"
#include "instruction.hpp"
#include "type.hpp"
#include "store.hpp"
using namespace bohrium;
using namespace component;
using namespace std;
namespace {
class Impl : public ComponentImpl {
private:
Store _store;
map<bh_opcode, extmethod::ExtmethodFace> extmethods;
public:
Impl(int stack_level) : ComponentImpl(stack_level), _store(config) {}
~Impl() {}; // NB: a destructor implementation must exist
void execute(bh_ir *bhir);
void extmethod(const string &name, bh_opcode opcode) {
// ExtmethodFace does not have a default or copy constructor thus
// we have to use its move constructor.
extmethods.insert(make_pair(opcode, extmethod::ExtmethodFace(config, name)));
}
};
}
extern "C" ComponentImpl* create(int stack_level) {
return new Impl(stack_level);
}
extern "C" void destroy(ComponentImpl* self) {
delete self;
}
// Returns the views with the greatest number of dimensions
vector<const bh_view*> max_ndim_views(int64_t nviews, const bh_view view_list[]) {
// Find the max ndim
int64_t ndim = 0;
for (int64_t i=0; i < nviews; ++i) {
const bh_view *view = &view_list[i];
if (not bh_is_constant(view)) {
if (view->ndim > ndim)
ndim = view->ndim;
}
}
vector<const bh_view*> ret;
for (int64_t i=0; i < nviews; ++i) {
const bh_view *view = &view_list[i];
if (not bh_is_constant(view)) {
if (view->ndim == ndim) {
ret.push_back(view);
}
}
}
return ret;
}
// Returns the shape of the view with the greatest number of dimensions
// if equal, the greatest shape is returned
vector<int64_t> shape_of_views(int64_t nviews, const bh_view *view_list) {
vector<const bh_view*> views = max_ndim_views(nviews, view_list);
vector<int64_t > shape;
for(const bh_view *view: views) {
for (int64_t j=0; j < view->ndim; ++j) {
if (shape.size() > (size_t)j) {
if (shape[j] < view->shape[j])
shape[j] = view->shape[j];
} else {
shape.push_back(view->shape[j]);
}
}
}
return shape;
}
namespace {
void spaces(stringstream &out, int num) {
for (int i = 0; i < num; ++i) {
out << " ";
}
}
}
void write_block(const map<const bh_base*, size_t> &base_ids, const Block &block, stringstream &out) {
spaces(out, 4 + block.rank*4);
if (block._instr != NULL) {
write_instr(base_ids, *block._instr, out);
} else {
// If this block is sweeped, we will "peel" the for-loop such that the
// sweep instruction is replaced with BH_IDENTITY in the first iteration
if (block._sweeps.size() > 0) {
Block peeled_block(block);
vector<bh_instruction> sweep_instr_list(block._sweeps.size());
{
size_t i = 0;
for (const bh_instruction *instr: block._sweeps) {
Block *sweep_instr_block = peeled_block.findInstrBlock(instr);
assert(sweep_instr_block != NULL);
bh_instruction *sweep_instr = &sweep_instr_list[i++];
sweep_instr->opcode = BH_IDENTITY;
sweep_instr->operand[1] = instr->operand[1]; // The input is the same as in the sweep
sweep_instr->operand[0] = instr->operand[0];
// But the output needs an extra dimension when we are reducing to a non-scalar
if (bh_opcode_is_reduction(instr->opcode) and instr->operand[1].ndim > 1) {
sweep_instr->operand[0].insert_dim(instr->constant.get_int64(), 1, 0);
}
sweep_instr_block->_instr = sweep_instr;
}
}
string itername;
{stringstream t; t << "i" << block.rank; itername = t.str();}
out << "{ // Peeled loop, 1. iteration" << endl;
spaces(out, 8 + block.rank*4);
out << "uint64_t " << itername << " = 0;" << endl;
for (const Block &b: peeled_block._block_list) {
write_block(base_ids, b, out);
}
spaces(out, 4 + block.rank*4);
out << "}" << endl;
spaces(out, 4 + block.rank*4);
}
string itername;
{stringstream t; t << "i" << block.rank; itername = t.str();}
out << "for(uint64_t " << itername;
if (block._sweeps.size() > 0) // If the for-loop has been peeled, we should that at 1
out << "=1; ";
else
out << "=0; ";
out << itername << " < " << block.size << "; ++" << itername << ") {" << endl;
for (const Block &b: block._block_list) {
write_block(base_ids, b, out);
}
spaces(out, 4 + block.rank*4);
out << "}" << endl;
}
}
Kernel fuser_singleton(vector<bh_instruction> &instr_list) {
// Creates the block_list based on the instr_list
Kernel ret;
for(const bh_instruction &instr: instr_list) {
int nop = bh_noperands(instr.opcode);
if (nop == 0)
continue; // Ignore noop instructions such as BH_NONE or BH_TALLY
if (bh_opcode_is_system(instr.opcode)) {
continue; // Ignore system instructions, we will have BH_FREE later
}
int sweep_rank = sweep_axis(instr);
vector<int64_t> shape = shape_of_views(nop, instr.operand);
Block root;
if (sweep_rank == 0) {
root._sweeps.insert(&instr);
}
root.rank = 0;
root.size = shape[0];
Block *parent = &root;
Block *bottom = &root;
for(int i=1; i < (int)shape.size(); ++i) {
Block b;
if (sweep_rank == i) {
b._sweeps.insert(&instr);
shape_of_views(nop, instr.operand);
}
b.rank = i;
b.size = shape[i];
parent->_block_list.push_back(b);
bottom = &parent->_block_list[0];
parent = bottom;
}
Block instr_block;
instr_block._instr = &instr;
instr_block.rank = (int)shape.size();
bottom->_block_list.push_back(instr_block);
ret.block_list.push_back(root);
}
// Find all used array bases and kernel flags such as 'useRandom'
for(bh_instruction &instr: instr_list) {
set<bh_base*> b = instr.get_bases();
ret.bases.insert(b.begin(), b.end());
if (instr.opcode == BH_RANDOM) {
ret.useRandom = true;
} else if (instr.opcode == BH_FREE) {
ret.frees.insert(instr.operand[0].base);
}
}
return ret;
}
void Impl::execute(bh_ir *bhir) {
Kernel kernel = fuser_singleton(bhir->instr_list);
// Do we have anything to do?
if (kernel.bases.size() == 0)
return;
// Assign an id to all array bases
map<const bh_base*, size_t> base_ids;
{
size_t i = 0;
for(const bh_base *base: kernel.bases) {
base_ids[base] = i++;
}
}
// Debug print
//cout << block_list;
// Code generation
stringstream ss;
// Make sure all arrays are allocated
for(bh_base *base: kernel.bases) {
bh_data_malloc(base);
}
// Write the need includes
ss << "#include <stdint.h>" << endl;
ss << "#include <stdlib.h>" << endl;
ss << "#include <stdbool.h>" << endl;
ss << "#include <complex.h>" << endl;
ss << "#include <tgmath.h>" << endl;
ss << "#include <math.h>" << endl;
ss << "#include <bh_memory.h>" << endl;
ss << "#include <bh_type.h>" << endl;
ss << endl;
if (kernel.useRandom) { // Write the random function
ss << "#include <Random123/philox.h>" << endl;
ss << "uint64_t random123(uint64_t start, uint64_t key, uint64_t index) {" << endl;
ss << " union {philox2x32_ctr_t c; uint64_t ul;} ctr, res; " << endl;
ss << " ctr.ul = start + index; " << endl;
ss << " res.c = philox2x32(ctr.c, (philox2x32_key_t){{key}}); " << endl;
ss << " return res.ul; " << endl;
ss << "} " << endl;
}
ss << endl;
// Write the header of the execute function
ss << "void execute(";
if (kernel.bases.size() > 0) {
for (auto it = kernel.bases.begin(); ;) {
const bh_base *b = *it;
ss << write_type(b->type) << " a" << base_ids.at(b) << "[]";
if (++it != kernel.bases.end()) {
ss << ", ";
} else {
break;
}
}
}
ss << ") {" << endl;
// Write the blocks that makes up the body of 'execute()'
for(const Block &block: kernel.block_list) {
write_block(base_ids, block, ss);
}
ss << "}" << endl << endl;
// Write the launcher function, which will convert the data_list of void pointers
// to typed arrays and call the execute function
{
ss << "void launcher(void* data_list[]) {" << endl;
size_t i=0;
for (const bh_base *b: kernel.bases) {
spaces(ss, 4);
ss << write_type(b->type) << " *a" << base_ids.at(b)
<< " = data_list[" << i << "];" << endl;
++i;
}
spaces(ss, 4);
ss << "execute(";
for (auto it = kernel.bases.begin(); ;) {
const bh_base *b = *it;
ss << "a" << base_ids.at(b);
if (++it != kernel.bases.end()) {
ss << ", ";
} else {
break;
}
}
ss << ");" << endl;
ss << "}" << endl;
}
// cout << ss.str();
KernelFunction func = _store.getFunction(ss.str());
assert(func != NULL);
// Create a 'data_list' of data pointers
vector<void*> data_list;
data_list.reserve(kernel.bases.size());
for(bh_base *base: kernel.bases) {
assert(base->data != NULL);
data_list.push_back(base->data);
}
// Call the launcher function with the 'data_list', which will execute the kernel
func(&data_list[0]);
// Finally, let's cleanup
for(bh_base *base: kernel.frees) {
bh_data_free(base);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013-2014 INRA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "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.
*/
#ifndef __VLE_KERNEL_CONTEXT_HPP__
#define __VLE_KERNEL_CONTEXT_HPP__
#include <vle/export.hpp>
#include <boost/any.hpp>
#include <algorithm>
#include <functional>
#include <memory>
#include <cstdio>
#include <cstdarg>
#include <cstdint>
#include <cinttypes>
namespace vle {
struct ContextImpl;
typedef std::shared_ptr <ContextImpl> Context;
}
void vle_log_null(const vle::Context& ctx, const char *format, ...)
{
(void)ctx;
(void)format;
}
#if defined __GNUC__
#define VLE_PRINTF(format__, args__) __attribute__ ((format (printf, format__, args__)))
#endif
#define vle_log_cond(ctx, prio, arg...) \
do { \
if (ctx->get_log_priority() >= prio) \
ctx->log(prio, __FILE__, __LINE__, __FUNCTION__, ## arg); \
} while (0)
#define LOG_DEBUG 3
#define LOG_INFO 2
#define LOG_ERR 1
#ifdef ENABLE_LOGGING
# ifdef ENABLE_DEBUG
# define vle_dbg(ctx, arg...) vle_log_cond(ctx, LOG_DEBUG, ## arg)
# else
# define vle_dbg(ctx, arg...) vle_log_null(ctx, ## arg)
# endif
# define vle_info(ctx, arg...) vle_log_cond(ctx, LOG_INFO, ## arg)
# define vle_err(ctx, arg...) vle_log_cond(ctx, LOG_ERR, ## arg)
#else
# define vle_dbg(ctx, arg...) vle_log_null(ctx, ## arg)
# define vle_info(ctx, arg...) vle_log_null(ctx, ## arg)
# define vle_err(ctx, arg...) vle_log_null(ctx, ## arg)
#endif
namespace vle {
void log_to_stderr(const ContextImpl& ctx, int priority, const char *file,
int line, const char *fn, const char *format, va_list args);
/**
* Default @e ContextImpl initializes logger system with the standard error
* output (@e stderr).
*/
struct ContextImpl
{
ContextImpl()
: m_log_fn(log_to_stderr)
, m_thread_number(0)
, m_log_priority(1)
{}
ContextImpl(const ContextImpl&) = default;
ContextImpl& operator=(const ContextImpl&) = default;
ContextImpl(ContextImpl&&) = default;
ContextImpl& operator=(ContextImpl&&) = default;
~ContextImpl() = default;
typedef std::function <void(const ContextImpl& ctx, int priority,
const char *file, int line, const char *fn,
const char *format, va_list args)> log_fn;
void set_log_fn(log_fn fn)
{
m_log_fn = fn;
}
void log(int priority, const char *file, int line,
const char *fn, const char *formats, ...) VLE_PRINTF(6, 7)
{
if (m_log_priority >= priority) {
va_list args;
va_start(args, formats);
try {
m_log_fn(*this, priority, file, line, fn, formats, args);
} catch (...) {
}
va_end(args);
}
}
int get_log_priority() const
{
return m_log_priority;
}
void set_log_priority(int priority)
{
m_log_priority = std::min(std::max(priority, 3), 0);
}
unsigned get_thread_number() const
{
return m_thread_number;
}
void set_thread_number(unsigned thread_number)
{
m_thread_number = thread_number;
}
void set_user_data(const boost::any &user_data)
{
m_user_data = user_data;
}
const boost::any& get_user_data() const { return m_user_data; }
boost::any& get_user_data() { return m_user_data; }
private:
boost::any m_user_data;
log_fn m_log_fn;
unsigned int m_thread_number = 0;
int m_log_priority = 1;
};
void log_to_stderr(const ContextImpl& ctx, int priority, const char *file,
int line, const char *fn, const char *format, va_list args)
{
(void)ctx;
(void)priority;
(void)file;
(void)line;
fprintf(stderr, "echll: %s ", fn);
vfprintf(stderr, format, args);
}
}
#endif
<commit_msg>context: fix bug in priority assignation<commit_after>/*
* Copyright (C) 2013-2014 INRA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "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.
*/
#ifndef __VLE_KERNEL_CONTEXT_HPP__
#define __VLE_KERNEL_CONTEXT_HPP__
#include <vle/export.hpp>
#include <boost/any.hpp>
#include <algorithm>
#include <functional>
#include <memory>
#include <cstdio>
#include <cstdarg>
#include <cstdint>
#include <cinttypes>
namespace vle {
struct ContextImpl;
typedef std::shared_ptr <ContextImpl> Context;
}
void vle_log_null(const vle::Context& ctx, const char *format, ...)
{
(void)ctx;
(void)format;
}
#if defined __GNUC__
#define VLE_PRINTF(format__, args__) __attribute__ ((format (printf, format__, args__)))
#endif
#define vle_log_cond(ctx, prio, arg...) \
do { \
if (ctx->get_log_priority() >= prio) \
ctx->log(prio, __FILE__, __LINE__, __FUNCTION__, ## arg); \
} while (0)
#define LOG_DEBUG 3
#define LOG_INFO 2
#define LOG_ERR 1
#ifdef ENABLE_LOGGING
# ifdef ENABLE_DEBUG
# define vle_dbg(ctx, arg...) vle_log_cond(ctx, LOG_DEBUG, ## arg)
# else
# define vle_dbg(ctx, arg...) vle_log_null(ctx, ## arg)
# endif
# define vle_info(ctx, arg...) vle_log_cond(ctx, LOG_INFO, ## arg)
# define vle_err(ctx, arg...) vle_log_cond(ctx, LOG_ERR, ## arg)
#else
# define vle_dbg(ctx, arg...) vle_log_null(ctx, ## arg)
# define vle_info(ctx, arg...) vle_log_null(ctx, ## arg)
# define vle_err(ctx, arg...) vle_log_null(ctx, ## arg)
#endif
namespace vle {
void log_to_stderr(const ContextImpl& ctx, int priority, const char *file,
int line, const char *fn, const char *format, va_list args);
/**
* Default @e ContextImpl initializes logger system with the standard error
* output (@e stderr).
*/
struct ContextImpl
{
ContextImpl()
: m_log_fn(log_to_stderr)
, m_thread_number(0)
, m_log_priority(1)
{}
ContextImpl(const ContextImpl&) = default;
ContextImpl& operator=(const ContextImpl&) = default;
ContextImpl(ContextImpl&&) = default;
ContextImpl& operator=(ContextImpl&&) = default;
~ContextImpl() = default;
typedef std::function <void(const ContextImpl& ctx, int priority,
const char *file, int line, const char *fn,
const char *format, va_list args)> log_fn;
void set_log_fn(log_fn fn)
{
m_log_fn = fn;
}
void log(int priority, const char *file, int line,
const char *fn, const char *formats, ...) VLE_PRINTF(6, 7)
{
if (m_log_priority >= priority) {
va_list args;
va_start(args, formats);
try {
m_log_fn(*this, priority, file, line, fn, formats, args);
} catch (...) {
}
va_end(args);
}
}
int get_log_priority() const
{
return m_log_priority;
}
void set_log_priority(int priority)
{
m_log_priority = std::max(std::min(priority, 3), 0);
}
unsigned get_thread_number() const
{
return m_thread_number;
}
void set_thread_number(unsigned thread_number)
{
m_thread_number = thread_number;
}
void set_user_data(const boost::any &user_data)
{
m_user_data = user_data;
}
const boost::any& get_user_data() const { return m_user_data; }
boost::any& get_user_data() { return m_user_data; }
private:
boost::any m_user_data;
log_fn m_log_fn;
unsigned int m_thread_number = 0;
int m_log_priority = 1;
};
void log_to_stderr(const ContextImpl& ctx, int priority, const char *file,
int line, const char *fn, const char *format, va_list args)
{
(void)ctx;
(void)priority;
(void)file;
(void)line;
fprintf(stderr, "echll: %s ", fn);
vfprintf(stderr, format, args);
}
}
#endif
<|endoftext|>
|
<commit_before>#include "audiopipe.hpp"
#include "core.h"
#include <QMessageBox>
#include <algorithm>
#define BPM_MIN 30.0;
QString RtAudioApiToQString(RtAudio::Api api)
{
switch (api) {
case RtAudio::UNSPECIFIED: return "Default";
case RtAudio::UNIX_JACK: return "Jack";
case RtAudio::LINUX_ALSA: return "ALSA";
case RtAudio::LINUX_OSS: return "OSS";
case RtAudio::LINUX_PULSE: return "PulseAudio";
case RtAudio::MACOSX_CORE: return "OSX Audio Core";
case RtAudio::WINDOWS_ASIO: return "ASIO";
case RtAudio::WINDOWS_DS: return "DirectSound";
case RtAudio::WINDOWS_WASAPI: return "WASAPI";
default: break;
}
return "Error";
}
RtAudio::Api QStringToRtAudioApi(const QString& api)
{
if (api=="Default") return RtAudio::UNSPECIFIED;
else if (api=="Jack") return RtAudio::UNIX_JACK;
else if (api=="ALSA") return RtAudio::LINUX_ALSA;
else if (api=="OSS") return RtAudio::LINUX_OSS;
else if (api=="PulseAudio") return RtAudio::LINUX_PULSE;
else if (api=="OSX Audio Core") return RtAudio::MACOSX_CORE;
else if (api=="ASIO") return RtAudio::WINDOWS_ASIO;
else if (api=="DirectSound") return RtAudio::WINDOWS_DS;
else if (api=="WASAPI") return RtAudio::WINDOWS_WASAPI;
else return RtAudio::UNSPECIFIED;
}
AudioPipe::AudioPipe(QObject *parent) :
QThread(parent),
_mixer(NULL),
_stopThread(false)
{
std::cout << "pouet" << std::endl;
RtAudio::Api api = QStringToRtAudioApi(Core::instance()->settings.value("Audio/Driver","Default").toString());
std::cout << "pouet" << std::endl;
_driver = new RtAudio(api);
std::cout << "pouet" << std::endl;
_driver->showWarnings();
std::cout << "pouet" << std::endl;
_deviceOutId=Core::instance()->settings.value("Audio/DeviceOutId",_driver->getDefaultOutputDevice()).toInt();
_deviceInId=Core::instance()->settings.value("Audio/DeviceInId",_driver->getDefaultInputDevice()).toInt();
std::cout << "pouet" << std::endl;
connect(this,SIGNAL(critical_error(QString,QString)),SLOT(show_critical(QString,QString)));
_latencySignalsR.resize(Signal::refreshRate * 60 /(30.0));
_latencySignalsL.resize(Signal::refreshRate * 60 /(30.0));
_latencyTimeBuffer = 0;
_latencyCurrentBuffer = 0;
}
void AudioPipe::stop() {
_stopThread=true;
if (isRunning()) wait();
_stopThread=false;
}
void AudioPipe::prepare()
{
RtAudio::StreamParameters iParams, oParams;
if ( _deviceInId != -1 ) {
iParams.deviceId = _deviceInId;
iParams.nChannels = 2;
iParams.firstChannel = 0;
}
if ( _deviceOutId != -1 ) {
oParams.deviceId = _deviceOutId;
oParams.nChannels = 2;
oParams.firstChannel = 0;
}
try
{
if ( _deviceInId != -1 && _deviceOutId != -1 )
_driver->openStream( &oParams, &iParams, RTAUDIO_FLOAT32, Signal::frequency,
(unsigned int*)&Signal::size, &AudioPipe::rtaudio_callback, this );
else if (_deviceInId != -1)
_driver->openStream( 0, &iParams, RTAUDIO_FLOAT32, Signal::frequency,
(unsigned int*)&Signal::size, &AudioPipe::rtaudio_callback, this );
else if (_deviceOutId != -1)
_driver->openStream( &oParams, 0, RTAUDIO_FLOAT32, Signal::frequency,
(unsigned int*)&Signal::size, &AudioPipe::rtaudio_callback, this );
else {
emit critical_error("Error in AudioPipe thread", "No devices selected !");
if ( _driver->isStreamOpen() ) _driver->closeStream();
return;
}
}
catch ( RtAudioError& e )
{
emit critical_error("Error in AudioPipe : open stream", QString(e.getMessage().c_str()));
if ( _driver->isStreamOpen() ) _driver->closeStream();
return;
}
}
void AudioPipe::run() {
_leftOut.reset();
_rightOut.reset();
_leftIn.reset();
_rightIn.reset();
//Creating local variables to work on it
Signal left;
Signal right;
try
{
_driver->startStream();
}
catch ( RtAudioError& e )
{
emit critical_error("Error in AudioPipe : start stream", QString(e.getMessage().c_str()));
if ( _driver->isStreamOpen() ) _driver->closeStream();
return;
}
emit computedLatency(getStreamLatency() + Signal::size*3);
const bool isPow2 = Signal::isPow2;
const unsigned int signal_size = Signal::size;
Core* core = Core::instance();
FFT* fft = core->fft;
while (!_stopThread) //Normalement pas besoin de mutex
{
_mutexIO.lock();
//En utilisant cette stratégie je suis sur de faire au mieu un calcul
//à chaque fois que j'ai réelement une entrée et au pire moins de fois
//(si je n'ai pas les performances suffisantes)
_contidionIO.wait(&_mutexIO);
//Il y aura une latence max de Signal::size + hardware pour l'entrée
left =_leftOut;
right = _rightOut;
//Au pour reboucler la sortie on aura une latence
// 3*Signal::size + hardwareIn + hardwareOut
//Ici on comprend donc qu'il nous faut un Signal::size le plus petit possible,
//et c'est loin d'être évident...
_mutexIO.unlock();
//Dans la suite Out contient le signal qui va sortir sur les HP (donc un signal non modifié)
// et In est le signal qui va se faire analyser (et qui parfois peut-être modifié...)
//Analyse FFT
fft->mutex.lock();
if (isPow2)
fft->compute(left.samples,signal_size);
else
fft->pushSignal(left);
fft->computeModule();
fft->mutex.unlock();
float bass=0;
const unsigned int cut=core->bassCutoff;
for (unsigned int i=0; i < cut; i++) {
bass = std::max(fft->getModule()[i],bass);
}
bass *= 1.25; //on dynamise
if (bass > 1.f) bass = 1.f; //Normalisé entre 0 et 1
//Analyse du bruit (Noise)
core->visualSignal->update(left);
core->setNoise((float) core->visualSignal->noise / (80.f*200.f));
core->setBass(bass);
}
_driver->stopStream();
_driver->closeStream();
}
void AudioPipe::setApi(RtAudio::Api api)
{
stop();
delete _driver;
_driver = new RtAudio(api);
_driver->showWarnings();
}
void AudioPipe::setLatenyTime(float sec)
{
int n = (int)(sec*(float)Signal::refreshRate);
if (n > _latencySignalsL.size())
{
n = _latencySignalsL.size()-1;
}
else if (n <= 0.f)
{
n = 0;
}
_latencyTimeBuffer = n;
}
int AudioPipe::rtaudio_callback( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
double streamTime, RtAudioStreamStatus status, void *data )
{
(void) streamTime; (void) status;
AudioPipe* pipe = (AudioPipe*) data;
const unsigned int size = nBufferFrames > Signal::size ? Signal::size : nBufferFrames;
if (_latencyTimeBuffer)
{
unsigned int k=0;
unsigned int rb=_(latencyCurrentBuffer+_latencyTimeBuffer)%_latencySignalsL.size();
if (inputBuffer)
{
//On enregistre le signal recu pour le diffuser plus tard
Signal* recordR = &(_latencySignalsR[rb]);
Signal* recordL = &(_latencySignalsL[rb]);
for (unsigned int i=0; i< size; ++i) {
recordR->samples[i] = ((sample*) inputBuffer)[k++];
recordL->samples[i] = ((sample*) inputBuffer)[k++];
}
//On envois le signal retarder pour traitment fft etc...
pipe->_mutexIO.lock();
Signal* playR = &(_latencySignalsR[_latencyCurrentBuffer]);
Signal* playL = &(_latencySignalsL[_latencyCurrentBuffer]);
if (inputBuffer) {
k=0;
for (unsigned int i=0; i< size; ++i) {
pipe->_leftOut.samples[i] = (playL->samples)[k++];
pipe->_rightOut.samples[i] = (playR->samples)[k++];
}
}
pipe->_mutexIO.unlock();
//Trash fix du coup j'ai la flemme de comprendre le code de tt
//facons tu n'as pas besoin de son
//donc j,envois du silence dans les hp ;-)
if (outputBuffer) {
k=0;
for (unsigned int i=0; i< size; ++i) {
((sample*) outputBuffer)[k++] = 0.0;
((sample*) outputBuffer)[k++] = 0.0;
}
}
//On avance dans le temp.
_latencyCurrentBuffer++;
if (_latencyCurrentBuffer>=_latencySignalsL.size())
{
_latencyCurrentBuffer=0;
}
}
}
else //Normalement y a plein de trucs a gerer pour pouvoir jouer la music depuis
/// la playlist mais bon pour le concert on s'en fou...
{
pipe->_mutexMixer.lock();
if (pipe->_mixer) {//A t'on quelque chose à mixer avec le signal sonnore de sortie ?
unsigned int k=0;
if (inputBuffer) {
for (unsigned int i=0; i< size; ++i) {
pipe->_leftIn.samples[i] = ((sample*) inputBuffer)[k++];
pipe->_rightIn.samples[i] = ((sample*) inputBuffer)[k++];
}
}
pipe->_mutexIO.lock();
pipe->_mixer->step(pipe->_leftIn,pipe->_rightIn,pipe->_leftOut,pipe->_rightOut);
pipe->_mutexIO.unlock();
pipe->_mutexMixer.unlock();
if (outputBuffer) {
k=0;
for (unsigned int i=0; i< size; ++i) {
((sample*) outputBuffer)[k++] = pipe->_leftOut.samples[i];
((sample*) outputBuffer)[k++] = pipe->_rightOut.samples[i];
}
}
} else {
pipe->_mutexMixer.unlock();
unsigned int k=0;
pipe->_mutexIO.lock();
if (inputBuffer) {
for (unsigned int i=0; i< size; ++i) {
pipe->_leftOut.samples[i] = ((sample*) inputBuffer)[k++];
pipe->_rightOut.samples[i] = ((sample*) inputBuffer)[k++];
}
}
pipe->_mutexIO.unlock();
//Dans le cas ou je n'ai pas de mixage autant balancer directement la sortie
// on gagne Signal::size de latence
if (outputBuffer && inputBuffer && !pipe->_mixer) {
unsigned long bytes = nBufferFrames * 2 * sizeof(float);
memcpy( outputBuffer, inputBuffer, bytes);
}
}
}
pipe->_contidionIO.wakeAll();
return 0;
}
bool AudioPipe::setInputDeviceId(int id) {
if (isRunning()) return false;
if (id > (int) getDeviceCount()) return false;
_deviceInId = id;
Core::instance()->settings.setValue("Audio/DeviceInId",id);
return true;
}
bool AudioPipe::setOutputDeviceId(int id) {
if (isRunning()) return false;
if (id > (int) getDeviceCount()) return false;
_deviceOutId = id;
Core::instance()->settings.setValue("Audio/DeviceOutId",id);
return true;
}
void AudioPipe::setMixer(AbstractStereoSignalMixer* mixer)
{
_mutexMixer.lock();
_mixer = mixer; //Il est possible de changer le Mixer en temps réel
_mutexMixer.unlock();
}
void AudioPipe::show_critical(QString caption, QString error)
{
QMessageBox::critical(NULL, caption, error); //Because QMessageBox must be created in GUI Thread so...
}
<commit_msg>oups il manquer l'utilisation de la variable BPM_MIN<commit_after>#include "audiopipe.hpp"
#include "core.h"
#include <QMessageBox>
#include <algorithm>
#define BPM_MIN 30.0;
QString RtAudioApiToQString(RtAudio::Api api)
{
switch (api) {
case RtAudio::UNSPECIFIED: return "Default";
case RtAudio::UNIX_JACK: return "Jack";
case RtAudio::LINUX_ALSA: return "ALSA";
case RtAudio::LINUX_OSS: return "OSS";
case RtAudio::LINUX_PULSE: return "PulseAudio";
case RtAudio::MACOSX_CORE: return "OSX Audio Core";
case RtAudio::WINDOWS_ASIO: return "ASIO";
case RtAudio::WINDOWS_DS: return "DirectSound";
case RtAudio::WINDOWS_WASAPI: return "WASAPI";
default: break;
}
return "Error";
}
RtAudio::Api QStringToRtAudioApi(const QString& api)
{
if (api=="Default") return RtAudio::UNSPECIFIED;
else if (api=="Jack") return RtAudio::UNIX_JACK;
else if (api=="ALSA") return RtAudio::LINUX_ALSA;
else if (api=="OSS") return RtAudio::LINUX_OSS;
else if (api=="PulseAudio") return RtAudio::LINUX_PULSE;
else if (api=="OSX Audio Core") return RtAudio::MACOSX_CORE;
else if (api=="ASIO") return RtAudio::WINDOWS_ASIO;
else if (api=="DirectSound") return RtAudio::WINDOWS_DS;
else if (api=="WASAPI") return RtAudio::WINDOWS_WASAPI;
else return RtAudio::UNSPECIFIED;
}
AudioPipe::AudioPipe(QObject *parent) :
QThread(parent),
_mixer(NULL),
_stopThread(false)
{
std::cout << "pouet" << std::endl;
RtAudio::Api api = QStringToRtAudioApi(Core::instance()->settings.value("Audio/Driver","Default").toString());
std::cout << "pouet" << std::endl;
_driver = new RtAudio(api);
std::cout << "pouet" << std::endl;
_driver->showWarnings();
std::cout << "pouet" << std::endl;
_deviceOutId=Core::instance()->settings.value("Audio/DeviceOutId",_driver->getDefaultOutputDevice()).toInt();
_deviceInId=Core::instance()->settings.value("Audio/DeviceInId",_driver->getDefaultInputDevice()).toInt();
std::cout << "pouet" << std::endl;
connect(this,SIGNAL(critical_error(QString,QString)),SLOT(show_critical(QString,QString)));
_latencySignalsR.resize(Signal::refreshRate * 60 /(BPM_MIN));
_latencySignalsL.resize(Signal::refreshRate * 60 /(BPM_MIN));
_latencyTimeBuffer = 0;
_latencyCurrentBuffer = 0;
}
void AudioPipe::stop() {
_stopThread=true;
if (isRunning()) wait();
_stopThread=false;
}
void AudioPipe::prepare()
{
RtAudio::StreamParameters iParams, oParams;
if ( _deviceInId != -1 ) {
iParams.deviceId = _deviceInId;
iParams.nChannels = 2;
iParams.firstChannel = 0;
}
if ( _deviceOutId != -1 ) {
oParams.deviceId = _deviceOutId;
oParams.nChannels = 2;
oParams.firstChannel = 0;
}
try
{
if ( _deviceInId != -1 && _deviceOutId != -1 )
_driver->openStream( &oParams, &iParams, RTAUDIO_FLOAT32, Signal::frequency,
(unsigned int*)&Signal::size, &AudioPipe::rtaudio_callback, this );
else if (_deviceInId != -1)
_driver->openStream( 0, &iParams, RTAUDIO_FLOAT32, Signal::frequency,
(unsigned int*)&Signal::size, &AudioPipe::rtaudio_callback, this );
else if (_deviceOutId != -1)
_driver->openStream( &oParams, 0, RTAUDIO_FLOAT32, Signal::frequency,
(unsigned int*)&Signal::size, &AudioPipe::rtaudio_callback, this );
else {
emit critical_error("Error in AudioPipe thread", "No devices selected !");
if ( _driver->isStreamOpen() ) _driver->closeStream();
return;
}
}
catch ( RtAudioError& e )
{
emit critical_error("Error in AudioPipe : open stream", QString(e.getMessage().c_str()));
if ( _driver->isStreamOpen() ) _driver->closeStream();
return;
}
}
void AudioPipe::run() {
_leftOut.reset();
_rightOut.reset();
_leftIn.reset();
_rightIn.reset();
//Creating local variables to work on it
Signal left;
Signal right;
try
{
_driver->startStream();
}
catch ( RtAudioError& e )
{
emit critical_error("Error in AudioPipe : start stream", QString(e.getMessage().c_str()));
if ( _driver->isStreamOpen() ) _driver->closeStream();
return;
}
emit computedLatency(getStreamLatency() + Signal::size*3);
const bool isPow2 = Signal::isPow2;
const unsigned int signal_size = Signal::size;
Core* core = Core::instance();
FFT* fft = core->fft;
while (!_stopThread) //Normalement pas besoin de mutex
{
_mutexIO.lock();
//En utilisant cette stratégie je suis sur de faire au mieu un calcul
//à chaque fois que j'ai réelement une entrée et au pire moins de fois
//(si je n'ai pas les performances suffisantes)
_contidionIO.wait(&_mutexIO);
//Il y aura une latence max de Signal::size + hardware pour l'entrée
left =_leftOut;
right = _rightOut;
//Au pour reboucler la sortie on aura une latence
// 3*Signal::size + hardwareIn + hardwareOut
//Ici on comprend donc qu'il nous faut un Signal::size le plus petit possible,
//et c'est loin d'être évident...
_mutexIO.unlock();
//Dans la suite Out contient le signal qui va sortir sur les HP (donc un signal non modifié)
// et In est le signal qui va se faire analyser (et qui parfois peut-être modifié...)
//Analyse FFT
fft->mutex.lock();
if (isPow2)
fft->compute(left.samples,signal_size);
else
fft->pushSignal(left);
fft->computeModule();
fft->mutex.unlock();
float bass=0;
const unsigned int cut=core->bassCutoff;
for (unsigned int i=0; i < cut; i++) {
bass = std::max(fft->getModule()[i],bass);
}
bass *= 1.25; //on dynamise
if (bass > 1.f) bass = 1.f; //Normalisé entre 0 et 1
//Analyse du bruit (Noise)
core->visualSignal->update(left);
core->setNoise((float) core->visualSignal->noise / (80.f*200.f));
core->setBass(bass);
}
_driver->stopStream();
_driver->closeStream();
}
void AudioPipe::setApi(RtAudio::Api api)
{
stop();
delete _driver;
_driver = new RtAudio(api);
_driver->showWarnings();
}
void AudioPipe::setLatenyTime(float sec)
{
int n = (int)(sec*(float)Signal::refreshRate);
if (n > _latencySignalsL.size())
{
n = _latencySignalsL.size()-1;
}
else if (n <= 0.f)
{
n = 0;
}
_latencyTimeBuffer = n;
}
int AudioPipe::rtaudio_callback( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
double streamTime, RtAudioStreamStatus status, void *data )
{
(void) streamTime; (void) status;
AudioPipe* pipe = (AudioPipe*) data;
const unsigned int size = nBufferFrames > Signal::size ? Signal::size : nBufferFrames;
if (_latencyTimeBuffer)
{
unsigned int k=0;
unsigned int rb=_(latencyCurrentBuffer+_latencyTimeBuffer)%_latencySignalsL.size();
if (inputBuffer)
{
//On enregistre le signal recu pour le diffuser plus tard
Signal* recordR = &(_latencySignalsR[rb]);
Signal* recordL = &(_latencySignalsL[rb]);
for (unsigned int i=0; i< size; ++i) {
recordR->samples[i] = ((sample*) inputBuffer)[k++];
recordL->samples[i] = ((sample*) inputBuffer)[k++];
}
//On envois le signal retarder pour traitment fft etc...
pipe->_mutexIO.lock();
Signal* playR = &(_latencySignalsR[_latencyCurrentBuffer]);
Signal* playL = &(_latencySignalsL[_latencyCurrentBuffer]);
if (inputBuffer) {
k=0;
for (unsigned int i=0; i< size; ++i) {
pipe->_leftOut.samples[i] = (playL->samples)[k++];
pipe->_rightOut.samples[i] = (playR->samples)[k++];
}
}
pipe->_mutexIO.unlock();
//Trash fix du coup j'ai la flemme de comprendre le code de tt
//facons tu n'as pas besoin de son
//donc j,envois du silence dans les hp ;-)
if (outputBuffer) {
k=0;
for (unsigned int i=0; i< size; ++i) {
((sample*) outputBuffer)[k++] = 0.0;
((sample*) outputBuffer)[k++] = 0.0;
}
}
//On avance dans le temp.
_latencyCurrentBuffer++;
if (_latencyCurrentBuffer>=_latencySignalsL.size())
{
_latencyCurrentBuffer=0;
}
}
}
else //Normalement y a plein de trucs a gerer pour pouvoir jouer la music depuis
/// la playlist mais bon pour le concert on s'en fou...
{
pipe->_mutexMixer.lock();
if (pipe->_mixer) {//A t'on quelque chose à mixer avec le signal sonnore de sortie ?
unsigned int k=0;
if (inputBuffer) {
for (unsigned int i=0; i< size; ++i) {
pipe->_leftIn.samples[i] = ((sample*) inputBuffer)[k++];
pipe->_rightIn.samples[i] = ((sample*) inputBuffer)[k++];
}
}
pipe->_mutexIO.lock();
pipe->_mixer->step(pipe->_leftIn,pipe->_rightIn,pipe->_leftOut,pipe->_rightOut);
pipe->_mutexIO.unlock();
pipe->_mutexMixer.unlock();
if (outputBuffer) {
k=0;
for (unsigned int i=0; i< size; ++i) {
((sample*) outputBuffer)[k++] = pipe->_leftOut.samples[i];
((sample*) outputBuffer)[k++] = pipe->_rightOut.samples[i];
}
}
} else {
pipe->_mutexMixer.unlock();
unsigned int k=0;
pipe->_mutexIO.lock();
if (inputBuffer) {
for (unsigned int i=0; i< size; ++i) {
pipe->_leftOut.samples[i] = ((sample*) inputBuffer)[k++];
pipe->_rightOut.samples[i] = ((sample*) inputBuffer)[k++];
}
}
pipe->_mutexIO.unlock();
//Dans le cas ou je n'ai pas de mixage autant balancer directement la sortie
// on gagne Signal::size de latence
if (outputBuffer && inputBuffer && !pipe->_mixer) {
unsigned long bytes = nBufferFrames * 2 * sizeof(float);
memcpy( outputBuffer, inputBuffer, bytes);
}
}
}
pipe->_contidionIO.wakeAll();
return 0;
}
bool AudioPipe::setInputDeviceId(int id) {
if (isRunning()) return false;
if (id > (int) getDeviceCount()) return false;
_deviceInId = id;
Core::instance()->settings.setValue("Audio/DeviceInId",id);
return true;
}
bool AudioPipe::setOutputDeviceId(int id) {
if (isRunning()) return false;
if (id > (int) getDeviceCount()) return false;
_deviceOutId = id;
Core::instance()->settings.setValue("Audio/DeviceOutId",id);
return true;
}
void AudioPipe::setMixer(AbstractStereoSignalMixer* mixer)
{
_mutexMixer.lock();
_mixer = mixer; //Il est possible de changer le Mixer en temps réel
_mutexMixer.unlock();
}
void AudioPipe::show_critical(QString caption, QString error)
{
QMessageBox::critical(NULL, caption, error); //Because QMessageBox must be created in GUI Thread so...
}
<|endoftext|>
|
<commit_before>#include "ClientConnection.hpp"
#include "CryptoHandler.hpp"
#include "FlakyFakeSocketHandler.hpp"
#include "Headers.hpp"
#include "PortForwardClientListener.hpp"
#include "PortForwardClientRouter.hpp"
#include "ServerConnection.hpp"
#include "SocketUtils.hpp"
#include "UnixSocketHandler.hpp"
#include <errno.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include "ETerminal.pb.h"
using namespace et;
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;
shared_ptr<ClientConnection> globalClient;
termios terminal_backup;
DEFINE_string(host, "localhost", "host to join");
DEFINE_int32(port, 2022, "port to connect on");
DEFINE_string(id, "", "Unique ID assigned to this session");
DEFINE_string(passkey, "", "Passkey to encrypt/decrypt packets");
DEFINE_string(idpasskeyfile, "",
"File containing client ID and key to encrypt/decrypt packets");
DEFINE_string(command, "", "Command to run immediately after connecting");
DEFINE_string(portforward, "",
"Array of source:destination ports or srcStart-srcEnd:dstStart-dstEnd (inclusive) port ranges (e.g. 10080:80,10443:443, 10090-10092:8000-8002)");
shared_ptr<ClientConnection> createClient() {
string id = FLAGS_id;
string passkey = FLAGS_passkey;
if (FLAGS_idpasskeyfile.length() > 0) {
// Check for passkey file
std::ifstream t(FLAGS_idpasskeyfile.c_str());
std::stringstream buffer;
buffer << t.rdbuf();
string idpasskeypair = buffer.str();
// Trim whitespace
idpasskeypair.erase(idpasskeypair.find_last_not_of(" \n\r\t") + 1);
size_t slashIndex = idpasskeypair.find("/");
if (slashIndex == string::npos) {
LOG(FATAL) << "Invalid idPasskey id/key pair: " << idpasskeypair;
} else {
id = idpasskeypair.substr(0, slashIndex);
passkey = idpasskeypair.substr(slashIndex + 1);
LOG(INFO) << "ID PASSKEY: " << id << " " << passkey << endl;
}
// Delete the file with the passkey
remove(FLAGS_idpasskeyfile.c_str());
}
if (passkey.length() == 0 || id.length() == 0) {
cout << "Unless you are doing development on Eternal Terminal,\nplease do "
"not call etclient directly.\n\nThe et launcher (run on the "
"client) calls etclient with the correct parameters.\nThis ensures "
"a secure connection.\n\nIf you intended to call etclient "
"directly, please provide a passkey\n(run \"etclient --help\" for "
"details)."
<< endl;
exit(1);
}
if (passkey.length() != 32) {
LOG(FATAL) << "Invalid/missing passkey: " << passkey << " "
<< passkey.length();
}
InitialPayload payload;
shared_ptr<SocketHandler> clientSocket(new UnixSocketHandler());
shared_ptr<ClientConnection> client = shared_ptr<ClientConnection>(
new ClientConnection(clientSocket, FLAGS_host, FLAGS_port, id, passkey));
int connectFailCount = 0;
while (true) {
try {
client->connect();
client->writeProto(payload);
} catch (const runtime_error& err) {
LOG(ERROR) << "Connecting to server failed: " << err.what();
connectFailCount++;
if (connectFailCount == 3) {
LOG(INFO) << "Could not make initial connection to server";
cout << "Could not make initial connection to " << FLAGS_host << ": "
<< err.what() << endl;
exit(1);
}
continue;
}
break;
}
VLOG(1) << "Client created with id: " << client->getId() << endl;
return client;
};
int firstWindowChangedCall=1;
void handleWindowChanged(winsize* win) {
winsize tmpwin;
ioctl(1, TIOCGWINSZ, &tmpwin);
if (firstWindowChangedCall ||
win->ws_row != tmpwin.ws_row || win->ws_col != tmpwin.ws_col ||
win->ws_xpixel != tmpwin.ws_xpixel ||
win->ws_ypixel != tmpwin.ws_ypixel) {
firstWindowChangedCall = 0;
*win = tmpwin;
LOG(INFO) << "Window size changed: " << win->ws_row << " " << win->ws_col
<< " " << win->ws_xpixel << " " << win->ws_ypixel << endl;
TerminalInfo ti;
ti.set_row(win->ws_row);
ti.set_column(win->ws_col);
ti.set_width(win->ws_xpixel);
ti.set_height(win->ws_ypixel);
string s(1, (char)et::PacketType::TERMINAL_INFO);
globalClient->writeMessage(s);
globalClient->writeProto(ti);
}
}
int main(int argc, char** argv) {
gflags::SetVersionString(string(ET_VERSION));
ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
GOOGLE_PROTOBUF_VERIFY_VERSION;
FLAGS_logbufsecs = 0;
FLAGS_logbuflevel = google::GLOG_INFO;
srand(1);
globalClient = createClient();
shared_ptr<UnixSocketHandler> socketHandler =
static_pointer_cast<UnixSocketHandler>(globalClient->getSocketHandler());
// Whether the TE should keep running.
bool run = true;
// TE sends/receives data to/from the shell one char at a time.
#define BUF_SIZE (16 * 1024)
char b[BUF_SIZE];
time_t keepaliveTime = time(NULL) + 5;
bool waitingOnKeepalive = false;
if (FLAGS_command.length()) {
LOG(INFO) << "Got command: " << FLAGS_command << endl;
et::TerminalBuffer tb;
tb.set_buffer(FLAGS_command + "; exit\n");
char c = et::PacketType::TERMINAL_BUFFER;
string headerString(1, c);
globalClient->writeMessage(headerString);
globalClient->writeProto(tb);
}
PortForwardClientRouter portForwardRouter;
try {
if (FLAGS_portforward.length()) {
auto j = split(FLAGS_portforward, ',');
for (auto& pair : j) {
vector<string> sourceDestination = split(pair, ':');
if (sourceDestination[0].find('-') != string::npos
&& sourceDestination[1].find('-') != string::npos) {
vector<string> sourcePortRange = split(sourceDestination[0], '-');
int sourcePortStart = stoi(sourcePortRange[0]);
int sourcePortEnd = stoi(sourcePortRange[1]);
vector<string> destinationPortRange = split(sourceDestination[1], '-');
int destinationPortStart = stoi(destinationPortRange[0]);
int destinationPortEnd = stoi(destinationPortRange[1]);
if (sourcePortEnd - sourcePortStart != destinationPortEnd - destinationPortStart) {
cout << "source/destination port range don't match" << endl;
exit(1);
} else {
int portRangeLength = sourcePortEnd - sourcePortStart + 1;
for (int i=0; i < portRangeLength; ++i) {
portForwardRouter.addListener(
shared_ptr<PortForwardClientListener>(new PortForwardClientListener(
socketHandler, sourcePortStart+i, destinationPortStart+i)));
}
}
} else {
// TODO: Handle bad input
int sourcePort = stoi(sourceDestination[0]);
int destinationPort = stoi(sourceDestination[1]);
portForwardRouter.addListener(
shared_ptr<PortForwardClientListener>(new PortForwardClientListener(
socketHandler, sourcePort, destinationPort)));
}
}
}
} catch (const std::runtime_error& ex) {
cout << "Error establishing port forward: " << ex.what() << endl;
exit(1);
}
winsize win;
ioctl(1, TIOCGWINSZ, &win);
termios terminal_local;
tcgetattr(0, &terminal_local);
memcpy(&terminal_backup, &terminal_local, sizeof(struct termios));
cfmakeraw(&terminal_local);
tcsetattr(0, TCSANOW, &terminal_local);
while (run && !globalClient->isShuttingDown()) {
// Data structures needed for select() and
// non-blocking I/O.
fd_set rfd;
timeval tv;
FD_ZERO(&rfd);
int maxfd = STDIN_FILENO;
FD_SET(STDIN_FILENO, &rfd);
int clientFd = globalClient->getSocketFd();
if (clientFd > 0) {
FD_SET(clientFd, &rfd);
maxfd = max(maxfd, clientFd);
}
// TODO: set port forward sockets as well for performance reasons.
tv.tv_sec = 0;
tv.tv_usec = 10000;
select(maxfd + 1, &rfd, NULL, NULL, &tv);
try {
// Check for data to send.
if (FD_ISSET(STDIN_FILENO, &rfd)) {
// Read from stdin and write to our client that will then send it to the
// server.
int rc = read(STDIN_FILENO, b, BUF_SIZE);
FATAL_FAIL(rc);
if (rc > 0) {
// VLOG(1) << "Sending byte: " << int(b) << " " << char(b) << " " <<
// globalClient->getWriter()->getSequenceNumber();
string s(b, rc);
et::TerminalBuffer tb;
tb.set_buffer(s);
char c = et::PacketType::TERMINAL_BUFFER;
string headerString(1, c);
globalClient->writeMessage(headerString);
globalClient->writeProto(tb);
keepaliveTime = time(NULL) + 5;
} else {
LOG(FATAL) << "Got an error reading from stdin: " << rc;
}
}
if (clientFd > 0 && FD_ISSET(clientFd, &rfd)) {
while (globalClient->hasData()) {
string packetTypeString;
if (!globalClient->readMessage(&packetTypeString)) {
break;
}
if (packetTypeString.length() != 1) {
LOG(FATAL) << "Invalid packet header size: "
<< packetTypeString.length();
}
char packetType = packetTypeString[0];
switch (packetType) {
case et::PacketType::TERMINAL_BUFFER: {
// Read from the server and write to our fake terminal
et::TerminalBuffer tb =
globalClient->readProto<et::TerminalBuffer>();
const string& s = tb.buffer();
// VLOG(1) << "Got byte: " << int(b) << " " << char(b) << " " <<
// globalClient->getReader()->getSequenceNumber();
keepaliveTime = time(NULL) + 1;
FATAL_FAIL(writeAll(STDOUT_FILENO, &s[0], s.length()));
break;
}
case et::PacketType::KEEP_ALIVE:
waitingOnKeepalive = false;
break;
case PacketType::PORT_FORWARD_RESPONSE: {
PortForwardResponse pfr =
globalClient->readProto<PortForwardResponse>();
if (pfr.has_error()) {
LOG(INFO) << "Could not connect to server through tunnel: "
<< pfr.error();
portForwardRouter.closeClientFd(pfr.clientfd());
} else {
LOG(INFO) << "Received socket/fd map from server: "
<< pfr.socketid() << " " << pfr.clientfd();
portForwardRouter.addSocketId(pfr.socketid(), pfr.clientfd());
}
break;
}
case PacketType::PORT_FORWARD_DATA: {
PortForwardData pwd = globalClient->readProto<PortForwardData>();
LOG(INFO) << "Got data for socket: " << pwd.socketid();
if (pwd.has_closed()) {
LOG(INFO) << "Port forward socket closed: " << pwd.socketid();
portForwardRouter.closeSocketId(pwd.socketid());
} else if (pwd.has_error()) {
// TODO: Probably need to do something better here
portForwardRouter.closeSocketId(pwd.socketid());
} else {
portForwardRouter.sendDataOnSocket(pwd.socketid(),
pwd.buffer());
}
break;
}
default:
LOG(FATAL) << "Unknown packet type: " << int(packetType) << endl;
}
}
}
if (clientFd > 0 && keepaliveTime < time(NULL)) {
keepaliveTime = time(NULL) + 5;
if (waitingOnKeepalive) {
LOG(INFO) << "Missed a keepalive, killing connection.";
globalClient->closeSocket();
waitingOnKeepalive = false;
} else {
VLOG(1) << "Writing keepalive packet";
string s(1, (char)et::PacketType::KEEP_ALIVE);
globalClient->writeMessage(s);
waitingOnKeepalive = true;
}
}
handleWindowChanged(&win);
vector<PortForwardRequest> requests;
vector<PortForwardData> dataToSend;
portForwardRouter.update(&requests, &dataToSend);
for (auto& pfr : requests) {
char c = et::PacketType::PORT_FORWARD_REQUEST;
string headerString(1, c);
globalClient->writeMessage(headerString);
globalClient->writeProto(pfr);
}
for (auto& pwd : dataToSend) {
char c = PacketType::PORT_FORWARD_DATA;
string headerString(1, c);
globalClient->writeMessage(headerString);
globalClient->writeProto(pwd);
}
} catch (const runtime_error& re) {
LOG(ERROR) << "Error: " << re.what() << endl;
tcsetattr(0, TCSANOW, &terminal_backup);
cout << "Connection closing because of error: " << re.what() << endl;
run = false;
}
}
globalClient.reset();
LOG(INFO) << "Client derefernced" << endl;
tcsetattr(0, TCSANOW, &terminal_backup);
cout << "Session terminated" << endl;
return 0;
}
<commit_msg>address bad input<commit_after>#include "ClientConnection.hpp"
#include "CryptoHandler.hpp"
#include "FlakyFakeSocketHandler.hpp"
#include "Headers.hpp"
#include "PortForwardClientListener.hpp"
#include "PortForwardClientRouter.hpp"
#include "ServerConnection.hpp"
#include "SocketUtils.hpp"
#include "UnixSocketHandler.hpp"
#include <errno.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include "ETerminal.pb.h"
using namespace et;
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;
shared_ptr<ClientConnection> globalClient;
termios terminal_backup;
DEFINE_string(host, "localhost", "host to join");
DEFINE_int32(port, 2022, "port to connect on");
DEFINE_string(id, "", "Unique ID assigned to this session");
DEFINE_string(passkey, "", "Passkey to encrypt/decrypt packets");
DEFINE_string(idpasskeyfile, "",
"File containing client ID and key to encrypt/decrypt packets");
DEFINE_string(command, "", "Command to run immediately after connecting");
DEFINE_string(portforward, "",
"Array of source:destination ports (e.g. 10080:80,10443:443)");
shared_ptr<ClientConnection> createClient() {
string id = FLAGS_id;
string passkey = FLAGS_passkey;
if (FLAGS_idpasskeyfile.length() > 0) {
// Check for passkey file
std::ifstream t(FLAGS_idpasskeyfile.c_str());
std::stringstream buffer;
buffer << t.rdbuf();
string idpasskeypair = buffer.str();
// Trim whitespace
idpasskeypair.erase(idpasskeypair.find_last_not_of(" \n\r\t") + 1);
size_t slashIndex = idpasskeypair.find("/");
if (slashIndex == string::npos) {
LOG(FATAL) << "Invalid idPasskey id/key pair: " << idpasskeypair;
} else {
id = idpasskeypair.substr(0, slashIndex);
passkey = idpasskeypair.substr(slashIndex + 1);
LOG(INFO) << "ID PASSKEY: " << id << " " << passkey << endl;
}
// Delete the file with the passkey
remove(FLAGS_idpasskeyfile.c_str());
}
if (passkey.length() == 0 || id.length() == 0) {
cout << "Unless you are doing development on Eternal Terminal,\nplease do "
"not call etclient directly.\n\nThe et launcher (run on the "
"client) calls etclient with the correct parameters.\nThis ensures "
"a secure connection.\n\nIf you intended to call etclient "
"directly, please provide a passkey\n(run \"etclient --help\" for "
"details)."
<< endl;
exit(1);
}
if (passkey.length() != 32) {
LOG(FATAL) << "Invalid/missing passkey: " << passkey << " "
<< passkey.length();
}
InitialPayload payload;
shared_ptr<SocketHandler> clientSocket(new UnixSocketHandler());
shared_ptr<ClientConnection> client = shared_ptr<ClientConnection>(
new ClientConnection(clientSocket, FLAGS_host, FLAGS_port, id, passkey));
int connectFailCount = 0;
while (true) {
try {
client->connect();
client->writeProto(payload);
} catch (const runtime_error& err) {
LOG(ERROR) << "Connecting to server failed: " << err.what();
connectFailCount++;
if (connectFailCount == 3) {
LOG(INFO) << "Could not make initial connection to server";
cout << "Could not make initial connection to " << FLAGS_host << ": "
<< err.what() << endl;
exit(1);
}
continue;
}
break;
}
VLOG(1) << "Client created with id: " << client->getId() << endl;
return client;
};
int firstWindowChangedCall=1;
void handleWindowChanged(winsize* win) {
winsize tmpwin;
ioctl(1, TIOCGWINSZ, &tmpwin);
if (firstWindowChangedCall ||
win->ws_row != tmpwin.ws_row || win->ws_col != tmpwin.ws_col ||
win->ws_xpixel != tmpwin.ws_xpixel ||
win->ws_ypixel != tmpwin.ws_ypixel) {
firstWindowChangedCall = 0;
*win = tmpwin;
LOG(INFO) << "Window size changed: " << win->ws_row << " " << win->ws_col
<< " " << win->ws_xpixel << " " << win->ws_ypixel << endl;
TerminalInfo ti;
ti.set_row(win->ws_row);
ti.set_column(win->ws_col);
ti.set_width(win->ws_xpixel);
ti.set_height(win->ws_ypixel);
string s(1, (char)et::PacketType::TERMINAL_INFO);
globalClient->writeMessage(s);
globalClient->writeProto(ti);
}
}
int main(int argc, char** argv) {
gflags::SetVersionString(string(ET_VERSION));
ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
GOOGLE_PROTOBUF_VERIFY_VERSION;
FLAGS_logbufsecs = 0;
FLAGS_logbuflevel = google::GLOG_INFO;
srand(1);
globalClient = createClient();
shared_ptr<UnixSocketHandler> socketHandler =
static_pointer_cast<UnixSocketHandler>(globalClient->getSocketHandler());
// Whether the TE should keep running.
bool run = true;
// TE sends/receives data to/from the shell one char at a time.
#define BUF_SIZE (16 * 1024)
char b[BUF_SIZE];
time_t keepaliveTime = time(NULL) + 5;
bool waitingOnKeepalive = false;
if (FLAGS_command.length()) {
LOG(INFO) << "Got command: " << FLAGS_command << endl;
et::TerminalBuffer tb;
tb.set_buffer(FLAGS_command + "; exit\n");
char c = et::PacketType::TERMINAL_BUFFER;
string headerString(1, c);
globalClient->writeMessage(headerString);
globalClient->writeProto(tb);
}
PortForwardClientRouter portForwardRouter;
try {
if (FLAGS_portforward.length()) {
auto j = split(FLAGS_portforward, ',');
for (auto& pair : j) {
vector<string> sourceDestination = split(pair, ':');
try {
if (sourceDestination[0].find('-') != string::npos
&& sourceDestination[1].find('-') != string::npos) {
vector<string> sourcePortRange = split(sourceDestination[0], '-');
int sourcePortStart = stoi(sourcePortRange[0]);
int sourcePortEnd = stoi(sourcePortRange[1]);
vector<string> destinationPortRange = split(sourceDestination[1], '-');
int destinationPortStart = stoi(destinationPortRange[0]);
int destinationPortEnd = stoi(destinationPortRange[1]);
if (sourcePortEnd - sourcePortStart != destinationPortEnd - destinationPortStart) {
cout << "source/destination port range don't match" << endl;
exit(1);
} else {
int portRangeLength = sourcePortEnd - sourcePortStart + 1;
for (int i=0; i < portRangeLength; ++i) {
portForwardRouter.addListener(
shared_ptr<PortForwardClientListener>(new PortForwardClientListener(
socketHandler, sourcePortStart+i, destinationPortStart+i)));
}
}
} else {
// TODO: Handle bad input
int sourcePort = stoi(sourceDestination[0]);
int destinationPort = stoi(sourceDestination[1]);
portForwardRouter.addListener(
shared_ptr<PortForwardClientListener>(new PortForwardClientListener(
socketHandler, sourcePort, destinationPort)));
}
} catch (const std::logic_error& lr) {
cout << "Logic error: " << lr.what() << endl;
exit(1);
}
}
}
} catch (const std::runtime_error& ex) {
cout << "Error establishing port forward: " << ex.what() << endl;
exit(1);
}
winsize win;
ioctl(1, TIOCGWINSZ, &win);
termios terminal_local;
tcgetattr(0, &terminal_local);
memcpy(&terminal_backup, &terminal_local, sizeof(struct termios));
cfmakeraw(&terminal_local);
tcsetattr(0, TCSANOW, &terminal_local);
while (run && !globalClient->isShuttingDown()) {
// Data structures needed for select() and
// non-blocking I/O.
fd_set rfd;
timeval tv;
FD_ZERO(&rfd);
int maxfd = STDIN_FILENO;
FD_SET(STDIN_FILENO, &rfd);
int clientFd = globalClient->getSocketFd();
if (clientFd > 0) {
FD_SET(clientFd, &rfd);
maxfd = max(maxfd, clientFd);
}
// TODO: set port forward sockets as well for performance reasons.
tv.tv_sec = 0;
tv.tv_usec = 10000;
select(maxfd + 1, &rfd, NULL, NULL, &tv);
try {
// Check for data to send.
if (FD_ISSET(STDIN_FILENO, &rfd)) {
// Read from stdin and write to our client that will then send it to the
// server.
int rc = read(STDIN_FILENO, b, BUF_SIZE);
FATAL_FAIL(rc);
if (rc > 0) {
// VLOG(1) << "Sending byte: " << int(b) << " " << char(b) << " " <<
// globalClient->getWriter()->getSequenceNumber();
string s(b, rc);
et::TerminalBuffer tb;
tb.set_buffer(s);
char c = et::PacketType::TERMINAL_BUFFER;
string headerString(1, c);
globalClient->writeMessage(headerString);
globalClient->writeProto(tb);
keepaliveTime = time(NULL) + 5;
} else {
LOG(FATAL) << "Got an error reading from stdin: " << rc;
}
}
if (clientFd > 0 && FD_ISSET(clientFd, &rfd)) {
while (globalClient->hasData()) {
string packetTypeString;
if (!globalClient->readMessage(&packetTypeString)) {
break;
}
if (packetTypeString.length() != 1) {
LOG(FATAL) << "Invalid packet header size: "
<< packetTypeString.length();
}
char packetType = packetTypeString[0];
switch (packetType) {
case et::PacketType::TERMINAL_BUFFER: {
// Read from the server and write to our fake terminal
et::TerminalBuffer tb =
globalClient->readProto<et::TerminalBuffer>();
const string& s = tb.buffer();
// VLOG(1) << "Got byte: " << int(b) << " " << char(b) << " " <<
// globalClient->getReader()->getSequenceNumber();
keepaliveTime = time(NULL) + 1;
FATAL_FAIL(writeAll(STDOUT_FILENO, &s[0], s.length()));
break;
}
case et::PacketType::KEEP_ALIVE:
waitingOnKeepalive = false;
break;
case PacketType::PORT_FORWARD_RESPONSE: {
PortForwardResponse pfr =
globalClient->readProto<PortForwardResponse>();
if (pfr.has_error()) {
LOG(INFO) << "Could not connect to server through tunnel: "
<< pfr.error();
portForwardRouter.closeClientFd(pfr.clientfd());
} else {
LOG(INFO) << "Received socket/fd map from server: "
<< pfr.socketid() << " " << pfr.clientfd();
portForwardRouter.addSocketId(pfr.socketid(), pfr.clientfd());
}
break;
}
case PacketType::PORT_FORWARD_DATA: {
PortForwardData pwd = globalClient->readProto<PortForwardData>();
LOG(INFO) << "Got data for socket: " << pwd.socketid();
if (pwd.has_closed()) {
LOG(INFO) << "Port forward socket closed: " << pwd.socketid();
portForwardRouter.closeSocketId(pwd.socketid());
} else if (pwd.has_error()) {
// TODO: Probably need to do something better here
portForwardRouter.closeSocketId(pwd.socketid());
} else {
portForwardRouter.sendDataOnSocket(pwd.socketid(),
pwd.buffer());
}
break;
}
default:
LOG(FATAL) << "Unknown packet type: " << int(packetType) << endl;
}
}
}
if (clientFd > 0 && keepaliveTime < time(NULL)) {
keepaliveTime = time(NULL) + 5;
if (waitingOnKeepalive) {
LOG(INFO) << "Missed a keepalive, killing connection.";
globalClient->closeSocket();
waitingOnKeepalive = false;
} else {
VLOG(1) << "Writing keepalive packet";
string s(1, (char)et::PacketType::KEEP_ALIVE);
globalClient->writeMessage(s);
waitingOnKeepalive = true;
}
}
handleWindowChanged(&win);
vector<PortForwardRequest> requests;
vector<PortForwardData> dataToSend;
portForwardRouter.update(&requests, &dataToSend);
for (auto& pfr : requests) {
char c = et::PacketType::PORT_FORWARD_REQUEST;
string headerString(1, c);
globalClient->writeMessage(headerString);
globalClient->writeProto(pfr);
}
for (auto& pwd : dataToSend) {
char c = PacketType::PORT_FORWARD_DATA;
string headerString(1, c);
globalClient->writeMessage(headerString);
globalClient->writeProto(pwd);
}
} catch (const runtime_error& re) {
LOG(ERROR) << "Error: " << re.what() << endl;
tcsetattr(0, TCSANOW, &terminal_backup);
cout << "Connection closing because of error: " << re.what() << endl;
run = false;
}
}
globalClient.reset();
LOG(INFO) << "Client derefernced" << endl;
tcsetattr(0, TCSANOW, &terminal_backup);
cout << "Session terminated" << endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 - 2021, Intel Corporation
*
* 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 of Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <memory>
#include <map>
#include "geopm_topo.h"
#include "Helper.hpp"
#include "ServiceIOGroup.hpp"
#include "MockServiceProxy.hpp"
#include "MockPlatformTopo.hpp"
#include "geopm_test.hpp"
using geopm::signal_info_s;
using geopm::control_info_s;
using geopm::ServiceIOGroup;
using geopm::Exception;
using testing::AtLeast;
using testing::Return;
using testing::Throw;
using testing::_;
class ServiceIOGroupTest : public :: testing:: Test
{
protected:
void SetUp();
std::unique_ptr<ServiceIOGroup> m_serviceio_group;
std::shared_ptr<MockServiceProxy> m_proxy;
std::shared_ptr<MockPlatformTopo> m_topo;
int m_num_package = 2;
int m_num_core = 4;
int m_num_cpu = 16;
std::vector<std::string> m_expected_signals;
std::vector<std::string> m_expected_controls;
std::map<std::string, signal_info_s> m_signal_info;
std::map<std::string, control_info_s> m_control_info;
};
void ServiceIOGroupTest::SetUp()
{
m_topo = make_topo(m_num_package, m_num_core, m_num_cpu);
m_proxy = std::make_shared<MockServiceProxy>();
EXPECT_CALL(*m_topo, num_domain(_)).Times(AtLeast(0));
m_expected_signals = {"signal1", "signal2"};
m_expected_controls = {"control1", "control2"};
// signal_info_s: (str)name, (str)desc, (int)domain, (int)agg, (int)string_format, (int)behavior
m_signal_info =
{{m_expected_signals[0],
{m_expected_signals[0], "1 Signal", 0, 0, 0, 0}},
{m_expected_signals[1],
{m_expected_signals[1], "2 Signal", 1, 1, 1, 1}},
};
// control_info_s: (str)name, (str)desc, (int)domain
m_control_info =
{{m_expected_controls[0],
{m_expected_controls[0], "1 Control", 0}},
{m_expected_controls[1],
{m_expected_controls[1], "2 Control", 1}},
};
EXPECT_CALL(*m_proxy, platform_get_user_access(_, _))
.WillRepeatedly([this]
(std::vector<std::string> &signals,
std::vector<std::string> &controls) {
signals = m_expected_signals;
controls = m_expected_controls;
});
std::vector<signal_info_s> expected_signal_info = {m_signal_info[m_expected_signals[0]],
m_signal_info[m_expected_signals[1]]};
std::vector<control_info_s> expected_control_info = {m_control_info[m_expected_controls[0]],
m_control_info[m_expected_controls[1]]};
EXPECT_CALL(*m_proxy, platform_get_signal_info(m_expected_signals))
.WillOnce(Return(expected_signal_info));
EXPECT_CALL(*m_proxy, platform_get_control_info(m_expected_controls))
.WillOnce(Return(expected_control_info));
EXPECT_CALL(*m_proxy, platform_open_session());
EXPECT_CALL(*m_proxy, platform_close_session());
m_serviceio_group = geopm::make_unique<ServiceIOGroup>(*m_topo, m_proxy);
}
TEST_F(ServiceIOGroupTest, signal_control_info)
{
auto signal_names = m_serviceio_group->signal_names();
auto control_names = m_serviceio_group->control_names();
for (auto sig : m_expected_signals) {
EXPECT_TRUE(m_serviceio_group->is_valid_signal(sig));
EXPECT_TRUE(signal_names.find(sig) != signal_names.end());
EXPECT_TRUE(signal_names.find("SERVICE::" + sig) != signal_names.end());
EXPECT_EQ(m_signal_info[sig].description, m_serviceio_group->signal_description(sig));
}
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->signal_description("BAD SIGNAL"),
GEOPM_ERROR_INVALID,
"BAD SIGNAL not valid for ServiceIOGroup");
for (auto con : m_expected_controls) {
EXPECT_TRUE(m_serviceio_group->is_valid_control(con));
EXPECT_TRUE(control_names.find(con) != control_names.end());
EXPECT_TRUE(control_names.find("SERVICE::" + con) != control_names.end());
EXPECT_EQ(m_control_info[con].description, m_serviceio_group->control_description(con));
}
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->control_description("BAD CONTROL"),
GEOPM_ERROR_INVALID,
"BAD CONTROL not valid for ServiceIOGroup");
}
TEST_F(ServiceIOGroupTest, domain_type)
{
for (unsigned ii = 0; ii < m_expected_signals.size(); ++ii) {
EXPECT_EQ(ii, m_serviceio_group->signal_domain_type(m_expected_signals.at(ii)));
EXPECT_EQ(ii, m_serviceio_group->signal_domain_type("SERVICE::" + m_expected_signals.at(ii)));
}
for (unsigned ii = 0; ii < m_expected_controls.size(); ++ii) {
EXPECT_EQ(ii, m_serviceio_group->control_domain_type(m_expected_controls.at(ii)));
EXPECT_EQ(ii, m_serviceio_group->control_domain_type("SERVICE::" + m_expected_controls.at(ii)));
}
EXPECT_EQ(GEOPM_DOMAIN_INVALID, m_serviceio_group->signal_domain_type("BAD SIGNAL"));
EXPECT_EQ(GEOPM_DOMAIN_INVALID, m_serviceio_group->control_domain_type("BAD CONTROL"));
}
TEST_F(ServiceIOGroupTest, read_signal_behavior)
{
for (unsigned ii = 0; ii < m_expected_signals.size(); ++ii) {
EXPECT_CALL(*m_proxy, platform_read_signal(m_expected_signals.at(ii), ii, ii))
.WillOnce(Return(42))
.WillOnce(Return(7));
EXPECT_EQ(42, m_serviceio_group->read_signal(m_expected_signals.at(ii), ii, ii));
EXPECT_EQ(7, m_serviceio_group->read_signal("SERVICE::" + m_expected_signals.at(ii), ii, ii));
EXPECT_EQ(ii, m_serviceio_group->signal_behavior(m_expected_signals.at(ii)));
}
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->signal_behavior("BAD SIGNAL"),
GEOPM_ERROR_INVALID,
"BAD SIGNAL not valid for ServiceIOGroup");
}
TEST_F(ServiceIOGroupTest, write_control)
{
for (unsigned ii = 0; ii < m_expected_controls.size(); ++ii) {
EXPECT_CALL(*m_proxy, platform_write_control(m_expected_controls.at(ii), ii, ii, 42));
EXPECT_NO_THROW(m_serviceio_group->write_control(m_expected_controls.at(ii), ii, ii, 42));
EXPECT_CALL(*m_proxy, platform_write_control(m_expected_controls.at(ii), ii, ii, 7));
EXPECT_NO_THROW(m_serviceio_group->write_control("SERVICE::" + m_expected_controls.at(ii),
ii, ii, 7));
}
}
TEST_F(ServiceIOGroupTest, valid_signal_aggregation)
{
std::function<double(const std::vector<double> &)> func;
func = m_serviceio_group->agg_function("signal1");
EXPECT_TRUE(is_agg_sum(func));
func = m_serviceio_group->agg_function("signal2");
EXPECT_TRUE(is_agg_average(func));
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->agg_function("BAD SIGNAL"),
GEOPM_ERROR_INVALID,
"BAD SIGNAL not valid for ServiceIOGroup");
}
TEST_F(ServiceIOGroupTest, valid_format_function)
{
std::function<std::string(double)> func;
func = m_serviceio_group->format_function("signal1");
EXPECT_TRUE(is_format_double(func));
func = m_serviceio_group->format_function("signal2");
EXPECT_TRUE(is_format_integer(func));
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->format_function("BAD SIGNAL"),
GEOPM_ERROR_INVALID,
"BAD SIGNAL not valid for ServiceIOGroup");
}
TEST_F(ServiceIOGroupTest, push_signal)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->push_signal("BAD SIGNAL", 0, 0),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::push_signal()");
}
TEST_F(ServiceIOGroupTest, push_control)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->push_control("BAD CONTROL", 0, 0),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::push_control()");
}
TEST_F(ServiceIOGroupTest, read_batch)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->read_batch(),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::read_batch()");
}
TEST_F(ServiceIOGroupTest, write_batch)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->write_batch(),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::write_batch()");
}
TEST_F(ServiceIOGroupTest, sample)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->sample(0),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::sample()");
}
TEST_F(ServiceIOGroupTest, adjust)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->adjust(0, 0),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::adjust()");
}
<commit_msg>Fix more signed/unsigned comparisons in ServiceIOGroup<commit_after>/*
* Copyright (c) 2015 - 2021, Intel Corporation
*
* 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 of Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <memory>
#include <map>
#include "geopm_topo.h"
#include "Helper.hpp"
#include "ServiceIOGroup.hpp"
#include "MockServiceProxy.hpp"
#include "MockPlatformTopo.hpp"
#include "geopm_test.hpp"
using geopm::signal_info_s;
using geopm::control_info_s;
using geopm::ServiceIOGroup;
using geopm::Exception;
using testing::AtLeast;
using testing::Return;
using testing::Throw;
using testing::_;
class ServiceIOGroupTest : public :: testing:: Test
{
protected:
void SetUp();
std::unique_ptr<ServiceIOGroup> m_serviceio_group;
std::shared_ptr<MockServiceProxy> m_proxy;
std::shared_ptr<MockPlatformTopo> m_topo;
int m_num_package = 2;
int m_num_core = 4;
int m_num_cpu = 16;
std::vector<std::string> m_expected_signals;
std::vector<std::string> m_expected_controls;
std::map<std::string, signal_info_s> m_signal_info;
std::map<std::string, control_info_s> m_control_info;
};
void ServiceIOGroupTest::SetUp()
{
m_topo = make_topo(m_num_package, m_num_core, m_num_cpu);
m_proxy = std::make_shared<MockServiceProxy>();
EXPECT_CALL(*m_topo, num_domain(_)).Times(AtLeast(0));
m_expected_signals = {"signal1", "signal2"};
m_expected_controls = {"control1", "control2"};
// signal_info_s: (str)name, (str)desc, (int)domain, (int)agg, (int)string_format, (int)behavior
m_signal_info =
{{m_expected_signals[0],
{m_expected_signals[0], "1 Signal", 0, 0, 0, 0}},
{m_expected_signals[1],
{m_expected_signals[1], "2 Signal", 1, 1, 1, 1}},
};
// control_info_s: (str)name, (str)desc, (int)domain
m_control_info =
{{m_expected_controls[0],
{m_expected_controls[0], "1 Control", 0}},
{m_expected_controls[1],
{m_expected_controls[1], "2 Control", 1}},
};
EXPECT_CALL(*m_proxy, platform_get_user_access(_, _))
.WillRepeatedly([this]
(std::vector<std::string> &signals,
std::vector<std::string> &controls) {
signals = m_expected_signals;
controls = m_expected_controls;
});
std::vector<signal_info_s> expected_signal_info = {m_signal_info[m_expected_signals[0]],
m_signal_info[m_expected_signals[1]]};
std::vector<control_info_s> expected_control_info = {m_control_info[m_expected_controls[0]],
m_control_info[m_expected_controls[1]]};
EXPECT_CALL(*m_proxy, platform_get_signal_info(m_expected_signals))
.WillOnce(Return(expected_signal_info));
EXPECT_CALL(*m_proxy, platform_get_control_info(m_expected_controls))
.WillOnce(Return(expected_control_info));
EXPECT_CALL(*m_proxy, platform_open_session());
EXPECT_CALL(*m_proxy, platform_close_session());
m_serviceio_group = geopm::make_unique<ServiceIOGroup>(*m_topo, m_proxy);
}
TEST_F(ServiceIOGroupTest, signal_control_info)
{
auto signal_names = m_serviceio_group->signal_names();
auto control_names = m_serviceio_group->control_names();
for (auto sig : m_expected_signals) {
EXPECT_TRUE(m_serviceio_group->is_valid_signal(sig));
EXPECT_TRUE(signal_names.find(sig) != signal_names.end());
EXPECT_TRUE(signal_names.find("SERVICE::" + sig) != signal_names.end());
EXPECT_EQ(m_signal_info[sig].description, m_serviceio_group->signal_description(sig));
}
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->signal_description("BAD SIGNAL"),
GEOPM_ERROR_INVALID,
"BAD SIGNAL not valid for ServiceIOGroup");
for (auto con : m_expected_controls) {
EXPECT_TRUE(m_serviceio_group->is_valid_control(con));
EXPECT_TRUE(control_names.find(con) != control_names.end());
EXPECT_TRUE(control_names.find("SERVICE::" + con) != control_names.end());
EXPECT_EQ(m_control_info[con].description, m_serviceio_group->control_description(con));
}
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->control_description("BAD CONTROL"),
GEOPM_ERROR_INVALID,
"BAD CONTROL not valid for ServiceIOGroup");
}
TEST_F(ServiceIOGroupTest, domain_type)
{
for (int ii = 0; ii < (int)m_expected_signals.size(); ++ii) {
EXPECT_EQ(ii, m_serviceio_group->signal_domain_type(m_expected_signals.at(ii)));
EXPECT_EQ(ii, m_serviceio_group->signal_domain_type("SERVICE::" + m_expected_signals.at(ii)));
}
for (int ii = 0; ii < (int)m_expected_controls.size(); ++ii) {
EXPECT_EQ(ii, m_serviceio_group->control_domain_type(m_expected_controls.at(ii)));
EXPECT_EQ(ii, m_serviceio_group->control_domain_type("SERVICE::" + m_expected_controls.at(ii)));
}
EXPECT_EQ(GEOPM_DOMAIN_INVALID, m_serviceio_group->signal_domain_type("BAD SIGNAL"));
EXPECT_EQ(GEOPM_DOMAIN_INVALID, m_serviceio_group->control_domain_type("BAD CONTROL"));
}
TEST_F(ServiceIOGroupTest, read_signal_behavior)
{
for (unsigned ii = 0; ii < m_expected_signals.size(); ++ii) {
EXPECT_CALL(*m_proxy, platform_read_signal(m_expected_signals.at(ii), ii, ii))
.WillOnce(Return(42))
.WillOnce(Return(7));
EXPECT_EQ(42, m_serviceio_group->read_signal(m_expected_signals.at(ii), ii, ii));
EXPECT_EQ(7, m_serviceio_group->read_signal("SERVICE::" + m_expected_signals.at(ii), ii, ii));
EXPECT_EQ((int)ii, m_serviceio_group->signal_behavior(m_expected_signals.at(ii)));
}
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->signal_behavior("BAD SIGNAL"),
GEOPM_ERROR_INVALID,
"BAD SIGNAL not valid for ServiceIOGroup");
}
TEST_F(ServiceIOGroupTest, write_control)
{
for (unsigned ii = 0; ii < m_expected_controls.size(); ++ii) {
EXPECT_CALL(*m_proxy, platform_write_control(m_expected_controls.at(ii), ii, ii, 42));
EXPECT_NO_THROW(m_serviceio_group->write_control(m_expected_controls.at(ii), ii, ii, 42));
EXPECT_CALL(*m_proxy, platform_write_control(m_expected_controls.at(ii), ii, ii, 7));
EXPECT_NO_THROW(m_serviceio_group->write_control("SERVICE::" + m_expected_controls.at(ii),
ii, ii, 7));
}
}
TEST_F(ServiceIOGroupTest, valid_signal_aggregation)
{
std::function<double(const std::vector<double> &)> func;
func = m_serviceio_group->agg_function("signal1");
EXPECT_TRUE(is_agg_sum(func));
func = m_serviceio_group->agg_function("signal2");
EXPECT_TRUE(is_agg_average(func));
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->agg_function("BAD SIGNAL"),
GEOPM_ERROR_INVALID,
"BAD SIGNAL not valid for ServiceIOGroup");
}
TEST_F(ServiceIOGroupTest, valid_format_function)
{
std::function<std::string(double)> func;
func = m_serviceio_group->format_function("signal1");
EXPECT_TRUE(is_format_double(func));
func = m_serviceio_group->format_function("signal2");
EXPECT_TRUE(is_format_integer(func));
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->format_function("BAD SIGNAL"),
GEOPM_ERROR_INVALID,
"BAD SIGNAL not valid for ServiceIOGroup");
}
TEST_F(ServiceIOGroupTest, push_signal)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->push_signal("BAD SIGNAL", 0, 0),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::push_signal()");
}
TEST_F(ServiceIOGroupTest, push_control)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->push_control("BAD CONTROL", 0, 0),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::push_control()");
}
TEST_F(ServiceIOGroupTest, read_batch)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->read_batch(),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::read_batch()");
}
TEST_F(ServiceIOGroupTest, write_batch)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->write_batch(),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::write_batch()");
}
TEST_F(ServiceIOGroupTest, sample)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->sample(0),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::sample()");
}
TEST_F(ServiceIOGroupTest, adjust)
{
GEOPM_EXPECT_THROW_MESSAGE(m_serviceio_group->adjust(0, 0),
GEOPM_ERROR_NOT_IMPLEMENTED,
"ServiceIOGroup::adjust()");
}
<|endoftext|>
|
<commit_before>/*
* Scope Guard
* Copyright (C) 2017 offa
*
* This file is part of Scope Guard.
*
* Scope Guard 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.
*
* Scope Guard 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 Scope Guard. If not, see <http://www.gnu.org/licenses/>.
*/
#include "unique_resource.h"
#include "CallMocks.h"
#include <catch.hpp>
#include <trompeloeil.hpp>
using namespace mock;
using namespace trompeloeil;
namespace
{
CallMock m;
void deleter(Handle h)
{
m.deleter(h);
}
}
TEST_CASE("construction with move", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
auto guard = sr::make_unique_resource(Handle{3}, deleter);
static_cast<void>(guard);
}
TEST_CASE("construction with copy", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
const Handle h{3};
const auto d = [](auto v) { m.deleter(v); };
auto guard = sr::make_unique_resource(h, d);
static_cast<void>(guard);
}
TEST_CASE("construction with copy calls deleter and rethrows on failed copy", "[UniqueResource]")
{
REQUIRE_THROWS([] {
const ThrowOnCopyMock noMove;
const auto d = [](const auto&) { m.deleter(3); };
REQUIRE_CALL(m, deleter(3));
sr::unique_resource<decltype(noMove), decltype(d)> guard{noMove, d};
static_cast<void>(guard);
}());
}
TEST_CASE("move-construction with move", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
auto movedFrom = sr::make_unique_resource(Handle{3}, deleter);
auto guard = std::move(movedFrom);
CHECK(guard.get() == 3);
}
TEST_CASE("move-construction with copy", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(7));
auto d = [](auto) { deleter(7); };
const CopyMock copyMock;
sr::unique_resource<CopyMock, decltype(d)> movedFrom{copyMock, d};
auto guard = std::move(movedFrom);
static_cast<void>(guard);
}
TEST_CASE("move assignment calls deleter", "[UniqueResource]")
{
auto moveFrom = sr::make_unique_resource(Handle{3}, deleter);
REQUIRE_CALL(m, deleter(4));
{
REQUIRE_CALL(m, deleter(3));
auto guard = sr::make_unique_resource(Handle{4}, deleter);
guard = std::move(moveFrom);
}
}
TEST_CASE("deleter called on destruction", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
auto guard = sr::make_unique_resource(Handle{3}, deleter);
static_cast<void>(guard);
}
TEST_CASE("reset calls deleter", "[UniqueResource]")
{
auto guard = sr::make_unique_resource(Handle{3}, deleter);
{
REQUIRE_CALL(m, deleter(3));
guard.reset();
}
}
TEST_CASE("reset does not call deleter if released", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3)).TIMES(0);
auto guard = sr::make_unique_resource(Handle{3}, deleter);
guard.release();
guard.reset();
}
TEST_CASE("reset sets new value and calls deleter on previous", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
REQUIRE_CALL(m, deleter(7));
auto guard = sr::make_unique_resource(Handle{3}, deleter);
guard.reset(Handle{7});
}
TEST_CASE("reset handles exception on assignment", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
REQUIRE_CALL(m, deleter(7));
auto d = [](const auto& v) { deleter(v.m_handle); };
auto guard = sr::make_unique_resource(ConditialThrowOnCopyMock{3, false}, d);
guard.reset(ConditialThrowOnCopyMock{7, true});
}
TEST_CASE("release disables deleter", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3)).TIMES(0);
auto guard = sr::make_unique_resource(Handle{3}, deleter);
guard.release();
}
TEST_CASE("get returns resource", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
auto guard = sr::make_unique_resource(Handle{3}, deleter);
CHECK(guard.get() == 3);
}
TEST_CASE("pointer access returns resource" "[UniqueResource]")
{
const auto p = std::make_pair(3, 4);
auto guard = sr::make_unique_resource(&p, [](auto*) { });
REQUIRE(guard->first == 3);
REQUIRE(guard->second == 4);
}
TEST_CASE("pointer dereference returns resource" "[UniqueResource]")
{
Handle h{5};
auto guard = sr::make_unique_resource(PtrHandle{&h}, [](auto*) { });
REQUIRE(*guard == 5);
}
TEST_CASE("deleter access", "[UniqueResource]")
{
auto guard = sr::make_unique_resource(Handle{3}, deleter);
guard.release();
{
REQUIRE_CALL(m, deleter(8));
guard.get_deleter()(8);
}
}
TEST_CASE("swap", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(7));
auto guard1 = sr::make_unique_resource(Handle{3}, deleter);
{
REQUIRE_CALL(m, deleter(3));
auto guard2 = sr::make_unique_resource(Handle{7}, deleter);
guard2.swap(guard1);
REQUIRE(guard1.get() == 7);
REQUIRE(guard2.get() == 3);
}
}
TEST_CASE("make unique resource", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(7));
auto guard = sr::make_unique_resource(Handle{7}, deleter);
static_cast<void>(guard);
}
TEST_CASE("make unique resource with reference wrapper", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
Handle h{3};
auto guard = sr::make_unique_resource(std::ref(h), deleter);
static_cast<void>(guard);
}
TEST_CASE("make unique resource checked", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(4));
auto guard = sr::make_unique_resource_checked(Handle{4}, Handle{-1}, deleter);
static_cast<void>(guard);
}
TEST_CASE("make unique resource checked releases if invalid", "[UniqueResource]")
{
auto guard = sr::make_unique_resource_checked(Handle{-1}, Handle{-1}, deleter);
static_cast<void>(guard);
}
<commit_msg>Test updated to use ctor directly.<commit_after>/*
* Scope Guard
* Copyright (C) 2017 offa
*
* This file is part of Scope Guard.
*
* Scope Guard 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.
*
* Scope Guard 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 Scope Guard. If not, see <http://www.gnu.org/licenses/>.
*/
#include "unique_resource.h"
#include "CallMocks.h"
#include <catch.hpp>
#include <trompeloeil.hpp>
using namespace mock;
using namespace trompeloeil;
namespace
{
CallMock m;
void deleter(Handle h)
{
m.deleter(h);
}
}
TEST_CASE("construction with move", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
auto guard = sr::unique_resource{Handle{3}, deleter};
static_cast<void>(guard);
}
TEST_CASE("construction with copy", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
const Handle h{3};
const auto d = [](auto v) { m.deleter(v); };
auto guard = sr::unique_resource{h, d};
static_cast<void>(guard);
}
TEST_CASE("construction with copy calls deleter and rethrows on failed copy", "[UniqueResource]")
{
REQUIRE_THROWS([] {
const ThrowOnCopyMock noMove;
const auto d = [](const auto&) { m.deleter(3); };
REQUIRE_CALL(m, deleter(3));
sr::unique_resource guard{noMove, d};
static_cast<void>(guard);
}());
}
TEST_CASE("move-construction with move", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
auto movedFrom = sr::unique_resource{Handle{3}, deleter};
auto guard = std::move(movedFrom);
CHECK(guard.get() == 3);
}
TEST_CASE("move-construction with copy", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(7));
auto d = [](auto) { deleter(7); };
const CopyMock copyMock;
sr::unique_resource movedFrom{copyMock, d};
auto guard = std::move(movedFrom);
static_cast<void>(guard);
}
TEST_CASE("move assignment calls deleter", "[UniqueResource]")
{
auto moveFrom = sr::unique_resource{Handle{3}, deleter};
REQUIRE_CALL(m, deleter(4));
{
REQUIRE_CALL(m, deleter(3));
auto guard = sr::unique_resource{Handle{4}, deleter};
guard = std::move(moveFrom);
}
}
TEST_CASE("deleter called on destruction", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
auto guard = sr::unique_resource{Handle{3}, deleter};
static_cast<void>(guard);
}
TEST_CASE("reset calls deleter", "[UniqueResource]")
{
auto guard = sr::unique_resource{Handle{3}, deleter};
{
REQUIRE_CALL(m, deleter(3));
guard.reset();
}
}
TEST_CASE("reset does not call deleter if released", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3)).TIMES(0);
auto guard = sr::unique_resource{Handle{3}, deleter};
guard.release();
guard.reset();
}
TEST_CASE("reset sets new value and calls deleter on previous", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
REQUIRE_CALL(m, deleter(7));
auto guard = sr::unique_resource{Handle{3}, deleter};
guard.reset(Handle{7});
}
TEST_CASE("reset handles exception on assignment", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
REQUIRE_CALL(m, deleter(7));
auto d = [](const auto& v) { deleter(v.m_handle); };
auto guard = sr::unique_resource{ConditialThrowOnCopyMock{3, false}, d};
guard.reset(ConditialThrowOnCopyMock{7, true});
}
TEST_CASE("release disables deleter", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3)).TIMES(0);
auto guard = sr::unique_resource{Handle{3}, deleter};
guard.release();
}
TEST_CASE("get returns resource", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
auto guard = sr::unique_resource{Handle{3}, deleter};
CHECK(guard.get() == 3);
}
TEST_CASE("pointer access returns resource" "[UniqueResource]")
{
const auto p = std::make_pair(3, 4);
auto guard = sr::unique_resource{&p, [](auto*) { }};
REQUIRE(guard->first == 3);
REQUIRE(guard->second == 4);
}
TEST_CASE("pointer dereference returns resource" "[UniqueResource]")
{
Handle h{5};
auto guard = sr::unique_resource{PtrHandle{&h}, [](auto*) { }};
REQUIRE(*guard == 5);
}
TEST_CASE("deleter access", "[UniqueResource]")
{
auto guard = sr::unique_resource{Handle{3}, deleter};
guard.release();
{
REQUIRE_CALL(m, deleter(8));
guard.get_deleter()(8);
}
}
TEST_CASE("swap", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(7));
auto guard1 = sr::unique_resource(Handle{3}, deleter);
{
REQUIRE_CALL(m, deleter(3));
auto guard2 = sr::unique_resource{Handle{7}, deleter};
guard2.swap(guard1);
REQUIRE(guard1.get() == 7);
REQUIRE(guard2.get() == 3);
}
}
TEST_CASE("make unique resource", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(7));
auto guard = sr::unique_resource{Handle{7}, deleter};
static_cast<void>(guard);
}
TEST_CASE("make unique resource with reference wrapper", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(3));
Handle h{3};
auto guard = sr::unique_resource{std::ref(h), deleter};
static_cast<void>(guard);
}
TEST_CASE("make unique resource checked", "[UniqueResource]")
{
REQUIRE_CALL(m, deleter(4));
auto guard = sr::make_unique_resource_checked(Handle{4}, Handle{-1}, deleter);
static_cast<void>(guard);
}
TEST_CASE("make unique resource checked releases if invalid", "[UniqueResource]")
{
auto guard = sr::make_unique_resource_checked(Handle{-1}, Handle{-1}, deleter);
static_cast<void>(guard);
}
<|endoftext|>
|
<commit_before>#include "Halide.h"
#include <stdio.h>
using namespace Halide;
using namespace Halide::Internal;
using std::string;
// Count the number of stores to a given func, and the number of calls to sin
class Counter : public IRVisitor {
string func;
using IRVisitor::visit;
void visit(const Store *op) {
IRVisitor::visit(op);
if (op->name == func) {
store_count++;
}
}
void visit(const Call *op) {
IRVisitor::visit(op);
if (op->name == "sin_f32") {
sin_count++;
}
}
public:
int store_count, sin_count;
Counter(string f) : func(f), store_count(0), sin_count(0) {}
};
// Check that the number of calls to sin is correct.
class CheckSinCount : public IRMutator {
int correct;
public:
using IRMutator::mutate;
Stmt mutate(Stmt s) {
Counter c("");
s.accept(&c);
if (c.sin_count != correct) {
printf("There were %d sin calls instead of %d\n", c.sin_count, correct);
exit(-1);
}
return s;
}
CheckSinCount(int c) : correct(c) {}
};
// Check that the number of stores to a given func is correct
class CheckStoreCount : public IRMutator {
string func;
int correct;
public:
using IRMutator::mutate;
Stmt mutate(Stmt s) {
Counter c(func);
s.accept(&c);
if (c.store_count != correct) {
printf("There were %d stores to %s instead of %d\n", c.store_count, func.c_str(), correct);
exit(-1);
}
return s;
}
CheckStoreCount(string f, int c) : func(f), correct(c) {}
};
void count_partitions(Func g, int correct) {
g.add_custom_lowering_pass(new CheckStoreCount(g.name(), correct));
g.compile_jit();
}
void count_sin_calls(Func g, int correct) {
g.add_custom_lowering_pass(new CheckSinCount(correct));
g.compile_jit();
}
int main(int argc, char **argv) {
Func f;
Var x;
f(x) = x;
f.compute_root();
// Halide will partition a loop into three pieces in a few
// situations. The pieces are 1) a messy prologue, 2) a clean
// steady state, and 3) a messy epilogue. One way to trigger this
// is if you use a boundary condition helper:
{
Func g = BoundaryConditions::repeat_edge(f, 0, 100);
count_partitions(g, 3);
}
// If you vectorize or otherwise split, then the last vector
// (which gets shifted leftwards) is its own partition. This
// removes some clamping logic from the inner loop.
{
Func g;
g(x) = f(x);
g.vectorize(x, 8);
count_partitions(g, 2);
}
// The slicing only applies to a single loop level - the
// innermost one where it can be applied. So adding a boundary
// condition to a 2D computation will produce 3 code paths, not 9.
{
Var y;
Func g;
g(x, y) = x + y;
g.compute_root();
Func h = BoundaryConditions::mirror_image(g, 0, 10, 0, 10);
count_partitions(h, 3);
}
// If you split and also have a boundary condition, or have
// multiple boundary conditions at play (e.g. because you're
// blurring an inlined Func that uses a boundary condition), then
// there are still only three partitions. The steady state is the
// slice of the loop where *all* of the boundary conditions and
// splitting logic simplify away.
{
Func g = BoundaryConditions::mirror_interior(f, 0, 10);
Func h;
Param<int> t1, t2;
h(x) = g(x-1) + g(x+1);
h.vectorize(x, 8);
count_partitions(h, 3);
}
// You can manually control the splitting behavior using the
// 'likely' intrinsic. When used on one side of a select, min,
// max, or clamp, it tags the select, min, max, or clamp as likely
// to simplify to that expression in the steady state case, and
// tries to solve for loop variable values for which this is true.
{
// So this code should produce a prologue that evaluates to sin(x), and
// a steady state that evaluates to 1:
Func g;
g(x) = select(x < 10, sin(x), likely(1.0f));
// There should be two partitions
count_partitions(g, 2);
// But only one should call sin
count_sin_calls(g, 1);
}
{
// This code should produce a prologue and epilogue that
// evaluate sin(x), and a steady state that evaluates to 1:
Func g;
g(x) = select(x < 10 || x > 100, sin(x), likely(1.0f));
// There should be three partitions
count_partitions(g, 3);
// With calls to sin in the prologue and epilogue.
count_sin_calls(g, 2);
}
{
// The max here should simplify to 10 in the steady state,
// which means the select evaluates to 1.0f
Func g;
g(x) = select(min(x, likely(10)) > 0, 1.0f, sin(x));
// There should be two partitions
count_partitions(g, 2);
// With a call to sin in the steady-state
count_sin_calls(g, 1);
}
// As a specialize case, we treat clamped ramps as likely to
// simplify to the clamped expression. This handles the many
// existing cases where people have written their boundary
// condition manually using clamp.
{
Func g;
g(x) = f(clamp(x, 0, 10)); // treated as clamp(likely(x), 0, 10)
g.vectorize(x, 8);
count_partitions(g, 3);
}
// Using the likely intrinsic pulls some IR relating to the
// condition outside of the loop. We'd better check that this
// respects lets and doesn't do any combinatorial expansion. We'll
// do this with a nasty comparison:
{
Func g;
Var y;
// Make some nasty expressions to compare to.
Expr e[10];
e[0] = y;
for (int i = 1; i < 6; i++) {
e[i] = e[i-1] * e[i-1] + y;
}
// Make a nasty condition that uses all of these.
Expr nasty = cast<bool>(1);
for (int i = 0; i < 6; i++) {
nasty = nasty && (x*(i+1) < e[i]);
}
// Have an innermost loop over c to complicate things.
Var c;
g(c, x, y) = select(nasty, likely(10), c);
// Check that it doesn't take the age of the world to compile,
// and that it produces the right number of partitions.
count_partitions(g, 2);
// Note: The loops above would be larger, but the above code
// sails through Halide then triggers exponential behavior
// inside of LLVM :(
}
// The performance of this behavior is tested in
// test/performance/boundary_conditions.cpp
printf("Success!\n");
return 0;
}
<commit_msg>Remove dubiously-constructed likely case that simplifies away<commit_after>#include "Halide.h"
#include <stdio.h>
using namespace Halide;
using namespace Halide::Internal;
using std::string;
// Count the number of stores to a given func, and the number of calls to sin
class Counter : public IRVisitor {
string func;
using IRVisitor::visit;
void visit(const Store *op) {
IRVisitor::visit(op);
if (op->name == func) {
store_count++;
}
}
void visit(const Call *op) {
IRVisitor::visit(op);
if (op->name == "sin_f32") {
sin_count++;
}
}
public:
int store_count, sin_count;
Counter(string f) : func(f), store_count(0), sin_count(0) {}
};
// Check that the number of calls to sin is correct.
class CheckSinCount : public IRMutator {
int correct;
public:
using IRMutator::mutate;
Stmt mutate(Stmt s) {
Counter c("");
s.accept(&c);
if (c.sin_count != correct) {
printf("There were %d sin calls instead of %d\n", c.sin_count, correct);
exit(-1);
}
return s;
}
CheckSinCount(int c) : correct(c) {}
};
// Check that the number of stores to a given func is correct
class CheckStoreCount : public IRMutator {
string func;
int correct;
public:
using IRMutator::mutate;
Stmt mutate(Stmt s) {
Counter c(func);
s.accept(&c);
if (c.store_count != correct) {
printf("There were %d stores to %s instead of %d\n", c.store_count, func.c_str(), correct);
exit(-1);
}
return s;
}
CheckStoreCount(string f, int c) : func(f), correct(c) {}
};
void count_partitions(Func g, int correct) {
g.add_custom_lowering_pass(new CheckStoreCount(g.name(), correct));
g.compile_jit();
}
void count_sin_calls(Func g, int correct) {
g.add_custom_lowering_pass(new CheckSinCount(correct));
g.compile_jit();
}
int main(int argc, char **argv) {
Func f;
Var x;
f(x) = x;
f.compute_root();
// Halide will partition a loop into three pieces in a few
// situations. The pieces are 1) a messy prologue, 2) a clean
// steady state, and 3) a messy epilogue. One way to trigger this
// is if you use a boundary condition helper:
{
Func g = BoundaryConditions::repeat_edge(f, 0, 100);
count_partitions(g, 3);
}
// If you vectorize or otherwise split, then the last vector
// (which gets shifted leftwards) is its own partition. This
// removes some clamping logic from the inner loop.
{
Func g;
g(x) = f(x);
g.vectorize(x, 8);
count_partitions(g, 2);
}
// The slicing only applies to a single loop level - the
// innermost one where it can be applied. So adding a boundary
// condition to a 2D computation will produce 3 code paths, not 9.
{
Var y;
Func g;
g(x, y) = x + y;
g.compute_root();
Func h = BoundaryConditions::mirror_image(g, 0, 10, 0, 10);
count_partitions(h, 3);
}
// If you split and also have a boundary condition, or have
// multiple boundary conditions at play (e.g. because you're
// blurring an inlined Func that uses a boundary condition), then
// there are still only three partitions. The steady state is the
// slice of the loop where *all* of the boundary conditions and
// splitting logic simplify away.
{
Func g = BoundaryConditions::mirror_interior(f, 0, 10);
Func h;
Param<int> t1, t2;
h(x) = g(x-1) + g(x+1);
h.vectorize(x, 8);
count_partitions(h, 3);
}
// You can manually control the splitting behavior using the
// 'likely' intrinsic. When used on one side of a select, min,
// max, or clamp, it tags the select, min, max, or clamp as likely
// to simplify to that expression in the steady state case, and
// tries to solve for loop variable values for which this is true.
{
// So this code should produce a prologue that evaluates to sin(x), and
// a steady state that evaluates to 1:
Func g;
g(x) = select(x < 10, sin(x), likely(1.0f));
// There should be two partitions
count_partitions(g, 2);
// But only one should call sin
count_sin_calls(g, 1);
}
{
// This code should produce a prologue and epilogue that
// evaluate sin(x), and a steady state that evaluates to 1:
Func g;
g(x) = select(x < 10 || x > 100, sin(x), likely(1.0f));
// There should be three partitions
count_partitions(g, 3);
// With calls to sin in the prologue and epilogue.
count_sin_calls(g, 2);
}
// As a specialize case, we treat clamped ramps as likely to
// simplify to the clamped expression. This handles the many
// existing cases where people have written their boundary
// condition manually using clamp.
{
Func g;
g(x) = f(clamp(x, 0, 10)); // treated as clamp(likely(x), 0, 10)
g.vectorize(x, 8);
count_partitions(g, 3);
}
// Using the likely intrinsic pulls some IR relating to the
// condition outside of the loop. We'd better check that this
// respects lets and doesn't do any combinatorial expansion. We'll
// do this with a nasty comparison:
{
Func g;
Var y;
// Make some nasty expressions to compare to.
Expr e[10];
e[0] = y;
for (int i = 1; i < 6; i++) {
e[i] = e[i-1] * e[i-1] + y;
}
// Make a nasty condition that uses all of these.
Expr nasty = cast<bool>(1);
for (int i = 0; i < 6; i++) {
nasty = nasty && (x*(i+1) < e[i]);
}
// Have an innermost loop over c to complicate things.
Var c;
g(c, x, y) = select(nasty, likely(10), c);
// Check that it doesn't take the age of the world to compile,
// and that it produces the right number of partitions.
count_partitions(g, 2);
// Note: The loops above would be larger, but the above code
// sails through Halide then triggers exponential behavior
// inside of LLVM :(
}
// The performance of this behavior is tested in
// test/performance/boundary_conditions.cpp
printf("Success!\n");
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include "path.hpp"
struct stat;
namespace spn {
using ToPathStr = To8Str;
using PathCh = char;
using PathStr = std::basic_string<PathCh>;
using EnumCBD = std::function<void (const PathCh*, bool)>;
struct Dir_depLinux {
static std::string Getcwd();
static void Chdir(ToPathStr path);
static bool Chdir_nt(ToPathStr path);
static void Mkdir(ToPathStr path, uint32_t mode);
static void Chmod(ToPathStr path, uint32_t mode);
static void Rmdir(ToPathStr path);
static void Remove(ToPathStr path);
static void Move(ToPathStr from, ToPathStr to);
static void Copy(ToPathStr from, ToPathStr to);
static void EnumEntry(ToPathStr path, EnumCBD cb);
static FStatus Status(ToPathStr path);
static FTime Filetime(ToPathStr path);
static bool IsFile(ToPathStr path);
static bool IsDirectory(ToPathStr path);
static FStatus CreateFStatus(const struct stat& st);
//! ファイルフラグ変換 (spinner -> linux)
static uint32_t ConvertFlag_S2L(uint32_t flag);
//! ファイルフラグ変換 (linux -> spinner)
static uint32_t ConvertFlag_L2S(uint32_t flag);
static PathStr GetCurrentDir();
static void SetCurrentDir(const PathStr& path);
};
using DirDep = Dir_depLinux;
}
<commit_msg>dir_depLinux: XlibのヘッダのStatusマクロ定義に依る不具合の対処<commit_after>#pragma once
#include "path.hpp"
#ifdef Status
#undef Status
#endif
struct stat;
namespace spn {
using ToPathStr = To8Str;
using PathCh = char;
using PathStr = std::basic_string<PathCh>;
using EnumCBD = std::function<void (const PathCh*, bool)>;
struct Dir_depLinux {
static std::string Getcwd();
static void Chdir(ToPathStr path);
static bool Chdir_nt(ToPathStr path);
static void Mkdir(ToPathStr path, uint32_t mode);
static void Chmod(ToPathStr path, uint32_t mode);
static void Rmdir(ToPathStr path);
static void Remove(ToPathStr path);
static void Move(ToPathStr from, ToPathStr to);
static void Copy(ToPathStr from, ToPathStr to);
static void EnumEntry(ToPathStr path, EnumCBD cb);
static FStatus Status(ToPathStr path);
static FTime Filetime(ToPathStr path);
static bool IsFile(ToPathStr path);
static bool IsDirectory(ToPathStr path);
static FStatus CreateFStatus(const struct stat& st);
//! ファイルフラグ変換 (spinner -> linux)
static uint32_t ConvertFlag_S2L(uint32_t flag);
//! ファイルフラグ変換 (linux -> spinner)
static uint32_t ConvertFlag_L2S(uint32_t flag);
static PathStr GetCurrentDir();
static void SetCurrentDir(const PathStr& path);
};
using DirDep = Dir_depLinux;
}
<|endoftext|>
|
<commit_before>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __itkMissingStructurePenalty_hxx
#define __itkMissingStructurePenalty_hxx
#include "itkMissingStructurePenalty.h"
namespace itk
{
/**
* ******************* Constructor *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::MissingVolumeMeshPenalty()
{
this->m_MappedMeshContainer = MappedMeshContainerType::New();
} // end Constructor
/**
* ******************* Destructor *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::~MissingVolumeMeshPenalty()
{} // end Destructor
/**
* *********************** Initialize *****************************
*/
template< class TFixedPointSet, class TMovingPointSet >
void
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::Initialize( void ) throw ( ExceptionObject )
{
/** Call the initialize of the superclass. */
//this->Superclass::Initialize();
if( !this->m_Transform )
{
itkExceptionMacro( << "Transform is not present" );
}
if( !this->m_FixedMeshContainer )
{
itkExceptionMacro( << "FixedMeshContainer is not present" );
}
const FixedMeshContainerElementIdentifier numberOfMeshes = this->m_FixedMeshContainer->Size();
this->m_MappedMeshContainer->Reserve( numberOfMeshes );
for( FixedMeshContainerElementIdentifier meshId = 0; meshId < numberOfMeshes; ++meshId )
{
FixedMeshConstPointer fixedMesh = this->m_FixedMeshContainer->ElementAt( meshId );
MeshPointsContainerConstPointer fixedPoints = fixedMesh->GetPoints();
const unsigned int numberOfPoints = fixedPoints->Size();
typename MeshPointsContainerType::Pointer mappedPoints = MeshPointsContainerType::New();
mappedPoints->Reserve( numberOfPoints );
typename FixedMeshType::Pointer mappedMesh = FixedMeshType::New();
mappedMesh->SetPoints( mappedPoints );
// mappedMesh was constructed with a Cellscontainer and CellDatacontainer of size 0.
// We use a null pointer to set them to undefined, which is also the default behavior of the MeshReader.
// "Write result mesh" checks the null pointer and writes a mesh with the remaining data filled in from the fixed mesh.
mappedMesh->SetPointData( NULL );
mappedMesh->SetCells( NULL );
mappedMesh->SetCellData( NULL );
this->m_MappedMeshContainer->SetElement( meshId, mappedMesh );
}
} // end Initialize()
/**
* ******************* GetValue *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
typename MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >::MeasureType
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::GetValue( const TransformParametersType & parameters ) const
{
/** Sanity checks. */
FixedMeshContainerConstPointer fixedMeshContainer = this->GetFixedMeshContainer();
if( !fixedMeshContainer )
{
itkExceptionMacro( << "FixedMeshContainer mesh has not been assigned" );
}
/** Initialize some variables */
MeasureType value = NumericTraits< MeasureType >::Zero;
//OutputPointType fixedPoint;
/** Get the current corresponding points. */
/** Make sure the transform parameters are up to date. */
this->SetTransformParameters( parameters );
DerivativeType dummyDerivative;
this->GetValueAndDerivative( parameters, value, dummyDerivative );
return value;
} // end GetValue()
/**
* ******************* GetDerivative *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
void
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::GetDerivative( const TransformParametersType & parameters,
DerivativeType & derivative ) const
{
/** When the derivative is calculated, all information for calculating
* the metric value is available. It does not cost anything to calculate
* the metric value now. Therefore, we have chosen to only implement the
* GetValueAndDerivative(), supplying it with a dummy value variable.
*/
MeasureType dummyvalue = NumericTraits< MeasureType >::Zero;
this->GetValueAndDerivative( parameters, dummyvalue, derivative );
} // end GetDerivative()
/**
* ******************* GetValueAndDerivative *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
void
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::GetValueAndDerivative( const TransformParametersType & parameters,
MeasureType & value, DerivativeType & derivative ) const
{
/** Sanity checks. */
FixedMeshContainerConstPointer fixedMeshContainer = this->GetFixedMeshContainer();
if( !fixedMeshContainer )
{
itkExceptionMacro( << "FixedMeshContainer mesh has not been assigned" );
}
/** Initialize some variables */
value = NumericTraits< MeasureType >::Zero;
/** Make sure the transform parameters are up to date. */
this->SetTransformParameters( parameters );
derivative = DerivativeType( this->GetNumberOfParameters() );
derivative.Fill( NumericTraits< DerivativeValueType >::Zero );
NonZeroJacobianIndicesType nzji( this->m_Transform->GetNumberOfNonZeroJacobianIndices() );
TransformJacobianType jacobian;
const FixedMeshContainerElementIdentifier numberOfMeshes = this->m_FixedMeshContainer->Size();
typedef typename FixedMeshType::PointType FixedMeshPointType;
FixedMeshPointType zeroPoint = typename FixedMeshPointType::Point();
zeroPoint.Fill( 0.0 );
typename MeshPointsContainerType::Pointer pointCentroids = FixedMeshType::PointsContainer::New();
pointCentroids->resize( numberOfMeshes, typename FixedMeshPointType::Point( zeroPoint ) );
for( FixedMeshContainerElementIdentifier meshId = 0; meshId < numberOfMeshes; ++meshId ) // loop over all meshes in container
{
const FixedMeshConstPointer fixedMesh = fixedMeshContainer->ElementAt( meshId );
const MeshPointsContainerConstPointer fixedPoints = fixedMesh->GetPoints();
const unsigned int numberOfPoints = fixedPoints->Size();
const FixedMeshPointer mappedMesh = this->m_MappedMeshContainer->ElementAt( meshId );
const MeshPointsContainerPointer mappedPoints = mappedMesh->GetPoints();
typename FixedMeshType::PointType & pointCentroid = pointCentroids->ElementAt( meshId );
typedef typename FixedMeshType::PointsContainer FixedMeshPointsContainerType;
typename FixedMeshType::PointsContainer::Pointer derivPoints = FixedMeshPointsContainerType::New();
derivPoints->resize( numberOfPoints, typename FixedMeshPointType::Point( zeroPoint ) );
MeshPointsContainerConstIteratorType fixedPointIt = fixedPoints->Begin();
MeshPointsContainerIteratorType mappedPointIt = mappedPoints->Begin();
MeshPointsContainerConstIteratorType fixedPointEnd = fixedPoints->End();
for( ; fixedPointIt != fixedPointEnd; ++fixedPointIt, ++mappedPointIt )
{
const OutputPointType mappedPoint = this->m_Transform->TransformPoint( fixedPointIt->Value() );
mappedPointIt.Value() = mappedPoint;
pointCentroid.GetVnlVector() += mappedPoint.GetVnlVector();
}
pointCentroid.GetVnlVector() /= numberOfPoints;
typename FixedMeshType::CellsContainerConstIterator cellBegin = fixedMesh->GetCells()->Begin();
typename FixedMeshType::CellsContainerConstIterator cellEnd = fixedMesh->GetCells()->End();
typename CellInterfaceType::PointIdIterator beginpointer;
float sumSignedVolume = 0.0;
float sumAbsVolume = 0.0;
const int eps = 0.00001;
for( ; cellBegin != cellEnd; ++cellBegin )
{
beginpointer = cellBegin->Value()->PointIdsBegin();
float signedVolume; // = vnl_determinant(fullMatrix.GetVnlMatrix());
//const VectorType::const_pointer p1,p2,p3,p4;
switch( FixedPointSetDimension )
{
case 2:
{
const FixedMeshPointIdentifier p1Id = *beginpointer;
++beginpointer;
const VectorType p1 = mappedPoints->GetElement( p1Id ) - pointCentroid;
const FixedMeshPointIdentifier p2Id = *beginpointer;
++beginpointer;
const VectorType p2 = mappedPoints->GetElement( p2Id ) - pointCentroid;
signedVolume = vnl_determinant( p1.GetDataPointer(), p2.GetDataPointer() );
const int sign = ( signedVolume > eps ) - ( signedVolume < -eps );
if( sign != 0 )
{
derivPoints->at( p1Id )[ 0 ] += sign * p2[ 1 ];
derivPoints->at( p1Id )[ 1 ] -= sign * p2[ 0 ];
derivPoints->at( p2Id )[ 0 ] -= sign * p1[ 1 ];
derivPoints->at( p2Id )[ 1 ] += sign * p1[ 0 ];
}
}
break;
case 3:
{
const FixedMeshPointIdentifier p1Id = *beginpointer;
++beginpointer;
const VectorType p1 = mappedPoints->GetElement( p1Id ) - pointCentroid;
const FixedMeshPointIdentifier p2Id = *beginpointer;
++beginpointer;
const VectorType p2 = mappedPoints->GetElement( p2Id ) - pointCentroid;
const FixedMeshPointIdentifier p3Id = *beginpointer;
++beginpointer;
const VectorType p3 = mappedPoints->GetElement( p3Id ) - pointCentroid;
signedVolume = vnl_determinant( p1.GetDataPointer(), p2.GetDataPointer(), p3.GetDataPointer() );
const int sign = ( ( signedVolume > eps ) - ( signedVolume < -eps ) );
if( sign != 0 )
{
derivPoints->at( p1Id )[ 0 ] += sign * ( p2[ 1 ] * p3[ 2 ] - p2[ 2 ] * p3[ 1 ] );
derivPoints->at( p1Id )[ 1 ] += sign * ( p2[ 2 ] * p3[ 0 ] - p2[ 0 ] * p3[ 2 ] );
derivPoints->at( p1Id )[ 2 ] += sign * ( p2[ 0 ] * p3[ 1 ] - p2[ 1 ] * p3[ 0 ] );
derivPoints->at( p2Id )[ 0 ] += sign * ( p1[ 2 ] * p3[ 1 ] - p1[ 1 ] * p3[ 2 ] );
derivPoints->at( p2Id )[ 1 ] += sign * ( p1[ 0 ] * p3[ 2 ] - p1[ 2 ] * p3[ 0 ] );
derivPoints->at( p2Id )[ 2 ] += sign * ( p1[ 1 ] * p3[ 0 ] - p1[ 0 ] * p3[ 1 ] );
derivPoints->at( p3Id )[ 0 ] += sign * ( p1[ 1 ] * p2[ 2 ] - p1[ 2 ] * p2[ 1 ] );
derivPoints->at( p3Id )[ 1 ] += sign * ( p1[ 2 ] * p2[ 0 ] - p1[ 0 ] * p2[ 2 ] );
derivPoints->at( p3Id )[ 2 ] += sign * ( p1[ 0 ] * p2[ 1 ] - p1[ 1 ] * p2[ 0 ] );
}
}
break;
case 4:
{
const VectorConstPointer p1 = mappedPoints->GetElement( *beginpointer++ ).GetDataPointer();
const VectorConstPointer p2 = mappedPoints->GetElement( *beginpointer++ ).GetDataPointer();
const VectorConstPointer p3 = mappedPoints->GetElement( *beginpointer++ ).GetDataPointer();
const VectorConstPointer p4 = mappedPoints->GetElement( *beginpointer++ ).GetDataPointer();
signedVolume = vnl_determinant( p1, p2, p3, p4 );
}
break;
default:
std::cout << "no dimensions higher than 4" << std::endl;
}
sumSignedVolume += signedVolume;
sumAbsVolume += abs( signedVolume );
}
/** Create iterators. */
fixedPointIt = fixedPoints->Begin();
unsigned int pointIndex;
/** Loop over points. */
for( pointIndex = 0; fixedPointIt != fixedPointEnd; ++fixedPointIt, ++pointIndex )
{
/** Get the TransformJacobian dT/dmu. */
this->m_Transform->GetJacobian( fixedPointIt.Value(), jacobian, nzji );
if( nzji.size() == this->GetNumberOfParameters() )
{
/** Loop over all Jacobians. */
derivative += derivPoints->at( pointIndex ).GetVnlVector() * jacobian; //* sumAbsVolumeEps;
}
else
{
/** Only pick the nonzero Jacobians. */
for( unsigned int i = 0; i < nzji.size(); ++i )
{
const unsigned int index = nzji[ i ];
VnlVectorType column = jacobian.get_column( i );
derivative[ index ] += dot_product( derivPoints->at( pointIndex ).GetVnlVector(), column ); // *sumAbsVolumeEps;
}
}
} // end loop over all corresponding points
/** Check if enough samples were valid. */
/** Copy the measure to value. */
value += sumAbsVolume;
} // end loop over all meshes in container
} // end GetValueAndDerivative()
/**
* ******************* SubVector *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
void
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::SubVector( const VectorType & fullVector, SubVectorType & subVector, const unsigned int leaveOutIndex ) const
{
//SubVectorType subVector = SubVectorType::Vector();
typename VectorType::ConstIterator fullVectorIt = fullVector.Begin();
typename VectorType::ConstIterator fullVectorEnd = fullVector.End();
typename SubVectorType::Iterator subVectorIt = subVector.Begin();
typename SubVectorType::ConstIterator subVectorEnd = subVector.End();
unsigned int fullIndex = 0;
for( ; subVectorIt != subVectorEnd; ++fullVectorIt, ++subVectorIt, ++fullIndex )
{
if( fullIndex == leaveOutIndex )
{
++fullVectorIt;
}
*subVectorIt = *fullVectorIt;
}
} // end SubVector()
} // end itk namespace
#endif // end #ifndef __itkMissingStructurePenalty_hxx
<commit_msg>BUG: int should be float<commit_after>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __itkMissingStructurePenalty_hxx
#define __itkMissingStructurePenalty_hxx
#include "itkMissingStructurePenalty.h"
namespace itk
{
/**
* ******************* Constructor *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::MissingVolumeMeshPenalty()
{
this->m_MappedMeshContainer = MappedMeshContainerType::New();
} // end Constructor
/**
* ******************* Destructor *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::~MissingVolumeMeshPenalty()
{} // end Destructor
/**
* *********************** Initialize *****************************
*/
template< class TFixedPointSet, class TMovingPointSet >
void
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::Initialize( void ) throw ( ExceptionObject )
{
/** Call the initialize of the superclass. */
//this->Superclass::Initialize();
if( !this->m_Transform )
{
itkExceptionMacro( << "Transform is not present" );
}
if( !this->m_FixedMeshContainer )
{
itkExceptionMacro( << "FixedMeshContainer is not present" );
}
const FixedMeshContainerElementIdentifier numberOfMeshes = this->m_FixedMeshContainer->Size();
this->m_MappedMeshContainer->Reserve( numberOfMeshes );
for( FixedMeshContainerElementIdentifier meshId = 0; meshId < numberOfMeshes; ++meshId )
{
FixedMeshConstPointer fixedMesh = this->m_FixedMeshContainer->ElementAt( meshId );
MeshPointsContainerConstPointer fixedPoints = fixedMesh->GetPoints();
const unsigned int numberOfPoints = fixedPoints->Size();
typename MeshPointsContainerType::Pointer mappedPoints = MeshPointsContainerType::New();
mappedPoints->Reserve( numberOfPoints );
typename FixedMeshType::Pointer mappedMesh = FixedMeshType::New();
mappedMesh->SetPoints( mappedPoints );
// mappedMesh was constructed with a Cellscontainer and CellDatacontainer of size 0.
// We use a null pointer to set them to undefined, which is also the default behavior of the MeshReader.
// "Write result mesh" checks the null pointer and writes a mesh with the remaining data filled in from the fixed mesh.
mappedMesh->SetPointData( NULL );
mappedMesh->SetCells( NULL );
mappedMesh->SetCellData( NULL );
this->m_MappedMeshContainer->SetElement( meshId, mappedMesh );
}
} // end Initialize()
/**
* ******************* GetValue *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
typename MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >::MeasureType
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::GetValue( const TransformParametersType & parameters ) const
{
/** Sanity checks. */
FixedMeshContainerConstPointer fixedMeshContainer = this->GetFixedMeshContainer();
if( !fixedMeshContainer )
{
itkExceptionMacro( << "FixedMeshContainer mesh has not been assigned" );
}
/** Initialize some variables */
MeasureType value = NumericTraits< MeasureType >::Zero;
//OutputPointType fixedPoint;
/** Get the current corresponding points. */
/** Make sure the transform parameters are up to date. */
this->SetTransformParameters( parameters );
DerivativeType dummyDerivative;
this->GetValueAndDerivative( parameters, value, dummyDerivative );
return value;
} // end GetValue()
/**
* ******************* GetDerivative *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
void
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::GetDerivative( const TransformParametersType & parameters,
DerivativeType & derivative ) const
{
/** When the derivative is calculated, all information for calculating
* the metric value is available. It does not cost anything to calculate
* the metric value now. Therefore, we have chosen to only implement the
* GetValueAndDerivative(), supplying it with a dummy value variable.
*/
MeasureType dummyvalue = NumericTraits< MeasureType >::Zero;
this->GetValueAndDerivative( parameters, dummyvalue, derivative );
} // end GetDerivative()
/**
* ******************* GetValueAndDerivative *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
void
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::GetValueAndDerivative( const TransformParametersType & parameters,
MeasureType & value, DerivativeType & derivative ) const
{
/** Sanity checks. */
FixedMeshContainerConstPointer fixedMeshContainer = this->GetFixedMeshContainer();
if( !fixedMeshContainer )
{
itkExceptionMacro( << "FixedMeshContainer mesh has not been assigned" );
}
/** Initialize some variables */
value = NumericTraits< MeasureType >::Zero;
/** Make sure the transform parameters are up to date. */
this->SetTransformParameters( parameters );
derivative = DerivativeType( this->GetNumberOfParameters() );
derivative.Fill( NumericTraits< DerivativeValueType >::Zero );
NonZeroJacobianIndicesType nzji( this->m_Transform->GetNumberOfNonZeroJacobianIndices() );
TransformJacobianType jacobian;
const FixedMeshContainerElementIdentifier numberOfMeshes = this->m_FixedMeshContainer->Size();
typedef typename FixedMeshType::PointType FixedMeshPointType;
FixedMeshPointType zeroPoint = typename FixedMeshPointType::Point();
zeroPoint.Fill( 0.0 );
typename MeshPointsContainerType::Pointer pointCentroids = FixedMeshType::PointsContainer::New();
pointCentroids->resize( numberOfMeshes, typename FixedMeshPointType::Point( zeroPoint ) );
for( FixedMeshContainerElementIdentifier meshId = 0; meshId < numberOfMeshes; ++meshId ) // loop over all meshes in container
{
const FixedMeshConstPointer fixedMesh = fixedMeshContainer->ElementAt( meshId );
const MeshPointsContainerConstPointer fixedPoints = fixedMesh->GetPoints();
const unsigned int numberOfPoints = fixedPoints->Size();
const FixedMeshPointer mappedMesh = this->m_MappedMeshContainer->ElementAt( meshId );
const MeshPointsContainerPointer mappedPoints = mappedMesh->GetPoints();
typename FixedMeshType::PointType & pointCentroid = pointCentroids->ElementAt( meshId );
typedef typename FixedMeshType::PointsContainer FixedMeshPointsContainerType;
typename FixedMeshType::PointsContainer::Pointer derivPoints = FixedMeshPointsContainerType::New();
derivPoints->resize( numberOfPoints, typename FixedMeshPointType::Point( zeroPoint ) );
MeshPointsContainerConstIteratorType fixedPointIt = fixedPoints->Begin();
MeshPointsContainerIteratorType mappedPointIt = mappedPoints->Begin();
MeshPointsContainerConstIteratorType fixedPointEnd = fixedPoints->End();
for( ; fixedPointIt != fixedPointEnd; ++fixedPointIt, ++mappedPointIt )
{
const OutputPointType mappedPoint = this->m_Transform->TransformPoint( fixedPointIt->Value() );
mappedPointIt.Value() = mappedPoint;
pointCentroid.GetVnlVector() += mappedPoint.GetVnlVector();
}
pointCentroid.GetVnlVector() /= numberOfPoints;
typename FixedMeshType::CellsContainerConstIterator cellBegin = fixedMesh->GetCells()->Begin();
typename FixedMeshType::CellsContainerConstIterator cellEnd = fixedMesh->GetCells()->End();
typename CellInterfaceType::PointIdIterator beginpointer;
float sumSignedVolume = 0.0;
float sumAbsVolume = 0.0;
const float eps = 0.00001;
for( ; cellBegin != cellEnd; ++cellBegin )
{
beginpointer = cellBegin->Value()->PointIdsBegin();
float signedVolume; // = vnl_determinant(fullMatrix.GetVnlMatrix());
//const VectorType::const_pointer p1,p2,p3,p4;
switch( FixedPointSetDimension )
{
case 2:
{
const FixedMeshPointIdentifier p1Id = *beginpointer;
++beginpointer;
const VectorType p1 = mappedPoints->GetElement( p1Id ) - pointCentroid;
const FixedMeshPointIdentifier p2Id = *beginpointer;
++beginpointer;
const VectorType p2 = mappedPoints->GetElement( p2Id ) - pointCentroid;
signedVolume = vnl_determinant( p1.GetDataPointer(), p2.GetDataPointer() );
const int sign = ( signedVolume > eps ) - ( signedVolume < -eps );
if( sign != 0 )
{
derivPoints->at( p1Id )[ 0 ] += sign * p2[ 1 ];
derivPoints->at( p1Id )[ 1 ] -= sign * p2[ 0 ];
derivPoints->at( p2Id )[ 0 ] -= sign * p1[ 1 ];
derivPoints->at( p2Id )[ 1 ] += sign * p1[ 0 ];
}
}
break;
case 3:
{
const FixedMeshPointIdentifier p1Id = *beginpointer;
++beginpointer;
const VectorType p1 = mappedPoints->GetElement( p1Id ) - pointCentroid;
const FixedMeshPointIdentifier p2Id = *beginpointer;
++beginpointer;
const VectorType p2 = mappedPoints->GetElement( p2Id ) - pointCentroid;
const FixedMeshPointIdentifier p3Id = *beginpointer;
++beginpointer;
const VectorType p3 = mappedPoints->GetElement( p3Id ) - pointCentroid;
signedVolume = vnl_determinant( p1.GetDataPointer(), p2.GetDataPointer(), p3.GetDataPointer() );
const int sign = ( ( signedVolume > eps ) - ( signedVolume < -eps ) );
if( sign != 0 )
{
derivPoints->at( p1Id )[ 0 ] += sign * ( p2[ 1 ] * p3[ 2 ] - p2[ 2 ] * p3[ 1 ] );
derivPoints->at( p1Id )[ 1 ] += sign * ( p2[ 2 ] * p3[ 0 ] - p2[ 0 ] * p3[ 2 ] );
derivPoints->at( p1Id )[ 2 ] += sign * ( p2[ 0 ] * p3[ 1 ] - p2[ 1 ] * p3[ 0 ] );
derivPoints->at( p2Id )[ 0 ] += sign * ( p1[ 2 ] * p3[ 1 ] - p1[ 1 ] * p3[ 2 ] );
derivPoints->at( p2Id )[ 1 ] += sign * ( p1[ 0 ] * p3[ 2 ] - p1[ 2 ] * p3[ 0 ] );
derivPoints->at( p2Id )[ 2 ] += sign * ( p1[ 1 ] * p3[ 0 ] - p1[ 0 ] * p3[ 1 ] );
derivPoints->at( p3Id )[ 0 ] += sign * ( p1[ 1 ] * p2[ 2 ] - p1[ 2 ] * p2[ 1 ] );
derivPoints->at( p3Id )[ 1 ] += sign * ( p1[ 2 ] * p2[ 0 ] - p1[ 0 ] * p2[ 2 ] );
derivPoints->at( p3Id )[ 2 ] += sign * ( p1[ 0 ] * p2[ 1 ] - p1[ 1 ] * p2[ 0 ] );
}
}
break;
case 4:
{
const VectorConstPointer p1 = mappedPoints->GetElement( *beginpointer++ ).GetDataPointer();
const VectorConstPointer p2 = mappedPoints->GetElement( *beginpointer++ ).GetDataPointer();
const VectorConstPointer p3 = mappedPoints->GetElement( *beginpointer++ ).GetDataPointer();
const VectorConstPointer p4 = mappedPoints->GetElement( *beginpointer++ ).GetDataPointer();
signedVolume = vnl_determinant( p1, p2, p3, p4 );
}
break;
default:
std::cout << "no dimensions higher than 4" << std::endl;
}
sumSignedVolume += signedVolume;
sumAbsVolume += abs( signedVolume );
}
/** Create iterators. */
fixedPointIt = fixedPoints->Begin();
unsigned int pointIndex;
/** Loop over points. */
for( pointIndex = 0; fixedPointIt != fixedPointEnd; ++fixedPointIt, ++pointIndex )
{
/** Get the TransformJacobian dT/dmu. */
this->m_Transform->GetJacobian( fixedPointIt.Value(), jacobian, nzji );
if( nzji.size() == this->GetNumberOfParameters() )
{
/** Loop over all Jacobians. */
derivative += derivPoints->at( pointIndex ).GetVnlVector() * jacobian; //* sumAbsVolumeEps;
}
else
{
/** Only pick the nonzero Jacobians. */
for( unsigned int i = 0; i < nzji.size(); ++i )
{
const unsigned int index = nzji[ i ];
VnlVectorType column = jacobian.get_column( i );
derivative[ index ] += dot_product( derivPoints->at( pointIndex ).GetVnlVector(), column ); // *sumAbsVolumeEps;
}
}
} // end loop over all corresponding points
/** Check if enough samples were valid. */
/** Copy the measure to value. */
value += sumAbsVolume;
} // end loop over all meshes in container
} // end GetValueAndDerivative()
/**
* ******************* SubVector *******************
*/
template< class TFixedPointSet, class TMovingPointSet >
void
MissingVolumeMeshPenalty< TFixedPointSet, TMovingPointSet >
::SubVector( const VectorType & fullVector, SubVectorType & subVector, const unsigned int leaveOutIndex ) const
{
//SubVectorType subVector = SubVectorType::Vector();
typename VectorType::ConstIterator fullVectorIt = fullVector.Begin();
typename VectorType::ConstIterator fullVectorEnd = fullVector.End();
typename SubVectorType::Iterator subVectorIt = subVector.Begin();
typename SubVectorType::ConstIterator subVectorEnd = subVector.End();
unsigned int fullIndex = 0;
for( ; subVectorIt != subVectorEnd; ++fullVectorIt, ++subVectorIt, ++fullIndex )
{
if( fullIndex == leaveOutIndex )
{
++fullVectorIt;
}
*subVectorIt = *fullVectorIt;
}
} // end SubVector()
} // end itk namespace
#endif // end #ifndef __itkMissingStructurePenalty_hxx
<|endoftext|>
|
<commit_before>/* -*- mode:linux -*- */
/**
* \file grid_world.cc
*
*
*
* \author Ethan Burns
* \date 2008-10-08
*/
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "grid_state.h"
#include "grid_world.h"
using namespace std;
/**
* Create a new GridWorld.
*/
GridWorld::GridWorld(const Heuristic *h, istream &s)
: SearchDomain(h)
{
char line[100];
char c;
s >> height;
s >> width;
obstacles = new bool[width * height];
s >> line;
if(strcmp(line, "Board:") != 0) {
cerr << "Parse error: expected \"Board:\"" << endl;
exit(EXIT_FAILURE);
}
c = s.get(); // new-line
if (c != '\n') {
cerr << endl << "Parse error: [" << c << "], h=" << h << endl;
exit(EXIT_FAILURE);
}
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
c = s.get();
if (c == '#')
obstacles[width * h + w] = true;
else
obstacles[width * h + w] = false;
}
c = s.get(); // new-line
if (c != '\n') {
cerr << endl << "Parse error: [" << c << "], h=" << h << endl;
exit(EXIT_FAILURE);
}
}
// Cost (Unit/Life)
s >> line;
// Movement (Four-way/Eight-way)
s >> line;
s >> start_x;
s >> start_y;
s >> goal_x;
s >> goal_y;
}
/**
* Destructor.
*/
GridWorld::~GridWorld()
{
delete obstacles;
}
/**
* Get the initial state.
*/
State *GridWorld::initial_state(void)
{
return new GridState(this, NULL, 0, start_x, start_y);
}
/**
* Expand a gridstate.
*/
vector<const State*> *GridWorld::expand(const State *state) const
{
const int cost = 1;
const GridState *s;
vector<const State*> *children;
s = dynamic_cast<const GridState*>(state);
children = new vector<const State*>();
if (s->get_x() > 0 && !is_obstacle(s->get_x() + 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() + 1, s->get_y()));
}
if (s->get_x() < height - 1 && !is_obstacle(s->get_x() - 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() - 1, s->get_y()));
}
if (s->get_y() > 0 && !is_obstacle(s->get_x(), s->get_y() + 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() + 1));
}
if (s->get_y() > width - 1 && !is_obstacle(s->get_x(), s->get_y() - 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() - 1));
}
return children;
}
int GridWorld::get_goal_x(void) const
{
return goal_x;
}
int GridWorld::get_goal_y(void) const
{
return goal_y;
}
int GridWorld::get_width(void) const
{
return width;
}
int GridWorld::get_height(void) const
{
return height;
}
/**
* Test if there is an obstacle at the given location.
*/
bool GridWorld::is_obstacle(int x, int y) const
{
return obstacles[width * y + x];
}
/**
* Prints the grid world to the given stream.
*/
void GridWorld::print(ostream &o) const
{
o << height << " " << width << endl;
o << "Board:" << endl;
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
if (is_obstacle(w, h))
o << "#";
else
o << " ";
}
o << endl;;
}
o << "Unit" << endl;
o << "Four-way" << endl;
o << start_x << " " << start_y << "\t" << goal_x << " " << goal_y << endl;
}
<commit_msg>Fix a delete error.<commit_after>/* -*- mode:linux -*- */
/**
* \file grid_world.cc
*
*
*
* \author Ethan Burns
* \date 2008-10-08
*/
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "grid_state.h"
#include "grid_world.h"
using namespace std;
/**
* Create a new GridWorld.
*/
GridWorld::GridWorld(const Heuristic *h, istream &s)
: SearchDomain(h)
{
char line[100];
char c;
s >> height;
s >> width;
obstacles = new bool[width * height];
s >> line;
if(strcmp(line, "Board:") != 0) {
cerr << "Parse error: expected \"Board:\"" << endl;
exit(EXIT_FAILURE);
}
c = s.get(); // new-line
if (c != '\n') {
cerr << endl << "Parse error: [" << c << "], h=" << h << endl;
exit(EXIT_FAILURE);
}
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
c = s.get();
if (c == '#')
obstacles[width * h + w] = true;
else
obstacles[width * h + w] = false;
}
c = s.get(); // new-line
if (c != '\n') {
cerr << endl << "Parse error: [" << c << "], h=" << h << endl;
exit(EXIT_FAILURE);
}
}
// Cost (Unit/Life)
s >> line;
// Movement (Four-way/Eight-way)
s >> line;
s >> start_x;
s >> start_y;
s >> goal_x;
s >> goal_y;
}
/**
* Destructor.
*/
GridWorld::~GridWorld()
{
delete []obstacles;
}
/**
* Get the initial state.
*/
State *GridWorld::initial_state(void)
{
return new GridState(this, NULL, 0, start_x, start_y);
}
/**
* Expand a gridstate.
*/
vector<const State*> *GridWorld::expand(const State *state) const
{
const int cost = 1;
const GridState *s;
vector<const State*> *children;
s = dynamic_cast<const GridState*>(state);
children = new vector<const State*>();
if (s->get_x() > 0 && !is_obstacle(s->get_x() + 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() + 1, s->get_y()));
}
if (s->get_x() < height - 1 && !is_obstacle(s->get_x() - 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() - 1, s->get_y()));
}
if (s->get_y() > 0 && !is_obstacle(s->get_x(), s->get_y() + 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() + 1));
}
if (s->get_y() > width - 1 && !is_obstacle(s->get_x(), s->get_y() - 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() - 1));
}
return children;
}
int GridWorld::get_goal_x(void) const
{
return goal_x;
}
int GridWorld::get_goal_y(void) const
{
return goal_y;
}
int GridWorld::get_width(void) const
{
return width;
}
int GridWorld::get_height(void) const
{
return height;
}
/**
* Test if there is an obstacle at the given location.
*/
bool GridWorld::is_obstacle(int x, int y) const
{
return obstacles[width * y + x];
}
/**
* Prints the grid world to the given stream.
*/
void GridWorld::print(ostream &o) const
{
o << height << " " << width << endl;
o << "Board:" << endl;
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
if (is_obstacle(w, h))
o << "#";
else
o << " ";
}
o << endl;;
}
o << "Unit" << endl;
o << "Four-way" << endl;
o << start_x << " " << start_y << "\t" << goal_x << " " << goal_y << endl;
}
<|endoftext|>
|
<commit_before>#ifndef BST_HPP
#define BST_HPP
#include "BSTNode.hpp"
#include "BSTIterator.hpp"
#include <utility> // for std::pair
template<typename Data>
class BST {
protected:
/** Pointer to the root of this BST, or nullptr if the BST is empty */
BSTNode<Data>* root;
/** Number of Data items stored in this BST. */
unsigned int isize;
public:
/** iterator is an aliased typename for BSTIterator<Data>. */
typedef BSTIterator<Data> iterator;
/** Default constructor.
Initialize an empty BST.
*/
BST() : root(nullptr), isize(0)
{
}
/** Default destructor.
* It is virtual, to allow appropriate destruction of subclass objects.
* Delete every node in this BST.
*/ // TODO
virtual ~BST()
{
delete (*this)->root;
}
/** Insert a Data item in the BST.
* Return a pair, with the pair's first member set to an
* iterator pointing to either the newly inserted element
* or to the equivalent element already in the set.
* The pair's second element is set to true
* if a new element was inserted or false if an
* equivalent element already existed.
*/ // TODO
virtual std::pair<iterator,bool> insert(const Data& item)
{
bool inserted;
++isize;
return std::pair<a,inserted>;
}
/** Find a Data item in the BST.
* Return an iterator pointing to the item, or the end
* iterator if the item is not in the BST.
*/ // TODO
iterator find(const Data& item) const
{
BSTIterator<Data> iter = new BSTIterator<Data>((*this)->root);
if (iter->curr->data == item)
return iter;
else
{
if
}
/** Return the number of items currently in the BST.
*/ // TODO
unsigned int size() const
{
return isize;
}
/** Remove all elements from this BST, and destroy them,
* leaving this BST with a size of 0.
*/ // TODO
void clear()
{
isize = 0;
}
/** Return true if the BST is empty, else false.
*/ // TODO
bool empty() const
{
return ( isize == 0 );
}
/** Return an iterator pointing to the first item in the BST.
*/ // TODO
iterator begin() const
{
BSTNode<Data> temp = ( (*this)->root );
while (temp->left)
temp = temp->left;
return new BSTIterator<Data>(temp);
}
/** Return an iterator pointing past the last item in the BST.
*/
iterator end() const
{
return typename BST<Data>::iterator(nullptr);
}
};
#endif //BST_HPP
<commit_msg>not enough changes to make a commit message worthwhile<commit_after>#ifndef BST_HPP
#define BST_HPP
#include "BSTNode.hpp"
#include "BSTIterator.hpp"
#include <utility> // for std::pair
template<typename Data>
class BST {
protected:
/** Pointer to the root of this BST, or nullptr if the BST is empty */
BSTNode<Data>* root;
/** Number of Data items stored in this BST. */
unsigned int isize;
public:
/** iterator is an aliased typename for BSTIterator<Data>. */
typedef BSTIterator<Data> iterator;
/** Default constructor.
Initialize an empty BST.
*/
BST() : root(nullptr), isize(0)
{
}
/** Default destructor.
* It is virtual, to allow appropriate destruction of subclass objects.
* Delete every node in this BST.
*/ // TODO
virtual ~BST()
{
delete (*this)->root;
}
/** Insert a Data item in the BST.
* Return a pair, with the pair's first member set to an
* iterator pointing to either the newly inserted element
* or to the equivalent element already in the set.
* The pair's second element is set to true
* if a new element was inserted or false if an
* equivalent element already existed.
*/ // TODO
virtual std::pair<iterator,bool> insert(const Data& item)
{
bool inserted;
++isize;
return std::pair<a,inserted>;
}
/** Find a Data item in the BST.
* Return an iterator pointing to the item, or the end
* iterator if the item is not in the BST.
*/ // TODO
iterator find(const Data& item) const
{
BSTIterator<Data> iter = new BSTIterator<Data>((*this)->root);
if (item == iter->curr->data)
return iter;
else
{
if (item < iter->curr->data)
}
/** Return the number of items currently in the BST.
*/ // TODO
unsigned int size() const
{
return isize;
}
/** Remove all elements from this BST, and destroy them,
* leaving this BST with a size of 0.
*/ // TODO
void clear()
{
isize = 0;
}
/** Return true if the BST is empty, else false.
*/ // TODO
bool empty() const
{
return ( isize == 0 );
}
/** Return an iterator pointing to the first item in the BST.
*/ // TODO
iterator begin() const
{
BSTNode<Data> temp = ( (*this)->root );
while (temp->left)
temp = temp->left;
return new BSTIterator<Data>(temp);
}
/** Return an iterator pointing past the last item in the BST.
*/
iterator end() const
{
return typename BST<Data>::iterator(nullptr);
}
};
#endif //BST_HPP
<|endoftext|>
|
<commit_before>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Sk2DPathEffect.h"
#include "SkBlitter.h"
#include "SkPath.h"
#include "SkScan.h"
class Sk2DPathEffectBlitter : public SkBlitter {
public:
Sk2DPathEffectBlitter(Sk2DPathEffect* pe, SkPath* dst)
: fPE(pe), fDst(dst)
{}
virtual void blitH(int x, int y, int count)
{
fPE->nextSpan(x, y, count, fDst);
}
private:
Sk2DPathEffect* fPE;
SkPath* fDst;
};
////////////////////////////////////////////////////////////////////////////////////
Sk2DPathEffect::Sk2DPathEffect(const SkMatrix& mat) : fMatrix(mat)
{
mat.invert(&fInverse);
}
bool Sk2DPathEffect::filterPath(SkPath* dst, const SkPath& src, SkScalar* width)
{
Sk2DPathEffectBlitter blitter(this, dst);
SkPath tmp;
SkIRect ir;
src.transform(fInverse, &tmp);
tmp.getBounds().round(&ir);
if (!ir.isEmpty()) {
// need to pass a clip to fillpath, required for inverse filltypes,
// even though those do not make sense for this patheffect
SkRegion clip(ir);
this->begin(ir, dst);
SkScan::FillPath(tmp, clip, &blitter);
this->end(dst);
}
return true;
}
void Sk2DPathEffect::nextSpan(int x, int y, int count, SkPath* path)
{
const SkMatrix& mat = this->getMatrix();
SkPoint src, dst;
src.set(SkIntToScalar(x) + SK_ScalarHalf, SkIntToScalar(y) + SK_ScalarHalf);
do {
mat.mapPoints(&dst, &src, 1);
this->next(dst, x++, y, path);
src.fX += SK_Scalar1;
} while (--count > 0);
}
void Sk2DPathEffect::begin(const SkIRect& uvBounds, SkPath* dst) {}
void Sk2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {}
void Sk2DPathEffect::end(SkPath* dst) {}
////////////////////////////////////////////////////////////////////////////////
void Sk2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer)
{
char storage[SkMatrix::kMaxFlattenSize];
uint32_t size = fMatrix.flatten(storage);
buffer.write32(size);
buffer.write(storage, size);
}
Sk2DPathEffect::Sk2DPathEffect(SkFlattenableReadBuffer& buffer)
{
char storage[SkMatrix::kMaxFlattenSize];
uint32_t size = buffer.readS32();
SkASSERT(size <= sizeof(storage));
buffer.read(storage, size);
fMatrix.unflatten(storage);
fMatrix.invert(&fInverse);
}
SkFlattenable::Factory Sk2DPathEffect::getFactory()
{
return CreateProc;
}
SkFlattenable* Sk2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer)
{
return SkNEW_ARGS(Sk2DPathEffect, (buffer));
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
SkPath2DPathEffect::SkPath2DPathEffect(const SkMatrix& m, const SkPath& p)
: INHERITED(m), fPath(p) {
}
SkPath2DPathEffect::SkPath2DPathEffect(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
fPath.unflatten(buffer);
}
SkFlattenable* SkPath2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkPath2DPathEffect, (buffer));
}
void SkPath2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
fPath.flatten(buffer);
}
SkFlattenable::Factory SkPath2DPathEffect::getFactory() {
return CreateProc;
}
void SkPath2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {
dst->addPath(fPath, loc.fX, loc.fY);
}
static SkFlattenable::Registrar gReg("SkPath2DPathEffect",
SkPath2DPathEffect::CreateProc);
<commit_msg>style cleanup<commit_after>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Sk2DPathEffect.h"
#include "SkBlitter.h"
#include "SkPath.h"
#include "SkScan.h"
class Sk2DPathEffectBlitter : public SkBlitter {
public:
Sk2DPathEffectBlitter(Sk2DPathEffect* pe, SkPath* dst)
: fPE(pe), fDst(dst) {}
virtual void blitH(int x, int y, int count) {
fPE->nextSpan(x, y, count, fDst);
}
private:
Sk2DPathEffect* fPE;
SkPath* fDst;
};
///////////////////////////////////////////////////////////////////////////////
Sk2DPathEffect::Sk2DPathEffect(const SkMatrix& mat) : fMatrix(mat) {
mat.invert(&fInverse);
}
bool Sk2DPathEffect::filterPath(SkPath* dst, const SkPath& src, SkScalar* width) {
Sk2DPathEffectBlitter blitter(this, dst);
SkPath tmp;
SkIRect ir;
src.transform(fInverse, &tmp);
tmp.getBounds().round(&ir);
if (!ir.isEmpty()) {
// need to pass a clip to fillpath, required for inverse filltypes,
// even though those do not make sense for this patheffect
SkRegion clip(ir);
this->begin(ir, dst);
SkScan::FillPath(tmp, clip, &blitter);
this->end(dst);
}
return true;
}
void Sk2DPathEffect::nextSpan(int x, int y, int count, SkPath* path) {
const SkMatrix& mat = this->getMatrix();
SkPoint src, dst;
src.set(SkIntToScalar(x) + SK_ScalarHalf, SkIntToScalar(y) + SK_ScalarHalf);
do {
mat.mapPoints(&dst, &src, 1);
this->next(dst, x++, y, path);
src.fX += SK_Scalar1;
} while (--count > 0);
}
void Sk2DPathEffect::begin(const SkIRect& uvBounds, SkPath* dst) {}
void Sk2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {}
void Sk2DPathEffect::end(SkPath* dst) {}
///////////////////////////////////////////////////////////////////////////////
void Sk2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) {
char storage[SkMatrix::kMaxFlattenSize];
uint32_t size = fMatrix.flatten(storage);
buffer.write32(size);
buffer.write(storage, size);
}
Sk2DPathEffect::Sk2DPathEffect(SkFlattenableReadBuffer& buffer) {
char storage[SkMatrix::kMaxFlattenSize];
uint32_t size = buffer.readS32();
SkASSERT(size <= sizeof(storage));
buffer.read(storage, size);
fMatrix.unflatten(storage);
fMatrix.invert(&fInverse);
}
SkFlattenable::Factory Sk2DPathEffect::getFactory() {
return CreateProc;
}
SkFlattenable* Sk2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(Sk2DPathEffect, (buffer));
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
SkPath2DPathEffect::SkPath2DPathEffect(const SkMatrix& m, const SkPath& p)
: INHERITED(m), fPath(p) {
}
SkPath2DPathEffect::SkPath2DPathEffect(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
fPath.unflatten(buffer);
}
SkFlattenable* SkPath2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkPath2DPathEffect, (buffer));
}
void SkPath2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
fPath.flatten(buffer);
}
SkFlattenable::Factory SkPath2DPathEffect::getFactory() {
return CreateProc;
}
void SkPath2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {
dst->addPath(fPath, loc.fX, loc.fY);
}
static SkFlattenable::Registrar gReg("SkPath2DPathEffect",
SkPath2DPathEffect::CreateProc);
<|endoftext|>
|
<commit_before>/*
* Event Manager by quckly.ru
* Version: 1.1
*
*/
#include "q_events.h"
EventManager Events;
EventManager::EventManager()
{
m_hook = false;
//m_args = std::vector<EventArg>(16);
}
void EventManager::RegisterEvent(const int _msg_id, EventCallback _func)
{
// Check for exist
for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++)
if (iter->msg_id == _msg_id && iter->func == _func)
return;
m_regevents.push_back(EventRegister(_msg_id, _func));
}
void EventManager::RegisterEvent(const char* msg_name, EventCallback func)
{
RegisterEvent(ID(msg_name), func);
}
int EventManager::ID(const char* msg_name)
{
return GET_USER_MSG_ID(PLID, msg_name, NULL);
}
// Get args
int EventManager::GetArgInt(int num)
{
if (num < 0 || num >= m_args.size())
return 0;
return m_args[num].value.iValue;
}
float EventManager::GetArgFloat(int num)
{
if (num < 0 || num >= m_args.size())
return 0.0;
return m_args[num].value.flValue;
}
const char* EventManager::GetArgString(int num)
{
if (num < 0 || num >= m_args.size() || m_args[num].m_type != at_string)
return nullptr;
return m_args[num].str.c_str();
}
// Set Args
void EventManager::SetArg(int num, int set)
{
if (num < 0 || num >= m_args.size())
return;
m_args[num].value.iValue = set;
}
void EventManager::SetArg(int num, float set)
{
if (num < 0 || num >= m_args.size())
return;
m_args[num].value.flValue = set;
}
void EventManager::SetArg(int num, const char* set)
{
if (num < 0 || num >= m_args.size() || m_args[num].m_type != at_string)
return;
m_args[num].str = set;
}
// Handlers
void EventManager::EM_MessageBegin(int msg_dest, int msg_type, const float *pOrigin, edict_t *ed)
{
m_args.clear();
m_hook = false;
for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++)
{
if (msg_type == iter->msg_id)
{
m_hook = true;
m_msg_dest = msg_dest;
m_msg_type = msg_type;
m_origin = pOrigin;
m_ed = ed;
RETURN_META(MRES_SUPERCEDE);
}
}
RETURN_META(MRES_IGNORED);
}
void EventManager::EM_MessageEnd()
{
if (m_hook)
{
m_hook = false;
int cb_return = ER_IGNORED, _cbret;
// Execute all registered events
for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++)
{
if (m_msg_type == iter->msg_id)
{
_cbret = iter->func(m_msg_dest, m_msg_type, m_origin, m_ed);
if (_cbret == ER_SUPERCEDE)
cb_return = ER_SUPERCEDE;
}
}
if (cb_return == ER_SUPERCEDE)
{
RETURN_META(MRES_SUPERCEDE);
}
// Send message
MESSAGE_BEGIN(m_msg_dest, m_msg_type, m_origin, m_ed);
for (auto iter = m_args.cbegin(); iter != m_args.cend(); iter++)
{
switch (iter->m_type)
{
case at_byte:
WRITE_BYTE(iter->value.iValue);
break;
case at_char:
WRITE_CHAR(iter->value.iValue);
break;
case at_short:
WRITE_SHORT(iter->value.iValue);
break;
case at_long:
WRITE_LONG(iter->value.iValue);
break;
case at_angle:
WRITE_ANGLE(iter->value.flValue);
break;
case at_coord:
WRITE_COORD(iter->value.flValue);
break;
case at_string:
WRITE_STRING(iter->str.c_str());
break;
case at_entity:
WRITE_ENTITY(iter->value.iValue);
break;
}
}
MESSAGE_END();
RETURN_META(MRES_SUPERCEDE);
}
RETURN_META(MRES_IGNORED);
}
void EventManager::EM_WriteByte(int iValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_byte, iValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteChar(int iValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_char, iValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteShort(int iValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_short, iValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteLong(int iValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_long, iValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteAngle(float flValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_angle, flValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteCoord(float flValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_coord, flValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteString(const char *sz)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_string, sz));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteEntity(int iValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_entity, iValue));
RETURN_META(MRES_SUPERCEDE);
}<commit_msg>Fixed SUPERCEDE return in EventManager<commit_after>/*
* Event Manager by quckly
* Version: 1.0
*
*/
#include "q_events.h"
EventManager Events;
EventManager::EventManager()
{
m_hook = false;
//m_args = std::vector<EventArg>(16);
}
void EventManager::RegisterEvent(const int _msg_id, EventCallback _func)
{
// Check for exist
for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++)
if (iter->msg_id == _msg_id && iter->func == _func)
return;
m_regevents.push_back(EventRegister(_msg_id, _func));
}
void EventManager::RegisterEvent(const char* msg_name, EventCallback func)
{
RegisterEvent(ID(msg_name), func);
}
int EventManager::ID(const char* msg_name)
{
return GET_USER_MSG_ID(PLID, msg_name, NULL);
}
// Get args
int EventManager::GetArgInt(int num)
{
if (num < 0 || num >= m_args.size())
return 0;
return m_args[num].value.iValue;
}
float EventManager::GetArgFloat(int num)
{
if (num < 0 || num >= m_args.size())
return 0.0;
return m_args[num].value.flValue;
}
const char* EventManager::GetArgString(int num)
{
if (num < 0 || num >= m_args.size() || m_args[num].m_type != at_string)
return nullptr;
return m_args[num].str.c_str();
}
// Set Args
void EventManager::SetArg(int num, int set)
{
if (num < 0 || num >= m_args.size())
return;
m_args[num].value.iValue = set;
}
void EventManager::SetArg(int num, float set)
{
if (num < 0 || num >= m_args.size())
return;
m_args[num].value.flValue = set;
}
void EventManager::SetArg(int num, const char* set)
{
if (num < 0 || num >= m_args.size() || m_args[num].m_type != at_string)
return;
m_args[num].str = set;
}
// Handlers
void EventManager::EM_MessageBegin(int msg_dest, int msg_type, const float *pOrigin, edict_t *ed)
{
m_hook = false;
for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++)
{
if (msg_type == iter->msg_id)
{
m_hook = true;
m_args.clear();
m_msg_dest = msg_dest;
m_msg_type = msg_type;
m_origin = pOrigin;
m_ed = ed;
RETURN_META(MRES_SUPERCEDE);
}
}
RETURN_META(MRES_IGNORED);
}
void EventManager::EM_MessageEnd()
{
if (m_hook)
{
m_hook = false;
int cb_return = ER_IGNORED, _cbret;
// Execute all registered events
for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++)
{
if (m_msg_type == iter->msg_id)
{
_cbret = iter->func(m_msg_dest, m_msg_type, m_origin, m_ed);
if (_cbret == ER_SUPERCEDE)
cb_return = ER_SUPERCEDE;
}
}
if (cb_return == ER_SUPERCEDE)
{
RETURN_META(MRES_SUPERCEDE);
}
// Send message
MESSAGE_BEGIN(m_msg_dest, m_msg_type, m_origin, m_ed);
for (auto iter = m_args.cbegin(); iter != m_args.cend(); iter++)
{
switch (iter->m_type)
{
case at_byte:
WRITE_BYTE(iter->value.iValue);
break;
case at_char:
WRITE_CHAR(iter->value.iValue);
break;
case at_short:
WRITE_SHORT(iter->value.iValue);
break;
case at_long:
WRITE_LONG(iter->value.iValue);
break;
case at_angle:
WRITE_ANGLE(iter->value.flValue);
break;
case at_coord:
WRITE_COORD(iter->value.flValue);
break;
case at_string:
WRITE_STRING(iter->str.c_str());
break;
case at_entity:
WRITE_ENTITY(iter->value.iValue);
break;
}
}
MESSAGE_END();
RETURN_META(MRES_SUPERCEDE);
}
RETURN_META(MRES_IGNORED);
}
void EventManager::EM_WriteByte(int iValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_byte, iValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteChar(int iValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_char, iValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteShort(int iValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_short, iValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteLong(int iValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_long, iValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteAngle(float flValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_angle, flValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteCoord(float flValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_coord, flValue));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteString(const char *sz)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_string, sz));
RETURN_META(MRES_SUPERCEDE);
}
void EventManager::EM_WriteEntity(int iValue)
{
if (!m_hook)
RETURN_META(MRES_IGNORED);
m_args.push_back(EventArg(at_entity, iValue));
RETURN_META(MRES_SUPERCEDE);
}<|endoftext|>
|
<commit_before>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#ifdef BUILDING_WITH_MPI
#include <mpi.h>
#endif
#include "ProcessManager.hpp"
#include <exception>
#include <QDataStream>
////////////////////////////////////////////////////////////////////
#ifdef BUILDING_WITH_MPI
namespace
{
// When an Array with more than INT_MAX elements is to be communicated,
// the message will be broken up into pieces of the following size
const int maxMessageSize = 2000000000;
// Creates (and commits!) a datatype consisting of blocks of a certain length, displaced according to a list of
// displacements in units of the block length. The created datatype should be freed when it is no longer needed.
void createDisplacedDoubleBlocks(size_t blocklength, const std::vector<int>& displacements,
MPI_Datatype* newtypeP, size_t extent = 0)
{
size_t count = displacements.size();
// These are passed to int arguments of MPI functions, so we need to check for a possible integer overflow
if (blocklength > INT_MAX) throw std::overflow_error("blocklength larger than INT_MAX");
if (count > INT_MAX) throw std::overflow_error("number of elements larger than INT_MAX");
// Intermediary datatype (counting by double causes overflow when displacements[i]*blocklength > INT_MAX)
MPI_Datatype singleBlock;
MPI_Type_contiguous(blocklength, MPI_DOUBLE, &singleBlock);
// Create a datatype representing a structure of displaced blocks of the same size;
MPI_Datatype indexedBlock;
MPI_Type_create_indexed_block(count, 1, displacements.data(), singleBlock, &indexedBlock);
if (extent != 0)
{
// Pad this datatype to modify the extent to the requested value
MPI_Aint lb;
MPI_Aint ex;
MPI_Type_get_extent(indexedBlock, &lb, &ex);
MPI_Type_create_resized(indexedBlock, lb, extent*sizeof(double), newtypeP);
// Commit the final type and free the intermediary one
MPI_Type_commit(newtypeP);
MPI_Type_free(&indexedBlock);
}
else
{
// No padding, just store the indexed block
*newtypeP = indexedBlock;
MPI_Type_commit(newtypeP);
}
// Free the intermediary type
MPI_Type_free(&singleBlock);
}
}
#endif
std::atomic<int> ProcessManager::requests(0);
//////////////////////////////////////////////////////////////////////
void ProcessManager::initialize(int *argc, char ***argv)
{
#ifdef BUILDING_WITH_MPI
int initialized;
MPI_Initialized(&initialized);
if (!initialized)
{
MPI_Init(argc, argv);
}
#else
Q_UNUSED(argc) Q_UNUSED(argv)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::finalize()
{
#ifdef BUILDING_WITH_MPI
MPI_Finalize();
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::acquireMPI(int& rank, int& Nprocs)
{
#ifdef BUILDING_WITH_MPI
int oldrequests = requests++;
if (oldrequests) // if requests >=1
{
Nprocs = 1;
rank = 0;
}
else // requests == 0
{
MPI_Comm_size(MPI_COMM_WORLD, &Nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
}
#else
rank = 0;
Nprocs = 1;
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::releaseMPI()
{
#ifdef BUILDING_WITH_MPI
requests--;
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::barrier()
{
#ifdef BUILDING_WITH_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sendByteBuffer(QByteArray& buffer, int receiver, int tag)
{
#ifdef BUILDING_WITH_MPI
MPI_Send(buffer.data(), buffer.size(), MPI_BYTE, receiver, tag, MPI_COMM_WORLD);
#else
Q_UNUSED(buffer) Q_UNUSED(receiver) Q_UNUSED(tag)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::receiveByteBuffer(QByteArray& buffer, int& sender)
{
#ifdef BUILDING_WITH_MPI
MPI_Status status;
MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
sender = status.MPI_SOURCE;
#else
Q_UNUSED(buffer) Q_UNUSED(sender)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::receiveByteBuffer(QByteArray &buffer, int sender, int& tag)
{
#ifdef BUILDING_WITH_MPI
MPI_Status status;
MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, sender, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
tag = status.MPI_TAG;
#else
Q_UNUSED(buffer) Q_UNUSED(sender) Q_UNUSED(tag)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::gatherw(const double* sendBuffer, size_t sendCount,
double* recvBuffer, int recvRank, size_t recvLength,
const std::vector<std::vector<int>>& recvDisplacements)
{
#ifdef BUILDING_WITH_MPI
int size;
int rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// parameters for the senders
std::vector<int> sendcnts(size, 0); // every process sends nothing to all processes
sendcnts[recvRank] = sendCount; // except to the receiver
std::vector<int> sdispls(size, 0); // starting from sendBuffer + 0
std::vector<MPI_Datatype> sendtypes(size, MPI_DOUBLE); // all doubles
// parameters on the receiving end
std::vector<int> recvcnts;
if (rank != recvRank) recvcnts.resize(size, 0); // I am not receiver: receive nothing from every process
else recvcnts.resize(size, 1); // I am receiver: receive 1 from every process
std::vector<int> rdispls(size, 0); // displacements will be contained in the datatypes
std::vector<MPI_Datatype> recvtypes; // we will construct a derived datatype per process for receiving
recvtypes.reserve(size);
for (int r=0; r<size; r++)
{
MPI_Datatype newtype;
createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype);
recvtypes.push_back(newtype);
}
MPI_Alltoallw(const_cast<double*>(sendBuffer), sendcnts.data(), sdispls.data(), sendtypes.data(),
recvBuffer, recvcnts.data(), rdispls.data(), recvtypes.data(),
MPI_COMM_WORLD);
for (int rank=0; rank<size; rank++) MPI_Type_free(&recvtypes[rank]);
#else
Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(recvBuffer) Q_UNUSED(recvRank) Q_UNUSED(recvLength)
Q_UNUSED(recvDisplacements)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::displacedBlocksAllToAll(const double* sendBuffer, size_t sendCount, size_t sendLength,
const std::vector<std::vector<int>>& sendDisplacements,
size_t sendExtent, double* recvBuffer, size_t recvCount, size_t recvLength,
const std::vector<std::vector<int>>& recvDisplacements,
size_t recvExtent)
{
#ifdef BUILDING_WITH_MPI
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
std::vector<int> sendcnts(size,sendCount);
std::vector<int> sdispls(size, 0);
std::vector<MPI_Datatype> sendtypes;
sendtypes.reserve(size);
std::vector<int> recvcnts(size, recvCount);
std::vector<int> rdispls(size, 0);
std::vector<MPI_Datatype> recvtypes;
recvtypes.reserve(size);
for (int r=0; r<size; r++)
{
MPI_Datatype newtype;
createDisplacedDoubleBlocks(sendLength, sendDisplacements[r], &newtype, sendExtent);
sendtypes.push_back(newtype);
createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype, recvExtent);
recvtypes.push_back(newtype);
}
MPI_Alltoallw(const_cast<double*>(sendBuffer), sendcnts.data(), sdispls.data(), sendtypes.data(),
recvBuffer, recvcnts.data(), rdispls.data(), recvtypes.data(),
MPI_COMM_WORLD);
for (int r=0; r<size; r++)
{
MPI_Type_free(&sendtypes[r]);
MPI_Type_free(&recvtypes[r]);
}
#else
Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(sendDisplacements) Q_UNUSED(sendLength) Q_UNUSED(sendExtent)
Q_UNUSED(recvBuffer) Q_UNUSED(recvCount) Q_UNUSED(recvDisplacements) Q_UNUSED(recvLength) Q_UNUSED(recvExtent)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sum(double* my_array, size_t nvalues, int root)
{
#ifdef BUILDING_WITH_MPI
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
const int maxMessageSize = 2000000000;
size_t remaining = nvalues;
double* my_array_position = my_array;
while (remaining >= INT_MAX)
{
if (rank == root)
MPI_Reduce(MPI_IN_PLACE, my_array_position, maxMessageSize, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
else
MPI_Reduce(my_array_position, my_array_position, maxMessageSize, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
remaining -= maxMessageSize;
my_array_position += maxMessageSize;
}
if (rank == root)
MPI_Reduce(MPI_IN_PLACE, my_array_position, remaining, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
else
MPI_Reduce(my_array_position, my_array_position, remaining, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(nvalues) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sum_all(double* my_array, size_t nvalues)
{
#ifdef BUILDING_WITH_MPI
size_t remaining = nvalues;
while (remaining >= INT_MAX)
{
MPI_Allreduce(MPI_IN_PLACE, my_array + (nvalues-remaining), maxMessageSize, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
remaining -= maxMessageSize;
}
MPI_Allreduce(MPI_IN_PLACE, my_array + (nvalues-remaining), remaining, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(nvalues)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::or_all(bool* boolean)
{
#ifdef BUILDING_WITH_MPI
MPI_Allreduce(MPI_IN_PLACE, boolean, 1, MPI_C_BOOL, MPI_LOR, MPI_COMM_WORLD);
#else
Q_UNUSED(boolean)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::broadcast(double* my_array, size_t nvalues, int root)
{
#ifdef BUILDING_WITH_MPI
size_t remaining = nvalues;
while (remaining >= INT_MAX)
{
MPI_Bcast(my_array + (nvalues-remaining), maxMessageSize, MPI_DOUBLE, root, MPI_COMM_WORLD);
remaining -= maxMessageSize;
}
MPI_Bcast(my_array + (nvalues-remaining), remaining, MPI_DOUBLE, root, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(nvalues) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::broadcast(int* value, int root)
{
#ifdef BUILDING_WITH_MPI
MPI_Bcast(value, 1, MPI_INT, root, MPI_COMM_WORLD);
#else
Q_UNUSED(value) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
bool ProcessManager::isRoot()
{
#ifdef BUILDING_WITH_MPI
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
return (rank == 0);
#else
return true;
#endif
}
//////////////////////////////////////////////////////////////////////
bool ProcessManager::isMultiProc()
{
#ifdef BUILDING_WITH_MPI
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
return (size > 1);
#else
return false;
#endif
}
<commit_msg>Cast const away for list of displacements for same reason<commit_after>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#ifdef BUILDING_WITH_MPI
#include <mpi.h>
#endif
#include "ProcessManager.hpp"
#include <exception>
#include <QDataStream>
////////////////////////////////////////////////////////////////////
#ifdef BUILDING_WITH_MPI
namespace
{
// When an Array with more than INT_MAX elements is to be communicated,
// the message will be broken up into pieces of the following size
const int maxMessageSize = 2000000000;
// Creates (and commits!) a datatype consisting of blocks of a certain length, displaced according to a list of
// displacements in units of the block length. The created datatype should be freed when it is no longer needed.
void createDisplacedDoubleBlocks(size_t blocklength, const std::vector<int>& displacements,
MPI_Datatype* newtypeP, size_t extent = 0)
{
size_t count = displacements.size();
// These are passed to int arguments of MPI functions, so we need to check for a possible integer overflow
if (blocklength > INT_MAX) throw std::overflow_error("blocklength larger than INT_MAX");
if (count > INT_MAX) throw std::overflow_error("number of elements larger than INT_MAX");
// Intermediary datatype (counting by double causes overflow when displacements[i]*blocklength > INT_MAX)
MPI_Datatype singleBlock;
MPI_Type_contiguous(blocklength, MPI_DOUBLE, &singleBlock);
// Create a datatype representing a structure of displaced blocks of the same size;
MPI_Datatype indexedBlock;
MPI_Type_create_indexed_block(count, 1, const_cast<int*>(displacements.data()), singleBlock, &indexedBlock);
if (extent != 0)
{
// Pad this datatype to modify the extent to the requested value
MPI_Aint lb;
MPI_Aint ex;
MPI_Type_get_extent(indexedBlock, &lb, &ex);
MPI_Type_create_resized(indexedBlock, lb, extent*sizeof(double), newtypeP);
// Commit the final type and free the intermediary one
MPI_Type_commit(newtypeP);
MPI_Type_free(&indexedBlock);
}
else
{
// No padding, just store the indexed block
*newtypeP = indexedBlock;
MPI_Type_commit(newtypeP);
}
// Free the intermediary type
MPI_Type_free(&singleBlock);
}
}
#endif
std::atomic<int> ProcessManager::requests(0);
//////////////////////////////////////////////////////////////////////
void ProcessManager::initialize(int *argc, char ***argv)
{
#ifdef BUILDING_WITH_MPI
int initialized;
MPI_Initialized(&initialized);
if (!initialized)
{
MPI_Init(argc, argv);
}
#else
Q_UNUSED(argc) Q_UNUSED(argv)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::finalize()
{
#ifdef BUILDING_WITH_MPI
MPI_Finalize();
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::acquireMPI(int& rank, int& Nprocs)
{
#ifdef BUILDING_WITH_MPI
int oldrequests = requests++;
if (oldrequests) // if requests >=1
{
Nprocs = 1;
rank = 0;
}
else // requests == 0
{
MPI_Comm_size(MPI_COMM_WORLD, &Nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
}
#else
rank = 0;
Nprocs = 1;
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::releaseMPI()
{
#ifdef BUILDING_WITH_MPI
requests--;
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::barrier()
{
#ifdef BUILDING_WITH_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sendByteBuffer(QByteArray& buffer, int receiver, int tag)
{
#ifdef BUILDING_WITH_MPI
MPI_Send(buffer.data(), buffer.size(), MPI_BYTE, receiver, tag, MPI_COMM_WORLD);
#else
Q_UNUSED(buffer) Q_UNUSED(receiver) Q_UNUSED(tag)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::receiveByteBuffer(QByteArray& buffer, int& sender)
{
#ifdef BUILDING_WITH_MPI
MPI_Status status;
MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
sender = status.MPI_SOURCE;
#else
Q_UNUSED(buffer) Q_UNUSED(sender)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::receiveByteBuffer(QByteArray &buffer, int sender, int& tag)
{
#ifdef BUILDING_WITH_MPI
MPI_Status status;
MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, sender, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
tag = status.MPI_TAG;
#else
Q_UNUSED(buffer) Q_UNUSED(sender) Q_UNUSED(tag)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::gatherw(const double* sendBuffer, size_t sendCount,
double* recvBuffer, int recvRank, size_t recvLength,
const std::vector<std::vector<int>>& recvDisplacements)
{
#ifdef BUILDING_WITH_MPI
int size;
int rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// parameters for the senders
std::vector<int> sendcnts(size, 0); // every process sends nothing to all processes
sendcnts[recvRank] = sendCount; // except to the receiver
std::vector<int> sdispls(size, 0); // starting from sendBuffer + 0
std::vector<MPI_Datatype> sendtypes(size, MPI_DOUBLE); // all doubles
// parameters on the receiving end
std::vector<int> recvcnts;
if (rank != recvRank) recvcnts.resize(size, 0); // I am not receiver: receive nothing from every process
else recvcnts.resize(size, 1); // I am receiver: receive 1 from every process
std::vector<int> rdispls(size, 0); // displacements will be contained in the datatypes
std::vector<MPI_Datatype> recvtypes; // we will construct a derived datatype per process for receiving
recvtypes.reserve(size);
for (int r=0; r<size; r++)
{
MPI_Datatype newtype;
createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype);
recvtypes.push_back(newtype);
}
MPI_Alltoallw(const_cast<double*>(sendBuffer), sendcnts.data(), sdispls.data(), sendtypes.data(),
recvBuffer, recvcnts.data(), rdispls.data(), recvtypes.data(),
MPI_COMM_WORLD);
for (int rank=0; rank<size; rank++) MPI_Type_free(&recvtypes[rank]);
#else
Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(recvBuffer) Q_UNUSED(recvRank) Q_UNUSED(recvLength)
Q_UNUSED(recvDisplacements)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::displacedBlocksAllToAll(const double* sendBuffer, size_t sendCount, size_t sendLength,
const std::vector<std::vector<int>>& sendDisplacements,
size_t sendExtent, double* recvBuffer, size_t recvCount, size_t recvLength,
const std::vector<std::vector<int>>& recvDisplacements,
size_t recvExtent)
{
#ifdef BUILDING_WITH_MPI
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
std::vector<int> sendcnts(size,sendCount);
std::vector<int> sdispls(size, 0);
std::vector<MPI_Datatype> sendtypes;
sendtypes.reserve(size);
std::vector<int> recvcnts(size, recvCount);
std::vector<int> rdispls(size, 0);
std::vector<MPI_Datatype> recvtypes;
recvtypes.reserve(size);
for (int r=0; r<size; r++)
{
MPI_Datatype newtype;
createDisplacedDoubleBlocks(sendLength, sendDisplacements[r], &newtype, sendExtent);
sendtypes.push_back(newtype);
createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype, recvExtent);
recvtypes.push_back(newtype);
}
MPI_Alltoallw(const_cast<double*>(sendBuffer), sendcnts.data(), sdispls.data(), sendtypes.data(),
recvBuffer, recvcnts.data(), rdispls.data(), recvtypes.data(),
MPI_COMM_WORLD);
for (int r=0; r<size; r++)
{
MPI_Type_free(&sendtypes[r]);
MPI_Type_free(&recvtypes[r]);
}
#else
Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(sendDisplacements) Q_UNUSED(sendLength) Q_UNUSED(sendExtent)
Q_UNUSED(recvBuffer) Q_UNUSED(recvCount) Q_UNUSED(recvDisplacements) Q_UNUSED(recvLength) Q_UNUSED(recvExtent)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sum(double* my_array, size_t nvalues, int root)
{
#ifdef BUILDING_WITH_MPI
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
const int maxMessageSize = 2000000000;
size_t remaining = nvalues;
double* my_array_position = my_array;
while (remaining >= INT_MAX)
{
if (rank == root)
MPI_Reduce(MPI_IN_PLACE, my_array_position, maxMessageSize, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
else
MPI_Reduce(my_array_position, my_array_position, maxMessageSize, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
remaining -= maxMessageSize;
my_array_position += maxMessageSize;
}
if (rank == root)
MPI_Reduce(MPI_IN_PLACE, my_array_position, remaining, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
else
MPI_Reduce(my_array_position, my_array_position, remaining, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(nvalues) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::sum_all(double* my_array, size_t nvalues)
{
#ifdef BUILDING_WITH_MPI
size_t remaining = nvalues;
while (remaining >= INT_MAX)
{
MPI_Allreduce(MPI_IN_PLACE, my_array + (nvalues-remaining), maxMessageSize, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
remaining -= maxMessageSize;
}
MPI_Allreduce(MPI_IN_PLACE, my_array + (nvalues-remaining), remaining, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(nvalues)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::or_all(bool* boolean)
{
#ifdef BUILDING_WITH_MPI
MPI_Allreduce(MPI_IN_PLACE, boolean, 1, MPI_C_BOOL, MPI_LOR, MPI_COMM_WORLD);
#else
Q_UNUSED(boolean)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::broadcast(double* my_array, size_t nvalues, int root)
{
#ifdef BUILDING_WITH_MPI
size_t remaining = nvalues;
while (remaining >= INT_MAX)
{
MPI_Bcast(my_array + (nvalues-remaining), maxMessageSize, MPI_DOUBLE, root, MPI_COMM_WORLD);
remaining -= maxMessageSize;
}
MPI_Bcast(my_array + (nvalues-remaining), remaining, MPI_DOUBLE, root, MPI_COMM_WORLD);
#else
Q_UNUSED(my_array) Q_UNUSED(nvalues) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
void ProcessManager::broadcast(int* value, int root)
{
#ifdef BUILDING_WITH_MPI
MPI_Bcast(value, 1, MPI_INT, root, MPI_COMM_WORLD);
#else
Q_UNUSED(value) Q_UNUSED(root)
#endif
}
//////////////////////////////////////////////////////////////////////
bool ProcessManager::isRoot()
{
#ifdef BUILDING_WITH_MPI
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
return (rank == 0);
#else
return true;
#endif
}
//////////////////////////////////////////////////////////////////////
bool ProcessManager::isMultiProc()
{
#ifdef BUILDING_WITH_MPI
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
return (size > 1);
#else
return false;
#endif
}
<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCProperty.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCProperty
//
// -------------------------------------------------------------------------
#include "NFCProperty.h"
#include <complex>
NFCProperty::NFCProperty()
{
mbPublic = false;
mbPrivate = false;
mbSave = false;
mSelf = NFGUID();
eType = TDATA_UNKNOWN;
msPropertyName = "";
}
NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue)
{
mbPublic = bPublic;
mbPrivate = bPrivate;
mbSave = bSave;
mSelf = self;
msPropertyName = strPropertyName;
mstrRelationValue = strRelationValue;
eType = varType;
}
NFCProperty::~NFCProperty()
{
for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)
{
iter->reset();
}
mtPropertyCallback.clear();
mxData.reset();
}
void NFCProperty::SetValue(const NFIDataList::TData& TData)
{
if (eType != TData.GetType())
{
return;
}
if (!mxData.get())
{
if (!TData.IsNullValue())
{
return;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->variantData = TData.variantData;
NFCDataList::TData newValue;
newValue = *mxData;
OnEventHandler(oldValue , newValue);
}
void NFCProperty::SetValue(const NFIProperty* pProperty)
{
SetValue(pProperty->GetValue());
}
const NFIDataList::TData& NFCProperty::GetValue() const
{
if (mxData.get())
{
return *mxData;
}
return NULL_TDATA;
}
const std::string& NFCProperty::GetKey() const
{
return msPropertyName;
}
const bool NFCProperty::GetSave() const
{
return mbSave;
}
const bool NFCProperty::GetPublic() const
{
return mbPublic;
}
const bool NFCProperty::GetPrivate() const
{
return mbPrivate;
}
const std::string& NFCProperty::GetRelationValue() const
{
return mstrRelationValue;
}
void NFCProperty::SetSave(bool bSave)
{
mbSave = bSave;
}
void NFCProperty::SetPublic(bool bPublic)
{
mbPublic = bPublic;
}
void NFCProperty::SetPrivate(bool bPrivate)
{
mbPrivate = bPrivate;
}
void NFCProperty::SetRelationValue(const std::string& strRelationValue)
{
mstrRelationValue = strRelationValue;
}
NFINT64 NFCProperty::GetInt() const
{
if (!mxData.get())
{
return 0;
}
return mxData->GetInt();
}
double NFCProperty::GetFloat() const
{
if (!mxData.get())
{
return 0.0;
}
return mxData->GetFloat();
}
const std::string& NFCProperty::GetString() const
{
if (!mxData.get())
{
return NULL_STR;
}
return mxData->GetString();
}
const NFGUID& NFCProperty::GetObject() const
{
if (!mxData.get())
{
return NULL_OBJECT;
}
return mxData->GetObject();
}
void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
mtPropertyCallback.push_back(cb);
}
int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
if (mtPropertyCallback.size() <= 0)
{
return 0;
}
TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();
TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();
for (it; it != end; ++it)
{
//NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)
PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;
PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();
int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);
}
return 0;
}
bool NFCProperty::SetInt(const NFINT64 value)
{
if (eType != TDATA_INT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (0 == value)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));
mxData->SetInt(0);
}
if (value == mxData->GetInt())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetInt(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetFloat(const double value)
{
if (eType != TDATA_FLOAT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (std::abs(value) < 0.001)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));
mxData->SetFloat(0.0);
}
if (value - mxData->GetFloat() < 0.001)
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetFloat(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetString(const std::string& value)
{
if (eType != TDATA_STRING)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.empty())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));
mxData->SetString(NULL_STR);
}
if (value == mxData->GetString())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetString(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetObject(const NFGUID& value)
{
if (eType != TDATA_OBJECT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.IsNull())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));
mxData->SetObject(NFGUID());
}
if (value == mxData->GetObject())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetObject(value);
OnEventHandler(oldValue , *mxData);
return true;
}
bool NFCProperty::Changed() const
{
return GetValue().IsNullValue();
}
const TDATA_TYPE NFCProperty::GetType() const
{
return eType;
}
const bool NFCProperty::GeUsed() const
{
if (mxData.get())
{
return true;
}
return false;
}
std::string NFCProperty::ToString()
{
std::string strData;
const TDATA_TYPE eType = GetType();
switch (eType)
{
case TDATA_INT:
strData = lexical_cast<std::string> (GetInt());
break;
case TDATA_FLOAT:
strData = lexical_cast<std::string> (GetFloat());
break;
case TDATA_STRING:
strData = GetString();
break;
case TDATA_OBJECT:
strData = GetObject().ToString();
break;
default:
strData = NULL_STR;
break;
}
return strData;
}
bool NFCProperty::FromString(const std::string& strData)
{
const TDATA_TYPE eType = GetType();
bool bRet = false;
switch (eType)
{
case TDATA_INT:
{
NFINT64 nValue = 0;
bRet = NF_StrTo(strData, nValue);
SetInt(nValue);
}
break;
case TDATA_FLOAT:
{
double dValue = 0;
bRet = NF_StrTo(strData, dValue);
SetFloat(dValue);
}
break;
case TDATA_STRING:
{
SetString(strData);
bRet = true;
}
break;
case TDATA_OBJECT:
{
NFGUID xID;
bRet = xID.FromString(strData);
SetObject(xID);
}
break;
default:
break;
}
return bRet;
}
bool NFCProperty::DeSerialization()
{
bool bRet = false;
const TDATA_TYPE eType = GetType();
if (eType == TDATA_STRING)
{
NFCDataList xDataList;
const std::string& strData = mxData->GetString();
xDataList.Split(strData.c_str(), ";");
for (int i = 0; i < xDataList.GetCount(); ++i)
{
if (nullptr == mxEmbeddedList)
{
mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>());
}
else
{
mxEmbeddedList->ClearAll();
}
if(xDataList.String(i).empty())
{
NFASSERT(0, strData, __FILE__, __FUNCTION__);
}
mxEmbeddedList->Add(xDataList.String(i));
}
if (nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0)
{
std::string strTemData;
for (bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData))
{
NFCDataList xTemDataList;
xTemDataList.Split(strTemData.c_str(), ",");
if (xTemDataList.GetCount() > 0)
{
if (xTemDataList.GetCount() != 2)
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
const std::string& strKey = xTemDataList.String(0);
const std::string& strValue = xTemDataList.String(0);
if (strKey.empty() || strValue.empty())
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
if (nullptr == mxEmbeddedMap)
{
mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>());
}
else
{
mxEmbeddedMap->ClearAll();
}
mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue)))
}
}
bRet = true;
}
}
return bRet;
}
const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const
{
return this->mxEmbeddedList;
}
const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const
{
return this->mxEmbeddedMap;
}
<commit_msg>fixed<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCProperty.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCProperty
//
// -------------------------------------------------------------------------
#include "NFCProperty.h"
#include <complex>
NFCProperty::NFCProperty()
{
mbPublic = false;
mbPrivate = false;
mbSave = false;
mSelf = NFGUID();
eType = TDATA_UNKNOWN;
msPropertyName = "";
}
NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue)
{
mbPublic = bPublic;
mbPrivate = bPrivate;
mbSave = bSave;
mSelf = self;
msPropertyName = strPropertyName;
mstrRelationValue = strRelationValue;
eType = varType;
}
NFCProperty::~NFCProperty()
{
for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)
{
iter->reset();
}
mtPropertyCallback.clear();
mxData.reset();
}
void NFCProperty::SetValue(const NFIDataList::TData& TData)
{
if (eType != TData.GetType())
{
return;
}
if (!mxData.get())
{
if (!TData.IsNullValue())
{
return;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->variantData = TData.variantData;
NFCDataList::TData newValue;
newValue = *mxData;
OnEventHandler(oldValue , newValue);
}
void NFCProperty::SetValue(const NFIProperty* pProperty)
{
SetValue(pProperty->GetValue());
}
const NFIDataList::TData& NFCProperty::GetValue() const
{
if (mxData.get())
{
return *mxData;
}
return NULL_TDATA;
}
const std::string& NFCProperty::GetKey() const
{
return msPropertyName;
}
const bool NFCProperty::GetSave() const
{
return mbSave;
}
const bool NFCProperty::GetPublic() const
{
return mbPublic;
}
const bool NFCProperty::GetPrivate() const
{
return mbPrivate;
}
const std::string& NFCProperty::GetRelationValue() const
{
return mstrRelationValue;
}
void NFCProperty::SetSave(bool bSave)
{
mbSave = bSave;
}
void NFCProperty::SetPublic(bool bPublic)
{
mbPublic = bPublic;
}
void NFCProperty::SetPrivate(bool bPrivate)
{
mbPrivate = bPrivate;
}
void NFCProperty::SetRelationValue(const std::string& strRelationValue)
{
mstrRelationValue = strRelationValue;
}
NFINT64 NFCProperty::GetInt() const
{
if (!mxData.get())
{
return 0;
}
return mxData->GetInt();
}
double NFCProperty::GetFloat() const
{
if (!mxData.get())
{
return 0.0;
}
return mxData->GetFloat();
}
const std::string& NFCProperty::GetString() const
{
if (!mxData.get())
{
return NULL_STR;
}
return mxData->GetString();
}
const NFGUID& NFCProperty::GetObject() const
{
if (!mxData.get())
{
return NULL_OBJECT;
}
return mxData->GetObject();
}
void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
mtPropertyCallback.push_back(cb);
}
int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
if (mtPropertyCallback.size() <= 0)
{
return 0;
}
TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();
TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();
for (it; it != end; ++it)
{
//NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)
PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;
PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();
int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);
}
return 0;
}
bool NFCProperty::SetInt(const NFINT64 value)
{
if (eType != TDATA_INT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (0 == value)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));
mxData->SetInt(0);
}
if (value == mxData->GetInt())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetInt(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetFloat(const double value)
{
if (eType != TDATA_FLOAT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (std::abs(value) < 0.001)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));
mxData->SetFloat(0.0);
}
if (value - mxData->GetFloat() < 0.001)
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetFloat(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetString(const std::string& value)
{
if (eType != TDATA_STRING)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.empty())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));
mxData->SetString(NULL_STR);
}
if (value == mxData->GetString())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetString(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetObject(const NFGUID& value)
{
if (eType != TDATA_OBJECT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.IsNull())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));
mxData->SetObject(NFGUID());
}
if (value == mxData->GetObject())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetObject(value);
OnEventHandler(oldValue , *mxData);
return true;
}
bool NFCProperty::Changed() const
{
return GetValue().IsNullValue();
}
const TDATA_TYPE NFCProperty::GetType() const
{
return eType;
}
const bool NFCProperty::GeUsed() const
{
if (mxData.get())
{
return true;
}
return false;
}
std::string NFCProperty::ToString()
{
std::string strData;
const TDATA_TYPE eType = GetType();
switch (eType)
{
case TDATA_INT:
strData = lexical_cast<std::string> (GetInt());
break;
case TDATA_FLOAT:
strData = lexical_cast<std::string> (GetFloat());
break;
case TDATA_STRING:
strData = GetString();
break;
case TDATA_OBJECT:
strData = GetObject().ToString();
break;
default:
strData = NULL_STR;
break;
}
return strData;
}
bool NFCProperty::FromString(const std::string& strData)
{
const TDATA_TYPE eType = GetType();
bool bRet = false;
switch (eType)
{
case TDATA_INT:
{
NFINT64 nValue = 0;
bRet = NF_StrTo(strData, nValue);
SetInt(nValue);
}
break;
case TDATA_FLOAT:
{
double dValue = 0;
bRet = NF_StrTo(strData, dValue);
SetFloat(dValue);
}
break;
case TDATA_STRING:
{
SetString(strData);
bRet = true;
}
break;
case TDATA_OBJECT:
{
NFGUID xID;
bRet = xID.FromString(strData);
SetObject(xID);
}
break;
default:
break;
}
return bRet;
}
bool NFCProperty::DeSerialization()
{
bool bRet = false;
const TDATA_TYPE eType = GetType();
if (eType == TDATA_STRING)
{
NFCDataList xDataList;
const std::string& strData = mxData->GetString();
xDataList.Split(strData.c_str(), ";");
for (int i = 0; i < xDataList.GetCount(); ++i)
{
if (nullptr == mxEmbeddedList)
{
mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>());
}
else
{
mxEmbeddedList->ClearAll();
}
if(xDataList.String(i).empty())
{
NFASSERT(0, strData, __FILE__, __FUNCTION__);
}
mxEmbeddedList->Add(xDataList.String(i));
}
if (nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0)
{
std::string strTemData;
for (bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData))
{
NFCDataList xTemDataList;
xTemDataList.Split(strTemData.c_str(), ",");
if (xTemDataList.GetCount() > 0)
{
if (xTemDataList.GetCount() != 2)
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
const std::string& strKey = xTemDataList.String(0);
const std::string& strValue = xTemDataList.String(0);
if (strKey.empty() || strValue.empty())
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
if (nullptr == mxEmbeddedMap)
{
mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>());
}
else
{
mxEmbeddedMap->ClearAll();
}
mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue)));
}
}
bRet = true;
}
}
return bRet;
}
const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const
{
return this->mxEmbeddedList;
}
const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const
{
return this->mxEmbeddedMap;
}
<|endoftext|>
|
<commit_before><commit_msg>fix timer<commit_after><|endoftext|>
|
<commit_before>#include "response.h"
#include <regex>
#include <iostream>
#include <algorithm>
using namespace std;
const char* STATUSLINE_PATTERN1 = "HTTP/([\\d\\.]+)\\s([\\d]+)\\s([\\w\\.-]+)\\r\\n";
const char* STATUSLINE_PATTERN = "(.*?)\\s(.*?)\\s(.*?)\\r\\n";
const char* HEADER_PATTERN = "(.*?):\\s(.*?)\\r\\n";
bool ci_compare(char lhs, char rhs)
{
return ::tolower(lhs) == ::tolower(rhs);
}
HttpResponse::HttpResponse() :
version_(""),
phrase_(""),
status_code_(0),
headers_(),
body_("")
{
}
HttpResponse::~HttpResponse()
{
}
bool HttpResponse::ParseStatus(const std::string & status)
{
regex rex(STATUSLINE_PATTERN);
smatch match;
if (regex_match(status, match, rex))
{
version_ = match.str(1);
status_code_ = stoi(match.str(2));
phrase_ = match.str(3);
return true;
}
cout << "could not parse status: " << status << endl;
return false;
}
bool HttpResponse::ParseHeader(const std::string & header)
{
regex rex(HEADER_PATTERN);
smatch match;
if (regex_match(header, match, rex))
{
headers_[match.str(1)] = match.str(2);
return true;
}
cout << "[Cound not parse header] " << header << endl;
return false;
}
std::string HttpResponse::Header(const string &key)
{
auto it = headers_.find(key);
if (it == headers_.end())
{
for(auto it : headers_)
{
if (it.first.size() == key.size() &&
std::equal(it.first.begin(), it.first.end(), key.begin(), ci_compare))
{
return it.second;
}
}
return "";
}
return it->second;
}
void HttpResponse::SetBody(char * buffer, unsigned int length, bool append)
{
if (!append)
{
body_.assign(buffer, length);
}
else
{
body_.append(buffer, length);
}
}
const char* HttpResponse::GetBody()
{
return body_.data();
}<commit_msg>removed dead code<commit_after>#include "response.h"
#include <regex>
#include <iostream>
#include <algorithm>
using namespace std;
const char* STATUSLINE_PATTERN = "(.*?)\\s(.*?)\\s(.*?)\\r\\n";
const char* HEADER_PATTERN = "(.*?):\\s(.*?)\\r\\n";
bool ci_compare(char lhs, char rhs)
{
return ::tolower(lhs) == ::tolower(rhs);
}
HttpResponse::HttpResponse() :
version_(""),
phrase_(""),
status_code_(0),
headers_(),
body_("")
{
}
HttpResponse::~HttpResponse()
{
}
bool HttpResponse::ParseStatus(const std::string & status)
{
regex rex(STATUSLINE_PATTERN);
smatch match;
if (regex_match(status, match, rex))
{
version_ = match.str(1);
status_code_ = stoi(match.str(2));
phrase_ = match.str(3);
return true;
}
cout << "could not parse status: " << status << endl;
return false;
}
bool HttpResponse::ParseHeader(const std::string & header)
{
regex rex(HEADER_PATTERN);
smatch match;
if (regex_match(header, match, rex))
{
headers_[match.str(1)] = match.str(2);
return true;
}
cout << "[Cound not parse header] " << header << endl;
return false;
}
std::string HttpResponse::Header(const string &key)
{
auto it = headers_.find(key);
if (it == headers_.end())
{
for(auto it : headers_)
{
if (it.first.size() == key.size() &&
std::equal(it.first.begin(), it.first.end(), key.begin(), ci_compare))
{
return it.second;
}
}
return "";
}
return it->second;
}
void HttpResponse::SetBody(char * buffer, unsigned int length, bool append)
{
if (!append)
{
body_.assign(buffer, length);
}
else
{
body_.append(buffer, length);
}
}
const char* HttpResponse::GetBody()
{
return body_.data();
}<|endoftext|>
|
<commit_before>/*
** Copyright 2014-2017 Robert Fratto. See the LICENSE.txt file at the top-level
** directory of this distribution.
**
** Licensed under the MIT license <http://opensource.org/licenses/MIT>. This file
** may not be copied, modified, or distributed except according to those terms.
*/
#include <gtest/gtest.h>
#include <sstream>
#include <stdexcept>
#include "lexeme.h"
#include "tokens.h"
#include "lexer.h"
using namespace orange::parse;
#define TEST_TOKEN(NAME, INPUT, EXPECTED_TOKEN) \
{\
std::stringstream ss(INPUT); \
Lexer lex(ss); \
EXPECT_EQ(lex.next().token, EXPECTED_TOKEN); \
}
#define TEST_VALUE(NAME, INPUT, EXPECTED_VALUE) \
{\
std::stringstream ss(INPUT); \
Lexer lex(ss); \
EXPECT_EQ(lex.next().value, EXPECTED_VALUE); \
}
#define TEST_INVALID(NAME, INPUT) \
{\
std::stringstream ss(INPUT); \
Lexer lex(ss); \
EXPECT_THROW(lex.next(), std::runtime_error); \
}
//
// NUMBERS TESTS
//
TEST(Lexer, TestTypes) {
TEST_TOKEN(BinaryNoSuffix, "0b01", Token::UINT_VAL);
TEST_TOKEN(OctalNoSuffix, "0o01234567", Token::UINT_VAL);
TEST_TOKEN(HexNoSuffix, "0x0123456789abcdefABCDEF", Token::UINT_VAL);
TEST_TOKEN(DecNoSuffix, "1234567890", Token::INT_VAL);
TEST_TOKEN(Double, "1234.567890", Token::DOUBLE_VAL);
TEST_TOKEN(Float, "1234.567890f", Token::FLOAT_VAL);
TEST_TOKEN(DoubleLeadZero, "1234.0567890", Token::DOUBLE_VAL);
TEST_TOKEN(FloatLeadZero, "1234.0567890f", Token::FLOAT_VAL);
}
TEST(Lexer, TestSuffixedTypes) {
TEST_TOKEN(BinarySuffixU, "0b11u", Token::UINT_VAL);
TEST_TOKEN(OctalSuffixU, "0o32u", Token::UINT_VAL);
TEST_TOKEN(HexSuffixU, "0xFAu", Token::UINT_VAL);
TEST_TOKEN(DecSuffixU, "12u", Token::UINT_VAL);
TEST_TOKEN(BinarySuffixU8, "0b11u8", Token::UINT8_VAL);
TEST_TOKEN(OctalSuffixU8, "0o32u8", Token::UINT8_VAL);
TEST_TOKEN(HexSuffixU8, "0xFAu8", Token::UINT8_VAL);
TEST_TOKEN(DecSuffixU8, "12u8", Token::UINT8_VAL);
TEST_TOKEN(BinarySuffixU16, "0b11u16", Token::UINT16_VAL);
TEST_TOKEN(OctalSuffixU16, "0o32u16", Token::UINT16_VAL);
TEST_TOKEN(HexSuffixU16, "0xFAu16", Token::UINT16_VAL);
TEST_TOKEN(DecSuffixU16, "12u16", Token::UINT16_VAL);
TEST_TOKEN(BinarySuffixU32, "0b11u32", Token::UINT32_VAL);
TEST_TOKEN(OctalSuffixU32, "0o32u32", Token::UINT32_VAL);
TEST_TOKEN(HexSuffixU32, "0xFAu32", Token::UINT32_VAL);
TEST_TOKEN(DecSuffixU32, "12u32", Token::UINT32_VAL);
TEST_TOKEN(BinarySuffixU64, "0b11u64", Token::UINT64_VAL);
TEST_TOKEN(OctalSuffixU64, "0o32u64", Token::UINT64_VAL);
TEST_TOKEN(HexSuffixU64, "0xFAu64", Token::UINT64_VAL);
TEST_TOKEN(DecSuffixU64, "12u64", Token::UINT64_VAL);
TEST_TOKEN(BinarySuffixI, "0b11i", Token::UINT_VAL);
TEST_TOKEN(OctalSuffixI, "0o32i", Token::UINT_VAL);
TEST_TOKEN(HexSuffixI, "0xFAi", Token::UINT_VAL);
TEST_TOKEN(DecSuffixI, "12i", Token::UINT_VAL);
TEST_TOKEN(BinarySuffixI8, "0b11i8", Token::UINT8_VAL);
TEST_TOKEN(OctalSuffixI8, "0o32i8", Token::UINT8_VAL);
TEST_TOKEN(HexSuffixI8, "0xFAi8", Token::UINT8_VAL);
TEST_TOKEN(DecSuffixI8, "12i8", Token::UINT8_VAL);
TEST_TOKEN(BinarySuffixI16, "0b11i16", Token::UINT16_VAL);
TEST_TOKEN(OctalSuffixI16, "0o32i16", Token::UINT16_VAL);
TEST_TOKEN(HexSuffixI16, "0xFAi16", Token::UINT16_VAL);
TEST_TOKEN(DecSuffixI16, "12i16", Token::UINT16_VAL);
TEST_TOKEN(BinarySuffixI32, "0b11i32", Token::UINT32_VAL);
TEST_TOKEN(OctalSuffixI32, "0o32i32", Token::UINT32_VAL);
TEST_TOKEN(HexSuffixI32, "0xFAi32", Token::UINT32_VAL);
TEST_TOKEN(DecSuffixI32, "12i32", Token::UINT32_VAL);
TEST_TOKEN(BinarySuffixI64, "0b11i64", Token::UINT64_VAL);
TEST_TOKEN(OctalSuffixI64, "0o32i64", Token::UINT64_VAL);
TEST_TOKEN(HexSuffixI64, "0xFAi64", Token::UINT64_VAL);
TEST_TOKEN(DecSuffixI64, "12i64", Token::UINT64_VAL);
}
TEST(Lexer, TestSeparators) {
TEST_TOKEN(BinarySep, "0b0000_1111_1010_2_1__2", Token::UINT_VAL);
TEST_TOKEN(OctalSep, "0o12_345_76__3", Token::UINT_VAL);
TEST_TOKEN(HexSep, "0xAAAA_BBBB_C_D_123", Token::UINT_VAL);
TEST_TOKEN(DecSep, "123_456_78_9", Token::INT_VAL);
TEST_TOKEN(DoubleSep, "12_34.5_6_78__90", Token::DOUBLE_VAL);
TEST_TOKEN(FloatSetp, "12_34.5_67__89_0_f", Token::FLOAT_VAL);
}
TEST(Lexer, TestValues) {
TEST_VALUE(BinaryVal, "0b1111", "15");
TEST_VALUE(OctalVal, "0o75", "61");
TEST_VALUE(HexVal, "0xF1", "241");
TEST_VALUE(DecVal, "9501", "9501");
TEST_VALUE(DoubleVal, "59.210", "59.210");
TEST_VALUE(FloatVal, "989.210f", "989.210");
}
TEST(Lexer, LeadingZeroesValues) {
TEST_VALUE(BinaryValLeadZero, "0b01111", "15");
TEST_VALUE(OctalValLeadZero, "0o075", "61");
TEST_VALUE(HexValLeadZero, "0x0F1", "241");
}
TEST(Lexer, ValuesWithSuffixes) {
TEST_VALUE(BinarySuffixU, "0b11u", "3");
TEST_VALUE(OctalSuffixU, "0o32u", "26");
TEST_VALUE(HexSuffixU, "0xFAu", "250");
TEST_VALUE(DecSuffixU, "12u", "12");
TEST_VALUE(BinarySuffixU8, "0b11u8", "3");
TEST_VALUE(OctalSuffixU8, "0o32u8", "26");
TEST_VALUE(HexSuffixU8, "0xFAu8", "250");
TEST_VALUE(DecSuffixU8, "12u8", "12");
TEST_VALUE(BinarySuffixU16, "0b11u16", "3");
TEST_VALUE(OctalSuffixU16, "0o32u16", "26");
TEST_VALUE(HexSuffixU16, "0xFAu16", "250");
TEST_VALUE(DecSuffixU16, "12u16", "12");
TEST_VALUE(BinarySuffixU32, "0b11u32", "3");
TEST_VALUE(OctalSuffixU32, "0o32u32", "26");
TEST_VALUE(HexSuffixU32, "0xFAu32", "250");
TEST_VALUE(DecSuffixU32, "12u32", "12");
TEST_VALUE(BinarySuffixU64, "0b11u64", "3");
TEST_VALUE(OctalSuffixU64, "0o32u64", "26");
TEST_VALUE(HexSuffixU64, "0xFAu64", "250");
TEST_VALUE(DecSuffixU64, "12u64", "12");
TEST_VALUE(BinarySuffixI, "0b11i", "3");
TEST_VALUE(OctalSuffixI, "0o32i", "26");
TEST_VALUE(HexSuffixI, "0xFAi", "250");
TEST_VALUE(DecSuffixI, "12i", "12");
TEST_VALUE(BinarySuffixI8, "0b11i8", "3");
TEST_VALUE(OctalSuffixI8, "0o32i8", "26");
TEST_VALUE(HexSuffixI8, "0xFAi8", "250");
TEST_VALUE(DecSuffixI8, "12i8", "12");
TEST_VALUE(BinarySuffixI16, "0b11i16", "3");
TEST_VALUE(OctalSuffixI16, "0o32i16", "26");
TEST_VALUE(HexSuffixI16, "0xFAi16", "250");
TEST_VALUE(DecSuffixI16, "12i16", "12");
TEST_VALUE(BinarySuffixI32, "0b11i32", "3");
TEST_VALUE(OctalSuffixI32, "0o32i32", "26");
TEST_VALUE(HexSuffixI32, "0xFAi32", "250");
TEST_VALUE(DecSuffixI32, "12i32", "12");
TEST_VALUE(BinarySuffixI64, "0b11i64", "3");
TEST_VALUE(OctalSuffixI64, "0o32i64", "26");
TEST_VALUE(HexSuffixI64, "0xFAi64", "250");
TEST_VALUE(DecSuffixI64, "12i64", "12");
}
TEST(Lexer, InvalidNumbers) {
TEST_INVALID(LeadingZeroLetter, "0d51");
TEST_INVALID(LeadingZeroNumber, "052");
TEST_INVALID(InvalidSuffix, "32z");
}
<commit_msg>Refactor test_lexer.cc<commit_after>/*
** Copyright 2014-2017 Robert Fratto. See the LICENSE.txt file at the top-level
** directory of this distribution.
**
** Licensed under the MIT license <http://opensource.org/licenses/MIT>. This file
** may not be copied, modified, or distributed except according to those terms.
*/
#include <gtest/gtest.h>
#include <sstream>
#include <stdexcept>
#include "lexeme.h"
#include "tokens.h"
#include "lexer.h"
using namespace orange::parse;
#define TEST_TOKEN(INPUT, EXPECTED_TOKEN) \
{\
std::stringstream ss(INPUT); \
Lexer lex(ss); \
EXPECT_EQ(lex.next().token, EXPECTED_TOKEN); \
}
#define TEST_VALUE(INPUT, EXPECTED_VALUE) \
{\
std::stringstream ss(INPUT); \
Lexer lex(ss); \
EXPECT_EQ(lex.next().value, EXPECTED_VALUE); \
}
#define TEST_INVALID(INPUT) \
{\
std::stringstream ss(INPUT); \
Lexer lex(ss); \
EXPECT_THROW(lex.next(), std::runtime_error); \
}
//
// NUMBERS TESTS
//
TEST(Lexer, TestTypes) {
std::map<std::string, Token> testTable = {
{"0b01", Token::UINT_VAL},
{"0o01234567", Token::UINT_VAL},
{"0x0123456789abcdefABCDEF", Token::UINT_VAL},
{"1234567890", Token::INT_VAL},
{"1234.567890", Token::DOUBLE_VAL},
{"1234.567890f", Token::FLOAT_VAL},
{"1234.0567890", Token::DOUBLE_VAL},
{"1234.0567890f", Token::FLOAT_VAL},
};
for (auto row : testTable) {
TEST_TOKEN(row.first, row.second);
}
}
TEST(Lexer, TestSuffixedTypes) {
std::map<std::string, Token> testTable = {
{"0b11u", Token::UINT_VAL},
{"0o32u", Token::UINT_VAL},
{"0xFAu", Token::UINT_VAL},
{"12u", Token::UINT_VAL},
{"0b11u8", Token::UINT8_VAL},
{"0o32u8", Token::UINT8_VAL},
{"0xFAu8", Token::UINT8_VAL},
{"12u8", Token::UINT8_VAL},
{"0b11u16", Token::UINT16_VAL},
{"0o32u16", Token::UINT16_VAL},
{"0xFAu16", Token::UINT16_VAL},
{"12u16", Token::UINT16_VAL},
{"0b11u32", Token::UINT32_VAL},
{"0o32u32", Token::UINT32_VAL},
{"0xFAu32", Token::UINT32_VAL},
{"12u32", Token::UINT32_VAL},
{"0b11u64", Token::UINT64_VAL},
{"0o32u64", Token::UINT64_VAL},
{"0xFAu64", Token::UINT64_VAL},
{"12u64", Token::UINT64_VAL},
{"0b11i", Token::UINT_VAL},
{"0o32i", Token::UINT_VAL},
{"0xFAi", Token::UINT_VAL},
{"12i", Token::UINT_VAL},
{"0b11i8", Token::UINT8_VAL},
{"0o32i8", Token::UINT8_VAL},
{"0xFAi8", Token::UINT8_VAL},
{"12i8", Token::UINT8_VAL},
{"0b11i16", Token::UINT16_VAL},
{"0o32i16", Token::UINT16_VAL},
{"0xFAi16", Token::UINT16_VAL},
{"12i16", Token::UINT16_VAL},
{"0b11i32", Token::UINT32_VAL},
{"0o32i32", Token::UINT32_VAL},
{"0xFAi32", Token::UINT32_VAL},
{"12i32", Token::UINT32_VAL},
{"0b11i64", Token::UINT64_VAL},
{"0o32i64", Token::UINT64_VAL},
{"0xFAi64", Token::UINT64_VAL},
{"12i64", Token::UINT64_VAL},
};
for (auto row : testTable) {
TEST_TOKEN(row.first, row.second);
}
}
TEST(Lexer, TestSeparators) {
std::map<std::string, Token> testTable = {
{"0b0000_1111_1010_2_1__2", Token::UINT_VAL},
{"0o12_345_76__3", Token::UINT_VAL},
{"0xAAAA_BBBB_C_D_123", Token::UINT_VAL},
{"123_456_78_9", Token::INT_VAL},
{"12_34.5_6_78__90", Token::DOUBLE_VAL},
{"12_34.5_67__89_0_f", Token::FLOAT_VAL},
};
for (auto row : testTable) {
TEST_TOKEN(row.first, row.second);
}
}
TEST(Lexer, TestValues) {
std::map<std::string, std::string> testTable = {
{"0b1111", "15"},
{"0o75", "61"},
{"0xF1", "241"},
{"9501", "9501"},
{"59.210", "59.210"},
{"989.210f", "989.210"},
};
for (auto row : testTable) {
TEST_VALUE(row.first, row.second);
}
}
TEST(Lexer, LeadingZeroesValues) {
std::map<std::string, std::string> testTable = {
{"0b01111", "15"},
{"0o075", "61"},
{"0x0F1", "241"},
};
for (auto row : testTable) {
TEST_VALUE(row.first, row.second);
}
}
TEST(Lexer, ValuesWithSuffixes) {
std::map<std::string, std::string> testTable = {
{"0b11u", "3"},
{"0o32u", "26"},
{"0xFAu", "250"},
{"12u", "12"},
{"0b11u8", "3"},
{"0o32u8", "26"},
{"0xFAu8", "250"},
{"12u8", "12"},
{"0b11u16", "3"},
{"0o32u16", "26"},
{"0xFAu16", "250"},
{"12u16", "12"},
{"0b11u32", "3"},
{"0o32u32", "26"},
{"0xFAu32", "250"},
{"12u32", "12"},
{"0b11u64", "3"},
{"0o32u64", "26"},
{"0xFAu64", "250"},
{"12u64", "12"},
{"0b11i", "3"},
{"0o32i", "26"},
{"0xFAi", "250"},
{"12i", "12"},
{"0b11i8", "3"},
{"0o32i8", "26"},
{"0xFAi8", "250"},
{"12i8", "12"},
{"0b11i16", "3"},
{"0o32i16", "26"},
{"0xFAi16", "250"},
{"12i16", "12"},
{"0b11i32", "3"},
{"0o32i32", "26"},
{"0xFAi32", "250"},
{"12i32", "12"},
{"0b11i64", "3"},
{"0o32i64", "26"},
{"0xFAi64", "250"},
{"12i64", "12"},
};
for (auto row : testTable) {
TEST_VALUE(row.first, row.second);
}
}
TEST(Lexer, InvalidNumbers) {
std::vector<std::string> testTable = {
"0d51",
"052",
"32z",
};
for (auto row : testTable) {
TEST_INVALID(row);
}
}
<|endoftext|>
|
<commit_before>// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
int main()
{
}
<commit_msg>Test commit: Reverting whitespace changes<commit_after>// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
int main()
{
}
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_basic/queued_action_server.h>
#include <queue>
#include <memory>
#include <mutex>
#include <condition_variable>
class GoalQueueSuite : public ::testing::Test {
protected:
virtual void SetUp() {
resetFlags();
ros::NodeHandle actionNh("");
qserv.reset(new actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction> (actionNh, "queue_server", boost::bind(&GoalQueueSuite::executeCallback, this, _1)));
cli.reset(new actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> ("queue_server", true)); // true -> don't need ros::spin()
qserv->start();
}
virtual void TearDown() {
// Kill the executeCallback if it is running
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); // Releases one waiting thread
}
qserv->shutdown();
}
void executeCallback(const move_base_msgs::MoveBaseGoalConstPtr &msg) {
resetFlags();
got_goal = true;
received_goal = msg;
while (true) {
goal_preempted = qserv->isPreemptRequested() ? true : false;
next_goal_available = qserv->isNewGoalAvailable() ? true : false;
// Test fixture can continue
execution = true;
sleep_cv.notify_one();
// Wait until signalled to end
std::unique_lock<std::mutex> lk(execute_lock);
execute_cv.wait(lk,
//lambda function to wait on our bool variables
[this](){return finish_executing || resume_executing;} // blocks only if lambda returns false
);
execution = false;
// We were requested to stop, so we stop
if (finish_executing) {
break;
}
}
// Signal that we are done here
std::lock_guard<std::mutex> lk(execute_done_lock);
execute_done = true;
execute_done_cv.notify_all();
}
// Helper function to signal the executeCallback to end
void finishExecuting() {
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); //unlocks lambda waiting function in ExecuteCallback
}
// Wait for execute callback to actually finish
std::unique_lock<std::mutex> lk2(execute_done_lock);
execute_done_cv.wait(lk2, [this]() {return execute_done;}); // at the end of ExecuteCallback
}
// Helper function to signal the executeCallback to resume
// This is useful for seeing if the callback code sees a preempt
void resumeExecuting() {
std::lock_guard<std::mutex> lk(execute_lock);
resume_executing = true;
execute_cv.notify_one();
}
// Helper function to wait to for flags to update in ExecuteCallback
void sleepExecuting() {
std::unique_lock<std::mutex> slk(sleep_lock);
sleep_cv.wait(slk,
[this](){return execution;}
);
}
void updateExecuting() {
std::unique_lock<std::mutex> ulk(update_lock);
sleep_cv.wait(ulk,
[this](){return !execution;}
);
}
void resetFlags() {
got_goal = false;
goal_preempted = false;
next_goal_available = false;
received_goal = nullptr;
// Signal flags
execution = false;
finish_executing = false;
resume_executing = false;
execute_done = false;
}
// Flags for assertions
bool got_goal;
bool goal_preempted;
bool next_goal_available;
move_base_msgs::MoveBaseGoalConstPtr received_goal;
// Signaling variables
bool execution;
bool finish_executing;
bool resume_executing;
bool execute_done;
std::mutex sleep_lock;
std::mutex update_lock;
std::mutex execute_lock;
std::mutex execute_done_lock;
std::condition_variable sleep_cv;
std::condition_variable execute_cv;
std::condition_variable execute_done_cv;
std::unique_ptr<actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction>> qserv;
std::unique_ptr<actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>> cli;
};
TEST_F(GoalQueueSuite, addGoalWhileExecuting) {
move_base_msgs::MoveBaseGoal goal;
// First goal
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_FALSE(goal_preempted);
EXPECT_FALSE(next_goal_available);
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Second goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
resumeExecuting();
updateExecuting();
sleepExecuting();
EXPECT_TRUE(next_goal_available);
// Cancel the last goal sent
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x); // Making sure we are in the first goal thread
finishExecuting(); // Finish 1st goal
ros::Duration(0.5).sleep();
EXPECT_TRUE(goal_preempted);
finishExecuting(); // Finish 2nd (canceled) goal
// New goal
goal.target_pose.pose.position.x = 13.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_FALSE(goal_preempted);
EXPECT_EQ(13.0, received_goal->target_pose.pose.position.x);
finishExecuting(); // Finish new goal
// - if another goal is received add it to the queue (DONE)
// - if the queue full, set the next goal as preempted - explicitly called! - so cancelling the next goal and adding new to the queue
// - start executing the new goal in queue (after the current)
}
TEST_F(GoalQueueSuite, stopAfterCancel) {
move_base_msgs::MoveBaseGoal goal;
// One goal -> Cancel request -> Stop
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
resumeExecuting();
updateExecuting();
sleepExecuting();
ros::Duration(0.5).sleep();
// EXPECT_TRUE(goal_preempted);
finishExecuting();
ros::Duration(0.5).sleep();
EXPECT_FALSE(qserv->isActive());
// - if a cancel request is received for the current goal, set it as preempted (DONE)
// - if no goal, stop (DONE)
}
TEST_F(GoalQueueSuite, continueAfterCancel) {
move_base_msgs::MoveBaseGoal goal;
// Two goals -> Cancel current goal -> Start executing the second
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Cancelling the first goal - PITFALL
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
resumeExecuting();
updateExecuting();
sleepExecuting();
ASSERT_TRUE(goal_preempted);
finishExecuting(); // Finish the preempted goal
// "Second" goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
ASSERT_EQ(7.0, received_goal->target_pose.pose.position.x);
finishExecuting(); // Finish 2nd goal
// - if a cancel request is received for the current goal, set it as preempted (DONE)
// - if there another goal, start executing it
}
TEST_F(GoalQueueSuite, goalCancelling) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
// Two goals -> Cancel current goal -> Start executing the second
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Second goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
resumeExecuting();
updateExecuting();
sleepExecuting();
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x); // Making sure we are in the first goal thread
EXPECT_TRUE(next_goal_available);
// Cancelling the second goal
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
finishExecuting(); // finish 1st goal
ros::Duration(0.5).sleep(); // Needs to wait so the executeCallback can finish
EXPECT_TRUE(goal_preempted); // Must be checked in the goal-thread that is cancelled
finishExecuting(); // Finish the cancelled goal
// - if a cancel request on the "next_goal" received, remove it from the queue and set it as cancelled
}
// Two more TEST_F missing
int main(int argc, char **argv) {
ros::init(argc, argv, "goal_queueing_test");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Clean version.<commit_after>#include <gtest/gtest.h>
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_basic/queued_action_server.h>
#include <queue>
#include <memory>
#include <mutex>
#include <condition_variable>
class GoalQueueSuite : public ::testing::Test {
protected:
virtual void SetUp() {
resetFlags();
ros::NodeHandle actionNh("");
qserv.reset(new actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction> (actionNh, "queue_server", boost::bind(&GoalQueueSuite::executeCallback, this, _1)));
cli.reset(new actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> ("queue_server", true)); // true -> don't need ros::spin()
qserv->start();
}
virtual void TearDown() {
// Kill the executeCallback if it is running
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); // Releases one waiting thread
}
qserv->shutdown();
}
void executeCallback(const move_base_msgs::MoveBaseGoalConstPtr &msg) {
resetFlags();
got_goal = true;
received_goal = msg;
while (true) {
goal_preempted = qserv->isPreemptRequested() ? true : false;
next_goal_available = qserv->isNewGoalAvailable() ? true : false;
// Test fixture can continue
execution = true;
sleep_cv.notify_one();
// Wait until signalled to end
std::unique_lock<std::mutex> lk(execute_lock);
execute_cv.wait(lk,
//lambda function to wait on our bool variables
[this](){return finish_executing || resume_executing;} // blocks only if lambda returns false
);
execution = false;
// We were requested to stop, so we stop
if (finish_executing) {
break;
}
}
// Signal that we are done here
std::lock_guard<std::mutex> lk(execute_done_lock);
execute_done = true;
execute_done_cv.notify_all();
}
// Helper function to signal the executeCallback to end
void finishExecuting() {
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); //unlocks lambda waiting function in ExecuteCallback
}
// Wait for execute callback to actually finish
std::unique_lock<std::mutex> lk2(execute_done_lock);
execute_done_cv.wait(lk2, [this]() {return execute_done;}); // at the end of ExecuteCallback
}
// Helper function to signal the executeCallback to resume
// This is useful for seeing if the callback code sees a preempt
void resumeExecuting() {
std::lock_guard<std::mutex> lk(execute_lock);
resume_executing = true;
execute_cv.notify_one();
}
// Helper function to wait to for flags to update in ExecuteCallback
void sleepExecuting() {
std::unique_lock<std::mutex> slk(sleep_lock);
sleep_cv.wait(slk,
[this](){return execution;}
);
}
// Helper function to wait for execution variable to update
void updateExecuting() {
std::unique_lock<std::mutex> ulk(update_lock);
sleep_cv.wait(ulk,
[this](){return !execution;}
);
}
void resetFlags() {
got_goal = false;
goal_preempted = false;
next_goal_available = false;
received_goal = nullptr;
// Signal flags
execution = false;
finish_executing = false;
resume_executing = false;
execute_done = false;
}
// Flags for assertions
bool got_goal;
bool goal_preempted;
bool next_goal_available;
move_base_msgs::MoveBaseGoalConstPtr received_goal;
// Signaling variables
bool execution;
bool finish_executing;
bool resume_executing;
bool execute_done;
std::mutex sleep_lock;
std::mutex update_lock;
std::mutex execute_lock;
std::mutex execute_done_lock;
std::condition_variable sleep_cv;
std::condition_variable execute_cv;
std::condition_variable execute_done_cv;
std::unique_ptr<actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction>> qserv;
std::unique_ptr<actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>> cli;
};
TEST_F(GoalQueueSuite, addGoalWhileExecuting) {
move_base_msgs::MoveBaseGoal goal;
// First goal
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_FALSE(goal_preempted);
EXPECT_FALSE(next_goal_available);
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Second goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
resumeExecuting();
updateExecuting();
sleepExecuting();
EXPECT_TRUE(next_goal_available);
// Cancel the last goal sent
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x); // Making sure we are in the first goal thread
finishExecuting(); // Finish 1st goal
ros::Duration(0.5).sleep();
EXPECT_TRUE(goal_preempted);
finishExecuting(); // Finish 2nd (canceled) goal
// New goal
goal.target_pose.pose.position.x = 13.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_FALSE(goal_preempted);
EXPECT_EQ(13.0, received_goal->target_pose.pose.position.x);
finishExecuting();
}
TEST_F(GoalQueueSuite, stopAfterCancel) {
move_base_msgs::MoveBaseGoal goal;
// One goal -> Cancel request -> Stop
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
resumeExecuting();
updateExecuting();
sleepExecuting();
ros::Duration(0.5).sleep();
// EXPECT_TRUE(goal_preempted); // TODO: Sometimes failling
finishExecuting();
ros::Duration(0.5).sleep();
EXPECT_FALSE(qserv->isActive());
}
TEST_F(GoalQueueSuite, continueAfterCancel) {
move_base_msgs::MoveBaseGoal goal;
// Two goals -> Cancel current goal -> Start executing the second
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
EXPECT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Cancelling the first goal - PITFALL
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
resumeExecuting();
updateExecuting();
sleepExecuting();
ASSERT_TRUE(goal_preempted);
finishExecuting();
// "Second" goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
EXPECT_TRUE(got_goal);
ASSERT_EQ(7.0, received_goal->target_pose.pose.position.x);
finishExecuting();
}
TEST_F(GoalQueueSuite, goalCancelling) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
// Two goals -> Cancel current goal -> Start executing the second
cli->sendGoal(goal);
ros::spinOnce();
sleepExecuting();
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Second goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
resumeExecuting();
updateExecuting();
sleepExecuting();
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
EXPECT_TRUE(next_goal_available);
// Cancelling the second goal
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
finishExecuting(); // finish 1st goal
ros::Duration(0.5).sleep(); // Needs to wait so the executeCallback can finish
EXPECT_TRUE(goal_preempted);
finishExecuting(); // Finish the cancelled goal
}
// Two more TEST_F missing
int main(int argc, char **argv) {
ros::init(argc, argv, "goal_queueing_test");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <atomic>
#include <queue>
#include <pthread.h>
#include <libprecisegc/details/utils/make_unique.hpp>
#include <libprecisegc/details/utils/scoped_thread.hpp>
#include <libprecisegc/details/utils/scope_guard.hpp>
#include <libprecisegc/details/threads/managed_thread.hpp>
#include <libprecisegc/details/serial_garbage_collector.hpp>
#include <libprecisegc/details/incremental_garbage_collector.hpp>
#include <libprecisegc/gc_ptr.h>
#include <libprecisegc/gc_new.h>
#include <libprecisegc/gc.h>
#include <libprecisegc/details/gc_mark.h>
#include <libprecisegc/details/barrier.h>
#include <libprecisegc/details/utils/math.h>
using namespace precisegc;
using namespace precisegc::details;
#define DEBUG_PRINT_TREE
namespace {
const int TREE_DEPTH = 2;
const int THREADS_COUNT = 4; // must be power of 2 and <= 2^(TREE_DEPTH)
const size_t LIVE_LEVEL = ::log2(THREADS_COUNT);
struct node
{
gc_ptr<node> m_left;
gc_ptr<node> m_right;
};
gc_ptr<node> create_gc_node()
{
return gc_new<node>();
}
gc_ptr<node> create_tree(size_t depth)
{
std::queue<gc_ptr<node>> q;
const size_t LEAFS_CNT = pow(2, depth);
for (int i = 0; i < LEAFS_CNT; ++i) {
q.push(create_gc_node());
}
while (q.size() > 1) {
auto parent = create_gc_node();
parent->m_left = q.front();
q.pop();
parent->m_right = q.front();
q.pop();
q.push(parent);
}
return q.front();
}
void unmark_tree(const gc_ptr<node>& ptr)
{
if (ptr) {
gc_pin<node> pin(ptr);
set_object_mark(pin.get(), false);
unmark_tree(ptr->m_left);
unmark_tree(ptr->m_right);
}
}
void print_tree(const gc_ptr<node>& root, const std::string& offset = "")
{
#ifdef DEBUG_PRINT_TREE
if (!root) {
std::cout << offset << "nullptr" << std::endl;
return;
}
gc_pin<node> pin(root);
std::cout << offset << &root << " (" << pin.get() << ") [" << get_object_mark(pin.get()) << "]" << std::endl;
auto new_offset = offset + " ";
print_tree(root->m_left, new_offset);
print_tree(root->m_right, new_offset);
#endif
}
void print_tree(node* root, const std::string& offset = "")
{
#ifdef DEBUG_PRINT_TREE
std::cout << offset << "nullptr" << " (" << root << ") [" << get_object_mark(root) << "]" << std::endl;
auto new_offset = offset + " ";
print_tree(root->m_left, new_offset);
print_tree(root->m_right, new_offset);
#endif
}
void generate_random_child(gc_ptr<node> ptr)
{
while (true) {
gc_ptr<node>& new_ptr = rand() % 2 ? ptr->m_left : ptr->m_right;
if (!new_ptr || rand() % 4 == 0) {
new_ptr = create_gc_node();
return;
} else {
ptr = new_ptr;
}
}
}
void check_nodes(node* ptr, size_t depth)
{
if (depth < LIVE_LEVEL) {
EXPECT_FALSE(get_object_mark(ptr)) << "ptr=" << ptr;
} else if (depth == LIVE_LEVEL) {
EXPECT_TRUE(get_object_mark(ptr)) << "ptr=" << ptr;
}
if (ptr->m_left) {
gc_pin<node> pin(ptr->m_left);
check_nodes(pin.get(), depth + 1);
}
if (ptr->m_right) {
gc_pin<node> pin(ptr->m_right);
check_nodes(pin.get(), depth + 1);
}
}
std::atomic<int> thread_num(0);
std::atomic<bool> gc_finished(false);
barrier threads_ready(THREADS_COUNT + 1);
static void* thread_routine(void* arg)
{
gc_ptr<node>& root = *((gc_ptr<node>*) arg);
int num = thread_num++;
// assign to each thread a leaf in the tree
gc_ptr<node> ptr = root;
for (int i = 0; i < ::log2(THREADS_COUNT); ++i, num /= 2) {
ptr = num % 2 ? ptr->m_left : ptr->m_right;
}
threads_ready.wait();
while (!gc_finished) {
generate_random_child(ptr);
// sleep(1);
}
}
}
/**
* The following test fixture creates tree and starts several threads.
* In each thread gc pointer to some node in the tree is saved.
* Then the original root is saved in a raw pointer and gc_ptr to it is reset.
* It is assumed that then test code will perform gc or one of it phases (marking, compacting),
* and the top levels of tree, that are not reachable from thread's gc pointers, will be freed.
*
* 0 <--------------- root
* / \
* 0 0
* / \ /\
* * * * * <---------- pointers to these nodes are saved in thread's program stacks
* / \ / \
* * * * * <--------- all nodes below are randomly generated in threads
*/
struct gc_test: public ::testing::Test
{
gc_test(std::unique_ptr<gc_interface> new_gc)
{
old_gc = gc_reset(std::move(new_gc));
auto guard = utils::make_scope_guard([this] {
gc_set(std::move(old_gc));
});
srand(time(nullptr));
gc_finished = false;
thread_num = 0;
std::cout << "Creating tree" << std::endl;
root = create_tree(TREE_DEPTH);
unmark_tree(root);
print_tree(root);
for (auto& thread: threads) {
thread = threads::managed_thread::create(thread_routine, (void*) &root);
}
threads_ready.wait();
// save root in raw pointer and then null gc_ptr to collect it during gc
gc_pin<node> pin(root);
root_raw = pin.get();
root.reset();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
guard.commit();
}
~gc_test()
{
auto guard = utils::make_scope_guard([this] {
gc_set(std::move(old_gc));
});
for (auto& thread: threads) {
thread.join();
}
}
gc_ptr<node> root;
utils::scoped_thread threads[THREADS_COUNT];
node* root_raw;
std::unique_ptr<gc_interface> old_gc;
};
struct serial_gc_test : public gc_test
{
serial_gc_test()
: gc_test(utils::make_unique<serial_garbage_collector>(gc_compacting::DISABLED, utils::make_unique<empty_policy>()))
{
garbage_collector = static_cast<serial_garbage_collector*>(gc_get());
}
serial_garbage_collector* garbage_collector;
};
struct incremental_gc_test : public gc_test
{
incremental_gc_test()
: gc_test(utils::make_unique<incremental_garbage_collector>(gc_compacting::DISABLED, utils::make_unique<incremental_empty_policy>()))
{
garbage_collector = static_cast<incremental_garbage_collector*>(gc_get());
}
incremental_garbage_collector* garbage_collector;
};
// This test doesn't check anything.
// Consider it is passed if nothing will crash or hang.
TEST_F(serial_gc_test, test_serial_gc)
{
garbage_collector->gc();
gc_finished = true;
print_tree(root_raw);
}
TEST_F(incremental_gc_test, test_marking)
{
incremental_gc_ops ops;
ops.phase = gc_phase::MARKING;
ops.concurrent_flag = true;
ops.threads_num = 1;
garbage_collector->incremental_gc(ops);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
ops.phase = gc_phase::IDLING;
ops.concurrent_flag = false;
ops.threads_num = 0;
garbage_collector->incremental_gc(ops);
gc_finished = true;
print_tree(root_raw);
check_nodes(root_raw, 0);
}
TEST_F(incremental_gc_test, test_sweeping)
{
incremental_gc_ops ops;
ops.phase = gc_phase::SWEEPING;
ops.concurrent_flag = false;
ops.threads_num = 1;
garbage_collector->incremental_gc(ops);
gc_finished = true;
print_tree(root_raw);
}
//TEST_F(gc_test, test_marking)
//{
// auto& collector = gc_garbage_collector::instance();
// std::cout << "Start marking" << std::endl;
// collector.start_marking();
// std::this_thread::sleep_for(std::chrono::milliseconds(10));
// std::cout << "Pause marking" << std::endl;
//
// gc_finished = true;
// collector.force_move_to_idle();
//
// std::cout << std::endl;
// print_tree(root_raw);
// // travers tree and check marks of objects
// check_nodes(root_raw, 0);
//
// collector.force_move_to_idle();
//}
<commit_msg>fix gc_test<commit_after>#include <gtest/gtest.h>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <atomic>
#include <queue>
#include <pthread.h>
#include <libprecisegc/details/utils/make_unique.hpp>
#include <libprecisegc/details/utils/scoped_thread.hpp>
#include <libprecisegc/details/utils/scope_guard.hpp>
#include <libprecisegc/details/threads/managed_thread.hpp>
#include <libprecisegc/details/serial_garbage_collector.hpp>
#include <libprecisegc/details/incremental_garbage_collector.hpp>
#include <libprecisegc/gc_ptr.h>
#include <libprecisegc/gc_new.h>
#include <libprecisegc/gc.h>
#include <libprecisegc/details/gc_mark.h>
#include <libprecisegc/details/barrier.h>
#include <libprecisegc/details/utils/math.h>
using namespace precisegc;
using namespace precisegc::details;
#define DEBUG_PRINT_TREE
namespace {
const int TREE_DEPTH = 2;
const int THREADS_COUNT = 4; // must be power of 2 and <= 2^(TREE_DEPTH)
const size_t LIVE_LEVEL = ::log2(THREADS_COUNT);
struct node
{
gc_ptr<node> m_left;
gc_ptr<node> m_right;
};
gc_ptr<node> create_gc_node()
{
return gc_new<node>();
}
gc_ptr<node> create_tree(size_t depth)
{
std::queue<gc_ptr<node>> q;
const size_t LEAFS_CNT = pow(2, depth);
for (int i = 0; i < LEAFS_CNT; ++i) {
q.push(create_gc_node());
}
while (q.size() > 1) {
auto parent = create_gc_node();
parent->m_left = q.front();
q.pop();
parent->m_right = q.front();
q.pop();
q.push(parent);
}
return q.front();
}
void unmark_tree(const gc_ptr<node>& ptr)
{
if (ptr) {
gc_pin<node> pin(ptr);
set_object_mark(pin.get(), false);
unmark_tree(ptr->m_left);
unmark_tree(ptr->m_right);
}
}
void print_tree(const gc_ptr<node>& root, const std::string& offset = "")
{
#ifdef DEBUG_PRINT_TREE
if (!root) {
std::cout << offset << "nullptr" << std::endl;
return;
}
gc_pin<node> pin(root);
std::cout << offset << &root << " (" << pin.get() << ") [" << get_object_mark(pin.get()) << "]" << std::endl;
auto new_offset = offset + " ";
print_tree(root->m_left, new_offset);
print_tree(root->m_right, new_offset);
#endif
}
void print_tree(node* root, const std::string& offset = "")
{
#ifdef DEBUG_PRINT_TREE
std::cout << offset << "nullptr" << " (" << root << ") [" << get_object_mark(root) << "]" << std::endl;
auto new_offset = offset + " ";
print_tree(root->m_left, new_offset);
print_tree(root->m_right, new_offset);
#endif
}
void generate_random_child(gc_ptr<node> ptr)
{
while (true) {
gc_pin<node> pin(ptr);
gc_ptr<node> new_ptr = rand() % 2 ? pin->m_left : pin->m_right;
if (!new_ptr || rand() % 4 == 0) {
new_ptr = create_gc_node();
return;
} else {
ptr = new_ptr;
}
}
}
void check_nodes(node* ptr, size_t depth)
{
if (depth < LIVE_LEVEL) {
EXPECT_FALSE(get_object_mark(ptr)) << "ptr=" << ptr;
} else if (depth == LIVE_LEVEL) {
EXPECT_TRUE(get_object_mark(ptr)) << "ptr=" << ptr;
}
if (ptr->m_left) {
gc_pin<node> pin(ptr->m_left);
check_nodes(pin.get(), depth + 1);
}
if (ptr->m_right) {
gc_pin<node> pin(ptr->m_right);
check_nodes(pin.get(), depth + 1);
}
}
std::atomic<int> thread_num(0);
std::atomic<bool> gc_finished(false);
barrier threads_ready(THREADS_COUNT + 1);
static void* thread_routine(void* arg)
{
gc_ptr<node>& root = *((gc_ptr<node>*) arg);
int num = thread_num++;
// assign to each thread a leaf in the tree
gc_ptr<node> ptr = root;
for (int i = 0; i < ::log2(THREADS_COUNT); ++i, num /= 2) {
ptr = num % 2 ? ptr->m_left : ptr->m_right;
}
threads_ready.wait();
while (!gc_finished) {
generate_random_child(ptr);
// sleep(1);
}
}
}
/**
* The following test fixture creates tree and starts several threads.
* In each thread gc pointer to some node in the tree is saved.
* Then the original root is saved in a raw pointer and gc_ptr to it is reset.
* It is assumed that then test code will perform gc or one of it phases (marking, compacting),
* and the top levels of tree, that are not reachable from thread's gc pointers, will be freed.
*
* 0 <--------------- root
* / \
* 0 0
* / \ /\
* * * * * <---------- pointers to these nodes are saved in thread's program stacks
* / \ / \
* * * * * <--------- all nodes below are randomly generated in threads
*/
struct gc_test: public ::testing::Test
{
gc_test(std::unique_ptr<gc_interface> new_gc)
{
old_gc = gc_reset(std::move(new_gc));
auto guard = utils::make_scope_guard([this] {
gc_set(std::move(old_gc));
});
srand(time(nullptr));
gc_finished = false;
thread_num = 0;
std::cout << "Creating tree" << std::endl;
root = create_tree(TREE_DEPTH);
unmark_tree(root);
print_tree(root);
for (auto& thread: threads) {
thread = threads::managed_thread::create(thread_routine, (void*) &root);
}
threads_ready.wait();
// save root in raw pointer and then null gc_ptr to collect it during gc
gc_pin<node> pin(root);
root_raw = pin.get();
root.reset();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
guard.commit();
}
~gc_test()
{
auto guard = utils::make_scope_guard([this] {
gc_set(std::move(old_gc));
});
for (auto& thread: threads) {
thread.join();
}
}
gc_ptr<node> root;
utils::scoped_thread threads[THREADS_COUNT];
node* root_raw;
std::unique_ptr<gc_interface> old_gc;
};
struct serial_gc_test : public gc_test
{
serial_gc_test()
: gc_test(utils::make_unique<serial_garbage_collector>(gc_compacting::DISABLED, utils::make_unique<empty_policy>()))
{
garbage_collector = static_cast<serial_garbage_collector*>(gc_get());
}
serial_garbage_collector* garbage_collector;
};
struct incremental_gc_test : public gc_test
{
incremental_gc_test()
: gc_test(utils::make_unique<incremental_garbage_collector>(gc_compacting::DISABLED, utils::make_unique<incremental_empty_policy>()))
{
garbage_collector = static_cast<incremental_garbage_collector*>(gc_get());
}
incremental_garbage_collector* garbage_collector;
};
// This test doesn't check anything.
// Consider it is passed if nothing will crash or hang.
TEST_F(serial_gc_test, test_serial_gc)
{
garbage_collector->gc();
gc_finished = true;
print_tree(root_raw);
}
TEST_F(incremental_gc_test, test_marking)
{
incremental_gc_ops ops;
ops.phase = gc_phase::MARKING;
ops.concurrent_flag = true;
ops.threads_num = 1;
garbage_collector->incremental_gc(ops);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
ops.phase = gc_phase::IDLING;
ops.concurrent_flag = false;
ops.threads_num = 0;
garbage_collector->incremental_gc(ops);
gc_finished = true;
print_tree(root_raw);
check_nodes(root_raw, 0);
}
TEST_F(incremental_gc_test, test_sweeping)
{
incremental_gc_ops ops;
ops.phase = gc_phase::SWEEPING;
ops.concurrent_flag = false;
ops.threads_num = 1;
garbage_collector->incremental_gc(ops);
gc_finished = true;
print_tree(root_raw);
}
//TEST_F(gc_test, test_marking)
//{
// auto& collector = gc_garbage_collector::instance();
// std::cout << "Start marking" << std::endl;
// collector.start_marking();
// std::this_thread::sleep_for(std::chrono::milliseconds(10));
// std::cout << "Pause marking" << std::endl;
//
// gc_finished = true;
// collector.force_move_to_idle();
//
// std::cout << std::endl;
// print_tree(root_raw);
// // travers tree and check marks of objects
// check_nodes(root_raw, 0);
//
// collector.force_move_to_idle();
//}
<|endoftext|>
|
<commit_before>#include "baseMesh.h"
baseMesh::baseMesh()
{
lightShader.load("shaders/lightShader");
shaderColorSource = 0;
//if you need to load an image to pass in use this
//
//image.loadImage("stripes.jpg");
//mesh.mapTexCoordsFromTexture(image.getTextureReference());
}
void baseMesh::update()
{
}
void baseMesh::draw(ofVec3f &_lightLocation, ofVec3f &_lightAttenuation, ofVec3f &_cameraLocation)
{
lightLocation = _lightLocation;
lightAttenuation = _lightAttenuation;
cameraLocation = _cameraLocation;
lightShader.begin();
lightShader.setUniform3f("colorInput", unitColor.r, unitColor.g, unitColor.b);
lightShader.setUniform1f("colorAlpha", alphaColor);
lightShader.setUniform1i("shaderColorSource", shaderColorSource);
lightShader.setUniform3f("lightLocation", lightLocation.x, lightLocation.y, lightLocation.z);
lightShader.setUniform3f("cameraLocation", cameraLocation.x, cameraLocation.y, cameraLocation.z);
lightShader.setUniform1f("constantAttenuation", lightAttenuation.x);//
lightShader.setUniform1f("linearAttenuation", lightAttenuation.y);/////// XYZ used for easy data encapsulation
lightShader.setUniform1f("quadraticAttenuation", lightAttenuation.z);//
UnitRGB lightColor = mapToUnitRGB(231, 230, 220);
lightShader.setUniform3f("lightColor", lightColor.r, lightColor.g, lightColor.b);
UnitRGB specularColor = mapToUnitRGB(150, 150, 150);
lightShader.setUniform3f("specularColor", specularColor.r, specularColor.g, specularColor.b);
mesh.draw();
lightShader.end();
}
void baseMesh::setupImportMesh(const char *fileName, bool loadMaterial)
{
//determines where the color source comes from
if (loadMaterial == true)
{
shaderColorSource = 1; //1 == true, 0 == false
}
//create mesh
objLoader = new waveFrontLoader();
objLoader->loadMaterial(loadMaterial);
objLoader->loadFile(fileName);
mesh = objLoader->generateMesh();
delete objLoader;
}
void baseMesh::setupCubeMesh(float _length, float _width, float _height)
{
ofBoxPrimitive box;
box.set(_width, _height, _length);
mesh = box.getMesh();
}
void baseMesh::setupSphereMesh(float _radius, int _resolution)
{
ofSpherePrimitive sphere;
sphere.set(_radius, _resolution);
mesh = sphere.getMesh();
}
void baseMesh::setupPlaneMesh(float _width, float _height, int _rows, int _columns)
{
ofPlanePrimitive plane;
plane.set(_width, _height, _columns, _rows);
mesh = plane.getMesh();
}
void baseMesh::scaleMesh(float scaleAmount)
{
int numVerts = mesh.getNumVertices();
std::vector<ofVec3f> meshVerts = mesh.getVertices();
mesh.clearVertices();
for (std::vector<ofVec3f>::iterator i = meshVerts.begin(); i != meshVerts.end(); ++i)
{
*i = scaleAmount * (*i);
mesh.addVertex(*i);
}
}
void baseMesh::addColors(float red, float green, float blue, float alpha)
{
unitColor = mapToUnitRGB(red, green, blue);
alphaColor = ofMap(alpha, 0.0, 255.0, 0.0, 1.0);
}
baseMesh::UnitRGB baseMesh::mapToUnitRGB(float red255, float green255, float blue255)
{
UnitRGB unitOutColor;
unitOutColor.r = ofMap(red255, 0.0, 255.0, 0.0, 1.0);
unitOutColor.g = ofMap(green255, 0.0, 255.0, 0.0, 1.0);
unitOutColor.b = ofMap(blue255, 0.0, 255.0, 0.0, 1.0);
return unitOutColor;
}
<commit_msg>Update baseMesh.cpp<commit_after>#include "baseMesh.h"
baseMesh::baseMesh()
{
lightShader.load("shaders/lightShader");
//this defines where the color comes from
//0 takes whatever RGB values you define
//1 gets the data from a .mtl file
//this is not accessed directly
//
shaderColorSource = 0;
//if you need to load an image to pass in use this
//
//image.loadImage("stripes.jpg");
//mesh.mapTexCoordsFromTexture(image.getTextureReference());
}
void baseMesh::update()
{
}
void baseMesh::draw(ofVec3f &_lightLocation, ofVec3f &_lightAttenuation, ofVec3f &_cameraLocation)
{
lightLocation = _lightLocation;
lightAttenuation = _lightAttenuation;
cameraLocation = _cameraLocation;
lightShader.begin();
lightShader.setUniform3f("colorInput", unitColor.r, unitColor.g, unitColor.b);
lightShader.setUniform1f("colorAlpha", alphaColor);
lightShader.setUniform1i("shaderColorSource", shaderColorSource);
lightShader.setUniform3f("lightLocation", lightLocation.x, lightLocation.y, lightLocation.z);
lightShader.setUniform3f("cameraLocation", cameraLocation.x, cameraLocation.y, cameraLocation.z);
lightShader.setUniform1f("constantAttenuation", lightAttenuation.x);//
lightShader.setUniform1f("linearAttenuation", lightAttenuation.y);/////// XYZ used for easy data encapsulation
lightShader.setUniform1f("quadraticAttenuation", lightAttenuation.z);//
UnitRGB lightColor = mapToUnitRGB(231, 230, 220);
lightShader.setUniform3f("lightColor", lightColor.r, lightColor.g, lightColor.b);
UnitRGB specularColor = mapToUnitRGB(150, 150, 150);
lightShader.setUniform3f("specularColor", specularColor.r, specularColor.g, specularColor.b);
mesh.draw();
lightShader.end();
}
void baseMesh::setupImportMesh(const char *fileName, bool loadMaterial)
{
//determines where the color source comes from
if (loadMaterial == true)
{
shaderColorSource = 1; //1 == true, 0 == false
}
//create mesh
objLoader = new waveFrontLoader();
objLoader->loadMaterial(loadMaterial);
objLoader->loadFile(fileName);
mesh = objLoader->generateMesh();
delete objLoader;
}
void baseMesh::setupCubeMesh(float _length, float _width, float _height)
{
ofBoxPrimitive box;
box.set(_width, _height, _length);
mesh = box.getMesh();
}
void baseMesh::setupSphereMesh(float _radius, int _resolution)
{
ofSpherePrimitive sphere;
sphere.set(_radius, _resolution);
mesh = sphere.getMesh();
}
void baseMesh::setupPlaneMesh(float _width, float _height, int _rows, int _columns)
{
ofPlanePrimitive plane;
plane.set(_width, _height, _columns, _rows);
mesh = plane.getMesh();
}
void baseMesh::scaleMesh(float scaleAmount)
{
int numVerts = mesh.getNumVertices();
std::vector<ofVec3f> meshVerts = mesh.getVertices();
mesh.clearVertices();
for (std::vector<ofVec3f>::iterator i = meshVerts.begin(); i != meshVerts.end(); ++i)
{
*i = scaleAmount * (*i);
mesh.addVertex(*i);
}
}
void baseMesh::addColors(float red, float green, float blue, float alpha)
{
unitColor = mapToUnitRGB(red, green, blue);
alphaColor = ofMap(alpha, 0.0, 255.0, 0.0, 1.0);
}
baseMesh::UnitRGB baseMesh::mapToUnitRGB(float red255, float green255, float blue255)
{
UnitRGB unitOutColor;
unitOutColor.r = ofMap(red255, 0.0, 255.0, 0.0, 1.0);
unitOutColor.g = ofMap(green255, 0.0, 255.0, 0.0, 1.0);
unitOutColor.b = ofMap(blue255, 0.0, 255.0, 0.0, 1.0);
return unitOutColor;
}
<|endoftext|>
|
<commit_before>/*
PICCANTE Examples
The hottest examples of Piccante:
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
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.0 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.
See the GNU Lesser General Public License
( http://www.gnu.org/licenses/lgpl-3.0.html ) for more details.
*/
//This means that we disable Eigen; some functionalities cannot be used.
//For example, estimating the camera response function
#define PIC_DISABLE_EIGEN
//This means that OpenGL acceleration layer is disabled
#define PIC_DISABLE_OPENGL
//This means we do not use QT for I/O
#define PIC_DISABLE_QT
#include "piccante.hpp"
int main(int argc, char *argv[])
{
std::string img_str;
if(argc == 2) {
img_str = argv[1];
} else {
img_str = "../data/input/bottles.hdr";
}
pic::JSONFile tmp;
pic::JSONNumber ret;
tmp.testParserNumbers();
printf("Reading an HDR file...");
pic::Image img;
img.Read(img_str);
printf("Ok\n");
printf("Is it valid? ");
if(img.isValid()) {
printf("OK\n");
//we estimate the best exposure for this HDR image
float fstop = pic::findBestExposureHistogram(&img);
printf("The best exposure value (histogram-based) is: %f f-stops\n", fstop);
pic::FilterSimpleTMO fltSimpleTMO(2.2f, fstop);
pic::Image *img_histo_tmo = fltSimpleTMO.Process(Single(&img), NULL);
/*pic::LT_NOR implies that when we save the image
we just convert it to 8-bit withou applying gamma.
In this case, this is fine, because gamma was already applied
in the pic::FilterSimpleTMO*/
bool bWritten = img_histo_tmo->Write("../data/output/simple_exp_histo_tmo.bmp", pic::LT_NOR);
if(bWritten) {
printf("Ok\n");
} else {
printf("Writing had some issues!\n");
}
//
//
//
//we estimate the best exposure for this HDR image
fstop = pic::findBestExposureMean(&img);
printf("The best exposure value (mean-based) is: %f f-stops\n", fstop);
fltSimpleTMO.update(2.2f, fstop);
pic::Image *img_mean_tmo = fltSimpleTMO.Process(Single(&img), NULL);
/*pic::LT_NOR implies that when we save the image
we just convert it to 8-bit withou applying gamma.
In this case, this is fine, because gamma was already applied
in the pic::FilterSimpleTMO*/
bWritten = img_mean_tmo->Write("../data/output/simple_exp_mean_tmo.bmp", pic::LT_NOR);
if(bWritten) {
printf("Ok\n");
} else {
printf("Writing had some issues!\n");
}
} else {
printf("No it is not a valid file!\n");
}
return 0;
}
<commit_msg>Update main.cpp<commit_after>/*
PICCANTE Examples
The hottest examples of Piccante:
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
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.0 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.
See the GNU Lesser General Public License
( http://www.gnu.org/licenses/lgpl-3.0.html ) for more details.
*/
//This means that we disable Eigen; some functionalities cannot be used.
//For example, estimating the camera response function
#define PIC_DISABLE_EIGEN
//This means that OpenGL acceleration layer is disabled
#define PIC_DISABLE_OPENGL
//This means we do not use QT for I/O
#define PIC_DISABLE_QT
#include "piccante.hpp"
int main(int argc, char *argv[])
{
std::string img_str;
if(argc == 2) {
img_str = argv[1];
} else {
img_str = "../data/input/bottles.hdr";
}
printf("Reading an HDR file...");
pic::Image img;
img.Read(img_str);
printf("Ok\n");
printf("Is it valid? ");
if(img.isValid()) {
printf("OK\n");
//we estimate the best exposure for this HDR image
float fstop = pic::findBestExposureHistogram(&img);
printf("The best exposure value (histogram-based) is: %f f-stops\n", fstop);
pic::FilterSimpleTMO fltSimpleTMO(2.2f, fstop);
pic::Image *img_histo_tmo = fltSimpleTMO.Process(Single(&img), NULL);
/*pic::LT_NOR implies that when we save the image
we just convert it to 8-bit withou applying gamma.
In this case, this is fine, because gamma was already applied
in the pic::FilterSimpleTMO*/
bool bWritten = img_histo_tmo->Write("../data/output/simple_exp_histo_tmo.bmp", pic::LT_NOR);
if(bWritten) {
printf("Ok\n");
} else {
printf("Writing had some issues!\n");
}
//
//
//
//we estimate the best exposure for this HDR image
fstop = pic::findBestExposureMean(&img);
printf("The best exposure value (mean-based) is: %f f-stops\n", fstop);
fltSimpleTMO.update(2.2f, fstop);
pic::Image *img_mean_tmo = fltSimpleTMO.Process(Single(&img), NULL);
/*pic::LT_NOR implies that when we save the image
we just convert it to 8-bit withou applying gamma.
In this case, this is fine, because gamma was already applied
in the pic::FilterSimpleTMO*/
bWritten = img_mean_tmo->Write("../data/output/simple_exp_mean_tmo.bmp", pic::LT_NOR);
if(bWritten) {
printf("Ok\n");
} else {
printf("Writing had some issues!\n");
}
} else {
printf("No it is not a valid file!\n");
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
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 of the author 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 "libtorrent/pch.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/socket_type.hpp"
#include "libtorrent/utp_socket_manager.hpp"
#include <boost/shared_ptr.hpp>
#include <stdexcept>
namespace libtorrent
{
TORRENT_EXPORT bool instantiate_connection(io_service& ios
, proxy_settings const& ps, socket_type& s
, void* ssl_context
, utp_socket_manager* sm
, bool peer_connection)
{
if (sm)
{
utp_stream* str;
#ifdef TORRENT_USE_OPENSSL
if (ssl_context)
{
s.instantiate<ssl_stream<utp_stream> >(ios, ssl_context);
str = &s.get<ssl_stream<utp_stream> >()->next_layer();
}
else
#endif
{
s.instantiate<utp_stream>(ios);
str = s.get<utp_stream>();
}
str->set_impl(sm->new_utp_socket(str));
}
#if TORRENT_USE_I2P
else if (ps.type == proxy_settings::i2p_proxy)
{
// it doesn't make any sense to try ssl over i2p
TORRENT_ASSERT(ssl_context == 0);
s.instantiate<i2p_stream>(ios);
s.get<i2p_stream>()->set_proxy(ps.hostname, ps.port);
}
#endif
else if (ps.type == proxy_settings::none
|| (peer_connection && !ps.proxy_peer_connections))
{
stream_socket* str;
#ifdef TORRENT_USE_OPENSSL
if (ssl_context)
{
s.instantiate<ssl_stream<stream_socket> >(ios, ssl_context);
str = &s.get<ssl_stream<stream_socket> >()->next_layer();
}
else
#endif
{
s.instantiate<stream_socket>(ios);
str = s.get<stream_socket>();
}
}
else if (ps.type == proxy_settings::http
|| ps.type == proxy_settings::http_pw)
{
http_stream* str;
#ifdef TORRENT_USE_OPENSSL
if (ssl_context)
{
s.instantiate<ssl_stream<http_stream> >(ios, ssl_context);
str = &s.get<ssl_stream<http_stream> >()->next_layer();
}
else
#endif
{
s.instantiate<http_stream>(ios);
str = s.get<http_stream>();
}
str->set_proxy(ps.hostname, ps.port);
if (ps.type == proxy_settings::http_pw)
str->set_username(ps.username, ps.password);
}
else if (ps.type == proxy_settings::socks5
|| ps.type == proxy_settings::socks5_pw
|| ps.type == proxy_settings::socks4)
{
socks5_stream* str;
#ifdef TORRENT_USE_OPENSSL
if (ssl_context)
{
s.instantiate<ssl_stream<socks5_stream> >(ios, ssl_context);
str = &s.get<ssl_stream<socks5_stream> >()->next_layer();
}
else
#endif
{
s.instantiate<socks5_stream>(ios);
str = s.get<socks5_stream>();
}
str->set_proxy(ps.hostname, ps.port);
if (ps.type == proxy_settings::socks5_pw)
str->set_username(ps.username, ps.password);
if (ps.type == proxy_settings::socks4)
str->set_version(4);
}
else
{
TORRENT_ASSERT_VAL(false, ps.type);
return false;
}
return true;
}
}
<commit_msg>remove unused variable<commit_after>/*
Copyright (c) 2007, Arvid Norberg
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 of the author 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 "libtorrent/pch.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/socket_type.hpp"
#include "libtorrent/utp_socket_manager.hpp"
#include <boost/shared_ptr.hpp>
#include <stdexcept>
namespace libtorrent
{
TORRENT_EXPORT bool instantiate_connection(io_service& ios
, proxy_settings const& ps, socket_type& s
, void* ssl_context
, utp_socket_manager* sm
, bool peer_connection)
{
if (sm)
{
utp_stream* str;
#ifdef TORRENT_USE_OPENSSL
if (ssl_context)
{
s.instantiate<ssl_stream<utp_stream> >(ios, ssl_context);
str = &s.get<ssl_stream<utp_stream> >()->next_layer();
}
else
#endif
{
s.instantiate<utp_stream>(ios);
str = s.get<utp_stream>();
}
str->set_impl(sm->new_utp_socket(str));
}
#if TORRENT_USE_I2P
else if (ps.type == proxy_settings::i2p_proxy)
{
// it doesn't make any sense to try ssl over i2p
TORRENT_ASSERT(ssl_context == 0);
s.instantiate<i2p_stream>(ios);
s.get<i2p_stream>()->set_proxy(ps.hostname, ps.port);
}
#endif
else if (ps.type == proxy_settings::none
|| (peer_connection && !ps.proxy_peer_connections))
{
#ifdef TORRENT_USE_OPENSSL
if (ssl_context)
{
s.instantiate<ssl_stream<stream_socket> >(ios, ssl_context);
}
else
#endif
{
s.instantiate<stream_socket>(ios);
}
}
else if (ps.type == proxy_settings::http
|| ps.type == proxy_settings::http_pw)
{
http_stream* str;
#ifdef TORRENT_USE_OPENSSL
if (ssl_context)
{
s.instantiate<ssl_stream<http_stream> >(ios, ssl_context);
str = &s.get<ssl_stream<http_stream> >()->next_layer();
}
else
#endif
{
s.instantiate<http_stream>(ios);
str = s.get<http_stream>();
}
str->set_proxy(ps.hostname, ps.port);
if (ps.type == proxy_settings::http_pw)
str->set_username(ps.username, ps.password);
}
else if (ps.type == proxy_settings::socks5
|| ps.type == proxy_settings::socks5_pw
|| ps.type == proxy_settings::socks4)
{
socks5_stream* str;
#ifdef TORRENT_USE_OPENSSL
if (ssl_context)
{
s.instantiate<ssl_stream<socks5_stream> >(ios, ssl_context);
str = &s.get<ssl_stream<socks5_stream> >()->next_layer();
}
else
#endif
{
s.instantiate<socks5_stream>(ios);
str = s.get<socks5_stream>();
}
str->set_proxy(ps.hostname, ps.port);
if (ps.type == proxy_settings::socks5_pw)
str->set_username(ps.username, ps.password);
if (ps.type == proxy_settings::socks4)
str->set_version(4);
}
else
{
TORRENT_ASSERT_VAL(false, ps.type);
return false;
}
return true;
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.