text
stringlengths
54
60.6k
<commit_before>70e8c1fe-2e4e-11e5-9284-b827eb9e62be<commit_msg>70edbeca-2e4e-11e5-9284-b827eb9e62be<commit_after>70edbeca-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4370f1b0-2e4e-11e5-9284-b827eb9e62be<commit_msg>43760290-2e4e-11e5-9284-b827eb9e62be<commit_after>43760290-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1e8d074a-2e4d-11e5-9284-b827eb9e62be<commit_msg>1e92002e-2e4d-11e5-9284-b827eb9e62be<commit_after>1e92002e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e40f9d30-2e4c-11e5-9284-b827eb9e62be<commit_msg>e414a78a-2e4c-11e5-9284-b827eb9e62be<commit_after>e414a78a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>479e8004-2e4e-11e5-9284-b827eb9e62be<commit_msg>47a3779e-2e4e-11e5-9284-b827eb9e62be<commit_after>47a3779e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8cc7d90a-2e4e-11e5-9284-b827eb9e62be<commit_msg>8ccce260-2e4e-11e5-9284-b827eb9e62be<commit_after>8ccce260-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fad5f184-2e4e-11e5-9284-b827eb9e62be<commit_msg>fadae8ba-2e4e-11e5-9284-b827eb9e62be<commit_after>fadae8ba-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>95d88da6-2e4d-11e5-9284-b827eb9e62be<commit_msg>95dd92ba-2e4d-11e5-9284-b827eb9e62be<commit_after>95dd92ba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4ab63656-2e4e-11e5-9284-b827eb9e62be<commit_msg>4abb3b74-2e4e-11e5-9284-b827eb9e62be<commit_after>4abb3b74-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include "stdafx.h" #include "bindings.h" #include "helper.h" #include <game_sa\CPed.h> #include <injector\calling.hpp> using namespace Bindings; JsValueRef CALLBACK getFloat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK setFloat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK getInt(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK setInt(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK getBool(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK setBool(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); void Bindings::Ped(JsValueRef ped, Container& container) { void* data; JsGetExternalData(ped, &data); CPed* pedNative = (CPed*)data; Js::DefineProperty(ped, L"health", getFloat, setFloat, &pedNative->m_fHealth); Js::DefineProperty(ped, L"armor", getFloat, setFloat, &pedNative->m_fArmour); Js::DefineProperty(ped, L"isDriving", getBool, nullptr, container.create_pointer(pedNative, 0x46C, 8)); Js::DefineProperty(ped, L"isArrested", getBool, nullptr, container.create_pointer(pedNative, 0x474, 6)); Js::DefineProperty(ped, L"isInvisible", getBool, setBool, container.create_pointer(pedNative, 0x474, 1)); Js::DefineProperty(ped, L"model", getInt, nullptr, &pedNative->m_wModelIndex); } JsValueRef CALLBACK getFloat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { float* floatValue = (float*)callbackState; JsValueRef numberValue; JsDoubleToNumber(*floatValue, &numberValue); return numberValue; } JsValueRef CALLBACK setFloat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { float* floatValue = (float*)callbackState; double doubleValue; JsNumberToDouble(arguments[1], &doubleValue); *floatValue = doubleValue; return JS_INVALID_REFERENCE; } JsValueRef CALLBACK getInt(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { int* intValue = (int*)callbackState; JsValueRef numberValue; JsIntToNumber(*intValue, &numberValue); return numberValue; } JsValueRef CALLBACK setInt(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { int* intValue = (int*)callbackState; int tempIntValue; JsNumberToInt(arguments[1], &tempIntValue); *intValue = tempIntValue; return JS_INVALID_REFERENCE; } JsValueRef CALLBACK getBool(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { fake_ptr* ptr = (fake_ptr*)callbackState; bool boolValue = get(ptr->pointer, ptr->offset, ptr->shift); JsValueRef booleanValue; JsBoolToBoolean(boolValue, &booleanValue); return booleanValue; } JsValueRef CALLBACK setBool(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { fake_ptr* ptr = (fake_ptr*)callbackState; bool tempBoolValue; JsBooleanToBool(arguments[1], &tempBoolValue); set(ptr->pointer, ptr->offset, ptr->shift, tempBoolValue); return JS_INVALID_REFERENCE; } Bindings::fake_ptr::fake_ptr(void* pointer, int offset, int shift) { this->pointer = pointer; this->offset = offset; this->shift = shift; } Bindings::Container::Container() { } Bindings::Container::~Container() { while (!pointers.empty()) { delete pointers.front(); pointers.pop(); } } fake_ptr* Bindings::Container::create_pointer(void* base, int offset, int shift) { auto pointer = new fake_ptr(base, offset, shift); pointers.push(pointer); return pointer; } <commit_msg>Added position<commit_after>#include "stdafx.h" #include "bindings.h" #include "helper.h" #include <game_sa\CPed.h> #include <injector\calling.hpp> using namespace Bindings; JsValueRef CALLBACK getFloat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK setFloat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK getInt(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK setInt(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK getBool(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK setBool(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK getVector(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); JsValueRef CALLBACK setVector(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState); void Bindings::Ped(JsValueRef ped, Container& container) { void* data; JsGetExternalData(ped, &data); CPed* pedNative = (CPed*)data; Js::DefineProperty(ped, L"position", getVector, setVector, &pedNative->m_pCoords->pos); Js::DefineProperty(ped, L"health", getFloat, setFloat, &pedNative->m_fHealth); Js::DefineProperty(ped, L"armor", getFloat, setFloat, &pedNative->m_fArmour); Js::DefineProperty(ped, L"isDriving", getBool, nullptr, container.create_pointer(pedNative, 0x46C, 8)); Js::DefineProperty(ped, L"isArrested", getBool, nullptr, container.create_pointer(pedNative, 0x474, 6)); Js::DefineProperty(ped, L"isInvisible", getBool, setBool, container.create_pointer(pedNative, 0x474, 1)); Js::DefineProperty(ped, L"model", getInt, nullptr, &pedNative->m_wModelIndex); } JsValueRef CALLBACK getFloat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { float* floatValue = (float*)callbackState; JsValueRef numberValue; JsDoubleToNumber(*floatValue, &numberValue); return numberValue; } JsValueRef CALLBACK setFloat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { float* floatValue = (float*)callbackState; double doubleValue; JsNumberToDouble(arguments[1], &doubleValue); *floatValue = doubleValue; return JS_INVALID_REFERENCE; } JsValueRef CALLBACK getInt(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { int* intValue = (int*)callbackState; JsValueRef numberValue; JsIntToNumber(*intValue, &numberValue); return numberValue; } JsValueRef CALLBACK setInt(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { int* intValue = (int*)callbackState; int tempIntValue; JsNumberToInt(arguments[1], &tempIntValue); *intValue = tempIntValue; return JS_INVALID_REFERENCE; } JsValueRef CALLBACK getBool(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { fake_ptr* ptr = (fake_ptr*)callbackState; bool boolValue = get(ptr->pointer, ptr->offset, ptr->shift); JsValueRef booleanValue; JsBoolToBoolean(boolValue, &booleanValue); return booleanValue; } JsValueRef CALLBACK setBool(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { fake_ptr* ptr = (fake_ptr*)callbackState; bool tempBoolValue; JsBooleanToBool(arguments[1], &tempBoolValue); set(ptr->pointer, ptr->offset, ptr->shift, tempBoolValue); return JS_INVALID_REFERENCE; } Bindings::fake_ptr::fake_ptr(void* pointer, int offset, int shift) { this->pointer = pointer; this->offset = offset; this->shift = shift; } Bindings::Container::Container() { } Bindings::Container::~Container() { while (!pointers.empty()) { delete pointers.front(); pointers.pop(); } } fake_ptr* Bindings::Container::create_pointer(void* base, int offset, int shift) { auto pointer = new fake_ptr(base, offset, shift); pointers.push(pointer); return pointer; } JsValueRef CALLBACK getVector(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { CVector* vectorValue = (CVector*)callbackState; JsValueRef vectorObject; JsCreateExternalObject(vectorValue, nullptr, &vectorObject); Js::DefineProperty(vectorObject, L"x", getFloat, setFloat, &vectorValue->x); Js::DefineProperty(vectorObject, L"y", getFloat, setFloat, &vectorValue->y); Js::DefineProperty(vectorObject, L"z", getFloat, setFloat, &vectorValue->z); return vectorObject; } JsValueRef CALLBACK setVector(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { CVector* vectorValue = (CVector*)callbackState; JsValueRef x, y, z; Js::GetPropertyFromObject(arguments[1], L"x", &x); Js::GetPropertyFromObject(arguments[1], L"y", &y); Js::GetPropertyFromObject(arguments[1], L"z", &z); double tempX, tempY, tempZ; JsNumberToDouble(x, &tempX); vectorValue->x = tempX; JsNumberToDouble(y, &tempY); vectorValue->y = tempY; JsNumberToDouble(z, &tempZ); vectorValue->z = tempZ; return JS_INVALID_REFERENCE; } <|endoftext|>
<commit_before>42dbbe16-2e4d-11e5-9284-b827eb9e62be<commit_msg>42e0bfb0-2e4d-11e5-9284-b827eb9e62be<commit_after>42e0bfb0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>// Copyright (c) 2012-2013 Plenluno All rights reserved. #include <gtest/gtest.h> #include <float.h> #include <libj/array_list.h> #include <libj/error.h> #include <libj/json.h> #include <libj/js_array.h> #include <libj/js_object.h> #include <libj/map.h> #include <libj/string_builder.h> namespace libj { TEST(GTestJson, TestStringify) { ASSERT_FALSE(json::stringify(UNDEFINED)); ASSERT_TRUE(json::stringify(static_cast<Byte>(3)) ->equals(String::create("3"))); ASSERT_TRUE(json::stringify(static_cast<Short>(4)) ->equals(String::create("4"))); ASSERT_TRUE(json::stringify(static_cast<Int>(5)) ->equals(String::create("5"))); ASSERT_TRUE(json::stringify(static_cast<Long>(6)) ->equals(String::create("6"))); ASSERT_TRUE(json::stringify(static_cast<Float>(2.5)) ->equals(String::create("2.5"))); ASSERT_TRUE(json::stringify(static_cast<Double>(3.5)) ->equals(String::create("3.5"))); ASSERT_TRUE(json::stringify(DBL_MAX) ->equals(String::create("1.7976931348623157e+308"))); ASSERT_TRUE(json::stringify(-DBL_MIN) ->equals(String::create("-2.2250738585072014e-308"))); ASSERT_TRUE(json::stringify(true) ->equals(String::create("true"))); ASSERT_TRUE(json::stringify(false) ->equals(String::create("false"))); ASSERT_TRUE(json::stringify(Object::null()) ->equals(String::create("null"))); ASSERT_TRUE(json::stringify(String::create("456")) ->equals(String::create("\"456\""))); ASSERT_TRUE(json::stringify(Map::create()) ->equals(String::create("{}"))); ASSERT_TRUE(json::stringify(ArrayList::create()) ->equals(String::create("[]"))); Map::Ptr m = Map::create(); m->put(3, false); m->put(String::create("w"), UNDEFINED); m->put(String::create("x"), 123); m->put(String::create("y"), String::create("456")); m->put(String::create("z"), String::null()); ASSERT_TRUE(json::stringify(m) ->equals(String::create("{\"x\":123,\"y\":\"456\",\"z\":null}"))); ArrayList::Ptr a = ArrayList::create(); a->add(3); a->add(UNDEFINED); a->add(false); ASSERT_TRUE(json::stringify(a) ->equals(String::create("[3,null,false]"))); } TEST(GTestJson, TestRecursiveStringify) { Map::Ptr m = Map::create(); m->put(String::create("x"), 123); m->put(String::create("y"), ArrayList::create()); JsObject::Ptr jo = JsObject::create(); jo->put(3, false); jo->put(Object::null(), m); ASSERT_TRUE(json::stringify(jo)->equals( String::create("{\"3\":false,\"null\":{\"x\":123,\"y\":[]}}"))); ArrayList::Ptr a = ArrayList::create(); a->add(3); a->add(m); JsArray::Ptr ja = JsArray::create(); ja->add(UNDEFINED); ja->add(Object::null()); ja->add(a); ASSERT_TRUE(json::stringify(ja)->equals( String::create("[null,null,[3,{\"x\":123,\"y\":[]}]]"))); } TEST(GTestJson, TestParse) { String::CPtr json = String::create("{\"x\":123,\"y\":[3.5,false],\"z\":null}"); Value v = json::parse(json); ASSERT_TRUE(v.instanceof(Type<Map>::id())); ASSERT_TRUE(v.instanceof(Type<JsObject>::id())); JsObject::CPtr m = toCPtr<JsObject>(v); ASSERT_EQ(3, m->size()); Value xv = m->get(String::create("x")); ASSERT_EQ(Type<Long>::id(), xv.type()); Long l; to<Long>(xv, &l); ASSERT_EQ(123, l); Value yv = m->get(String::create("y")); ASSERT_TRUE(yv.instanceof(Type<ArrayList>::id())); ASSERT_TRUE(yv.instanceof(Type<JsArray>::id())); JsArray::CPtr a = toCPtr<JsArray>(yv); Value a0 = a->get(0); ASSERT_EQ(Type<Double>::id(), a0.type()); Double d; to<Double>(a0, &d); ASSERT_EQ(3.5, d); Value a1 = a->get(1); ASSERT_EQ(Type<Boolean>::id(), a1.type()); Boolean b; to<Boolean>(a1, &b); ASSERT_FALSE(b); Value zv = m->get(String::create("z")); ASSERT_TRUE(zv.equals(Object::null())); } TEST(GTestJson, TestParseString) { String::CPtr s = String::create("\"\\u0026\""); ASSERT_TRUE(json::parse(s).equals(String::create("&"))); String::CPtr s1 = String::create("\"\\ud84c\\udfd0\""); #ifdef LIBJ_USE_UTF32 String::CPtr s2 = String::create(0x233d0); #else std::u16string s16; s16 += static_cast<char16_t>(0xd84c); s16 += static_cast<char16_t>(0xdfd0); String::CPtr s2 = String::create(s16); #endif ASSERT_TRUE(json::parse(s1).equals(s2)); std::u32string s32; s32 += 0x3042; s32 += 0x2000b; s = String::create(s32); StringBuilder::Ptr sb = StringBuilder::create(); sb->appendCStr("\""); sb->append(s); sb->appendCStr("\""); ASSERT_TRUE(json::parse(sb->toString()).equals(s)); } TEST(GTestJson, TestParseNumber) { String::CPtr s1 = String::create("1.0"); Value v1 = json::parse(s1); ASSERT_EQ(Type<Long>::id(), v1.type()); ASSERT_TRUE(v1.equals(static_cast<Long>(1))); String::CPtr s2 = String::create("9007199254740990"); Value v2 = json::parse(s2); ASSERT_TRUE(v2.equals(static_cast<Long>(9007199254740990))); String::CPtr s3 = String::create("9007199254740991"); Value v3 = json::parse(s3); ASSERT_TRUE(v3.equals(static_cast<Long>(9007199254740991))); String::CPtr s4 = String::create("9007199254740992"); Value v4 = json::parse(s4); ASSERT_TRUE(v4.equals(9007199254740992.0)); String::CPtr s5 = String::create("9007199254740993"); Value v5 = json::parse(s5); ASSERT_TRUE(v5.equals(9007199254740992.0)); String::CPtr s6 = String::create("-9007199254740990"); Value v6 = json::parse(s6); ASSERT_TRUE(v6.equals(-9007199254740990LL)); String::CPtr s7 = String::create("-9007199254740991"); Value v7 = json::parse(s7); ASSERT_TRUE(v7.equals(-9007199254740991LL)); String::CPtr s8 = String::create("-9007199254740992"); Value v8 = json::parse(s8); ASSERT_TRUE(v8.equals(-9007199254740992.0)); String::CPtr s9 = String::create("-9007199254740993"); Value v9 = json::parse(s9); ASSERT_TRUE(v9.equals(-9007199254740992.0)); String::CPtr s10 = String::create("1.7976931348623157e+308"); Value v10 = json::parse(s10); ASSERT_TRUE(v10.equals(1.7976931348623157e+308)); } TEST(GTestJson, TestParseError) { Value v1 = json::parse(String::null()); ASSERT_TRUE(v1.instanceof(Type<Error>::id())); Value v2 = json::parse(String::create("\"")); ASSERT_TRUE(v2.instanceof(Type<Error>::id())); } TEST(GTestJson, TestEscape) { String::CPtr str = String::create("\b\f\n\r\t'\"\\"); String::CPtr json = String::create("\"\\b\\f\\n\\r\\t'\\\"\\\\\""); String::CPtr s = toCPtr<String>(json::parse(json)); ASSERT_TRUE(s->equals(str)); s = json::stringify(str); ASSERT_TRUE(s->equals(json)); } } // namespace libj <commit_msg>fix travis errors<commit_after>// Copyright (c) 2012-2013 Plenluno All rights reserved. #include <gtest/gtest.h> #include <float.h> #include <libj/array_list.h> #include <libj/error.h> #include <libj/json.h> #include <libj/js_array.h> #include <libj/js_object.h> #include <libj/map.h> #include <libj/string_builder.h> namespace libj { TEST(GTestJson, TestStringify) { ASSERT_FALSE(json::stringify(UNDEFINED)); ASSERT_TRUE(json::stringify(static_cast<Byte>(3)) ->equals(String::create("3"))); ASSERT_TRUE(json::stringify(static_cast<Short>(4)) ->equals(String::create("4"))); ASSERT_TRUE(json::stringify(static_cast<Int>(5)) ->equals(String::create("5"))); ASSERT_TRUE(json::stringify(static_cast<Long>(6)) ->equals(String::create("6"))); ASSERT_TRUE(json::stringify(static_cast<Float>(2.5)) ->equals(String::create("2.5"))); ASSERT_TRUE(json::stringify(static_cast<Double>(3.5)) ->equals(String::create("3.5"))); ASSERT_TRUE(json::stringify(DBL_MAX) ->equals(String::create("1.7976931348623157e+308"))); ASSERT_TRUE(json::stringify(-DBL_MIN) ->equals(String::create("-2.2250738585072014e-308"))); ASSERT_TRUE(json::stringify(true) ->equals(String::create("true"))); ASSERT_TRUE(json::stringify(false) ->equals(String::create("false"))); ASSERT_TRUE(json::stringify(Object::null()) ->equals(String::create("null"))); ASSERT_TRUE(json::stringify(String::create("456")) ->equals(String::create("\"456\""))); ASSERT_TRUE(json::stringify(Map::create()) ->equals(String::create("{}"))); ASSERT_TRUE(json::stringify(ArrayList::create()) ->equals(String::create("[]"))); Map::Ptr m = Map::create(); m->put(3, false); m->put(String::create("w"), UNDEFINED); m->put(String::create("x"), 123); m->put(String::create("y"), String::create("456")); m->put(String::create("z"), String::null()); ASSERT_TRUE(json::stringify(m) ->equals(String::create("{\"x\":123,\"y\":\"456\",\"z\":null}"))); ArrayList::Ptr a = ArrayList::create(); a->add(3); a->add(UNDEFINED); a->add(false); ASSERT_TRUE(json::stringify(a) ->equals(String::create("[3,null,false]"))); } TEST(GTestJson, TestRecursiveStringify) { Map::Ptr m = Map::create(); m->put(String::create("x"), 123); m->put(String::create("y"), ArrayList::create()); JsObject::Ptr jo = JsObject::create(); jo->put(3, false); jo->put(Object::null(), m); ASSERT_TRUE(json::stringify(jo)->equals( String::create("{\"3\":false,\"null\":{\"x\":123,\"y\":[]}}"))); ArrayList::Ptr a = ArrayList::create(); a->add(3); a->add(m); JsArray::Ptr ja = JsArray::create(); ja->add(UNDEFINED); ja->add(Object::null()); ja->add(a); ASSERT_TRUE(json::stringify(ja)->equals( String::create("[null,null,[3,{\"x\":123,\"y\":[]}]]"))); } TEST(GTestJson, TestParse) { String::CPtr json = String::create("{\"x\":123,\"y\":[3.5,false],\"z\":null}"); Value v = json::parse(json); ASSERT_TRUE(v.instanceof(Type<Map>::id())); ASSERT_TRUE(v.instanceof(Type<JsObject>::id())); JsObject::CPtr m = toCPtr<JsObject>(v); ASSERT_EQ(3, m->size()); Value xv = m->get(String::create("x")); ASSERT_EQ(Type<Long>::id(), xv.type()); Long l; to<Long>(xv, &l); ASSERT_EQ(123, l); Value yv = m->get(String::create("y")); ASSERT_TRUE(yv.instanceof(Type<ArrayList>::id())); ASSERT_TRUE(yv.instanceof(Type<JsArray>::id())); JsArray::CPtr a = toCPtr<JsArray>(yv); Value a0 = a->get(0); ASSERT_EQ(Type<Double>::id(), a0.type()); Double d; to<Double>(a0, &d); ASSERT_EQ(3.5, d); Value a1 = a->get(1); ASSERT_EQ(Type<Boolean>::id(), a1.type()); Boolean b; to<Boolean>(a1, &b); ASSERT_FALSE(b); Value zv = m->get(String::create("z")); ASSERT_TRUE(zv.equals(Object::null())); } TEST(GTestJson, TestParseString) { String::CPtr s = String::create("\"\\u0026\""); ASSERT_TRUE(json::parse(s).equals(String::create("&"))); String::CPtr s1 = String::create("\"\\ud84c\\udfd0\""); #ifdef LIBJ_USE_UTF32 String::CPtr s2 = String::create(0x233d0); #else std::u16string s16; s16 += static_cast<char16_t>(0xd84c); s16 += static_cast<char16_t>(0xdfd0); String::CPtr s2 = String::create(s16); #endif ASSERT_TRUE(json::parse(s1).equals(s2)); std::u32string s32; s32 += 0x3042; s32 += 0x2000b; s = String::create(s32); StringBuilder::Ptr sb = StringBuilder::create(); sb->appendCStr("\""); sb->append(s); sb->appendCStr("\""); ASSERT_TRUE(json::parse(sb->toString()).equals(s)); } TEST(GTestJson, TestParseNumber) { String::CPtr s1 = String::create("1.0"); Value v1 = json::parse(s1); ASSERT_EQ(Type<Long>::id(), v1.type()); ASSERT_TRUE(v1.equals(static_cast<Long>(1))); String::CPtr s2 = String::create("9007199254740990"); Value v2 = json::parse(s2); ASSERT_TRUE(v2.equals(static_cast<Long>(9007199254740990))); String::CPtr s3 = String::create("9007199254740991"); Value v3 = json::parse(s3); ASSERT_TRUE(v3.equals(static_cast<Long>(9007199254740991))); String::CPtr s4 = String::create("9007199254740992"); Value v4 = json::parse(s4); ASSERT_TRUE(v4.equals(9007199254740992.0)); String::CPtr s5 = String::create("9007199254740993"); Value v5 = json::parse(s5); ASSERT_TRUE(v5.equals(9007199254740992.0)); String::CPtr s6 = String::create("-9007199254740990"); Value v6 = json::parse(s6); ASSERT_TRUE(v6.equals(static_cast<Long>(-9007199254740990))); String::CPtr s7 = String::create("-9007199254740991"); Value v7 = json::parse(s7); ASSERT_TRUE(v7.equals(static_cast<Long>(-9007199254740991))); String::CPtr s8 = String::create("-9007199254740992"); Value v8 = json::parse(s8); ASSERT_TRUE(v8.equals(-9007199254740992.0)); String::CPtr s9 = String::create("-9007199254740993"); Value v9 = json::parse(s9); ASSERT_TRUE(v9.equals(-9007199254740992.0)); String::CPtr s10 = String::create("1.7976931348623157e+308"); Value v10 = json::parse(s10); ASSERT_TRUE(v10.equals(1.7976931348623157e+308)); } TEST(GTestJson, TestParseError) { Value v1 = json::parse(String::null()); ASSERT_TRUE(v1.instanceof(Type<Error>::id())); Value v2 = json::parse(String::create("\"")); ASSERT_TRUE(v2.instanceof(Type<Error>::id())); } TEST(GTestJson, TestEscape) { String::CPtr str = String::create("\b\f\n\r\t'\"\\"); String::CPtr json = String::create("\"\\b\\f\\n\\r\\t'\\\"\\\\\""); String::CPtr s = toCPtr<String>(json::parse(json)); ASSERT_TRUE(s->equals(str)); s = json::stringify(str); ASSERT_TRUE(s->equals(json)); } } // namespace libj <|endoftext|>
<commit_before>25b0396a-2e4e-11e5-9284-b827eb9e62be<commit_msg>25b5431a-2e4e-11e5-9284-b827eb9e62be<commit_after>25b5431a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f9296f5c-2e4c-11e5-9284-b827eb9e62be<commit_msg>f92e6390-2e4c-11e5-9284-b827eb9e62be<commit_after>f92e6390-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include <algorithm> #include <type_traits> #include "caf/config.hpp" #include "caf/fwd.hpp" #include "caf/settings.hpp" #include "caf/span.hpp" #include "caf/telemetry/counter.hpp" #include "caf/telemetry/gauge.hpp" #include "caf/telemetry/label.hpp" #include "caf/telemetry/metric_type.hpp" namespace caf::telemetry { /// Represent aggregatable distributions of events. template <class ValueType> class histogram { public: // -- member types ----------------------------------------------------------- using value_type = ValueType; using gauge_type = gauge<value_type>; using counter_type = counter<value_type>; using family_setting = std::vector<value_type>; struct bucket_type { value_type upper_bound; counter_type count; }; // -- constants -------------------------------------------------------------- static constexpr metric_type runtime_type = std::is_same<value_type, double>::value ? metric_type::dbl_histogram : metric_type::int_histogram; // -- constructors, destructors, and assignment operators -------------------- histogram(span<const label> labels, const settings* cfg, span<const value_type> upper_bounds) { if (!init_buckets_from_config(labels, cfg)) init_buckets(upper_bounds); } explicit histogram(std::initializer_list<value_type> upper_bounds) : histogram({}, nullptr, make_span(upper_bounds.begin(), upper_bounds.size())) { // nop } histogram(const histogram&) = delete; histogram& operator=(const histogram&) = delete; ~histogram() { delete[] buckets_; } // -- modifiers -------------------------------------------------------------- /// Increments the bucket where the observed value falls into and increments /// the sum of all observed values. void observe(value_type value) { // The last bucket has an upper bound of +inf or int_max, so we'll always // find a bucket and increment the counters. for (size_t index = 0;; ++index) { auto& [upper_bound, count] = buckets_[index]; if (value <= upper_bound) { count.inc(); sum_.inc(value); return; } } } // -- observers -------------------------------------------------------------- /// Returns the ``counter`` objects with the configured upper bounds. span<const bucket_type> buckets() const noexcept { return {buckets_, num_buckets_}; } /// Returns the sum of all observed values. value_type sum() const noexcept { return sum_.value(); } private: void init_buckets(span<const value_type> upper_bounds) { CAF_ASSERT(std::is_sorted(upper_bounds.begin(), upper_bounds.end())); using limits = std::numeric_limits<value_type>; num_buckets_ = upper_bounds.size() + 1; buckets_ = new bucket_type[num_buckets_]; size_t index = 0; for (; index < upper_bounds.size(); ++index) buckets_[index].upper_bound = upper_bounds[index]; if constexpr (limits::has_infinity) buckets_[index].upper_bound = limits::infinity(); else buckets_[index].upper_bound = limits::max(); } bool init_buckets_from_config(span<const label> labels, const settings* cfg) { if (cfg == nullptr || labels.empty()) return false; for (const auto& lbl : labels) { if (auto ptr = get_if<settings>(cfg, lbl.str())) { if (auto bounds = get_as<std::vector<value_type>>(*ptr, "buckets")) { std::sort(bounds->begin(), bounds->end()); bounds->erase(std::unique(bounds->begin(), bounds->end()), bounds->end()); if (bounds->empty()) return false; init_buckets(*bounds); return true; } } } return false; } size_t num_buckets_; bucket_type* buckets_; gauge_type sum_; }; /// Convenience alias for a histogram with value type `double`. using dbl_histogram = histogram<double>; /// Convenience alias for a histogram with value type `int64_t`. using int_histogram = histogram<int64_t>; } // namespace caf::telemetry <commit_msg>Fix value type of histogram bucket counters<commit_after>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include <algorithm> #include <type_traits> #include "caf/config.hpp" #include "caf/fwd.hpp" #include "caf/settings.hpp" #include "caf/span.hpp" #include "caf/telemetry/counter.hpp" #include "caf/telemetry/gauge.hpp" #include "caf/telemetry/label.hpp" #include "caf/telemetry/metric_type.hpp" namespace caf::telemetry { /// Represent aggregatable distributions of events. template <class ValueType> class histogram { public: // -- member types ----------------------------------------------------------- using value_type = ValueType; using gauge_type = gauge<value_type>; using family_setting = std::vector<value_type>; struct bucket_type { value_type upper_bound; int_counter count; }; // -- constants -------------------------------------------------------------- static constexpr metric_type runtime_type = std::is_same<value_type, double>::value ? metric_type::dbl_histogram : metric_type::int_histogram; // -- constructors, destructors, and assignment operators -------------------- histogram(span<const label> labels, const settings* cfg, span<const value_type> upper_bounds) { if (!init_buckets_from_config(labels, cfg)) init_buckets(upper_bounds); } explicit histogram(std::initializer_list<value_type> upper_bounds) : histogram({}, nullptr, make_span(upper_bounds.begin(), upper_bounds.size())) { // nop } histogram(const histogram&) = delete; histogram& operator=(const histogram&) = delete; ~histogram() { delete[] buckets_; } // -- modifiers -------------------------------------------------------------- /// Increments the bucket where the observed value falls into and increments /// the sum of all observed values. void observe(value_type value) { // The last bucket has an upper bound of +inf or int_max, so we'll always // find a bucket and increment the counters. for (size_t index = 0;; ++index) { auto& [upper_bound, count] = buckets_[index]; if (value <= upper_bound) { count.inc(); sum_.inc(value); return; } } } // -- observers -------------------------------------------------------------- /// Returns the ``counter`` objects with the configured upper bounds. span<const bucket_type> buckets() const noexcept { return {buckets_, num_buckets_}; } /// Returns the sum of all observed values. value_type sum() const noexcept { return sum_.value(); } private: void init_buckets(span<const value_type> upper_bounds) { CAF_ASSERT(std::is_sorted(upper_bounds.begin(), upper_bounds.end())); using limits = std::numeric_limits<value_type>; num_buckets_ = upper_bounds.size() + 1; buckets_ = new bucket_type[num_buckets_]; size_t index = 0; for (; index < upper_bounds.size(); ++index) buckets_[index].upper_bound = upper_bounds[index]; if constexpr (limits::has_infinity) buckets_[index].upper_bound = limits::infinity(); else buckets_[index].upper_bound = limits::max(); } bool init_buckets_from_config(span<const label> labels, const settings* cfg) { if (cfg == nullptr || labels.empty()) return false; for (const auto& lbl : labels) { if (auto ptr = get_if<settings>(cfg, lbl.str())) { if (auto bounds = get_as<std::vector<value_type>>(*ptr, "buckets")) { std::sort(bounds->begin(), bounds->end()); bounds->erase(std::unique(bounds->begin(), bounds->end()), bounds->end()); if (bounds->empty()) return false; init_buckets(*bounds); return true; } } } return false; } size_t num_buckets_; bucket_type* buckets_; gauge_type sum_; }; /// Convenience alias for a histogram with value type `double`. using dbl_histogram = histogram<double>; /// Convenience alias for a histogram with value type `int64_t`. using int_histogram = histogram<int64_t>; } // namespace caf::telemetry <|endoftext|>
<commit_before>0eda842a-2e4e-11e5-9284-b827eb9e62be<commit_msg>0edf85ec-2e4e-11e5-9284-b827eb9e62be<commit_after>0edf85ec-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/** * @file edge.cpp * @brief Simple test for OpenCV * @author Denis Deryugin <deryugin.denis@gmail.com> * @version * @date 03.06.2019 */ #include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include <stdio.h> #include <time.h> #include <drivers/video/fb.h> using namespace cv; using namespace std; static void help(void) { printf("\nThis sample demonstrates Canny edge detection\n" "Call:\n" " ./edge [image [threshold]] \n\n"); } static const char* keys = { "{help h||}" "{@image | \"fruits.png\" | source image }" "{@repeat |1 | number}" }; static void imdrawfb(Mat& img) { struct fb_info *fbi; int w, h; fbi = fb_lookup(0); if (!fbi) { printf("fb0 not found\n"); return; } printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel); h = min((int) fbi->var.yres, img.rows); w = min((int) (fbi->var.bits_per_pixel * fbi->var.xres) / 8, 3 * img.cols); for (int y = 0; y < h; y++) { const uchar *row = &img.at<uchar>(y, 0); for (int x = 0; x < w; x += 3) { unsigned rgb888 = 0xFF000000 | unsigned(row[x]) | (unsigned(row[x + 1]) << 8) | (unsigned(row[x + 2]) << 16); ((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x / 3] = rgb888; } } } int main(int argc, const char** argv) { struct timeval tv_start, tv_end, tv_res; int edgeThresh = 2; Mat image, gray, edge, cedge; CommandLineParser parser(argc, argv, keys); if (parser.has("help")) { help(); return 0; } edgeThresh = parser.get<int>(1); string filename = parser.get<String>("@image"); image = imread(filename, 1); if(image.empty()) { printf("Cannot read image file: %s\n", filename.c_str()); help(); return -1; } cedge.create(image.size(), image.type()); cvtColor(image, gray, COLOR_BGR2GRAY); gettimeofday(&tv_start, NULL); { blur(gray, edge, Size(3,3)); Canny(edge, edge, edgeThresh, edgeThresh*3, 3); cedge = Scalar::all(0); } gettimeofday(&tv_end, NULL); timersub(&tv_end, &tv_start, &tv_res); image.copyTo(cedge, edge); printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh); printf("Detection time: %d s %d ms\n", tv_res.tv_sec, tv_res.tv_usec / 1000); imdrawfb(cedge); return 0; } <commit_msg>opencv: Fix edges sample build<commit_after>/** * @file edge.cpp * @brief Simple test for OpenCV * @author Denis Deryugin <deryugin.denis@gmail.com> * @version * @date 03.06.2019 */ #include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include <stdio.h> #include <time.h> #include <drivers/video/fb.h> using namespace cv; using namespace std; static void help(void) { printf("\nThis sample demonstrates Canny edge detection\n" "Call:\n" " ./edge [image [threshold]] \n\n"); } static const char* keys = { "{help h||}" "{@image | \"fruits.png\" | source image }" "{@repeat |1 | number}" }; static void imdrawfb(Mat& img) { struct fb_info *fbi; int w, h; fbi = fb_lookup(0); if (!fbi) { printf("fb0 not found\n"); return; } printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel); h = min((int) fbi->var.yres, img.rows); w = min((int) (fbi->var.bits_per_pixel * fbi->var.xres) / 8, 3 * img.cols); for (int y = 0; y < h; y++) { const uchar *row = &img.at<uchar>(y, 0); for (int x = 0; x < w; x += 3) { unsigned rgb888 = 0xFF000000 | unsigned(row[x]) | (unsigned(row[x + 1]) << 8) | (unsigned(row[x + 2]) << 16); ((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x / 3] = rgb888; } } } int main(int argc, const char** argv) { struct timeval tv_start, tv_end, tv_res; int edgeThresh = 2; Mat image, gray, edge, cedge; CommandLineParser parser(argc, argv, keys); if (parser.has("help")) { help(); return 0; } edgeThresh = parser.get<int>(1); string filename = parser.get<String>("@image"); image = imread(filename, 1); if(image.empty()) { printf("Cannot read image file: %s\n", filename.c_str()); help(); return -1; } cedge.create(image.size(), image.type()); cvtColor(image, gray, COLOR_BGR2GRAY); gettimeofday(&tv_start, NULL); { blur(gray, edge, Size(3,3)); Canny(edge, edge, edgeThresh, edgeThresh*3, 3); cedge = Scalar::all(0); } gettimeofday(&tv_end, NULL); timersub(&tv_end, &tv_start, &tv_res); image.copyTo(cedge, edge); printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh); printf("Detection time: %d s %d ms\n", (int) tv_res.tv_sec, (int) tv_res.tv_usec / 1000); imdrawfb(cedge); return 0; } <|endoftext|>
<commit_before>20fd64e8-2e4d-11e5-9284-b827eb9e62be<commit_msg>21025d9a-2e4d-11e5-9284-b827eb9e62be<commit_after>21025d9a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d4da9b12-2e4c-11e5-9284-b827eb9e62be<commit_msg>d4dfa6a2-2e4c-11e5-9284-b827eb9e62be<commit_after>d4dfa6a2-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0a5f26fe-2e4d-11e5-9284-b827eb9e62be<commit_msg>0a643266-2e4d-11e5-9284-b827eb9e62be<commit_after>0a643266-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2cefd3f2-2e4e-11e5-9284-b827eb9e62be<commit_msg>2cf4e496-2e4e-11e5-9284-b827eb9e62be<commit_after>2cf4e496-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5c366532-2e4d-11e5-9284-b827eb9e62be<commit_msg>5c3b79b4-2e4d-11e5-9284-b827eb9e62be<commit_after>5c3b79b4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>dd9e3cf8-2e4d-11e5-9284-b827eb9e62be<commit_msg>dda358be-2e4d-11e5-9284-b827eb9e62be<commit_after>dda358be-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>09e509b8-2e4e-11e5-9284-b827eb9e62be<commit_msg>09ea1f98-2e4e-11e5-9284-b827eb9e62be<commit_after>09ea1f98-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>011a4a82-2e4e-11e5-9284-b827eb9e62be<commit_msg>011f4af0-2e4e-11e5-9284-b827eb9e62be<commit_after>011f4af0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ad791c8c-2e4d-11e5-9284-b827eb9e62be<commit_msg>ad7e12be-2e4d-11e5-9284-b827eb9e62be<commit_after>ad7e12be-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1c38cd2e-2e4f-11e5-9284-b827eb9e62be<commit_msg>1c3dd6ca-2e4f-11e5-9284-b827eb9e62be<commit_after>1c3dd6ca-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8e1b698e-2e4e-11e5-9284-b827eb9e62be<commit_msg>8e2072da-2e4e-11e5-9284-b827eb9e62be<commit_after>8e2072da-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>836845fc-2e4e-11e5-9284-b827eb9e62be<commit_msg>836de426-2e4e-11e5-9284-b827eb9e62be<commit_after>836de426-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>da637c2a-2e4c-11e5-9284-b827eb9e62be<commit_msg>da688a8a-2e4c-11e5-9284-b827eb9e62be<commit_after>da688a8a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>125d12ca-2e4e-11e5-9284-b827eb9e62be<commit_msg>12620aaa-2e4e-11e5-9284-b827eb9e62be<commit_after>12620aaa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>33620994-2e4e-11e5-9284-b827eb9e62be<commit_msg>33670278-2e4e-11e5-9284-b827eb9e62be<commit_after>33670278-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>15c514f4-2e4d-11e5-9284-b827eb9e62be<commit_msg>15ca73c2-2e4d-11e5-9284-b827eb9e62be<commit_after>15ca73c2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6aebd738-2e4d-11e5-9284-b827eb9e62be<commit_msg>6af0dd96-2e4d-11e5-9284-b827eb9e62be<commit_after>6af0dd96-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1a462792-2e4e-11e5-9284-b827eb9e62be<commit_msg>1a4b39f8-2e4e-11e5-9284-b827eb9e62be<commit_after>1a4b39f8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0f974d08-2e4e-11e5-9284-b827eb9e62be<commit_msg>0f9c4218-2e4e-11e5-9284-b827eb9e62be<commit_after>0f9c4218-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>03781bde-2e4d-11e5-9284-b827eb9e62be<commit_msg>037d3628-2e4d-11e5-9284-b827eb9e62be<commit_after>037d3628-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>414c8422-2e4d-11e5-9284-b827eb9e62be<commit_msg>4151d7a6-2e4d-11e5-9284-b827eb9e62be<commit_after>4151d7a6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d256a1e2-2e4c-11e5-9284-b827eb9e62be<commit_msg>d25bb0d8-2e4c-11e5-9284-b827eb9e62be<commit_after>d25bb0d8-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>13f8353c-2e4f-11e5-9284-b827eb9e62be<commit_msg>13fd4928-2e4f-11e5-9284-b827eb9e62be<commit_after>13fd4928-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f69ae530-2e4d-11e5-9284-b827eb9e62be<commit_msg>f6a033b4-2e4d-11e5-9284-b827eb9e62be<commit_after>f6a033b4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2b8ded9a-2e4f-11e5-9284-b827eb9e62be<commit_msg>2b92e642-2e4f-11e5-9284-b827eb9e62be<commit_after>2b92e642-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ce5e8c4c-2e4e-11e5-9284-b827eb9e62be<commit_msg>ce638d8c-2e4e-11e5-9284-b827eb9e62be<commit_after>ce638d8c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2016 Nathan Osman * * 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 <QSignalSpy> #include <QTest> #include <nitroshare/deviceenumerator.h> #include <nitroshare/devicemodel.h> const QString TestUuid = "1234"; const QString TestName = "Test"; const QString TestAddress1 = "127.0.0.1"; const QString TestAddress2 = "::1"; class TestDeviceModel : public QObject { Q_OBJECT private Q_SLOTS: void testAddDevice(); void testUpdateDevice(); void testRemoveDevice(); private: void addDevice(); DeviceEnumerator enumerator; }; void TestDeviceModel::testAddDevice() { DeviceModel model; model.addEnumerator(&enumerator); // Watch for rows being inserted QSignalSpy spy(&model, &DeviceModel::rowsInserted); addDevice(); // Ensure one row was inserted at the expected point QCOMPARE(spy.count(), 1); QCOMPARE(spy.at(0).at(1).toInt(), 0); QCOMPARE(spy.at(0).at(2).toInt(), 0); // Ensure the row contains the expected values QModelIndex index = model.index(0, 0); QCOMPARE(model.data(index, DeviceModel::UuidRole).toString(), TestUuid); QCOMPARE(model.data(index, DeviceModel::NameRole).toString(), TestName); QStringList addresses = model.data(index, DeviceModel::AddressesRole).toStringList(); QCOMPARE(addresses.count(), 2); QVERIFY(addresses.contains(TestAddress1)); QVERIFY(addresses.contains(TestAddress2)); } void TestDeviceModel::testUpdateDevice() { //... } void TestDeviceModel::testRemoveDevice() { //... } void TestDeviceModel::addDevice() { // Emit a signal for a new device that has been discovered emit enumerator.deviceUpdated(TestUuid, { { "name", TestName }, { "addresses", QStringList({ TestAddress1, TestAddress2 }) } }); } QTEST_MAIN(TestDeviceModel) #include "TestDeviceModel.moc" <commit_msg>Finish writing tests for DeviceModel.<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2016 Nathan Osman * * 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 <QSignalSpy> #include <QTest> #include <nitroshare/deviceenumerator.h> #include <nitroshare/devicemodel.h> const QString TestUuid = "1234"; const QString TestName = "Test"; const QString TestAddress1 = "127.0.0.1"; const QString TestAddress2 = "::1"; class TestDeviceModel : public QObject { Q_OBJECT private Q_SLOTS: void testAddDevice(); void testUpdateDevice(); void testRemoveDevice(); void testRemoveEnumerator(); private: void addDevice(); DeviceEnumerator enumerator; }; void TestDeviceModel::testAddDevice() { DeviceModel model; model.addEnumerator(&enumerator); // Watch for rows being inserted QSignalSpy spy(&model, &DeviceModel::rowsInserted); addDevice(); // Ensure one row was inserted at the expected point QCOMPARE(spy.count(), 1); QCOMPARE(spy.at(0).at(1).toInt(), 0); QCOMPARE(spy.at(0).at(2).toInt(), 0); // Ensure the row contains the expected values QCOMPARE(model.rowCount(QModelIndex()), 1); QModelIndex index = model.index(0, 0); QCOMPARE(model.data(index, DeviceModel::UuidRole).toString(), TestUuid); QCOMPARE(model.data(index, DeviceModel::NameRole).toString(), TestName); QStringList addresses = model.data(index, DeviceModel::AddressesRole).toStringList(); QCOMPARE(addresses.count(), 2); QVERIFY(addresses.contains(TestAddress1)); QVERIFY(addresses.contains(TestAddress2)); } void TestDeviceModel::testUpdateDevice() { DeviceModel model; model.addEnumerator(&enumerator); addDevice(); // Update the device with identical data QSignalSpy spy(&model, &DeviceModel::dataChanged); addDevice(); // No signal should be emitted QCOMPARE(spy.count(), 0); // Make a change - remove one of the addresses emit enumerator.deviceUpdated(TestUuid, { { "addresses", QStringList({ TestAddress1 }) } }); // Ensure the dataChanged signal was emitted QCOMPARE(spy.count(), 1); QCOMPARE(spy.at(0).at(0).toModelIndex().row(), 0); QCOMPARE(spy.at(0).at(1).toModelIndex().row(), 0); // Ensure the row was updated QModelIndex index = model.index(0, 0); QStringList addresses = model.data(index, DeviceModel::AddressesRole).toStringList(); QCOMPARE(addresses.count(), 1); QVERIFY(addresses.contains(TestAddress1)); } void TestDeviceModel::testRemoveDevice() { DeviceModel model; model.addEnumerator(&enumerator); addDevice(); // Watch for removal of the device QSignalSpy spy(&model, &DeviceModel::rowsRemoved); emit enumerator.deviceRemoved(TestUuid); // Ensure one row was removed QCOMPARE(spy.count(), 1); QCOMPARE(spy.at(0).at(1).toInt(), 0); QCOMPARE(spy.at(0).at(2).toInt(), 0); // Ensure there is nothing left in the model QCOMPARE(model.rowCount(QModelIndex()), 0); } void TestDeviceModel::testRemoveEnumerator() { DeviceModel model; model.addEnumerator(&enumerator); addDevice(); // Watch for removal of the device once the enumerator is removed QSignalSpy spy(&model, &DeviceModel::rowsRemoved); model.removeEnumerator(&enumerator); // Ensure a row was removed QCOMPARE(spy.count(), 1); QCOMPARE(model.rowCount(QModelIndex()), 0); } void TestDeviceModel::addDevice() { // Emit a signal for a new device that has been discovered emit enumerator.deviceUpdated(TestUuid, { { "name", TestName }, { "addresses", QStringList({ TestAddress1, TestAddress2 }) } }); } QTEST_MAIN(TestDeviceModel) #include "TestDeviceModel.moc" <|endoftext|>
<commit_before>6e87de46-2e4d-11e5-9284-b827eb9e62be<commit_msg>6e8cf160-2e4d-11e5-9284-b827eb9e62be<commit_after>6e8cf160-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* ** transport-client.cpp ** Login : <hcuche@hcuche-de> ** Started on Thu Jan 5 15:21:13 2012 Herve Cuche ** $Id$ ** ** Author(s): ** - Herve Cuche <hcuche@aldebaran-robotics.com> ** ** Copyright (C) 2012 Herve Cuche */ #include <iostream> #include <cstring> #include <map> #include <qi/log.hpp> #include <event2/util.h> #include <event2/event.h> #include <event2/buffer.h> #include <event2/bufferevent.h> #include <boost/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <qimessaging/transport_socket.hpp> #include "src/network_thread.hpp" #include <qimessaging/message.hpp> #define MAX_LINE 16384 namespace qi { struct TransportSocketPrivate { TransportSocketPrivate() : tcd(NULL) , bev(NULL) , connected(false) , fd(-1) { } TransportSocketPrivate(int fileDesc) : tcd(NULL) , bev(NULL) , connected(false) , fd(fileDesc) { } ~TransportSocketPrivate() { } TransportSocketInterface *tcd; struct bufferevent *bev; bool connected; std::map<unsigned int, qi::Message*> msgSend; boost::mutex mtx; boost::condition_variable cond; int fd; }; static void readcb(struct bufferevent *bev, void *context) { TransportSocket *tc = static_cast<TransportSocket*>(context); tc->readcb(bev, context); } static void writecb(struct bufferevent* bev, void* context) { TransportSocket *tc = static_cast<TransportSocket*>(context); tc->writecb(bev, context); } static void eventcb(struct bufferevent *bev, short error, void *context) { TransportSocket *tc = static_cast<TransportSocket*>(context); tc->eventcb(bev, error, context); } void TransportSocket::readcb(struct bufferevent *bev, void *context) { // FIXME for multiple message & optimization qi::Buffer *buf = new qi::Buffer(); qi::Message *msg = new qi::Message(buf); struct evbuffer *input = bufferevent_get_input(bev); struct evbuffer *tmp = evbuffer_new(); // get the header evbuffer_remove(input, msg->_header, sizeof(qi::Message::MessageHeader)); // get the data //TODO check the return value evbuffer_remove_buffer(input, tmp, msg->_header->size); // set the data buf->setData(reinterpret_cast<void*>(tmp)); boost::mutex::scoped_lock l(_p->mtx); { _p->msgSend[msg->id()] = msg; _p->tcd->onReadyRead(this, *msg); _p->cond.notify_all(); } } void TransportSocket::writecb(struct bufferevent* bev, void* context) { _p->tcd->onWriteDone(this); } void TransportSocket::eventcb(struct bufferevent *bev, short events, void *context) { if (events & BEV_EVENT_CONNECTED) { qi::Message msg; _p->connected = true; _p->tcd->onConnected(this); } else if (events & BEV_EVENT_EOF) { qi::Message msg; _p->tcd->onDisconnected(this); _p->connected = false; // connection has been closed, do any clean up here qiLogInfo("qimessaging.TransportSocket") << "connection has been closed, do any clean up here" << std::endl; } else if (events & BEV_EVENT_ERROR) { bufferevent_free(_p->bev); // check errno to see what error occurred qiLogError("qimessaging.TransportSocket") << "Cannnot connect" << std::endl; } else if (events & BEV_EVENT_TIMEOUT) { // must be a timeout event handle, handle it qiLogError("qimessaging.TransportSocket") << "must be a timeout event handle, handle it" << std::endl; } } TransportSocket::TransportSocket() { _p = new TransportSocketPrivate(); } TransportSocket::TransportSocket(int fd, struct event_base *base) { _p = new TransportSocketPrivate(fd); _p->bev = bufferevent_socket_new(base, _p->fd, BEV_OPT_CLOSE_ON_FREE); bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this); bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE); bufferevent_enable(_p->bev, EV_READ|EV_WRITE); _p->connected = true; } TransportSocket::~TransportSocket() { disconnect(); delete _p; } bool TransportSocket::connect(const qi::Url &url, struct event_base *base) { const std::string &address = url.host(); unsigned short port = url.port(); if (!_p->connected) { _p->bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this); bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE); bufferevent_enable(_p->bev, EV_READ|EV_WRITE); bufferevent_socket_connect_hostname(_p->bev, NULL, AF_INET, address.c_str(), port); if (_p->connected) return true; } return false; } bool TransportSocket::waitForConnected(int msecs) { // no timeout if (msecs < 0) { while (!_p->connected) ; return true; } while (!_p->connected && msecs > 0) { qi::os::msleep(1); msecs--; } // timeout if (msecs == 0) return false; return true; } void TransportSocket::disconnect() { if (_p->connected) { bufferevent_free(_p->bev); _p->bev = NULL; _p->connected = false; } } bool TransportSocket::waitForDisconnected(int msecs) { // no timeout if (msecs < 0) { while (_p->connected) ; return true; } while (_p->connected && msecs > 0) { qi::os::msleep(1); msecs--; } // timeout if (msecs == 0) return false; return true; } bool TransportSocket::waitForId(int id, int msecs) { std::map<unsigned int, qi::Message*>::iterator it; { boost::mutex::scoped_lock l(_p->mtx); { it = _p->msgSend.find(id); if (it != _p->msgSend.end()) return true; if (msecs > 0) _p->cond.timed_wait(l, boost::posix_time::milliseconds(msecs)); else _p->cond.wait(l); it = _p->msgSend.find(id); if (it != _p->msgSend.end()) return true; } } return false; } void TransportSocket::read(int id, qi::Message *msg) { std::map<unsigned int, qi::Message*>::iterator it; { boost::mutex::scoped_lock l(_p->mtx); { it = _p->msgSend.find(id); if (it != _p->msgSend.end()) { qi::Message ans = *(it->second); *msg = ans; _p->msgSend.erase(it); } } } } bool TransportSocket::send(qi::Message &msg) { msg.complete(); struct evbuffer *output = bufferevent_get_output(_p->bev); if (_p->connected && !evbuffer_add_buffer(output, reinterpret_cast<struct evbuffer*>(msg.buffer()->data()))) { return true; } return false; } void TransportSocket::setDelegate(TransportSocketInterface *delegate) { _p->tcd = delegate; } bool TransportSocket::isConnected() { return _p->connected; } } <commit_msg>use bufferevent instead of evbuffer to send a message<commit_after>/* ** transport-client.cpp ** Login : <hcuche@hcuche-de> ** Started on Thu Jan 5 15:21:13 2012 Herve Cuche ** $Id$ ** ** Author(s): ** - Herve Cuche <hcuche@aldebaran-robotics.com> ** ** Copyright (C) 2012 Herve Cuche */ #include <iostream> #include <cstring> #include <map> #include <qi/log.hpp> #include <event2/util.h> #include <event2/event.h> #include <event2/buffer.h> #include <event2/bufferevent.h> #include <boost/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <qimessaging/transport_socket.hpp> #include "src/network_thread.hpp" #include <qimessaging/message.hpp> #define MAX_LINE 16384 namespace qi { struct TransportSocketPrivate { TransportSocketPrivate() : tcd(NULL) , bev(NULL) , connected(false) , fd(-1) { } TransportSocketPrivate(int fileDesc) : tcd(NULL) , bev(NULL) , connected(false) , fd(fileDesc) { } ~TransportSocketPrivate() { } TransportSocketInterface *tcd; struct bufferevent *bev; bool connected; std::map<unsigned int, qi::Message*> msgSend; boost::mutex mtx; boost::condition_variable cond; int fd; }; static void readcb(struct bufferevent *bev, void *context) { TransportSocket *tc = static_cast<TransportSocket*>(context); tc->readcb(bev, context); } static void writecb(struct bufferevent* bev, void* context) { TransportSocket *tc = static_cast<TransportSocket*>(context); tc->writecb(bev, context); } static void eventcb(struct bufferevent *bev, short error, void *context) { TransportSocket *tc = static_cast<TransportSocket*>(context); tc->eventcb(bev, error, context); } void TransportSocket::readcb(struct bufferevent *bev, void *context) { // FIXME for multiple message & optimization qi::Buffer *buf = new qi::Buffer(); qi::Message *msg = new qi::Message(buf); struct evbuffer *input = bufferevent_get_input(bev); struct evbuffer *tmp = evbuffer_new(); // get the header evbuffer_remove(input, msg->_header, sizeof(qi::Message::MessageHeader)); // get the data //TODO check the return value evbuffer_remove_buffer(input, tmp, msg->_header->size); // set the data buf->setData(reinterpret_cast<void*>(tmp)); boost::mutex::scoped_lock l(_p->mtx); { _p->msgSend[msg->id()] = msg; _p->tcd->onReadyRead(this, *msg); _p->cond.notify_all(); } } void TransportSocket::writecb(struct bufferevent* bev, void* context) { _p->tcd->onWriteDone(this); } void TransportSocket::eventcb(struct bufferevent *bev, short events, void *context) { if (events & BEV_EVENT_CONNECTED) { qi::Message msg; _p->connected = true; _p->tcd->onConnected(this); } else if (events & BEV_EVENT_EOF) { qi::Message msg; _p->tcd->onDisconnected(this); _p->connected = false; // connection has been closed, do any clean up here qiLogInfo("qimessaging.TransportSocket") << "connection has been closed, do any clean up here" << std::endl; } else if (events & BEV_EVENT_ERROR) { bufferevent_free(_p->bev); // check errno to see what error occurred qiLogError("qimessaging.TransportSocket") << "Cannnot connect" << std::endl; } else if (events & BEV_EVENT_TIMEOUT) { // must be a timeout event handle, handle it qiLogError("qimessaging.TransportSocket") << "must be a timeout event handle, handle it" << std::endl; } } TransportSocket::TransportSocket() { _p = new TransportSocketPrivate(); } TransportSocket::TransportSocket(int fd, struct event_base *base) { _p = new TransportSocketPrivate(fd); _p->bev = bufferevent_socket_new(base, _p->fd, BEV_OPT_CLOSE_ON_FREE); bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this); bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE); bufferevent_enable(_p->bev, EV_READ|EV_WRITE); _p->connected = true; } TransportSocket::~TransportSocket() { disconnect(); delete _p; } bool TransportSocket::connect(const qi::Url &url, struct event_base *base) { const std::string &address = url.host(); unsigned short port = url.port(); if (!_p->connected) { _p->bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this); bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE); bufferevent_enable(_p->bev, EV_READ|EV_WRITE); bufferevent_socket_connect_hostname(_p->bev, NULL, AF_INET, address.c_str(), port); if (_p->connected) return true; } return false; } bool TransportSocket::waitForConnected(int msecs) { // no timeout if (msecs < 0) { while (!_p->connected) ; return true; } while (!_p->connected && msecs > 0) { qi::os::msleep(1); msecs--; } // timeout if (msecs == 0) return false; return true; } void TransportSocket::disconnect() { if (_p->connected) { bufferevent_free(_p->bev); _p->bev = NULL; _p->connected = false; } } bool TransportSocket::waitForDisconnected(int msecs) { // no timeout if (msecs < 0) { while (_p->connected) ; return true; } while (_p->connected && msecs > 0) { qi::os::msleep(1); msecs--; } // timeout if (msecs == 0) return false; return true; } bool TransportSocket::waitForId(int id, int msecs) { std::map<unsigned int, qi::Message*>::iterator it; { boost::mutex::scoped_lock l(_p->mtx); { it = _p->msgSend.find(id); if (it != _p->msgSend.end()) return true; if (msecs > 0) _p->cond.timed_wait(l, boost::posix_time::milliseconds(msecs)); else _p->cond.wait(l); it = _p->msgSend.find(id); if (it != _p->msgSend.end()) return true; } } return false; } void TransportSocket::read(int id, qi::Message *msg) { std::map<unsigned int, qi::Message*>::iterator it; { boost::mutex::scoped_lock l(_p->mtx); { it = _p->msgSend.find(id); if (it != _p->msgSend.end()) { qi::Message ans = *(it->second); *msg = ans; _p->msgSend.erase(it); } } } } bool TransportSocket::send(qi::Message &msg) { msg.complete(); struct evbuffer *buf = reinterpret_cast<struct evbuffer*>(msg.buffer()->data()); if (_p->connected && (bufferevent_write_buffer(_p->bev, buf) == 0)) return true; return false; } void TransportSocket::setDelegate(TransportSocketInterface *delegate) { _p->tcd = delegate; } bool TransportSocket::isConnected() { return _p->connected; } } <|endoftext|>
<commit_before>9ac6ca62-2e4d-11e5-9284-b827eb9e62be<commit_msg>9acbcb34-2e4d-11e5-9284-b827eb9e62be<commit_after>9acbcb34-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>852e0a02-2e4e-11e5-9284-b827eb9e62be<commit_msg>85332000-2e4e-11e5-9284-b827eb9e62be<commit_after>85332000-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>477e613a-2e4d-11e5-9284-b827eb9e62be<commit_msg>47836f86-2e4d-11e5-9284-b827eb9e62be<commit_after>47836f86-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>92cf06e4-2e4d-11e5-9284-b827eb9e62be<commit_msg>92d413fa-2e4d-11e5-9284-b827eb9e62be<commit_after>92d413fa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>76f850b4-2e4e-11e5-9284-b827eb9e62be<commit_msg>76fd61bc-2e4e-11e5-9284-b827eb9e62be<commit_after>76fd61bc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aa993498-2e4d-11e5-9284-b827eb9e62be<commit_msg>aa9e388a-2e4d-11e5-9284-b827eb9e62be<commit_after>aa9e388a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8d07950a-2e4d-11e5-9284-b827eb9e62be<commit_msg>8d0c999c-2e4d-11e5-9284-b827eb9e62be<commit_after>8d0c999c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>084be49a-2e4f-11e5-9284-b827eb9e62be<commit_msg>0850d9a0-2e4f-11e5-9284-b827eb9e62be<commit_after>0850d9a0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aa6c0e56-2e4c-11e5-9284-b827eb9e62be<commit_msg>aa70f8d0-2e4c-11e5-9284-b827eb9e62be<commit_after>aa70f8d0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a7bfd366-2e4e-11e5-9284-b827eb9e62be<commit_msg>a7c4e4d2-2e4e-11e5-9284-b827eb9e62be<commit_after>a7c4e4d2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>acdf8398-2e4c-11e5-9284-b827eb9e62be<commit_msg>ace47b14-2e4c-11e5-9284-b827eb9e62be<commit_after>ace47b14-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbMultivariateAlterationDetectorImageFilter.h" namespace otb { namespace Wrapper { class MultivariateAlterationDetector: public Application { public: /** Standard class typedefs. */ typedef MultivariateAlterationDetector Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(MultivariateAlterationDetector, otb::Wrapper::Application); private: void DoInit() override { SetName("MultivariateAlterationDetector"); SetDescription("Change detection by Multivariate Alteration Detector (MAD) algorithm"); // Documentation SetDocLongDescription("This application performs change detection between two multispectral" " images using the Multivariate Alteration Detector (MAD) [1]" " algorithm.\n\n" "The MAD algorithm produces a set of N change maps (where N is the" " maximum number of bands in first and second input images), with the" " following properties:\n\n" "* Change maps are differences of a pair of linear combinations of " " bands from image 1 and bands from image 2 chosen to maximize the " " correlation, \n" "* Each change map is orthogonal to the others.\n\n" "This is a statistical method which can handle different modalities" " and even different bands and number of bands between images. \n" " \n" "The application will output all change maps into a single multiband" " image. If numbers of bands in image 1 and 2 are equal, then change" " maps are sorted by increasing correlation. If number of bands is" " different, the change maps are sorted by decreasing correlation. \n" " \n" "The application will also print the following information:\n" "- Mean1 and Mean2 which are the mean values of bands for both input" " images,\n" "- V1 and V2 which are the two linear transform that are applied to" " input image 1 and input image 2 to build the change map,\n" "- Rho, the vector of correlation associated to each change map.\n" " \n" "The OTB filter used in this application has been implemented from the" " Matlab code kindly made available by the authors here [2]. Both cases" " (same and different number of bands) have been validated" " by comparing the output image to the output produced by the Matlab " " code, and the reference images for testing have been generated from " " the Matlab code using Octave." ); SetDocLimitations("Input images 1 and 2 should share exactly the same origin, spacing, size, and projection if any."); SetDocAuthors("OTB-Team"); SetDocSeeAlso("[1] Nielsen, A. A., & Conradsen, K. (1997). Multivariate alteration" "detection (MAD) in multispectral, bi-temporal image data: A new" "approach to change detection studies.\n" "[2] http://www2.imm.dtu.dk/~aa/software.html"); AddDocTag(Tags::ChangeDetection); AddParameter(ParameterType_InputImage, "in1", "Input Image 1"); SetParameterDescription("in1","Multiband image of the scene before perturbations"); AddParameter(ParameterType_InputImage, "in2", "Input Image 2"); SetParameterDescription("in2","Mutliband image of the scene after perturbations."); AddParameter(ParameterType_OutputImage, "out", "Change Map"); SetParameterDescription("out","Multiband image containing change maps. Each map will be in the range [-1,1], so a floating point output type is advised."); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in1", "Spot5-Gloucester-before.tif"); SetDocExampleParameterValue("in2", "Spot5-Gloucester-after.tif"); SetDocExampleParameterValue("out", "detectedChangeImage.tif"); SetOfficialDocLink(); } void DoUpdateParameters() override { } void DoExecute() override { typedef otb::MultivariateAlterationDetectorImageFilter< FloatVectorImageType, FloatVectorImageType> ChangeFilterType; ChangeFilterType::Pointer changeFilter = ChangeFilterType::New(); changeFilter->SetInput1(GetParameterImage("in1")); changeFilter->SetInput2(GetParameterImage("in2")); changeFilter->GetOutput()->UpdateOutputInformation(); otbAppLogINFO("Input 1 mean: "<<changeFilter->GetMean1()); otbAppLogINFO("Input 2 mean: "<<changeFilter->GetMean2()); otbAppLogINFO("Input 1 transform: "<<changeFilter->GetV1()); otbAppLogINFO("Input 2 transform: "<<changeFilter->GetV2()); otbAppLogINFO("Rho: "<<changeFilter->GetRho()); m_Ref = changeFilter; SetParameterOutputImage("out", changeFilter->GetOutput()); } itk::LightObject::Pointer m_Ref; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::MultivariateAlterationDetector) <commit_msg>DOC: fix errors in the MAD application documentation<commit_after>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbMultivariateAlterationDetectorImageFilter.h" namespace otb { namespace Wrapper { class MultivariateAlterationDetector: public Application { public: /** Standard class typedefs. */ typedef MultivariateAlterationDetector Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(MultivariateAlterationDetector, otb::Wrapper::Application); private: void DoInit() override { SetName("MultivariateAlterationDetector"); SetDescription("Change detection by Multivariate Alteration Detector (MAD) algorithm"); // Documentation SetDocLongDescription("This application performs change detection between two multispectral" " images using the Multivariate Alteration Detector (MAD) [1]" " algorithm.\n\n" "The MAD algorithm produces a set of N change maps (where N is the" " maximum number of bands in first and second input images), with the" " following properties:\n\n" "* Change maps are differences of a pair of linear combinations of " " bands from image 1 and bands from image 2 chosen to maximize the " " correlation, \n" "* Each change map is orthogonal to the others.\n\n" "This is a statistical method which can handle different modalities" " and even different bands and number of bands between images. \n" " \n" "The application will output all change maps into a single multiband" " image. Change maps are sorted by increasing correlation. \n" " \n" "The application will also print the following information:\n\n" "- Mean1 and Mean2 which are the mean values of bands for both input" " images,\n" "- V1 and V2 which are the two linear transform that are applied to" " input image 1 and input image 2 to build the change map,\n" "- Rho, the vector of correlation associated to each change map.\n" " \n" "The OTB filter used in this application has been implemented from the" " Matlab code kindly made available by the authors here [2]. Both cases" " (same and different number of bands) have been validated" " by comparing the output image to the output produced by the Matlab " " code, and the reference images for testing have been generated from " " the Matlab code using Octave." ); SetDocLimitations("Input images 1 and 2 should share exactly the same origin, spacing, size, and projection if any."); SetDocAuthors("OTB-Team"); SetDocSeeAlso("[1] Nielsen, A. A., & Conradsen, K. (1997). Multivariate alteration" "detection (MAD) in multispectral, bi-temporal image data: A new" "approach to change detection studies.\n" "[2] http://www2.imm.dtu.dk/~aa/software.html"); AddDocTag(Tags::ChangeDetection); AddParameter(ParameterType_InputImage, "in1", "Input Image 1"); SetParameterDescription("in1","Multiband image of the scene before perturbations"); AddParameter(ParameterType_InputImage, "in2", "Input Image 2"); SetParameterDescription("in2","Mutliband image of the scene after perturbations."); AddParameter(ParameterType_OutputImage, "out", "Change Map"); SetParameterDescription("out","Multiband image containing change maps."); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in1", "Spot5-Gloucester-before.tif"); SetDocExampleParameterValue("in2", "Spot5-Gloucester-after.tif"); SetDocExampleParameterValue("out", "detectedChangeImage.tif"); SetOfficialDocLink(); } void DoUpdateParameters() override { } void DoExecute() override { typedef otb::MultivariateAlterationDetectorImageFilter< FloatVectorImageType, FloatVectorImageType> ChangeFilterType; ChangeFilterType::Pointer changeFilter = ChangeFilterType::New(); changeFilter->SetInput1(GetParameterImage("in1")); changeFilter->SetInput2(GetParameterImage("in2")); changeFilter->GetOutput()->UpdateOutputInformation(); otbAppLogINFO("Input 1 mean: "<<changeFilter->GetMean1()); otbAppLogINFO("Input 2 mean: "<<changeFilter->GetMean2()); otbAppLogINFO("Input 1 transform: "<<changeFilter->GetV1()); otbAppLogINFO("Input 2 transform: "<<changeFilter->GetV2()); otbAppLogINFO("Rho: "<<changeFilter->GetRho()); m_Ref = changeFilter; SetParameterOutputImage("out", changeFilter->GetOutput()); } itk::LightObject::Pointer m_Ref; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::MultivariateAlterationDetector) <|endoftext|>
<commit_before>67bfb4b6-2e4e-11e5-9284-b827eb9e62be<commit_msg>67c4ac32-2e4e-11e5-9284-b827eb9e62be<commit_after>67c4ac32-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ #ifndef itkVectorGradientMagnitudeImageFilter_hxx #define itkVectorGradientMagnitudeImageFilter_hxx #include "itkVectorGradientMagnitudeImageFilter.h" #include "itkNeighborhoodAlgorithm.h" #include "itkImageRegionIterator.h" #include "itkZeroFluxNeumannBoundaryCondition.h" #include "itkProgressReporter.h" #include "itkVectorCastImageFilter.h" #include "itkMath.h" namespace itk { template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { unsigned i; Superclass::PrintSelf(os, indent); os << indent << "m_UseImageSpacing = " << m_UseImageSpacing << std::endl; os << indent << "m_UsePrincipleComponents = " << m_UseImageSpacing << std::endl; os << indent << "m_RequestedNumberOfThreads = " << m_RequestedNumberOfThreads << std::endl; os << indent << "m_DerivativeWeights = "; for ( i = 0; i < ImageDimension; i++ ) { os << m_DerivativeWeights[i] << " "; } os << std::endl; os << indent << "m_ComponentWeights = "; for ( i = 0; i < VectorDimension; i++ ) { os << m_ComponentWeights[i] << " "; } os << std::endl; os << indent << "m_RealValuedInputImage = " << m_RealValuedInputImage.GetPointer() << std::endl; } template< typename TInputImage, typename TRealType, typename TOutputImage > VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::VectorGradientMagnitudeImageFilter() { unsigned int i; m_UseImageSpacing = true; m_UsePrincipleComponents = true; m_RequestedNumberOfThreads = this->GetNumberOfThreads(); for ( i = 0; i < ImageDimension; i++ ) { m_DerivativeWeights[i] = static_cast< TRealType >( 1.0 ); } for ( i = 0; i < VectorDimension; i++ ) { m_ComponentWeights[i] = static_cast< TRealType >( 1.0 ); m_SqrtComponentWeights[i] = static_cast< TRealType >( 1.0 ); } } template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::SetUseImageSpacing(bool f) { if ( m_UseImageSpacing == f ) { return; } // Only reset the weights if they were previously set to the image spacing, // otherwise, the user may have provided their own weightings. if ( f == false && m_UseImageSpacing == true ) { for ( unsigned i = 0; i < ImageDimension; ++i ) { m_DerivativeWeights[i] = static_cast< TRealType >( 1.0 ); } } m_UseImageSpacing = f; } template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::GenerateInputRequestedRegion() { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); // get pointers to the input and output InputImagePointer inputPtr = const_cast< InputImageType * >( this->GetInput() ); OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) { return; } // get a copy of the input requested region (should equal the output // requested region) typename TInputImage::RegionType inputRequestedRegion; inputRequestedRegion = inputPtr->GetRequestedRegion(); RadiusType r1; r1.Fill(1); // pad the input requested region by the operator radius inputRequestedRegion.PadByRadius(r1); // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() ) ) { inputPtr->SetRequestedRegion(inputRequestedRegion); return; } else { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. // store what we tried to request (prior to trying to crop) inputPtr->SetRequestedRegion(inputRequestedRegion); // build an exception InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; } } template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::BeforeThreadedGenerateData() { Superclass::BeforeThreadedGenerateData(); // Calculate the square-roots of the component weights. for ( unsigned i = 0; i < VectorDimension; ++i ) { if ( m_ComponentWeights[i] < 0 ) { itkExceptionMacro(<< "Component weights must be positive numbers"); } m_SqrtComponentWeights[i] = std::sqrt(m_ComponentWeights[i]); } // Set the weights on the derivatives. // Are we using image spacing in the calculations? If so we must update now // in case our input image has changed. if ( m_UseImageSpacing == true ) { for ( unsigned i = 0; i < ImageDimension; i++ ) { if ( static_cast< TRealType >( this->GetInput()->GetSpacing()[i] ) == 0.0 ) { itkExceptionMacro(<< "Image spacing in dimension " << i << " is zero."); } m_DerivativeWeights[i] = static_cast< TRealType >( 1.0 / static_cast< TRealType >( this->GetInput()->GetSpacing()[i] ) ); } } // If using the principle components method, then force this filter to use a // single thread because vnl eigensystem objects are not thread-safe. 3D // data is ok because we have a special solver. if ( m_UsePrincipleComponents == true && ImageDimension != 3 ) { m_RequestedNumberOfThreads = this->GetNumberOfThreads(); this->SetNumberOfThreads(1); } else { this->SetNumberOfThreads(m_RequestedNumberOfThreads); } // // cast might not be necessary, but CastImagefilter is optimized for // the case where the InputImageType == OutputImageType typename VectorCastImageFilter< TInputImage, RealVectorImageType >::Pointer caster = VectorCastImageFilter< TInputImage, RealVectorImageType >::New(); caster->SetInput( this->GetInput() ); caster->GetOutput()->SetRequestedRegion( this->GetInput()->GetRequestedRegion() ); caster->Update(); m_RealValuedInputImage = caster->GetOutput(); } template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId) { ZeroFluxNeumannBoundaryCondition< RealVectorImageType > nbc; ConstNeighborhoodIteratorType bit; ImageRegionIterator< TOutputImage > it; // Find the data-set boundary "faces" typename NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< RealVectorImageType >:: FaceListType faceList; NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< RealVectorImageType > bC; RadiusType r1; r1.Fill(1); faceList = bC(dynamic_cast< const RealVectorImageType * >( m_RealValuedInputImage.GetPointer() ), outputRegionForThread, r1); typename NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< RealVectorImageType >:: FaceListType::iterator fit; fit = faceList.begin(); // Support progress methods/callbacks ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); // Process each of the data set faces. The iterator is reinitialized on each // face so that it can determine whether or not to check for boundary // conditions. for ( fit = faceList.begin(); fit != faceList.end(); ++fit ) { bit = ConstNeighborhoodIteratorType(r1, dynamic_cast< const RealVectorImageType * >( m_RealValuedInputImage.GetPointer() ), *fit); it = ImageRegionIterator< TOutputImage >(this->GetOutput(), *fit); bit.OverrideBoundaryCondition(&nbc); bit.GoToBegin(); if ( m_UsePrincipleComponents == true ) { if ( ImageDimension == 3 ) { // Use the specialized eigensolve which can be threaded while ( !bit.IsAtEnd() ) { it.Set( this->EvaluateAtNeighborhood3D(bit) ); ++bit; ++it; progress.CompletedPixel(); } } else { while ( !bit.IsAtEnd() ) { it.Set( this->EvaluateAtNeighborhood(bit) ); ++bit; ++it; progress.CompletedPixel(); } } } else { while ( !bit.IsAtEnd() ) { it.Set( this->NonPCEvaluateAtNeighborhood(bit) ); ++bit; ++it; progress.CompletedPixel(); } } } } template< typename TInputImage, typename TRealType, typename TOutputImage > int VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::CubicSolver(double *c, double *s) { // IMPORTANT // This code is specialized for particular case of positive symmetric // matrix. It also assumes that x^3 coefficient is 1. c contains the // coefficients of the polynomial: x^3 + c[2]x^2 + c[1]x^1 + c[0]. The roots // s are not necessarily sorted, and int is the number of distinct roots // found in s. int num; const double dpi = itk::Math::pi; const double epsilon = 1.0e-11; // Substitution of x = y - c[2]/3 eliminate the quadric term x^3 +px + q = 0 double sq_c2 = c[2] * c[2]; double p = 1.0 / 3 * ( -1.0 / 3.0 * sq_c2 + c[1] ); double q = 1.0 / 2 * ( 2.0 / 27.0 * c[2] * sq_c2 - 1.0 / 3.0 * c[2] * c[1] + c[0] ); // Cardano's formula double cb_p = p * p * p; double D = q * q + cb_p; if ( D < -epsilon ) // D < 0, three real solutions, by far the common case. { double phi = 1.0 / 3.0 * std::acos( -q / std::sqrt(-cb_p) ); double t = 2.0 * std::sqrt(-p); s[0] = t * std::cos(phi); s[1] = -t *std::cos(phi + dpi / 3); s[2] = -t *std::cos(phi - dpi / 3); num = 3; } else if ( D < epsilon ) // D == 0 { if ( q > -epsilon && q < epsilon ) { s[0] = 0.0; num = 1; } else { double u = itk::Math::cbrt(-q); s[0] = 2 * u; s[1] = -u; num = 2; } } else // Only one real solution. This case misses a double root on rare // occasions with very large char eqn coefficients. { double sqrt_D = std::sqrt(D); double u = itk::Math::cbrt(sqrt_D - q); double v = -itk::Math::cbrt(sqrt_D + q); s[0] = u + v; num = 1; } // Resubstitute double sub = 1.0 / 3.0 * c[2]; for ( int i = 0; i < num; ++i ) { s[i] -= sub; } return num; } } // end namespace itk #endif <commit_msg>DOC: PrincipleComponent flag incorrectly reported by PrintSelf<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ #ifndef itkVectorGradientMagnitudeImageFilter_hxx #define itkVectorGradientMagnitudeImageFilter_hxx #include "itkVectorGradientMagnitudeImageFilter.h" #include "itkNeighborhoodAlgorithm.h" #include "itkImageRegionIterator.h" #include "itkZeroFluxNeumannBoundaryCondition.h" #include "itkProgressReporter.h" #include "itkVectorCastImageFilter.h" #include "itkMath.h" namespace itk { template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { unsigned i; Superclass::PrintSelf(os, indent); os << indent << "m_UseImageSpacing = " << m_UseImageSpacing << std::endl; os << indent << "m_UsePrincipleComponents = " << m_UsePrincipleComponents << std::endl; os << indent << "m_RequestedNumberOfThreads = " << m_RequestedNumberOfThreads << std::endl; os << indent << "m_DerivativeWeights = "; for ( i = 0; i < ImageDimension; i++ ) { os << m_DerivativeWeights[i] << " "; } os << std::endl; os << indent << "m_ComponentWeights = "; for ( i = 0; i < VectorDimension; i++ ) { os << m_ComponentWeights[i] << " "; } os << std::endl; os << indent << "m_RealValuedInputImage = " << m_RealValuedInputImage.GetPointer() << std::endl; } template< typename TInputImage, typename TRealType, typename TOutputImage > VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::VectorGradientMagnitudeImageFilter() { unsigned int i; m_UseImageSpacing = true; m_UsePrincipleComponents = true; m_RequestedNumberOfThreads = this->GetNumberOfThreads(); for ( i = 0; i < ImageDimension; i++ ) { m_DerivativeWeights[i] = static_cast< TRealType >( 1.0 ); } for ( i = 0; i < VectorDimension; i++ ) { m_ComponentWeights[i] = static_cast< TRealType >( 1.0 ); m_SqrtComponentWeights[i] = static_cast< TRealType >( 1.0 ); } } template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::SetUseImageSpacing(bool f) { if ( m_UseImageSpacing == f ) { return; } // Only reset the weights if they were previously set to the image spacing, // otherwise, the user may have provided their own weightings. if ( f == false && m_UseImageSpacing == true ) { for ( unsigned i = 0; i < ImageDimension; ++i ) { m_DerivativeWeights[i] = static_cast< TRealType >( 1.0 ); } } m_UseImageSpacing = f; } template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::GenerateInputRequestedRegion() { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); // get pointers to the input and output InputImagePointer inputPtr = const_cast< InputImageType * >( this->GetInput() ); OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) { return; } // get a copy of the input requested region (should equal the output // requested region) typename TInputImage::RegionType inputRequestedRegion; inputRequestedRegion = inputPtr->GetRequestedRegion(); RadiusType r1; r1.Fill(1); // pad the input requested region by the operator radius inputRequestedRegion.PadByRadius(r1); // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() ) ) { inputPtr->SetRequestedRegion(inputRequestedRegion); return; } else { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. // store what we tried to request (prior to trying to crop) inputPtr->SetRequestedRegion(inputRequestedRegion); // build an exception InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; } } template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::BeforeThreadedGenerateData() { Superclass::BeforeThreadedGenerateData(); // Calculate the square-roots of the component weights. for ( unsigned i = 0; i < VectorDimension; ++i ) { if ( m_ComponentWeights[i] < 0 ) { itkExceptionMacro(<< "Component weights must be positive numbers"); } m_SqrtComponentWeights[i] = std::sqrt(m_ComponentWeights[i]); } // Set the weights on the derivatives. // Are we using image spacing in the calculations? If so we must update now // in case our input image has changed. if ( m_UseImageSpacing == true ) { for ( unsigned i = 0; i < ImageDimension; i++ ) { if ( static_cast< TRealType >( this->GetInput()->GetSpacing()[i] ) == 0.0 ) { itkExceptionMacro(<< "Image spacing in dimension " << i << " is zero."); } m_DerivativeWeights[i] = static_cast< TRealType >( 1.0 / static_cast< TRealType >( this->GetInput()->GetSpacing()[i] ) ); } } // If using the principle components method, then force this filter to use a // single thread because vnl eigensystem objects are not thread-safe. 3D // data is ok because we have a special solver. if ( m_UsePrincipleComponents == true && ImageDimension != 3 ) { m_RequestedNumberOfThreads = this->GetNumberOfThreads(); this->SetNumberOfThreads(1); } else { this->SetNumberOfThreads(m_RequestedNumberOfThreads); } // // cast might not be necessary, but CastImagefilter is optimized for // the case where the InputImageType == OutputImageType typename VectorCastImageFilter< TInputImage, RealVectorImageType >::Pointer caster = VectorCastImageFilter< TInputImage, RealVectorImageType >::New(); caster->SetInput( this->GetInput() ); caster->GetOutput()->SetRequestedRegion( this->GetInput()->GetRequestedRegion() ); caster->Update(); m_RealValuedInputImage = caster->GetOutput(); } template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId) { ZeroFluxNeumannBoundaryCondition< RealVectorImageType > nbc; ConstNeighborhoodIteratorType bit; ImageRegionIterator< TOutputImage > it; // Find the data-set boundary "faces" typename NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< RealVectorImageType >:: FaceListType faceList; NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< RealVectorImageType > bC; RadiusType r1; r1.Fill(1); faceList = bC(dynamic_cast< const RealVectorImageType * >( m_RealValuedInputImage.GetPointer() ), outputRegionForThread, r1); typename NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< RealVectorImageType >:: FaceListType::iterator fit; fit = faceList.begin(); // Support progress methods/callbacks ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); // Process each of the data set faces. The iterator is reinitialized on each // face so that it can determine whether or not to check for boundary // conditions. for ( fit = faceList.begin(); fit != faceList.end(); ++fit ) { bit = ConstNeighborhoodIteratorType(r1, dynamic_cast< const RealVectorImageType * >( m_RealValuedInputImage.GetPointer() ), *fit); it = ImageRegionIterator< TOutputImage >(this->GetOutput(), *fit); bit.OverrideBoundaryCondition(&nbc); bit.GoToBegin(); if ( m_UsePrincipleComponents == true ) { if ( ImageDimension == 3 ) { // Use the specialized eigensolve which can be threaded while ( !bit.IsAtEnd() ) { it.Set( this->EvaluateAtNeighborhood3D(bit) ); ++bit; ++it; progress.CompletedPixel(); } } else { while ( !bit.IsAtEnd() ) { it.Set( this->EvaluateAtNeighborhood(bit) ); ++bit; ++it; progress.CompletedPixel(); } } } else { while ( !bit.IsAtEnd() ) { it.Set( this->NonPCEvaluateAtNeighborhood(bit) ); ++bit; ++it; progress.CompletedPixel(); } } } } template< typename TInputImage, typename TRealType, typename TOutputImage > int VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::CubicSolver(double *c, double *s) { // IMPORTANT // This code is specialized for particular case of positive symmetric // matrix. It also assumes that x^3 coefficient is 1. c contains the // coefficients of the polynomial: x^3 + c[2]x^2 + c[1]x^1 + c[0]. The roots // s are not necessarily sorted, and int is the number of distinct roots // found in s. int num; const double dpi = itk::Math::pi; const double epsilon = 1.0e-11; // Substitution of x = y - c[2]/3 eliminate the quadric term x^3 +px + q = 0 double sq_c2 = c[2] * c[2]; double p = 1.0 / 3 * ( -1.0 / 3.0 * sq_c2 + c[1] ); double q = 1.0 / 2 * ( 2.0 / 27.0 * c[2] * sq_c2 - 1.0 / 3.0 * c[2] * c[1] + c[0] ); // Cardano's formula double cb_p = p * p * p; double D = q * q + cb_p; if ( D < -epsilon ) // D < 0, three real solutions, by far the common case. { double phi = 1.0 / 3.0 * std::acos( -q / std::sqrt(-cb_p) ); double t = 2.0 * std::sqrt(-p); s[0] = t * std::cos(phi); s[1] = -t *std::cos(phi + dpi / 3); s[2] = -t *std::cos(phi - dpi / 3); num = 3; } else if ( D < epsilon ) // D == 0 { if ( q > -epsilon && q < epsilon ) { s[0] = 0.0; num = 1; } else { double u = itk::Math::cbrt(-q); s[0] = 2 * u; s[1] = -u; num = 2; } } else // Only one real solution. This case misses a double root on rare // occasions with very large char eqn coefficients. { double sqrt_D = std::sqrt(D); double u = itk::Math::cbrt(sqrt_D - q); double v = -itk::Math::cbrt(sqrt_D + q); s[0] = u + v; num = 1; } // Resubstitute double sub = 1.0 / 3.0 * c[2]; for ( int i = 0; i < num; ++i ) { s[i] -= sub; } return num; } } // end namespace itk #endif <|endoftext|>
<commit_before>c3a36f12-2e4d-11e5-9284-b827eb9e62be<commit_msg>c3a87fc0-2e4d-11e5-9284-b827eb9e62be<commit_after>c3a87fc0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #ifndef itkVectorRescaleIntensityImageFilter_hxx #define itkVectorRescaleIntensityImageFilter_hxx #include "itkVectorRescaleIntensityImageFilter.h" #include "itkImageRegionConstIterator.h" namespace itk { /** * */ template< typename TInputImage, typename TOutputImage > VectorRescaleIntensityImageFilter< TInputImage, TOutputImage > ::VectorRescaleIntensityImageFilter() : m_Scale(1.0), m_Shift(1.0), m_InputMaximumMagnitude(NumericTraits< InputRealType >::ZeroValue()), m_OutputMaximumMagnitude(NumericTraits< OutputRealType >::ZeroValue()) { } /** * */ template< typename TInputImage, typename TOutputImage > void VectorRescaleIntensityImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Output Maximum Magnitude: " << static_cast< typename NumericTraits< OutputRealType >::PrintType >( m_OutputMaximumMagnitude ) << std::endl; os << indent << "Input Maximum Magnitude: " << static_cast< typename NumericTraits< InputRealType >::PrintType >( m_InputMaximumMagnitude ) << std::endl; os << indent << "Internal Scale : " << static_cast< typename NumericTraits< InputRealType >::PrintType >( m_Scale ) << std::endl; } /** * */ template< typename TInputImage, typename TOutputImage > void VectorRescaleIntensityImageFilter< TInputImage, TOutputImage > ::BeforeThreadedGenerateData() { if ( m_OutputMaximumMagnitude < NumericTraits< OutputRealType >::ZeroValue() ) { itkExceptionMacro(<< "Maximum output value cannot be negative. You are passing " << m_OutputMaximumMagnitude); return; } InputImagePointer inputImage = this->GetInput(); typedef ImageRegionConstIterator< InputImageType > InputIterator; InputIterator it( inputImage, inputImage->GetBufferedRegion() ); it.GoToBegin(); InputRealType maximumSquaredMagnitude = NumericTraits< InputRealType >::ZeroValue(); while ( !it.IsAtEnd() ) { InputRealType magnitude = it.Get().GetSquaredNorm(); if ( magnitude > maximumSquaredMagnitude ) { maximumSquaredMagnitude = magnitude; } ++it; } m_InputMaximumMagnitude = std::sqrt(maximumSquaredMagnitude); m_Scale = static_cast< InputRealType >( m_OutputMaximumMagnitude ) / static_cast< InputRealType >( m_InputMaximumMagnitude ); // set up the functor values this->GetFunctor().SetFactor(m_Scale); } } // end namespace itk #endif <commit_msg>ENH: Print missing ivar in filter PrintSelf method.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #ifndef itkVectorRescaleIntensityImageFilter_hxx #define itkVectorRescaleIntensityImageFilter_hxx #include "itkVectorRescaleIntensityImageFilter.h" #include "itkImageRegionConstIterator.h" namespace itk { /** * */ template< typename TInputImage, typename TOutputImage > VectorRescaleIntensityImageFilter< TInputImage, TOutputImage > ::VectorRescaleIntensityImageFilter() : m_Scale(1.0), m_Shift(1.0), m_InputMaximumMagnitude(NumericTraits< InputRealType >::ZeroValue()), m_OutputMaximumMagnitude(NumericTraits< OutputRealType >::ZeroValue()) { } /** * */ template< typename TInputImage, typename TOutputImage > void VectorRescaleIntensityImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Output Maximum Magnitude: " << static_cast< typename NumericTraits< OutputRealType >::PrintType >( m_OutputMaximumMagnitude ) << std::endl; os << indent << "Input Maximum Magnitude: " << static_cast< typename NumericTraits< InputRealType >::PrintType >( m_InputMaximumMagnitude ) << std::endl; os << indent << "Internal Scale : " << static_cast< typename NumericTraits< InputRealType >::PrintType >( m_Scale ) << std::endl; os << indent << "Internal Shift : " << static_cast< typename NumericTraits< InputRealType >::PrintType >( m_Shift ) << std::endl; } /** * */ template< typename TInputImage, typename TOutputImage > void VectorRescaleIntensityImageFilter< TInputImage, TOutputImage > ::BeforeThreadedGenerateData() { if ( m_OutputMaximumMagnitude < NumericTraits< OutputRealType >::ZeroValue() ) { itkExceptionMacro(<< "Maximum output value cannot be negative. You are passing " << m_OutputMaximumMagnitude); return; } InputImagePointer inputImage = this->GetInput(); typedef ImageRegionConstIterator< InputImageType > InputIterator; InputIterator it( inputImage, inputImage->GetBufferedRegion() ); it.GoToBegin(); InputRealType maximumSquaredMagnitude = NumericTraits< InputRealType >::ZeroValue(); while ( !it.IsAtEnd() ) { InputRealType magnitude = it.Get().GetSquaredNorm(); if ( magnitude > maximumSquaredMagnitude ) { maximumSquaredMagnitude = magnitude; } ++it; } m_InputMaximumMagnitude = std::sqrt(maximumSquaredMagnitude); m_Scale = static_cast< InputRealType >( m_OutputMaximumMagnitude ) / static_cast< InputRealType >( m_InputMaximumMagnitude ); // set up the functor values this->GetFunctor().SetFactor(m_Scale); } } // end namespace itk #endif <|endoftext|>
<commit_before>32c8adca-2e4f-11e5-9284-b827eb9e62be<commit_msg>32cda74e-2e4f-11e5-9284-b827eb9e62be<commit_after>32cda74e-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9238bcb0-2e4e-11e5-9284-b827eb9e62be<commit_msg>923db8f0-2e4e-11e5-9284-b827eb9e62be<commit_after>923db8f0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f32ee428-2e4d-11e5-9284-b827eb9e62be<commit_msg>f333f440-2e4d-11e5-9284-b827eb9e62be<commit_after>f333f440-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include <node.h> #include <node_buffer.h> #include <string.h> #include <stdlib.h> #include "magic.h" using namespace node; using namespace v8; struct Baton { uv_work_t request; Persistent<Function> callback; char* data; uint32_t dataLen; bool dataIsPath; // libmagic info const char* path; int flags; bool error; char* error_message; const char* result; }; static Persistent<FunctionTemplate> constructor; const char* fallbackPath; struct magic_set* init_magic(const char* path, int mflags, char* err) { struct magic_set *magic = magic_open(mflags | MAGIC_NO_CHECK_COMPRESS); if (magic == NULL) { err = strdup(uv_strerror(uv_last_error(uv_default_loop()))); return NULL; } if (magic_load(magic, NULL) == -1) { /* Use magic file contained in addon distribution as last resort */ if (magic_load(magic, fallbackPath) == -1) { err = strdup(magic_error(magic)); magic_close(magic); return NULL; } } return magic; } class Magic : public ObjectWrap { public: const char* mpath; int mflags; Magic(const char* path, int flags) { if (path != NULL) { /* Windows blows up trying to look up the path '(null)' returned by magic_getpath() */ if (strncmp(path, "(null)", 6) == 0) path = NULL; } mpath = path; mflags = flags; } ~Magic() { if (mpath != NULL) { free((void*)mpath); mpath = NULL; } } static Handle<Value> New(const Arguments& args) { HandleScope scope; #ifndef _WIN32 int mflags = MAGIC_SYMLINK; #else int mflags = MAGIC_NONE; #endif char* path = NULL; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use `new` to create instances of this object.")) ); } if (args.Length() > 0) { if (args[0]->IsString()) { String::Utf8Value str(args[0]->ToString()); path = strdup((const char*)(*str)); } else if (args[0]->IsInt32()) mflags = args[0]->Int32Value(); else { return ThrowException(Exception::TypeError( String::New("First argument must be a string or integer"))); } } if (args.Length() > 1) { if (args[1]->IsInt32()) mflags = args[1]->Int32Value(); else { if (path) free(path); return ThrowException(Exception::TypeError( String::New("Second argument must be an integer"))); } } Magic* obj = new Magic(magic_getpath(path, 0/*FILE_LOAD*/), mflags); obj->Wrap(args.This()); return args.This(); } static Handle<Value> DetectFile(const Arguments& args) { HandleScope scope; Magic* obj = ObjectWrap::Unwrap<Magic>(args.This()); if (!args[0]->IsString()) { return ThrowException(Exception::TypeError( String::New("First argument must be a string"))); } if (!args[1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("Second argument must be a callback function"))); } Local<Function> callback = Local<Function>::Cast(args[1]); String::Utf8Value str(args[0]->ToString()); Baton* baton = new Baton(); baton->error = false; baton->request.data = baton; baton->callback = Persistent<Function>::New(callback); baton->data = strdup((const char*)*str); baton->dataIsPath = true; baton->path = obj->mpath; baton->flags = obj->mflags; int status = uv_queue_work(uv_default_loop(), &baton->request, Magic::DetectWork, Magic::DetectAfter); assert(status == 0); return Undefined(); } static Handle<Value> Detect(const Arguments& args) { HandleScope scope; Magic* obj = ObjectWrap::Unwrap<Magic>(args.This()); if (args.Length() < 2) { return ThrowException(Exception::TypeError( String::New("Expecting 2 arguments"))); } if (!Buffer::HasInstance(args[0])) { return ThrowException(Exception::TypeError( String::New("First argument must be a Buffer"))); } if (!args[1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("Second argument must be a callback function"))); } Local<Function> callback = Local<Function>::Cast(args[1]); Local<Object> buffer_obj = args[0]->ToObject(); Baton* baton = new Baton(); baton->error = false; baton->request.data = baton; baton->callback = Persistent<Function>::New(callback); baton->data = Buffer::Data(buffer_obj); baton->dataLen = Buffer::Length(buffer_obj); baton->dataIsPath = false; baton->path = obj->mpath; baton->flags = obj->mflags; int status = uv_queue_work(uv_default_loop(), &baton->request, Magic::DetectWork, Magic::DetectAfter); assert(status == 0); return Undefined(); } static void DetectWork(uv_work_t* req) { Baton* baton = static_cast<Baton*>(req->data); const char* result; struct magic_set* magic = init_magic(baton->path, baton->flags, baton->error_message); if (magic == NULL) { if (baton->error_message) baton->error = true; return; } if (baton->dataIsPath) result = magic_file(magic, baton->data); else result = magic_buffer(magic, (const void*)baton->data, baton->dataLen); if (result == NULL) { baton->error = true; baton->error_message = strdup(magic_error(magic)); } else baton->result = strdup(result); magic_close(magic); } static void DetectAfter(uv_work_t* req) { HandleScope scope; Baton* baton = static_cast<Baton*>(req->data); if (baton->error) { Local<Value> err = Exception::Error(String::New(baton->error_message)); free(baton->error_message); const unsigned argc = 1; Local<Value> argv[argc] = { err }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) FatalException(try_catch); } else { const unsigned argc = 2; Local<Value> argv[argc] = { Local<Value>::New(Null()), Local<Value>::New(String::New(baton->result)) }; free((void*)baton->result); TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) FatalException(try_catch); } if (baton->dataIsPath) free(baton->data); baton->callback.Dispose(); delete baton; } static Handle<Value> SetFallback(const Arguments& args) { HandleScope scope; if (fallbackPath) free((void*)fallbackPath); if (args.Length() > 0 && args[0]->IsString() && args[0]->ToString()->Length() > 0) { String::Utf8Value str(args[0]->ToString()); fallbackPath = strdup((const char*)(*str)); } else fallbackPath = NULL; return Undefined(); } static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); Local<String> name = String::NewSymbol("Magic"); constructor = Persistent<FunctionTemplate>::New(tpl); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(name); NODE_SET_PROTOTYPE_METHOD(constructor, "detectFile", DetectFile); NODE_SET_PROTOTYPE_METHOD(constructor, "detect", Detect); target->Set(String::NewSymbol("setFallback"), FunctionTemplate::New(SetFallback)->GetFunction()); target->Set(name, constructor->GetFunction()); } }; extern "C" { void init(Handle<Object> target) { HandleScope scope; Magic::Initialize(target); } NODE_MODULE(magic, init); } <commit_msg>Fix pointer errors<commit_after>#include <node.h> #include <node_buffer.h> #include <string.h> #include <stdlib.h> #include "magic.h" using namespace node; using namespace v8; struct Baton { uv_work_t request; Persistent<Function> callback; char* data; uint32_t dataLen; bool dataIsPath; // libmagic info const char* path; int flags; bool error; char* error_message; const char* result; }; static Persistent<FunctionTemplate> constructor; static const char* fallbackPath; class Magic : public ObjectWrap { public: const char* mpath; int mflags; Magic(const char* path, int flags) { if (path != NULL) { /* Windows blows up trying to look up the path '(null)' returned by magic_getpath() */ if (strncmp(path, "(null)", 6) == 0) path = NULL; } mpath = (path == NULL ? strdup(fallbackPath) : path); mflags = flags; } ~Magic() { if (mpath != NULL) { free((void*)mpath); mpath = NULL; } } static Handle<Value> New(const Arguments& args) { HandleScope scope; #ifndef _WIN32 int mflags = MAGIC_SYMLINK; #else int mflags = MAGIC_NONE; #endif char* path = NULL; bool use_bundled = true; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use `new` to create instances of this object.")) ); } if (args.Length() > 0) { if (args[0]->IsString()) { use_bundled = false; String::Utf8Value str(args[0]->ToString()); path = strdup((const char*)(*str)); } else if (args[0]->IsInt32()) mflags = args[0]->Int32Value(); else if (args[0]->IsBoolean() && !args[0]->BooleanValue()) { use_bundled = false; path = strdup(magic_getpath(NULL, 0/*FILE_LOAD*/)); } else { return ThrowException(Exception::TypeError( String::New("First argument must be a string or integer"))); } } if (args.Length() > 1) { if (args[1]->IsInt32()) mflags = args[1]->Int32Value(); else { if (path) free(path); return ThrowException(Exception::TypeError( String::New("Second argument must be an integer"))); } } Magic* obj = new Magic((use_bundled ? NULL : path), mflags); obj->Wrap(args.This()); obj->Ref(); return args.This(); } static Handle<Value> DetectFile(const Arguments& args) { HandleScope scope; Magic* obj = ObjectWrap::Unwrap<Magic>(args.This()); if (!args[0]->IsString()) { return ThrowException(Exception::TypeError( String::New("First argument must be a string"))); } if (!args[1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("Second argument must be a callback function"))); } Local<Function> callback = Local<Function>::Cast(args[1]); String::Utf8Value str(args[0]->ToString()); Baton* baton = new Baton(); baton->error = false; baton->error_message = NULL; baton->request.data = baton; baton->callback = Persistent<Function>::New(callback); baton->data = strdup((const char*)*str); baton->dataIsPath = true; baton->path = obj->mpath; baton->flags = obj->mflags; int status = uv_queue_work(uv_default_loop(), &baton->request, Magic::DetectWork, Magic::DetectAfter); assert(status == 0); return Undefined(); } static Handle<Value> Detect(const Arguments& args) { HandleScope scope; Magic* obj = ObjectWrap::Unwrap<Magic>(args.This()); if (args.Length() < 2) { return ThrowException(Exception::TypeError( String::New("Expecting 2 arguments"))); } if (!Buffer::HasInstance(args[0])) { return ThrowException(Exception::TypeError( String::New("First argument must be a Buffer"))); } if (!args[1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("Second argument must be a callback function"))); } Local<Function> callback = Local<Function>::Cast(args[1]); Local<Object> buffer_obj = args[0]->ToObject(); Baton* baton = new Baton(); baton->error = false; baton->error_message = NULL; baton->request.data = baton; baton->callback = Persistent<Function>::New(callback); baton->data = Buffer::Data(buffer_obj); baton->dataLen = Buffer::Length(buffer_obj); baton->dataIsPath = false; baton->path = obj->mpath; baton->flags = obj->mflags; int status = uv_queue_work(uv_default_loop(), &baton->request, Magic::DetectWork, Magic::DetectAfter); assert(status == 0); return Undefined(); } static void DetectWork(uv_work_t* req) { Baton* baton = static_cast<Baton*>(req->data); const char* result; struct magic_set *magic = magic_open(baton->flags | MAGIC_NO_CHECK_COMPRESS); if (magic == NULL) { baton->error_message = strdup(uv_strerror( uv_last_error(uv_default_loop()))); } else if (magic_load(magic, baton->path) == -1 && magic_load(magic, fallbackPath) == -1) { baton->error_message = strdup(magic_error(magic)); magic_close(magic); } if (magic == NULL) { if (baton->error_message) baton->error = true; return; } if (baton->dataIsPath) result = magic_file(magic, baton->data); else result = magic_buffer(magic, (const void*)baton->data, baton->dataLen); if (result == NULL) { baton->error = true; baton->error_message = strdup(magic_error(magic)); } else baton->result = strdup(result); magic_close(magic); } static void DetectAfter(uv_work_t* req) { HandleScope scope; Baton* baton = static_cast<Baton*>(req->data); if (baton->error) { Local<Value> err = Exception::Error(String::New(baton->error_message)); free(baton->error_message); const unsigned argc = 1; Local<Value> argv[argc] = { err }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) FatalException(try_catch); } else { const unsigned argc = 2; Local<Value> argv[argc] = { Local<Value>::New(Null()), Local<Value>::New(String::New(baton->result)) }; free((void*)baton->result); TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) FatalException(try_catch); } if (baton->dataIsPath) free(baton->data); baton->callback.Dispose(); delete baton; } static Handle<Value> SetFallback(const Arguments& args) { HandleScope scope; if (fallbackPath) free((void*)fallbackPath); if (args.Length() > 0 && args[0]->IsString() && args[0]->ToString()->Length() > 0) { String::Utf8Value str(args[0]->ToString()); fallbackPath = strdup((const char*)(*str)); } else fallbackPath = NULL; return Undefined(); } static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); Local<String> name = String::NewSymbol("Magic"); constructor = Persistent<FunctionTemplate>::New(tpl); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(name); NODE_SET_PROTOTYPE_METHOD(constructor, "detectFile", DetectFile); NODE_SET_PROTOTYPE_METHOD(constructor, "detect", Detect); target->Set(String::NewSymbol("setFallback"), FunctionTemplate::New(SetFallback)->GetFunction()); target->Set(name, constructor->GetFunction()); } }; extern "C" { void init(Handle<Object> target) { HandleScope scope; Magic::Initialize(target); } NODE_MODULE(magic, init); } <|endoftext|>
<commit_before>#include "manip.h" using namespace std; // Manipulator stuff is _always_ in namespace mysqlpp. namespace mysqlpp { bool dont_quote_auto = false; // quote manipulator SQLQueryParms& operator <<(quote_type2 p, SQLString& in) { if (in.is_string) { if (in.dont_escape) { SQLString in2 = "'" + in + "'"; in2.processed = true; return *p.qparms << in2; } else { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), (unsigned long)in.size()); SQLString in2 = SQLString("'") + s + "'"; in2.processed = true; *p.qparms << in2; delete[]s; return *p.qparms; } } else { in.processed = true; return *p.qparms << in; } } template<> ostream& operator<<(quote_type1 o, const string& in) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), (unsigned long)in.size()); *o.ostr << "'" << s << "'"; delete[] s; return *o.ostr; } template<> ostream& operator<<(quote_type1 o, const char* const& in) { unsigned int size; for (size = 0; in[size]; size++) ; char *s = new char[size * 2 + 1]; mysql_escape_string(s, const_cast < char *>(in), size); *o.ostr << "'" << s << "'"; delete[] s; return *o.ostr; } template<class Str> inline ostream& _manip(quote_type1 o, const ColData_Tmpl<Str>& in) { if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), (unsigned long)in.size()); if (in.quote_q()) *o.ostr << "'" << s << "'"; else *o.ostr << s; delete[] s; } else if (in.quote_q()) { *o.ostr << "'" << in << "'"; } else { *o.ostr << in; } return *o.ostr; } template<> ostream& operator<<(quote_type1 o, const ColData_Tmpl<string>& in) { return _manip(o, in); } template<> ostream& operator<<(quote_type1 o, const ColData_Tmpl<const_string>& in) { return _manip(o, in); } ostream& operator<<(ostream& o, const ColData_Tmpl<string>& in) { if (dont_quote_auto || (o.rdbuf() == cout.rdbuf()) || (o.rdbuf() == cerr.rdbuf())) { return o << in.get_string(); } if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), (unsigned long)in.size()); if (in.quote_q()) o << "'" << s << "'"; else o << s; delete[] s; } else if (in.quote_q()) { o << "'" << in.get_string() << "'"; } else { o << in.get_string(); } return o; } ostream& operator<<(ostream& o, const ColData_Tmpl<const_string>& in) { if (dont_quote_auto || (o.rdbuf() == cout.rdbuf()) || (o.rdbuf() == cerr.rdbuf())) { return o << in.get_string(); } if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, const_cast < char *>(in.c_str()), in.size()); if (in.quote_q()) o << "'" << s << "'"; else o << s; delete[] s; } else if (in.quote_q()) { o << "'" << in.get_string() << "'"; } else { o << in.get_string(); } return o; } SQLQuery& operator<<(SQLQuery& o, const ColData_Tmpl<string>& in) { if (dont_quote_auto) { o << in.get_string(); return o; } if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), (unsigned long)in.size()); if (in.quote_q()) static_cast<ostream &>(o) << "'" << s << "'"; else static_cast<ostream &>(o) << s; delete[] s; } else if (in.quote_q()) { static_cast<ostream &>(o) << "'" << in.get_string() << "'"; } else { static_cast<ostream &>(o) << in.get_string(); } return o; } SQLQuery& operator<<(SQLQuery& o, const ColData_Tmpl<const_string>& in) { if (dont_quote_auto) { o << in.get_string(); return o; } if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, const_cast < char *>(in.c_str()), in.size()); if (in.quote_q()) static_cast<ostream &>(o) << "'" << s << "'"; else static_cast<ostream &>(o) << s; delete[] s; } else if (in.quote_q()) { static_cast<ostream &>(o) << "'" << in.get_string() << "'"; } else { static_cast<ostream &>(o) << in.get_string(); } return o; } // quote only manipulator SQLQueryParms& operator<<(quote_only_type2 p, SQLString& in) { if (in.is_string) { SQLString in2 = "'" + in + "'"; in2.processed = true; return *p.qparms << in2; } else { in.processed = true; return *p.qparms << in; } } template<> ostream& operator<<(quote_only_type1 o, const ColData_Tmpl<string>& in) { if (in.quote_q()) { *o.ostr << "'" << in << "'"; } else { *o.ostr << in; } return *o.ostr; } template<> ostream& operator<<(quote_only_type1 o, const ColData_Tmpl<const_string>& in) { if (in.quote_q()) { *o.ostr << "'" << in << "'"; } else { *o.ostr << in; } return *o.ostr; } // quote double only manipulator SQLQueryParms& operator<<(quote_double_only_type2 p, SQLString& in) { if (in.is_string) { SQLString in2 = "\"" + in + "\""; in2.processed = true; return *p.qparms << in2; } else { in.processed = true; return *p.qparms << in; } } template<> ostream& operator<<(quote_double_only_type1 o, const ColData_Tmpl<string>& in) { if (in.quote_q()) { *o.ostr << "'" << in << "'"; } else { *o.ostr << in; } return *o.ostr; } template<> ostream& operator<<(quote_double_only_type1 o, const ColData_Tmpl<const_string>& in) { if (in.quote_q()) { *o.ostr << "'" << in << "'"; } else { *o.ostr << in; } return *o.ostr; } // escape manipulator SQLQueryParms& operator<<(escape_type2 p, SQLString& in) { if (in.is_string) { if (in.dont_escape) { in.processed = true; return *p.qparms << in; } else { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), (unsigned long)in.size()); SQLString in2 = s; in2.processed = true; *p.qparms << in2; delete[] s; return *p.qparms; } } else { in.processed = true; return *p.qparms << in; } } template<> ostream& operator<<(escape_type1 o, const string& in) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), (unsigned long)in.size()); *o.ostr << s; delete[] s; return *o.ostr; } template<> ostream& operator<<(escape_type1 o, const char* const& in) { unsigned int size; for (size = 0; in[size]; size++) ; char *s = new char[size * 2 + 1]; mysql_escape_string(s, const_cast < char *>(in), size); *o.ostr << s; delete[] s; return *o.ostr; } template<class Str> inline ostream& _manip(escape_type1 o, const ColData_Tmpl<Str>& in) { if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), (unsigned long)in.size()); delete[] s; } else { *o.ostr << in; } return *o.ostr; } template<> ostream& operator<<(escape_type1 o, const ColData_Tmpl<string>& in) { return _manip(o, in); } template<> ostream& operator<<(escape_type1 o, const ColData_Tmpl<const_string>& in) { return _manip(o, in); } } // end namespace mysqlpp <commit_msg>Changed some C-style casts to static_casts to avoid GCC 4 warnings.<commit_after>#include "manip.h" using namespace std; // Manipulator stuff is _always_ in namespace mysqlpp. namespace mysqlpp { bool dont_quote_auto = false; // quote manipulator SQLQueryParms& operator <<(quote_type2 p, SQLString& in) { if (in.is_string) { if (in.dont_escape) { SQLString in2 = "'" + in + "'"; in2.processed = true; return *p.qparms << in2; } else { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), static_cast <unsigned long> (in.size())); SQLString in2 = SQLString("'") + s + "'"; in2.processed = true; *p.qparms << in2; delete[]s; return *p.qparms; } } else { in.processed = true; return *p.qparms << in; } } template<> ostream& operator<<(quote_type1 o, const string& in) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), static_cast <unsigned long> (in.size())); *o.ostr << "'" << s << "'"; delete[] s; return *o.ostr; } template<> ostream& operator<<(quote_type1 o, const char* const& in) { unsigned int size; for (size = 0; in[size]; size++) ; char *s = new char[size * 2 + 1]; mysql_escape_string(s, const_cast < char *>(in), size); *o.ostr << "'" << s << "'"; delete[] s; return *o.ostr; } template<class Str> inline ostream& _manip(quote_type1 o, const ColData_Tmpl<Str>& in) { if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), static_cast <unsigned long> (in.size())); if (in.quote_q()) *o.ostr << "'" << s << "'"; else *o.ostr << s; delete[] s; } else if (in.quote_q()) { *o.ostr << "'" << in << "'"; } else { *o.ostr << in; } return *o.ostr; } template<> ostream& operator<<(quote_type1 o, const ColData_Tmpl<string>& in) { return _manip(o, in); } template<> ostream& operator<<(quote_type1 o, const ColData_Tmpl<const_string>& in) { return _manip(o, in); } ostream& operator<<(ostream& o, const ColData_Tmpl<string>& in) { if (dont_quote_auto || (o.rdbuf() == cout.rdbuf()) || (o.rdbuf() == cerr.rdbuf())) { return o << in.get_string(); } if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), static_cast <unsigned long> (in.size())); if (in.quote_q()) o << "'" << s << "'"; else o << s; delete[] s; } else if (in.quote_q()) { o << "'" << in.get_string() << "'"; } else { o << in.get_string(); } return o; } ostream& operator<<(ostream& o, const ColData_Tmpl<const_string>& in) { if (dont_quote_auto || (o.rdbuf() == cout.rdbuf()) || (o.rdbuf() == cerr.rdbuf())) { return o << in.get_string(); } if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, const_cast < char *>(in.c_str()), in.size()); if (in.quote_q()) o << "'" << s << "'"; else o << s; delete[] s; } else if (in.quote_q()) { o << "'" << in.get_string() << "'"; } else { o << in.get_string(); } return o; } SQLQuery& operator<<(SQLQuery& o, const ColData_Tmpl<string>& in) { if (dont_quote_auto) { o << in.get_string(); return o; } if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), static_cast <unsigned long> (in.size())); if (in.quote_q()) static_cast<ostream &>(o) << "'" << s << "'"; else static_cast<ostream &>(o) << s; delete[] s; } else if (in.quote_q()) { static_cast<ostream &>(o) << "'" << in.get_string() << "'"; } else { static_cast<ostream &>(o) << in.get_string(); } return o; } SQLQuery& operator<<(SQLQuery& o, const ColData_Tmpl<const_string>& in) { if (dont_quote_auto) { o << in.get_string(); return o; } if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, const_cast < char *>(in.c_str()), in.size()); if (in.quote_q()) static_cast<ostream &>(o) << "'" << s << "'"; else static_cast<ostream &>(o) << s; delete[] s; } else if (in.quote_q()) { static_cast<ostream &>(o) << "'" << in.get_string() << "'"; } else { static_cast<ostream &>(o) << in.get_string(); } return o; } // quote only manipulator SQLQueryParms& operator<<(quote_only_type2 p, SQLString& in) { if (in.is_string) { SQLString in2 = "'" + in + "'"; in2.processed = true; return *p.qparms << in2; } else { in.processed = true; return *p.qparms << in; } } template<> ostream& operator<<(quote_only_type1 o, const ColData_Tmpl<string>& in) { if (in.quote_q()) { *o.ostr << "'" << in << "'"; } else { *o.ostr << in; } return *o.ostr; } template<> ostream& operator<<(quote_only_type1 o, const ColData_Tmpl<const_string>& in) { if (in.quote_q()) { *o.ostr << "'" << in << "'"; } else { *o.ostr << in; } return *o.ostr; } // quote double only manipulator SQLQueryParms& operator<<(quote_double_only_type2 p, SQLString& in) { if (in.is_string) { SQLString in2 = "\"" + in + "\""; in2.processed = true; return *p.qparms << in2; } else { in.processed = true; return *p.qparms << in; } } template<> ostream& operator<<(quote_double_only_type1 o, const ColData_Tmpl<string>& in) { if (in.quote_q()) { *o.ostr << "'" << in << "'"; } else { *o.ostr << in; } return *o.ostr; } template<> ostream& operator<<(quote_double_only_type1 o, const ColData_Tmpl<const_string>& in) { if (in.quote_q()) { *o.ostr << "'" << in << "'"; } else { *o.ostr << in; } return *o.ostr; } // escape manipulator SQLQueryParms& operator<<(escape_type2 p, SQLString& in) { if (in.is_string) { if (in.dont_escape) { in.processed = true; return *p.qparms << in; } else { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), static_cast <unsigned long> (in.size())); SQLString in2 = s; in2.processed = true; *p.qparms << in2; delete[] s; return *p.qparms; } } else { in.processed = true; return *p.qparms << in; } } template<> ostream& operator<<(escape_type1 o, const string& in) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), static_cast <unsigned long> (in.size())); *o.ostr << s; delete[] s; return *o.ostr; } template<> ostream& operator<<(escape_type1 o, const char* const& in) { unsigned int size; for (size = 0; in[size]; size++) ; char *s = new char[size * 2 + 1]; mysql_escape_string(s, const_cast < char *>(in), size); *o.ostr << s; delete[] s; return *o.ostr; } template<class Str> inline ostream& _manip(escape_type1 o, const ColData_Tmpl<Str>& in) { if (in.escape_q()) { char *s = new char[in.size() * 2 + 1]; mysql_escape_string(s, in.c_str(), static_cast <unsigned long> (in.size())); delete[] s; } else { *o.ostr << in; } return *o.ostr; } template<> ostream& operator<<(escape_type1 o, const ColData_Tmpl<string>& in) { return _manip(o, in); } template<> ostream& operator<<(escape_type1 o, const ColData_Tmpl<const_string>& in) { return _manip(o, in); } } // end namespace mysqlpp <|endoftext|>
<commit_before>#include "memory.h" #include "../phasor-lua.hpp" #include <cstdint> #include <array> #include <Windows.h> #undef min #undef max void readData(lua_State* L, void* dest, void* src, size_t nbytes) { DWORD oldProtect = 0; if (VirtualProtect(src, nbytes, PAGE_EXECUTE_READ, &oldProtect)) { memcpy(dest, src, nbytes); VirtualProtect(src, nbytes, oldProtect, &oldProtect); } else { auto f = boost::format("invalid read: %u bytes from 0x%08X") % nbytes % src; luaL_error(L, "%s", f.str().c_str()); } } void writeData(lua_State* L, void* dest, const void* src, size_t nbytes) { DWORD oldProtect = 0; if (VirtualProtect(dest, nbytes, PAGE_EXECUTE_READWRITE, &oldProtect)) { memcpy(dest, src, nbytes); VirtualProtect(dest, nbytes, oldProtect, &oldProtect); } else { auto f = boost::format("invalid write: %u bytes from 0x%08X") % nbytes % src; luaL_error(L, "%s", f.str().c_str()); } } template <typename T> bool checkLimits(double value, T& out) { static const T max_value = std::numeric_limits<T>::max(); static const T min_value = std::numeric_limits<T>::lowest(); if (value <= max_value && value >= min_value) { out = static_cast<T>(value); return true; } else { return false; } } size_t addBitOffset(size_t x, int& offset) { x += offset / 8; offset %= 8; return x; } // -------------------------------------------------------- int l_readbit(lua_State* L) { size_t address; int bitOffset; if (lua_gettop(L) == 3) { // legacy: three args mean address, address_offset, bit_offset int addrOffset; std::tie(address, addrOffset, bitOffset) = phlua::callback::getArguments<size_t, int, int>(L, __FUNCTION__); address += addrOffset; } else { std::tie(address, bitOffset) = phlua::callback::getArguments<size_t, int>(L, __FUNCTION__); } address = addBitOffset(address, bitOffset); std::uint8_t b; readData(L, &b, (void*)address, sizeof(b)); bool bit = (b & (1 << bitOffset)) != 0; return phlua::callback::pushReturns(L, std::make_tuple(bit)); } int l_writebit(lua_State* L) { size_t address; int bitOffset; bool value; if (lua_gettop(L) == 4) { int addrOffset; // legacy: four args mean address, address_offset, bit_offset, value std::tie(address, addrOffset, bitOffset, value) = phlua::callback::getArguments<size_t, int, int, bool>(L, __FUNCTION__); address += addrOffset; } else { std::tie(address, bitOffset, value) = phlua::callback::getArguments<size_t, int, bool>(L, __FUNCTION__); } address = addBitOffset(address, bitOffset); std::uint8_t b; readData(L, &b, (void*)address, sizeof(b)); if (value) b |= 1 << bitOffset; else b &= ~(1 << bitOffset); writeData(L, (void*)address, &b, sizeof(b)); return 0; } // -------------------------------------------------------- template <typename T> int readNumber(lua_State* L, const char* f) { size_t address; boost::optional<size_t> offset; // backwards compatibility std::tie(address, offset) = phlua::callback::getArguments<size_t, decltype(offset)>(L, f); if (offset) address += *offset; T x; readData(L, &x, (void*)address, sizeof(T)); return phlua::callback::pushReturns(L, std::make_tuple(x)); } int l_readbyte(lua_State* L) { return readNumber<std::uint8_t>(L, __FUNCTION__); } int l_readchar(lua_State* L) { return readNumber<std::int8_t>(L, __FUNCTION__); } int l_readword(lua_State* L) { return readNumber<std::uint16_t>(L, __FUNCTION__); } int l_readshort(lua_State* L) { return readNumber<std::int16_t>(L, __FUNCTION__); } int l_readdword(lua_State* L) { return readNumber<std::uint32_t>(L, __FUNCTION__); } int l_readint(lua_State* L) { return readNumber<std::int32_t>(L, __FUNCTION__); } int l_readfloat(lua_State* L) { return readNumber<float>(L, __FUNCTION__); } int l_readdouble(lua_State* L) { return readNumber<double>(L, __FUNCTION__); } // -------------------------------------------------------- template <typename T> int writeNumber(lua_State* L, const char* f) { size_t address; lua_Number value; if (lua_gettop(L) == 3) { // backwards compatibility // address, offset, value int offset; std::tie(address, offset, value) = phlua::callback::getArguments<size_t, int, lua_Number>(L, f); address += offset; } else { std::tie(address, value) = phlua::callback::getArguments<size_t, lua_Number>(L, f); } T x; if (!checkLimits<T>(value, x)) { auto f = boost::format("invalid write: value (%.0f) outside of type's range") % value; luaL_error(L, "%s", f.str().c_str()); } writeData(L, (void*)address, &x, sizeof(T)); return 0; } int l_writebyte(lua_State* L) { return writeNumber<std::uint8_t>(L, __FUNCTION__); } int l_writechar(lua_State* L) { return writeNumber<std::int8_t>(L, __FUNCTION__); } int l_writeword(lua_State* L) { return writeNumber<std::uint16_t>(L, __FUNCTION__); } int l_writeshort(lua_State* L) { return writeNumber<std::int16_t>(L, __FUNCTION__); } int l_writedword(lua_State* L) { return writeNumber<std::uint32_t>(L, __FUNCTION__); } int l_writeint(lua_State* L) { return writeNumber<std::int32_t>(L, __FUNCTION__); } int l_writefloat(lua_State* L) { return writeNumber<float>(L, __FUNCTION__); } int l_writedouble(lua_State* L) { return writeNumber<double>(L, __FUNCTION__); } // -------------------------------------------------------- static const size_t kMaxStringElements = 160; template <typename T> int readstring(lua_State* L, const char* f) { size_t address; boost::optional<unsigned int> length; std::array<T, kMaxStringElements+1> dest; std::tie(address, length) = phlua::callback::getArguments<size_t, decltype(length)>(L, f); size_t readLength = kMaxStringElements; if (length) { if (length > kMaxStringElements) { auto f = boost::format("can only read strings to a maximum size of %u characters") % kMaxStringElements; luaL_argerror(L, 2, f.str().c_str()); } readLength = *length; } readData(L, dest.data(), (void*)address, readLength*sizeof(T)); dest[readLength] = 0; // ensure it's null terminated return phlua::callback::pushReturns(L, std::make_tuple(dest.data())); } int l_readstring(lua_State* L) { return readstring<char>(L, __FUNCTION__); } int l_readwidestring(lua_State* L) { return readstring<wchar_t>(L, __FUNCTION__); } // -------------------------------------------------------- template <typename StrType> int writestring(lua_State* L, const char* f) { typedef typename StrType::value_type char_type; size_t address; boost::optional<size_t> offset; StrType s; if (lua_gettop(L) == 3) { // backwards compatibility std::tie(address, offset, s) = phlua::callback::getArguments<size_t, decltype(offset), StrType>(L, f); } else { std::tie(address, s) = phlua::callback::getArguments<size_t, StrType>(L, f); } if (offset) address += *offset; size_t byteLength = s.size() * sizeof(char_type); writeData(L, (void*)address, s.c_str(), byteLength); char_type nullChar = 0; writeData(L, (void*)(address + byteLength), &nullChar, sizeof(nullChar)); return 0; } int l_writestring(lua_State* L) { return writestring<std::string>(L, __FUNCTION__); } int l_writewidestring(lua_State* L) { return writestring<std::wstring>(L, __FUNCTION__); } struct SigUnit { uint8_t x; enum class Mode { NORMAL, WILDCARD, WILDCARD_HIGH, WILDCARD_LOW } mode; }; uint8_t hex_to_int(char c) { c = tolower(c); if (c >= 'a' && c <= 'f') { return 10 + c - 'a'; } else { return c - '0'; } } // sig code in Addresses is really bad, so i'll just rewrite it... // sig should conform to ([A-Fa-f0-9?][A-Fa-f0-9?])+ // returns absolute address uint8_t* sigscan(const std::string& sig, int occurance) { // should refactor this, but for now a copy/paste works... uint8_t* module = (uint8_t*)GetModuleHandle(0); unsigned int OffsetToPE = *(unsigned int*)(module + 0x3C); unsigned int codeSize = *(unsigned int*)(module + OffsetToPE + 0x1C); unsigned int BaseOfCode = *(unsigned int*)(module + OffsetToPE + 0x2C); uint8_t* codeSection = (uint8_t*)(module + BaseOfCode); if (sig.size() % 2) return 0; // convert sig to byte values std::vector<SigUnit> bytes; bytes.reserve(sig.size() % 2); for (size_t x = 0; x < sig.size(); x += 2) { SigUnit unit; if (sig[x] == '?') { if (sig[x+1] == '?') { unit.mode = SigUnit::Mode::WILDCARD; } else { unit.mode = SigUnit::Mode::WILDCARD_HIGH; unit.x = hex_to_int(sig[x+1]); } } else if (sig[x+1] == '?') { unit.mode = SigUnit::Mode::WILDCARD_LOW; unit.x = hex_to_int(sig[x]); } else { unit.mode = SigUnit::Mode::NORMAL; unit.x = hex_to_int(sig[x]) << 4 | hex_to_int(sig[x+1]); } bytes.push_back(unit); } // todo: should probably use knp or something unsigned int found = 0; for (unsigned int x = 0; x < codeSize; x++) { unsigned int length = std::min(codeSize - x, bytes.size()); for (unsigned int i = 0; i < length; i++) { uint8_t b = codeSection[x+i]; bool match = true; switch (bytes[i].mode) { case SigUnit::Mode::WILDCARD: // nothing to do break; case SigUnit::Mode::WILDCARD_HIGH: // ?x match = (b & 0x0F) == bytes[i].x; break; case SigUnit::Mode::WILDCARD_LOW: // x? match = (b & 0xF0) == bytes[i].x; break; default: match = b == bytes[i].x; break; } if (match) { if (i + 1 == bytes.size()) { if (found++ == occurance) return codeSection + x; } } else break; } } return 0; } bool ishex(char c) { c = tolower(c); return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); } int l_findsig(lua_State* L) { std::string sig; boost::optional<int> occurance; std::tie(sig, occurance) = phlua::callback::getArguments<std::string, decltype(occurance)>(L, __FUNCTION__); if (!occurance) occurance = 0; if (sig.length() == 0) { luaL_argerror(L, 1, "empty signature"); } for (auto c : sig) { if (c != '?' && !ishex(c)) luaL_argerror(L, 1, "signature can only contain hexadecimal or ? characters"); } // If only part of a byte is specified, treat the next as a wildcard if (sig.length() % 2) { sig.append("?"); } uint8_t* mem = sigscan(sig, *occurance); if (mem) { return phlua::callback::pushReturns(L, std::make_tuple((unsigned int)mem)); } else { return phlua::callback::pushReturns(L, std::make_tuple(lua::types::Nil())); } }<commit_msg>Basic caching for findsig<commit_after>#include "memory.h" #include "../phasor-lua.hpp" #include <cstdint> #include <array> #include <Windows.h> #include <unordered_map> #undef min #undef max void readData(lua_State* L, void* dest, void* src, size_t nbytes) { DWORD oldProtect = 0; if (VirtualProtect(src, nbytes, PAGE_EXECUTE_READ, &oldProtect)) { memcpy(dest, src, nbytes); VirtualProtect(src, nbytes, oldProtect, &oldProtect); } else { auto f = boost::format("invalid read: %u bytes from 0x%08X") % nbytes % src; luaL_error(L, "%s", f.str().c_str()); } } void writeData(lua_State* L, void* dest, const void* src, size_t nbytes) { DWORD oldProtect = 0; if (VirtualProtect(dest, nbytes, PAGE_EXECUTE_READWRITE, &oldProtect)) { memcpy(dest, src, nbytes); VirtualProtect(dest, nbytes, oldProtect, &oldProtect); } else { auto f = boost::format("invalid write: %u bytes from 0x%08X") % nbytes % src; luaL_error(L, "%s", f.str().c_str()); } } template <typename T> bool checkLimits(double value, T& out) { static const T max_value = std::numeric_limits<T>::max(); static const T min_value = std::numeric_limits<T>::lowest(); if (value <= max_value && value >= min_value) { out = static_cast<T>(value); return true; } else { return false; } } size_t addBitOffset(size_t x, int& offset) { x += offset / 8; offset %= 8; return x; } // -------------------------------------------------------- int l_readbit(lua_State* L) { size_t address; int bitOffset; if (lua_gettop(L) == 3) { // legacy: three args mean address, address_offset, bit_offset int addrOffset; std::tie(address, addrOffset, bitOffset) = phlua::callback::getArguments<size_t, int, int>(L, __FUNCTION__); address += addrOffset; } else { std::tie(address, bitOffset) = phlua::callback::getArguments<size_t, int>(L, __FUNCTION__); } address = addBitOffset(address, bitOffset); std::uint8_t b; readData(L, &b, (void*)address, sizeof(b)); bool bit = (b & (1 << bitOffset)) != 0; return phlua::callback::pushReturns(L, std::make_tuple(bit)); } int l_writebit(lua_State* L) { size_t address; int bitOffset; bool value; if (lua_gettop(L) == 4) { int addrOffset; // legacy: four args mean address, address_offset, bit_offset, value std::tie(address, addrOffset, bitOffset, value) = phlua::callback::getArguments<size_t, int, int, bool>(L, __FUNCTION__); address += addrOffset; } else { std::tie(address, bitOffset, value) = phlua::callback::getArguments<size_t, int, bool>(L, __FUNCTION__); } address = addBitOffset(address, bitOffset); std::uint8_t b; readData(L, &b, (void*)address, sizeof(b)); if (value) b |= 1 << bitOffset; else b &= ~(1 << bitOffset); writeData(L, (void*)address, &b, sizeof(b)); return 0; } // -------------------------------------------------------- template <typename T> int readNumber(lua_State* L, const char* f) { size_t address; boost::optional<size_t> offset; // backwards compatibility std::tie(address, offset) = phlua::callback::getArguments<size_t, decltype(offset)>(L, f); if (offset) address += *offset; T x; readData(L, &x, (void*)address, sizeof(T)); return phlua::callback::pushReturns(L, std::make_tuple(x)); } int l_readbyte(lua_State* L) { return readNumber<std::uint8_t>(L, __FUNCTION__); } int l_readchar(lua_State* L) { return readNumber<std::int8_t>(L, __FUNCTION__); } int l_readword(lua_State* L) { return readNumber<std::uint16_t>(L, __FUNCTION__); } int l_readshort(lua_State* L) { return readNumber<std::int16_t>(L, __FUNCTION__); } int l_readdword(lua_State* L) { return readNumber<std::uint32_t>(L, __FUNCTION__); } int l_readint(lua_State* L) { return readNumber<std::int32_t>(L, __FUNCTION__); } int l_readfloat(lua_State* L) { return readNumber<float>(L, __FUNCTION__); } int l_readdouble(lua_State* L) { return readNumber<double>(L, __FUNCTION__); } // -------------------------------------------------------- template <typename T> int writeNumber(lua_State* L, const char* f) { size_t address; lua_Number value; if (lua_gettop(L) == 3) { // backwards compatibility // address, offset, value int offset; std::tie(address, offset, value) = phlua::callback::getArguments<size_t, int, lua_Number>(L, f); address += offset; } else { std::tie(address, value) = phlua::callback::getArguments<size_t, lua_Number>(L, f); } T x; if (!checkLimits<T>(value, x)) { auto f = boost::format("invalid write: value (%.0f) outside of type's range") % value; luaL_error(L, "%s", f.str().c_str()); } writeData(L, (void*)address, &x, sizeof(T)); return 0; } int l_writebyte(lua_State* L) { return writeNumber<std::uint8_t>(L, __FUNCTION__); } int l_writechar(lua_State* L) { return writeNumber<std::int8_t>(L, __FUNCTION__); } int l_writeword(lua_State* L) { return writeNumber<std::uint16_t>(L, __FUNCTION__); } int l_writeshort(lua_State* L) { return writeNumber<std::int16_t>(L, __FUNCTION__); } int l_writedword(lua_State* L) { return writeNumber<std::uint32_t>(L, __FUNCTION__); } int l_writeint(lua_State* L) { return writeNumber<std::int32_t>(L, __FUNCTION__); } int l_writefloat(lua_State* L) { return writeNumber<float>(L, __FUNCTION__); } int l_writedouble(lua_State* L) { return writeNumber<double>(L, __FUNCTION__); } // -------------------------------------------------------- static const size_t kMaxStringElements = 160; template <typename T> int readstring(lua_State* L, const char* f) { size_t address; boost::optional<unsigned int> length; std::array<T, kMaxStringElements+1> dest; std::tie(address, length) = phlua::callback::getArguments<size_t, decltype(length)>(L, f); size_t readLength = kMaxStringElements; if (length) { if (length > kMaxStringElements) { auto f = boost::format("can only read strings to a maximum size of %u characters") % kMaxStringElements; luaL_argerror(L, 2, f.str().c_str()); } readLength = *length; } readData(L, dest.data(), (void*)address, readLength*sizeof(T)); dest[readLength] = 0; // ensure it's null terminated return phlua::callback::pushReturns(L, std::make_tuple(dest.data())); } int l_readstring(lua_State* L) { return readstring<char>(L, __FUNCTION__); } int l_readwidestring(lua_State* L) { return readstring<wchar_t>(L, __FUNCTION__); } // -------------------------------------------------------- template <typename StrType> int writestring(lua_State* L, const char* f) { typedef typename StrType::value_type char_type; size_t address; boost::optional<size_t> offset; StrType s; if (lua_gettop(L) == 3) { // backwards compatibility std::tie(address, offset, s) = phlua::callback::getArguments<size_t, decltype(offset), StrType>(L, f); } else { std::tie(address, s) = phlua::callback::getArguments<size_t, StrType>(L, f); } if (offset) address += *offset; size_t byteLength = s.size() * sizeof(char_type); writeData(L, (void*)address, s.c_str(), byteLength); char_type nullChar = 0; writeData(L, (void*)(address + byteLength), &nullChar, sizeof(nullChar)); return 0; } int l_writestring(lua_State* L) { return writestring<std::string>(L, __FUNCTION__); } int l_writewidestring(lua_State* L) { return writestring<std::wstring>(L, __FUNCTION__); } struct SigUnit { uint8_t x; enum class Mode { NORMAL, WILDCARD, WILDCARD_HIGH, WILDCARD_LOW } mode; }; uint8_t hex_to_int(char c) { c = tolower(c); if (c >= 'a' && c <= 'f') { return 10 + c - 'a'; } else { return c - '0'; } } // sig code in Addresses is really bad, so i'll just rewrite it... // sig should conform to ([A-Fa-f0-9?][A-Fa-f0-9?])+ // returns absolute address uint8_t* sigscan(const std::string& sig, int occurance) { // should refactor this, but for now a copy/paste works... uint8_t* module = (uint8_t*)GetModuleHandle(0); unsigned int OffsetToPE = *(unsigned int*)(module + 0x3C); unsigned int codeSize = *(unsigned int*)(module + OffsetToPE + 0x1C); unsigned int BaseOfCode = *(unsigned int*)(module + OffsetToPE + 0x2C); uint8_t* codeSection = (uint8_t*)(module + BaseOfCode); if (sig.size() % 2) return 0; // convert sig to byte values std::vector<SigUnit> bytes; bytes.reserve(sig.size() % 2); for (size_t x = 0; x < sig.size(); x += 2) { SigUnit unit; if (sig[x] == '?') { if (sig[x+1] == '?') { unit.mode = SigUnit::Mode::WILDCARD; } else { unit.mode = SigUnit::Mode::WILDCARD_HIGH; unit.x = hex_to_int(sig[x+1]); } } else if (sig[x+1] == '?') { unit.mode = SigUnit::Mode::WILDCARD_LOW; unit.x = hex_to_int(sig[x]); } else { unit.mode = SigUnit::Mode::NORMAL; unit.x = hex_to_int(sig[x]) << 4 | hex_to_int(sig[x+1]); } bytes.push_back(unit); } // todo: should probably use knp or something unsigned int found = 0; for (unsigned int x = 0; x < codeSize; x++) { unsigned int length = std::min(codeSize - x, bytes.size()); for (unsigned int i = 0; i < length; i++) { uint8_t b = codeSection[x+i]; bool match = true; switch (bytes[i].mode) { case SigUnit::Mode::WILDCARD: // nothing to do break; case SigUnit::Mode::WILDCARD_HIGH: // ?x match = (b & 0x0F) == bytes[i].x; break; case SigUnit::Mode::WILDCARD_LOW: // x? match = (b & 0xF0) == bytes[i].x; break; default: match = b == bytes[i].x; break; } if (match) { if (i + 1 == bytes.size()) { if (found++ == occurance) return codeSection + x; } } else break; } } return 0; } bool ishex(char c) { c = tolower(c); return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); } std::unordered_map<std::string, unsigned int> sigMap; int l_findsig(lua_State* L) { std::string sig; boost::optional<int> occurance; std::tie(sig, occurance) = phlua::callback::getArguments<std::string, decltype(occurance)>(L, __FUNCTION__); if (!occurance) occurance = 0; if (sig.length() == 0) { luaL_argerror(L, 1, "empty signature"); } for (auto c : sig) { if (c != '?' && !ishex(c)) luaL_argerror(L, 1, "signature can only contain hexadecimal or ? characters"); } // If only part of a byte is specified, treat the next as a wildcard if (sig.length() % 2) { sig.append("?"); } // Basic caching because sig searching is really slow... unsigned int mem; std::unordered_map<std::string, unsigned int>::iterator itr; char occuranceStr[9]; static const std::string occ_key_header = "occ:"; sprintf_s(occuranceStr, sizeof(occuranceStr), "%08x", *occurance); std::string map_key = sig + occ_key_header + occuranceStr; itr = sigMap.find(map_key); if (itr != sigMap.end()) mem = itr->second; else { mem = (unsigned int)sigscan(sig, *occurance); sigMap.insert(std::make_pair(map_key, mem)); } if (mem) { return phlua::callback::pushReturns(L, std::make_tuple(mem)); } else { return phlua::callback::pushReturns(L, std::make_tuple(lua::types::Nil())); } }<|endoftext|>
<commit_before>#include <libdariadb/storage/strategy.h> #include <libdariadb/utils/strings.h> std::istream &dariadb::storage::operator>>(std::istream &in, STRATEGY &strat) { std::string token; in >> token; token = utils::strings::to_upper(token); if (token == "FAST_WRITE") { strat = dariadb::storage::STRATEGY::FAST_WRITE; } if (token == "COMPRESSED") { strat = dariadb::storage::STRATEGY::COMPRESSED; } if (token == "MEMORY") { strat = dariadb::storage::STRATEGY::MEMORY; } if (token == "CACHE") { strat = dariadb::storage::STRATEGY::CACHE; } return in; } std::ostream &dariadb::storage::operator<<(std::ostream &stream, const STRATEGY &strat) { switch (strat) { case STRATEGY::COMPRESSED: stream << "COMPRESSED"; break; case STRATEGY::FAST_WRITE: stream << "FAST_WRITE"; break; case STRATEGY::MEMORY: stream << "MEMORY"; break; case STRATEGY::CACHE: stream << "CACHE"; break; default: stream << "UNKNOW: ui16=" << (uint16_t)strat; break; }; return stream; } <commit_msg>throw exception if bad strategy name.<commit_after>#include <libdariadb/storage/strategy.h> #include <libdariadb/utils/strings.h> #include <libdariadb/utils/exception.h> std::istream &dariadb::storage::operator>>(std::istream &in, STRATEGY &strat) { std::string token; in >> token; token = utils::strings::to_upper(token); if (token == "FAST_WRITE") { strat = dariadb::storage::STRATEGY::FAST_WRITE; return in; } if (token == "COMPRESSED") { strat = dariadb::storage::STRATEGY::COMPRESSED; return in; } if (token == "MEMORY") { strat = dariadb::storage::STRATEGY::MEMORY; return in; } if (token == "CACHE") { strat = dariadb::storage::STRATEGY::CACHE; return in; } THROW_EXCEPTION("engine: bad strategy name - ", token); } std::ostream &dariadb::storage::operator<<(std::ostream &stream, const STRATEGY &strat) { switch (strat) { case STRATEGY::COMPRESSED: stream << "COMPRESSED"; break; case STRATEGY::FAST_WRITE: stream << "FAST_WRITE"; break; case STRATEGY::MEMORY: stream << "MEMORY"; break; case STRATEGY::CACHE: stream << "CACHE"; break; default: THROW_EXCEPTION("engine: bad strategy - ", (uint16_t)strat); break; }; return stream; } <|endoftext|>
<commit_before><commit_msg>createBillboard now uses the same lookAt transform (this is differs from view matrix)<commit_after><|endoftext|>
<commit_before>#include "common.hpp" #include "bini322.hpp" #include "classical.hpp" #include "fast333.hpp" #include "grey-fast234.hpp" #include "grey-fast243.hpp" #include "grey-fast322.hpp" #include "grey-fast324.hpp" #include "grey-fast332.hpp" #include "grey-fast333.hpp" #include "grey-fast342.hpp" #include "grey-fast423.hpp" #include "grey-fast432.hpp" #include "grey-fast433.hpp" #include "hk332.hpp" #include "strassen.hpp" #include <stdlib.h> #include <time.h> #include <algorithm> #include <chrono> #include <random> #include <vector> enum { BINI332, CLASSICAL, GREY322, GREY332, GREY333, GREY432, GREY423, GREY324, GREY342, GREY234, GREY243, GREY433, HK332, }; // Run a single benchmark for multiplying m x k x n with numsteps of recursion. // To just call GEMM, set numsteps to zero. // The median of five trials is printed to std::cout. // If run_check is true, then it also void SingleBenchmark(int m, int k, int n, int numsteps, int algorithm, bool run_check=false) { Matrix<double> A(m, k); Matrix<double> B(k, n); Matrix<double> C1(m, n); for (int j = 0; j < A.n(); ++j) { for (int i = 0; i < A.m(); ++i) { A.data()[i + j * A.stride()] = ((double) rand() / RAND_MAX) * 1024; } } for (int j = 0; j < B.n(); ++j) { for (int i = 0; i < B.m(); ++i) { B.data()[i + j * B.stride()] = ((double) rand() / RAND_MAX) * 1024; } } // Run a set number of trials and pick the median time. int num_trials = 5; std::vector<double> times(num_trials); for (int trial = 0; trial < num_trials; ++trial) { auto t1 = std::chrono::high_resolution_clock::now(); switch (algorithm) { case BINI332: bini322::FastMatmul(A, B, C1, numsteps); break; case CLASSICAL: classical::FastMatmul(A, B, C1, numsteps); break; case GREY322: grey322_11_50::FastMatmul(A, B, C1, numsteps); break; case GREY332: grey332_15_103::FastMatmul(A, B, C1, numsteps); break; case GREY333: grey333_23_152::FastMatmul(A, B, C1, numsteps); break; case GREY432: grey432_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY423: grey423_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY324: grey324_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY342: grey342_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY234: grey234_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY243: grey324_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY433: grey433_29_234::FastMatmul(A, B, C1, numsteps); break; case HK332: hk332_2::FastMatmul(A, B, C1, numsteps); break; default: std::cout << "Unknown algorithm type!" << std::endl; } auto t2 = std::chrono::high_resolution_clock::now(); times[trial] = std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count(); } // Spit out the median time std::sort(times.begin(), times.end()); size_t ind = num_trials / 2 + 1; std::cout << " " << m << " " << k << " " << n << " " << numsteps << " " << times[ind] << " " << "; ..." << std::endl; if (run_check) { // Test for correctness. Matrix<double> C2(m, n); Gemm(A, B, C2); std::cout << "Maximum relative difference: " << MaxRelativeDiff(C1, C2) << std::endl; } } // Runs a set of benchmarks. void BenchmarkSet(std::vector<int>& m_vals, std::vector<int>& k_vals, std::vector<int>& n_vals, std::vector<int>& numsteps, bool run_check=false) { assert(m_vals.size() == k_vals.size() && k_vals.size() == n_vals.size()); for (int i = 0; i < m_vals.size(); ++i) { for (int curr_numsteps : numsteps) { SingleBenchmark(m_vals[i], k_vals[i], n_vals[i], curr_numsteps, run_check); } } } int main(int argc, char **argv) { std::vector<int> numsteps = {0, 1}; std::vector<int> m_vals = {1200, 2100}; BenchmarkSet(m_vals, m_vals, m_vals, numsteps); } <commit_msg>benchmark figured out<commit_after>#include "common.hpp" #include "bini322.hpp" #include "classical.hpp" #include "fast333.hpp" #include "grey-fast234.hpp" #include "grey-fast243.hpp" #include "grey-fast322.hpp" #include "grey-fast324.hpp" #include "grey-fast332.hpp" #include "grey-fast333.hpp" #include "grey-fast342.hpp" #include "grey-fast423.hpp" #include "grey-fast432.hpp" #include "grey-fast433.hpp" #include "hk332.hpp" #include "strassen.hpp" #include <stdlib.h> #include <time.h> #include <algorithm> #include <chrono> #include <random> #include <vector> enum { BINI332, CLASSICAL, GREY322, GREY332, GREY333, GREY432, GREY423, GREY324, GREY342, GREY234, GREY243, GREY433, HK332, }; // Run a single benchmark for multiplying m x k x n with numsteps of recursion. // To just call GEMM, set numsteps to zero. // The median of five trials is printed to std::cout. // If run_check is true, then it also void SingleBenchmark(int m, int k, int n, int numsteps, int algorithm, bool run_check=false) { Matrix<double> A(m, k); Matrix<double> B(k, n); Matrix<double> C1(m, n); for (int j = 0; j < A.n(); ++j) { for (int i = 0; i < A.m(); ++i) { A.data()[i + j * A.stride()] = ((double) rand() / RAND_MAX) * 1024; } } for (int j = 0; j < B.n(); ++j) { for (int i = 0; i < B.m(); ++i) { B.data()[i + j * B.stride()] = ((double) rand() / RAND_MAX) * 1024; } } // Run a set number of trials and pick the median time. int num_trials = 5; std::vector<double> times(num_trials); for (int trial = 0; trial < num_trials; ++trial) { auto t1 = std::chrono::high_resolution_clock::now(); switch (algorithm) { case BINI332: bini322::FastMatmul(A, B, C1, numsteps); break; case CLASSICAL: classical::FastMatmul(A, B, C1, numsteps); break; case GREY322: grey322_11_50::FastMatmul(A, B, C1, numsteps); break; case GREY332: grey332_15_103::FastMatmul(A, B, C1, numsteps); break; case GREY333: grey333_23_152::FastMatmul(A, B, C1, numsteps); break; case GREY432: grey432_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY423: grey423_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY324: grey324_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY342: grey342_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY234: grey234_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY243: grey324_20_144::FastMatmul(A, B, C1, numsteps); break; case GREY433: grey433_29_234::FastMatmul(A, B, C1, numsteps); break; case HK332: hk332_2::FastMatmul(A, B, C1, numsteps); break; default: std::cout << "Unknown algorithm type!" << std::endl; } auto t2 = std::chrono::high_resolution_clock::now(); times[trial] = std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count(); } // Spit out the median time std::sort(times.begin(), times.end()); size_t ind = num_trials / 2 + 1; std::cout << " " << m << " " << k << " " << n << " " << numsteps << " " << times[ind] << " " << "; ..." << std::endl; if (run_check) { // Test for correctness. Matrix<double> C2(m, n); Gemm(A, B, C2); std::cout << "Maximum relative difference: " << MaxRelativeDiff(C1, C2) << std::endl; } } // Runs a set of benchmarks. void BenchmarkSet(std::vector<int>& m_vals, std::vector<int>& k_vals, std::vector<int>& n_vals, std::vector<int>& numsteps, int algorithm, bool run_check=false) { assert(m_vals.size() == k_vals.size() && k_vals.size() == n_vals.size()); for (int i = 0; i < m_vals.size(); ++i) { for (int curr_numsteps : numsteps) { SingleBenchmark(m_vals[i], k_vals[i], n_vals[i], curr_numsteps, algorithm, run_check); } } } int main(int argc, char **argv) { std::vector<int> numsteps = {0, 1}; std::vector<int> m_vals = {1200, 2100}; BenchmarkSet(m_vals, m_vals, m_vals, numsteps, GREY333); } <|endoftext|>
<commit_before>563ea08a-2e4e-11e5-9284-b827eb9e62be<commit_msg>5643c4fc-2e4e-11e5-9284-b827eb9e62be<commit_after>5643c4fc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #include "config.h" #include "SharedMemoryImp.hpp" #include <limits.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <string.h> #include <glob.h> #include <iostream> #include <sstream> #include <utility> #include "geopm_time.h" #include "geopm/Exception.hpp" #include "geopm/Helper.hpp" namespace geopm { void SharedMemory::cleanup_shmem(void) { std::string pattern = "/geopm-shm-" + std::to_string(geteuid()) + "-*"; pattern = SharedMemoryImp::construct_shm_path(pattern); glob_t globbuf; int err = glob(pattern.c_str(), 0, nullptr, &globbuf); if (err == 0) { for (size_t path_idx = 0; path_idx != globbuf.gl_pathc; ++path_idx) { int unlink_err = ::unlink(globbuf.gl_pathv[path_idx]); if (unlink_err != 0) { #ifdef GEOPM_DEBUG std::cerr << "Warning: <geopm> SharedMemory:cleanup_shmem(): unable to unlink file: " << globbuf.gl_pathv[path_idx] << "\n"; #endif } } globfree(&globbuf); } } /// @brief Size of the lock in memory. static constexpr size_t M_LOCK_SIZE = geopm::hardware_destructive_interference_size; static_assert(sizeof(pthread_mutex_t) <= M_LOCK_SIZE, "M_LOCK_SIZE not large enough for mutex type"); static void setup_mutex(pthread_mutex_t *lock) { pthread_mutexattr_t lock_attr; int err = pthread_mutexattr_init(&lock_attr); if (err) { throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_ERRORCHECK); if (err) { (void) pthread_mutexattr_destroy(&lock_attr); throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED); if (err) { (void) pthread_mutexattr_destroy(&lock_attr); throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = pthread_mutex_init(lock, &lock_attr); if (err) { (void) pthread_mutexattr_destroy(&lock_attr); throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = pthread_mutexattr_destroy(&lock_attr); if (err) { throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } std::unique_ptr<SharedMemory> SharedMemory::make_unique_owner(const std::string &shm_key, size_t size) { std::unique_ptr<SharedMemoryImp> owner = geopm::make_unique<SharedMemoryImp>(); owner->create_memory_region(shm_key, size, false); return std::unique_ptr<SharedMemory>(std::move(owner)); } std::unique_ptr<SharedMemory> SharedMemory::make_unique_owner_secure(const std::string &shm_key, size_t size) { std::unique_ptr<SharedMemoryImp> owner = geopm::make_unique<SharedMemoryImp>(); owner->create_memory_region(shm_key, size, true); return std::unique_ptr<SharedMemory>(std::move(owner)); } std::unique_ptr<SharedMemory> SharedMemory::make_unique_user(const std::string &shm_key, unsigned int timeout) { std::unique_ptr<SharedMemoryImp> user = geopm::make_unique<SharedMemoryImp>(); user->attach_memory_region(shm_key, timeout); return std::unique_ptr<SharedMemory>(std::move(user)); } SharedMemoryImp::SharedMemoryImp() : m_size(0) , m_ptr(NULL) , m_is_linked(false) , m_do_unlink_check(false) { } void SharedMemoryImp::create_memory_region(const std::string &shm_key, size_t size, bool is_secure) { if (!size) { throw Exception("SharedMemoryImp: Cannot create shared memory region of zero size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_shm_key = shm_key; m_shm_path = construct_shm_path(shm_key); m_size = size + M_LOCK_SIZE; mode_t old_mask = umask(0); int shm_id = 0; if (is_secure) { shm_id = open(m_shm_path.c_str(), O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); } else { shm_id = open(m_shm_path.c_str(), O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); } if (shm_id < 0) { std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not open shared memory with key " << m_shm_key; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } int err = ftruncate(shm_id, m_size); if (err) { (void) close(shm_id); (void) ::unlink(m_shm_path.c_str()); (void) umask(old_mask); std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not extend shared memory to size " << m_size; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0); if (m_ptr == MAP_FAILED) { (void) close(shm_id); (void) ::unlink(m_shm_path.c_str()); (void) umask(old_mask); throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = close(shm_id); if (err) { (void) umask(old_mask); throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } umask(old_mask); setup_mutex((pthread_mutex_t*)m_ptr); m_is_linked = true; m_do_unlink_check = false; } SharedMemoryImp::~SharedMemoryImp() { if (m_ptr != nullptr) { if (munmap(m_ptr, m_size)) { #ifdef GEOPM_DEBUG std::cerr << "Warning: <geopm> SharedMemoryImp: Could not unmap pointer" << std::endl; #endif } } } void SharedMemoryImp::unlink(void) { // ProfileSampler destructor calls unlink, so don't throw if constructed // as owner if (m_is_linked) { int err = ::unlink(m_shm_path.c_str()); if (err && m_do_unlink_check) { std::ostringstream tmp_str; tmp_str << "SharedMemoryImp::unlink() Call to unlink(" << m_shm_path << ") failed"; throw Exception(tmp_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_is_linked = false; } } void *SharedMemoryImp::pointer(void) const { return (char*)m_ptr + M_LOCK_SIZE; } std::string SharedMemoryImp::key(void) const { return m_shm_key; } size_t SharedMemoryImp::size(void) const { return m_size - M_LOCK_SIZE; } std::unique_ptr<SharedMemoryScopedLock> SharedMemoryImp::get_scoped_lock(void) { return geopm::make_unique<SharedMemoryScopedLock>((pthread_mutex_t*)m_ptr); } void SharedMemoryImp::attach_memory_region(const std::string &shm_key, unsigned int timeout) { m_shm_key = shm_key; m_shm_path = construct_shm_path(shm_key); m_is_linked = false; int shm_id = -1; struct stat stat_struct; int err = 0; if (!timeout) { shm_id = open(m_shm_path.c_str(), O_RDWR, 0); if (shm_id < 0) { std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not open shared memory with key \"" << shm_key << "\""; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = fstat(shm_id, &stat_struct); if (err) { (void) close(shm_id); std::ostringstream ex_str; ex_str << "SharedMemoryImp: fstat() error on shared memory with key \"" << shm_key << "\""; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_size = stat_struct.st_size; m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0); if (m_ptr == MAP_FAILED) { (void) close(shm_id); throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } else { struct geopm_time_s begin_time; geopm_time(&begin_time); while (shm_id < 0 && geopm_time_since(&begin_time) < (double)timeout) { shm_id = open(m_shm_path.c_str(), O_RDWR, 0); } if (shm_id < 0) { std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not open shared memory with key \"" << shm_key << "\""; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } while (!m_size && geopm_time_since(&begin_time) < (double)timeout) { err = fstat(shm_id, &stat_struct); if (!err) { m_size = stat_struct.st_size; } } if (!m_size) { (void) close(shm_id); throw Exception("SharedMemoryImp: Opened shared memory region, but it is zero length", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0); if (m_ptr == MAP_FAILED) { (void) close(shm_id); throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } err = close(shm_id); if (err) { throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_is_linked = true; m_do_unlink_check = true; } void SharedMemoryImp::chown(const unsigned int uid, const unsigned int gid) const { int err = 0; int shm_id = -1; if (m_is_linked) { shm_id = open(m_shm_path.c_str(), O_RDWR, 0); } else { throw Exception("SharedMemoryImp: Cannot chown shm that has been unlinked.", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } if (shm_id < 0) { std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not open shared memory with key \"" << m_shm_key << "\""; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = fchown(shm_id, uid, gid); if (err) { (void) close(shm_id); std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not chown shmem with key (" << m_shm_key << ") to UID (" << std::to_string(uid) << "), GID (" << std::to_string(gid) + ")"; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = close(shm_id); if (err) { throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } std::string SharedMemoryImp::construct_shm_path(const std::string &key) { std::string path; if (key.length() > 1 && key[0] == '/' && key.find('/', 1) == std::string::npos) { // shmem key // pam_systemd/logind enabled? std::string usr_run_dir = "/run/user/" + std::to_string(getuid()); if (access(usr_run_dir.c_str(), F_OK) == 0) { path = usr_run_dir + key; } else { path = "/dev/shm" + key; } } else { // regular file path path = key; } return path; } } <commit_msg>Avoid memory leak if glob fails<commit_after>/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #include "config.h" #include "SharedMemoryImp.hpp" #include <limits.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <string.h> #include <glob.h> #include <iostream> #include <sstream> #include <utility> #include "geopm_time.h" #include "geopm/Exception.hpp" #include "geopm/Helper.hpp" namespace geopm { void SharedMemory::cleanup_shmem(void) { std::string pattern = "/geopm-shm-" + std::to_string(geteuid()) + "-*"; pattern = SharedMemoryImp::construct_shm_path(pattern); glob_t globbuf; int err = glob(pattern.c_str(), 0, nullptr, &globbuf); if (err == 0) { for (size_t path_idx = 0; path_idx != globbuf.gl_pathc; ++path_idx) { int unlink_err = ::unlink(globbuf.gl_pathv[path_idx]); if (unlink_err != 0) { #ifdef GEOPM_DEBUG std::cerr << "Warning: <geopm> SharedMemory:cleanup_shmem(): unable to unlink file: " << globbuf.gl_pathv[path_idx] << "\n"; #endif } } } globfree(&globbuf); } /// @brief Size of the lock in memory. static constexpr size_t M_LOCK_SIZE = geopm::hardware_destructive_interference_size; static_assert(sizeof(pthread_mutex_t) <= M_LOCK_SIZE, "M_LOCK_SIZE not large enough for mutex type"); static void setup_mutex(pthread_mutex_t *lock) { pthread_mutexattr_t lock_attr; int err = pthread_mutexattr_init(&lock_attr); if (err) { throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_ERRORCHECK); if (err) { (void) pthread_mutexattr_destroy(&lock_attr); throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED); if (err) { (void) pthread_mutexattr_destroy(&lock_attr); throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = pthread_mutex_init(lock, &lock_attr); if (err) { (void) pthread_mutexattr_destroy(&lock_attr); throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = pthread_mutexattr_destroy(&lock_attr); if (err) { throw Exception("SharedMemory::setup_mutex(): pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } std::unique_ptr<SharedMemory> SharedMemory::make_unique_owner(const std::string &shm_key, size_t size) { std::unique_ptr<SharedMemoryImp> owner = geopm::make_unique<SharedMemoryImp>(); owner->create_memory_region(shm_key, size, false); return std::unique_ptr<SharedMemory>(std::move(owner)); } std::unique_ptr<SharedMemory> SharedMemory::make_unique_owner_secure(const std::string &shm_key, size_t size) { std::unique_ptr<SharedMemoryImp> owner = geopm::make_unique<SharedMemoryImp>(); owner->create_memory_region(shm_key, size, true); return std::unique_ptr<SharedMemory>(std::move(owner)); } std::unique_ptr<SharedMemory> SharedMemory::make_unique_user(const std::string &shm_key, unsigned int timeout) { std::unique_ptr<SharedMemoryImp> user = geopm::make_unique<SharedMemoryImp>(); user->attach_memory_region(shm_key, timeout); return std::unique_ptr<SharedMemory>(std::move(user)); } SharedMemoryImp::SharedMemoryImp() : m_size(0) , m_ptr(NULL) , m_is_linked(false) , m_do_unlink_check(false) { } void SharedMemoryImp::create_memory_region(const std::string &shm_key, size_t size, bool is_secure) { if (!size) { throw Exception("SharedMemoryImp: Cannot create shared memory region of zero size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_shm_key = shm_key; m_shm_path = construct_shm_path(shm_key); m_size = size + M_LOCK_SIZE; mode_t old_mask = umask(0); int shm_id = 0; if (is_secure) { shm_id = open(m_shm_path.c_str(), O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); } else { shm_id = open(m_shm_path.c_str(), O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); } if (shm_id < 0) { std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not open shared memory with key " << m_shm_key; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } int err = ftruncate(shm_id, m_size); if (err) { (void) close(shm_id); (void) ::unlink(m_shm_path.c_str()); (void) umask(old_mask); std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not extend shared memory to size " << m_size; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0); if (m_ptr == MAP_FAILED) { (void) close(shm_id); (void) ::unlink(m_shm_path.c_str()); (void) umask(old_mask); throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = close(shm_id); if (err) { (void) umask(old_mask); throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } umask(old_mask); setup_mutex((pthread_mutex_t*)m_ptr); m_is_linked = true; m_do_unlink_check = false; } SharedMemoryImp::~SharedMemoryImp() { if (m_ptr != nullptr) { if (munmap(m_ptr, m_size)) { #ifdef GEOPM_DEBUG std::cerr << "Warning: <geopm> SharedMemoryImp: Could not unmap pointer" << std::endl; #endif } } } void SharedMemoryImp::unlink(void) { // ProfileSampler destructor calls unlink, so don't throw if constructed // as owner if (m_is_linked) { int err = ::unlink(m_shm_path.c_str()); if (err && m_do_unlink_check) { std::ostringstream tmp_str; tmp_str << "SharedMemoryImp::unlink() Call to unlink(" << m_shm_path << ") failed"; throw Exception(tmp_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_is_linked = false; } } void *SharedMemoryImp::pointer(void) const { return (char*)m_ptr + M_LOCK_SIZE; } std::string SharedMemoryImp::key(void) const { return m_shm_key; } size_t SharedMemoryImp::size(void) const { return m_size - M_LOCK_SIZE; } std::unique_ptr<SharedMemoryScopedLock> SharedMemoryImp::get_scoped_lock(void) { return geopm::make_unique<SharedMemoryScopedLock>((pthread_mutex_t*)m_ptr); } void SharedMemoryImp::attach_memory_region(const std::string &shm_key, unsigned int timeout) { m_shm_key = shm_key; m_shm_path = construct_shm_path(shm_key); m_is_linked = false; int shm_id = -1; struct stat stat_struct; int err = 0; if (!timeout) { shm_id = open(m_shm_path.c_str(), O_RDWR, 0); if (shm_id < 0) { std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not open shared memory with key \"" << shm_key << "\""; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = fstat(shm_id, &stat_struct); if (err) { (void) close(shm_id); std::ostringstream ex_str; ex_str << "SharedMemoryImp: fstat() error on shared memory with key \"" << shm_key << "\""; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_size = stat_struct.st_size; m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0); if (m_ptr == MAP_FAILED) { (void) close(shm_id); throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } else { struct geopm_time_s begin_time; geopm_time(&begin_time); while (shm_id < 0 && geopm_time_since(&begin_time) < (double)timeout) { shm_id = open(m_shm_path.c_str(), O_RDWR, 0); } if (shm_id < 0) { std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not open shared memory with key \"" << shm_key << "\""; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } while (!m_size && geopm_time_since(&begin_time) < (double)timeout) { err = fstat(shm_id, &stat_struct); if (!err) { m_size = stat_struct.st_size; } } if (!m_size) { (void) close(shm_id); throw Exception("SharedMemoryImp: Opened shared memory region, but it is zero length", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_ptr = mmap(NULL, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0); if (m_ptr == MAP_FAILED) { (void) close(shm_id); throw Exception("SharedMemoryImp: Could not mmap shared memory region", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } err = close(shm_id); if (err) { throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_is_linked = true; m_do_unlink_check = true; } void SharedMemoryImp::chown(const unsigned int uid, const unsigned int gid) const { int err = 0; int shm_id = -1; if (m_is_linked) { shm_id = open(m_shm_path.c_str(), O_RDWR, 0); } else { throw Exception("SharedMemoryImp: Cannot chown shm that has been unlinked.", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } if (shm_id < 0) { std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not open shared memory with key \"" << m_shm_key << "\""; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = fchown(shm_id, uid, gid); if (err) { (void) close(shm_id); std::ostringstream ex_str; ex_str << "SharedMemoryImp: Could not chown shmem with key (" << m_shm_key << ") to UID (" << std::to_string(uid) << "), GID (" << std::to_string(gid) + ")"; throw Exception(ex_str.str(), errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = close(shm_id); if (err) { throw Exception("SharedMemoryImp: Could not close shared memory file", errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } std::string SharedMemoryImp::construct_shm_path(const std::string &key) { std::string path; if (key.length() > 1 && key[0] == '/' && key.find('/', 1) == std::string::npos) { // shmem key // pam_systemd/logind enabled? std::string usr_run_dir = "/run/user/" + std::to_string(getuid()); if (access(usr_run_dir.c_str(), F_OK) == 0) { path = usr_run_dir + key; } else { path = "/dev/shm" + key; } } else { // regular file path path = key; } return path; } } <|endoftext|>
<commit_before>#include "GameCtrl.h" int main() { auto game = GameCtrl::getInstance(); // Set FPS. Default is 60.0 game->setFPS(60.0); // Set whether to enable the snake AI. Default is true. game->setEnableAI(true); // Set whether to use a hamiltonian cycle to guide the AI. Default is true. game->setEnableHamilton(true); // Set the interval time between each snake's movement. Default is 30 ms. // To play classic snake game, set to 150 ms is perfect. game->setMoveInterval(30); // Set whether to record the snake's movements to file. Default is true. // The movements will be written to a file named "movements.txt". game->setRecordMovements(true); // Set whether to run the test program. Default is false. // You can select different testing methods by modifying GameCtrl::test(). game->setRunTest(false); // Set map's size(including boundaries). Default is 10*10. Minimum is 5*5. game->setMapRow(10); game->setMapCol(10); return game->run(); } <commit_msg>Create menu GUI #2<commit_after>#include "GameCtrl.h" char title[16][30]= { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,0,0,1,0,0,1,0,1,1,1,1,1,0}, {0,1,0,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,0,0}, {0,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,0,0,1,1,0,0,0,1,1,1,1,1,0}, {0,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,0,0}, {0,1,1,1,1,1,0,1,0,0,0,1,0,1,0,0,1,0,0,1,0,0,1,0,1,1,1,1,1,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,1,1,1,1,1,0,0,0,1,1,0,0,0,1,1,0,0,0,1,1,0,0,1,1,1,1,1,0}, {0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,0}, {0,0,1,0,0,1,1,0,0,1,1,1,1,0,0,1,0,1,0,1,0,1,0,0,1,1,1,1,1,0}, {0,0,1,1,1,1,1,0,0,1,0,0,1,0,0,1,0,1,0,1,0,1,0,0,1,0,0,0,0,0}, {0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,1,1,1,1,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} }; int main() { int menu; printf("\n"); for(int x=0;x<16;x++){ printf("\t"); for(int y=0;y<30;y++) { if(title[x][y] == 1) { printf(""); } if(title[x][y] == 0) { printf(""); } } printf("\n"); } printf("\t------------------------------------------------------------\n"); printf("\t\t\t\t<MENU>\n"); printf("\t\t\t 1.Snake Game\n"); printf("\t\t\t =>Input Menu Number : "); scanf("%d",&menu); if(menu==1) { auto game = GameCtrl::getInstance(); // Set FPS. Default is 60.0 game->setFPS(60.0); // Set whether to enable the snake AI. Default is true. game->setEnableAI(true); // Set whether to use a hamiltonian cycle to guide the AI. Default is true. game->setEnableHamilton(true); // Set the interval time between each snake's movement. Default is 30 ms. // To play classic snake game, set to 150 ms is perfect. game->setMoveInterval(30); // Set whether to record the snake's movements to file. Default is true. // The movements will be written to a file named "movements.txt". game->setRecordMovements(true); // Set whether to run the test program. Default is false. // You can select different testing methods by modifying GameCtrl::test(). game->setRunTest(false); // Set map's size(including boundaries). Default is 10*10. Minimum is 5*5. game->setMapRow(10); game->setMapCol(10); return game->run(); } else return 0; } <|endoftext|>
<commit_before>9517b2b0-2e4e-11e5-9284-b827eb9e62be<commit_msg>951cb09e-2e4e-11e5-9284-b827eb9e62be<commit_after>951cb09e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* * Copyright (c) 2013 New Designs Unlimited, LLC * Opensource Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenAlpr. * * OpenAlpr is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * 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 <cstdio> #include <sstream> #include <iostream> #include <iterator> #include <algorithm> #include <signal.h> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "tclap/CmdLine.h" #include "support/filesystem.h" #include "support/timing.h" #include "videobuffer.h" #include "alpr.h" const std::string MAIN_WINDOW_NAME = "ALPR main window"; const bool SAVE_LAST_VIDEO_STILL = false; const std::string LAST_VIDEO_STILL_LOCATION = "/tmp/laststill.jpg"; /** Function Headers */ bool detectandshow(Alpr* alpr, cv::Mat frame, std::string region, bool writeJson); void sighandler(int sig); bool measureProcessingTime = false; // This boolean is set to false when the user hits terminates (e.g., CTRL+C ) // so we can end infinite loops for things like video processing. bool program_active = true; int main( int argc, const char** argv ) { std::string filename; std::string configFile = ""; bool outputJson = false; int seektoms = 0; bool detectRegion = false; std::string templateRegion; std::string country; int topn; TCLAP::CmdLine cmd("OpenAlpr Command Line Utility", ' ', Alpr::getVersion()); TCLAP::UnlabeledValueArg<std::string> fileArg( "image_file", "Image containing license plates", false, "", "image_file_path" ); TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe). Default=us",false, "us" ,"country_code"); TCLAP::ValueArg<int> seekToMsArg("","seek","Seek to the specied millisecond in a video file. Default=0",false, 0 ,"integer_ms"); TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file",false, "" ,"config_file"); TCLAP::ValueArg<std::string> templateRegionArg("t","template_region","Attempt to match the plate number against a region template (e.g., md for Maryland, ca for California)",false, "" ,"region code"); TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return. Default=10",false, 10 ,"topN"); TCLAP::SwitchArg jsonSwitch("j","json","Output recognition results in JSON format. Default=off", cmd, false); TCLAP::SwitchArg detectRegionSwitch("d","detect_region","Attempt to detect the region of the plate image. Default=off", cmd, false); TCLAP::SwitchArg clockSwitch("","clock","Measure/print the total time to process image and all plates. Default=off", cmd, false); try { cmd.add( templateRegionArg ); cmd.add( seekToMsArg ); cmd.add( topNArg ); cmd.add( configFileArg ); cmd.add( fileArg ); cmd.add( countryCodeArg ); if (cmd.parse( argc, argv ) == false) { // Error occured while parsing. Exit now. return 1; } filename = fileArg.getValue(); country = countryCodeArg.getValue(); seektoms = seekToMsArg.getValue(); outputJson = jsonSwitch.getValue(); configFile = configFileArg.getValue(); detectRegion = detectRegionSwitch.getValue(); templateRegion = templateRegionArg.getValue(); topn = topNArg.getValue(); measureProcessingTime = clockSwitch.getValue(); } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; return 1; } struct sigaction sigIntHandler; sigIntHandler.sa_handler = sighandler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGHUP, &sigIntHandler, NULL); sigaction(SIGINT, &sigIntHandler, NULL); sigaction(SIGQUIT, &sigIntHandler, NULL); sigaction(SIGKILL, &sigIntHandler, NULL); sigaction(SIGTERM, &sigIntHandler, NULL); //sigaction(SIGABRT, &sigIntHandler, NULL); cv::Mat frame; Alpr alpr(country, configFile); alpr.setTopN(topn); if (detectRegion) alpr.setDetectRegion(detectRegion); if (templateRegion.empty() == false) alpr.setDefaultRegion(templateRegion); if (alpr.isLoaded() == false) { std::cerr << "Error loading OpenALPR" << std::endl; return 1; } if (filename.empty()) { std::string filename; while (std::getline(std::cin, filename)) { if (fileExists(filename.c_str())) { frame = cv::imread( filename ); detectandshow( &alpr, frame, "", outputJson); } else { std::cerr << "Image file not found: " << filename << std::endl; } } } else if (filename == "webcam") { int framenum = 0; cv::VideoCapture cap(0); if (!cap.isOpened()) { std::cout << "Error opening webcam" << std::endl; return 1; } while (cap.read(frame)) { detectandshow(&alpr, frame, "", outputJson); cv::waitKey(1); framenum++; } } else if (startsWith(filename, "http://") || startsWith(filename, "https://")) { int framenum = 0; VideoBuffer videoBuffer; videoBuffer.connect(filename, 5); cv::Mat latestFrame; while (program_active) { int response = videoBuffer.getLatestFrame(&latestFrame); if (response != -1) { detectandshow( &alpr, latestFrame, "", outputJson); } cv::waitKey(10); } videoBuffer.disconnect(); std::cout << "Video processing ended" << std::endl; } else if (hasEndingInsensitive(filename, ".avi") || hasEndingInsensitive(filename, ".mp4") || hasEndingInsensitive(filename, ".webm") || hasEndingInsensitive(filename, ".flv") || hasEndingInsensitive(filename, ".mjpg") || hasEndingInsensitive(filename, ".mjpeg")) { if (fileExists(filename.c_str())) { int framenum = 0; cv::VideoCapture cap=cv::VideoCapture(); cap.open(filename); cap.set(CV_CAP_PROP_POS_MSEC, seektoms); while (cap.read(frame)) { if (SAVE_LAST_VIDEO_STILL) { cv::imwrite(LAST_VIDEO_STILL_LOCATION, frame); } std::cout << "Frame: " << framenum << std::endl; detectandshow( &alpr, frame, "", outputJson); //create a 1ms delay cv::waitKey(1); framenum++; } } else { std::cerr << "Video file not found: " << filename << std::endl; } } else if (hasEndingInsensitive(filename, ".png") || hasEndingInsensitive(filename, ".jpg") || hasEndingInsensitive(filename, ".jpeg") || hasEndingInsensitive(filename, ".gif")) { if (fileExists(filename.c_str())) { frame = cv::imread( filename ); detectandshow( &alpr, frame, "", outputJson); } else { std::cerr << "Image file not found: " << filename << std::endl; } } else if (DirectoryExists(filename.c_str())) { std::vector<std::string> files = getFilesInDir(filename.c_str()); std::sort( files.begin(), files.end(), stringCompare ); for (int i = 0; i< files.size(); i++) { if (hasEndingInsensitive(files[i], ".jpg") || hasEndingInsensitive(files[i], ".png")) { std::string fullpath = filename + "/" + files[i]; std::cout << fullpath << std::endl; frame = cv::imread( fullpath.c_str() ); if (detectandshow( &alpr, frame, "", outputJson)) { //while ((char) cv::waitKey(50) != 'c') { } } else { //cv::waitKey(50); } } } } else { std::cerr << "Unknown file type" << std::endl; return 1; } return 0; } void sighandler(int sig) { program_active = false; //std::cout << "Sig handler caught " << sig << std::endl; } bool detectandshow( Alpr* alpr, cv::Mat frame, std::string region, bool writeJson) { std::vector<uchar> buffer; cv::imencode(".bmp", frame, buffer ); timespec startTime; getTime(&startTime); std::vector<AlprResult> results = alpr->recognize(buffer); if (writeJson) { std::cout << alpr->toJson(results) << std::endl; } else { for (int i = 0; i < results.size(); i++) { std::cout << "plate" << i << ": " << results[i].result_count << " results -- Processing Time = " << results[i].processing_time_ms << "ms." << std::endl; for (int k = 0; k < results[i].topNPlates.size(); k++) { std::cout << " - " << results[i].topNPlates[k].characters << "\t confidence: " << results[i].topNPlates[k].overall_confidence << "\t template_match: " << results[i].topNPlates[k].matches_template << std::endl; } } } timespec endTime; getTime(&endTime); if (measureProcessingTime) std::cout << "Total Time to process image: " << diffclock(startTime, endTime) << "ms." << std::endl; return results.size() > 0; } <commit_msg>Removed unnecessary signal handlers<commit_after>/* * Copyright (c) 2013 New Designs Unlimited, LLC * Opensource Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenAlpr. * * OpenAlpr is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * 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 <cstdio> #include <sstream> #include <iostream> #include <iterator> #include <algorithm> #include <signal.h> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "tclap/CmdLine.h" #include "support/filesystem.h" #include "support/timing.h" #include "videobuffer.h" #include "alpr.h" const std::string MAIN_WINDOW_NAME = "ALPR main window"; const bool SAVE_LAST_VIDEO_STILL = false; const std::string LAST_VIDEO_STILL_LOCATION = "/tmp/laststill.jpg"; /** Function Headers */ bool detectandshow(Alpr* alpr, cv::Mat frame, std::string region, bool writeJson); void sighandler(int sig); bool measureProcessingTime = false; // This boolean is set to false when the user hits terminates (e.g., CTRL+C ) // so we can end infinite loops for things like video processing. bool program_active = true; int main( int argc, const char** argv ) { std::string filename; std::string configFile = ""; bool outputJson = false; int seektoms = 0; bool detectRegion = false; std::string templateRegion; std::string country; int topn; TCLAP::CmdLine cmd("OpenAlpr Command Line Utility", ' ', Alpr::getVersion()); TCLAP::UnlabeledValueArg<std::string> fileArg( "image_file", "Image containing license plates", false, "", "image_file_path" ); TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe). Default=us",false, "us" ,"country_code"); TCLAP::ValueArg<int> seekToMsArg("","seek","Seek to the specied millisecond in a video file. Default=0",false, 0 ,"integer_ms"); TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file",false, "" ,"config_file"); TCLAP::ValueArg<std::string> templateRegionArg("t","template_region","Attempt to match the plate number against a region template (e.g., md for Maryland, ca for California)",false, "" ,"region code"); TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return. Default=10",false, 10 ,"topN"); TCLAP::SwitchArg jsonSwitch("j","json","Output recognition results in JSON format. Default=off", cmd, false); TCLAP::SwitchArg detectRegionSwitch("d","detect_region","Attempt to detect the region of the plate image. Default=off", cmd, false); TCLAP::SwitchArg clockSwitch("","clock","Measure/print the total time to process image and all plates. Default=off", cmd, false); try { cmd.add( templateRegionArg ); cmd.add( seekToMsArg ); cmd.add( topNArg ); cmd.add( configFileArg ); cmd.add( fileArg ); cmd.add( countryCodeArg ); if (cmd.parse( argc, argv ) == false) { // Error occured while parsing. Exit now. return 1; } filename = fileArg.getValue(); country = countryCodeArg.getValue(); seektoms = seekToMsArg.getValue(); outputJson = jsonSwitch.getValue(); configFile = configFileArg.getValue(); detectRegion = detectRegionSwitch.getValue(); templateRegion = templateRegionArg.getValue(); topn = topNArg.getValue(); measureProcessingTime = clockSwitch.getValue(); } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; return 1; } struct sigaction sigIntHandler; sigIntHandler.sa_handler = sighandler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGHUP, &sigIntHandler, NULL); sigaction(SIGINT, &sigIntHandler, NULL); cv::Mat frame; Alpr alpr(country, configFile); alpr.setTopN(topn); if (detectRegion) alpr.setDetectRegion(detectRegion); if (templateRegion.empty() == false) alpr.setDefaultRegion(templateRegion); if (alpr.isLoaded() == false) { std::cerr << "Error loading OpenALPR" << std::endl; return 1; } if (filename.empty()) { std::string filename; while (std::getline(std::cin, filename)) { if (fileExists(filename.c_str())) { frame = cv::imread( filename ); detectandshow( &alpr, frame, "", outputJson); } else { std::cerr << "Image file not found: " << filename << std::endl; } } } else if (filename == "webcam") { int framenum = 0; cv::VideoCapture cap(0); if (!cap.isOpened()) { std::cout << "Error opening webcam" << std::endl; return 1; } while (cap.read(frame)) { detectandshow(&alpr, frame, "", outputJson); cv::waitKey(1); framenum++; } } else if (startsWith(filename, "http://") || startsWith(filename, "https://")) { int framenum = 0; VideoBuffer videoBuffer; videoBuffer.connect(filename, 5); cv::Mat latestFrame; while (program_active) { int response = videoBuffer.getLatestFrame(&latestFrame); if (response != -1) { detectandshow( &alpr, latestFrame, "", outputJson); } cv::waitKey(10); } videoBuffer.disconnect(); std::cout << "Video processing ended" << std::endl; } else if (hasEndingInsensitive(filename, ".avi") || hasEndingInsensitive(filename, ".mp4") || hasEndingInsensitive(filename, ".webm") || hasEndingInsensitive(filename, ".flv") || hasEndingInsensitive(filename, ".mjpg") || hasEndingInsensitive(filename, ".mjpeg")) { if (fileExists(filename.c_str())) { int framenum = 0; cv::VideoCapture cap=cv::VideoCapture(); cap.open(filename); cap.set(CV_CAP_PROP_POS_MSEC, seektoms); while (cap.read(frame)) { if (SAVE_LAST_VIDEO_STILL) { cv::imwrite(LAST_VIDEO_STILL_LOCATION, frame); } std::cout << "Frame: " << framenum << std::endl; detectandshow( &alpr, frame, "", outputJson); //create a 1ms delay cv::waitKey(1); framenum++; } } else { std::cerr << "Video file not found: " << filename << std::endl; } } else if (hasEndingInsensitive(filename, ".png") || hasEndingInsensitive(filename, ".jpg") || hasEndingInsensitive(filename, ".jpeg") || hasEndingInsensitive(filename, ".gif")) { if (fileExists(filename.c_str())) { frame = cv::imread( filename ); detectandshow( &alpr, frame, "", outputJson); } else { std::cerr << "Image file not found: " << filename << std::endl; } } else if (DirectoryExists(filename.c_str())) { std::vector<std::string> files = getFilesInDir(filename.c_str()); std::sort( files.begin(), files.end(), stringCompare ); for (int i = 0; i< files.size(); i++) { if (hasEndingInsensitive(files[i], ".jpg") || hasEndingInsensitive(files[i], ".png")) { std::string fullpath = filename + "/" + files[i]; std::cout << fullpath << std::endl; frame = cv::imread( fullpath.c_str() ); if (detectandshow( &alpr, frame, "", outputJson)) { //while ((char) cv::waitKey(50) != 'c') { } } else { //cv::waitKey(50); } } } } else { std::cerr << "Unknown file type" << std::endl; return 1; } return 0; } void sighandler(int sig) { program_active = false; //std::cout << "Sig handler caught " << sig << std::endl; } bool detectandshow( Alpr* alpr, cv::Mat frame, std::string region, bool writeJson) { std::vector<uchar> buffer; cv::imencode(".bmp", frame, buffer ); timespec startTime; getTime(&startTime); std::vector<AlprResult> results = alpr->recognize(buffer); if (writeJson) { std::cout << alpr->toJson(results) << std::endl; } else { for (int i = 0; i < results.size(); i++) { std::cout << "plate" << i << ": " << results[i].result_count << " results -- Processing Time = " << results[i].processing_time_ms << "ms." << std::endl; for (int k = 0; k < results[i].topNPlates.size(); k++) { std::cout << " - " << results[i].topNPlates[k].characters << "\t confidence: " << results[i].topNPlates[k].overall_confidence << "\t template_match: " << results[i].topNPlates[k].matches_template << std::endl; } } } timespec endTime; getTime(&endTime); if (measureProcessingTime) std::cout << "Total Time to process image: " << diffclock(startTime, endTime) << "ms." << std::endl; return results.size() > 0; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkTestingHashImageFilter.h" #include "itkTestingMacros.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkCustomColormapFunction.h" #include "itkScalarToRGBColormapImageFilter.h" int itkScalarToRGBColormapImageFilterTest( int argc, char *argv[] ) { if ( argc < 4 ) { std::cout << "Usage: " << argv[0] << " inputImage outputImage colormap [customColormapFile]" << std::endl; std::cout << " Possible colormaps: grey, red, green, blue, copper, jet, hsv, "; std::cout << "spring, summer, autumn, winter, hot, cool, custom" << std::endl; return EXIT_FAILURE; } const unsigned int ImageDimension = 2; typedef unsigned int PixelType; typedef itk::RGBPixel<unsigned char> RGBPixelType; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::Image<float, ImageDimension> RealImageType; typedef itk::Image<RGBPixelType, ImageDimension> RGBImageType; typedef itk::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); reader->Update(); std::string colormapString( argv[3] ); typedef itk::VectorImage< unsigned char, ImageDimension> VectorImageType; typedef itk::ScalarToRGBColormapImageFilter<ImageType, VectorImageType> VectorFilterType; VectorFilterType::Pointer vfilter = VectorFilterType::New(); typedef itk::ScalarToRGBColormapImageFilter<ImageType, RGBImageType> RGBFilterType; RGBFilterType::Pointer rgbfilter = RGBFilterType::New(); rgbfilter->Print( std::cout ); rgbfilter->SetInput( reader->GetOutput() ); vfilter->SetInput( reader->GetOutput() ); if ( colormapString == "red" ) { rgbfilter->SetColormap( RGBFilterType::Red ); vfilter->SetColormap( VectorFilterType::Red ); } else if ( colormapString == "green" ) { rgbfilter->SetColormap( RGBFilterType::Green ); vfilter->SetColormap( VectorFilterType::Green ); } else if ( colormapString == "blue" ) { rgbfilter->SetColormap( RGBFilterType::Blue ); vfilter->SetColormap( VectorFilterType::Blue ); } else if ( colormapString == "grey" ) { rgbfilter->SetColormap( RGBFilterType::Grey ); vfilter->SetColormap( VectorFilterType::Grey ); } else if ( colormapString == "cool" ) { rgbfilter->SetColormap( RGBFilterType::Cool ); vfilter->SetColormap( VectorFilterType::Cool ); } else if ( colormapString == "hot" ) { rgbfilter->SetColormap( RGBFilterType::Hot ); vfilter->SetColormap( VectorFilterType::Hot ); } else if ( colormapString == "spring" ) { rgbfilter->SetColormap( RGBFilterType::Spring ); vfilter->SetColormap( VectorFilterType::Spring ); } else if ( colormapString == "autumn" ) { rgbfilter->SetColormap( RGBFilterType::Autumn ); vfilter->SetColormap( VectorFilterType::Autumn ); } else if ( colormapString == "winter" ) { rgbfilter->SetColormap( RGBFilterType::Winter ); vfilter->SetColormap( VectorFilterType::Winter ); } else if ( colormapString == "copper" ) { rgbfilter->SetColormap( RGBFilterType::Copper ); vfilter->SetColormap( VectorFilterType::Copper ); } else if ( colormapString == "summer" ) { rgbfilter->SetColormap( RGBFilterType::Summer ); vfilter->SetColormap( VectorFilterType::Summer ); } else if ( colormapString == "jet" ) { typedef itk::Function::JetColormapFunction< ImageType::PixelType, RGBImageType::PixelType> ColormapType; ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); typedef itk::Function::JetColormapFunction< ImageType::PixelType, VectorImageType::PixelType> VectorColormapType; VectorColormapType::Pointer vcolormap = VectorColormapType::New(); vfilter->SetColormap( vcolormap ); } else if ( colormapString == "hsv" ) { typedef itk::Function::HSVColormapFunction< ImageType::PixelType, RGBImageType::PixelType> ColormapType; ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); typedef itk::Function::HSVColormapFunction< ImageType::PixelType, VectorImageType::PixelType> VectorColormapType; VectorColormapType::Pointer vcolormap = VectorColormapType::New(); vfilter->SetColormap( vcolormap ); } else if ( colormapString == "overunder" ) { rgbfilter->SetColormap( RGBFilterType::OverUnder ); vfilter->SetColormap( VectorFilterType::OverUnder ); } else if ( colormapString == "custom" ) { typedef itk::Function::CustomColormapFunction< ImageType::PixelType, RGBImageType::PixelType> ColormapType; ColormapType::Pointer colormap = ColormapType::New(); typedef itk::Function::CustomColormapFunction< ImageType::PixelType, VectorImageType::PixelType> VectorColormapType; VectorColormapType::Pointer vcolormap = VectorColormapType::New(); std::ifstream str( argv[4] ); std::string line; float value; ColormapType::ChannelType channel; // Get red values std::getline( str, line ); std::istringstream issr( line ); while ( issr >> value ) { channel.push_back( value ); } colormap->SetRedChannel( channel ); vcolormap->SetRedChannel( channel ); // Get green values std::getline( str, line ); std::istringstream issg( line ); while ( issg >> value ) { channel.push_back( value ); } colormap->SetGreenChannel( channel ); vcolormap->SetGreenChannel( channel ); // Get blue values std::getline( str, line ); std::istringstream issb( line ); while ( issb >> value ) { channel.push_back( value ); } colormap->SetBlueChannel( channel ); vcolormap->SetBlueChannel( channel ); rgbfilter->SetColormap( colormap ); vfilter->SetColormap( vcolormap ); } rgbfilter->GetColormap()->SetMinimumRGBComponentValue( 0 ); rgbfilter->GetColormap()->SetMaximumRGBComponentValue( 255 ); typedef itk::Testing::HashImageFilter<RGBImageType> RGBHasher; RGBHasher::Pointer rgbhasher = RGBHasher::New(); rgbhasher->SetInput( rgbfilter->GetOutput() ); rgbhasher->InPlaceOff(); typedef itk::Testing::HashImageFilter<VectorImageType> VectorHasher; VectorHasher::Pointer vhasher = VectorHasher::New(); vhasher->SetInput( vfilter->GetOutput() ); try { rgbfilter->Update(); vfilter->Update(); rgbhasher->Update(); vhasher->Update(); } catch (...) { return EXIT_FAILURE; } typedef itk::ImageFileWriter<RGBImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput( rgbfilter->GetOutput() ); writer->Update(); // compare the hash values of the Image and RGBPixel Image to ensure // they are the same TEST_EXPECT_EQUAL( rgbhasher->GetHash(), vhasher->GetHash() ); return EXIT_SUCCESS; } <commit_msg>COMP: Colormap tests need platform specific image<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkTestingHashImageFilter.h" #include "itkTestingMacros.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkCustomColormapFunction.h" #include "itkScalarToRGBColormapImageFilter.h" int itkScalarToRGBColormapImageFilterTest( int argc, char *argv[] ) { if ( argc < 4 ) { std::cout << "Usage: " << argv[0] << " inputImage outputImage colormap [customColormapFile]" << std::endl; std::cout << " Possible colormaps: grey, red, green, blue, copper, jet, hsv, "; std::cout << "spring, summer, autumn, winter, hot, cool, custom" << std::endl; return EXIT_FAILURE; } const unsigned int ImageDimension = 2; typedef unsigned int PixelType; typedef itk::RGBPixel<unsigned char> RGBPixelType; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::Image<float, ImageDimension> RealImageType; typedef itk::Image<RGBPixelType, ImageDimension> RGBImageType; typedef itk::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); reader->Update(); std::string colormapString( argv[3] ); typedef itk::VectorImage< unsigned char, ImageDimension> VectorImageType; typedef itk::ScalarToRGBColormapImageFilter<ImageType, VectorImageType> VectorFilterType; VectorFilterType::Pointer vfilter = VectorFilterType::New(); typedef itk::ScalarToRGBColormapImageFilter<ImageType, RGBImageType> RGBFilterType; RGBFilterType::Pointer rgbfilter = RGBFilterType::New(); rgbfilter->Print( std::cout ); rgbfilter->SetInput( reader->GetOutput() ); vfilter->SetInput( reader->GetOutput() ); if ( colormapString == "red" ) { rgbfilter->SetColormap( RGBFilterType::Red ); vfilter->SetColormap( VectorFilterType::Red ); } else if ( colormapString == "green" ) { rgbfilter->SetColormap( RGBFilterType::Green ); vfilter->SetColormap( VectorFilterType::Green ); } else if ( colormapString == "blue" ) { rgbfilter->SetColormap( RGBFilterType::Blue ); vfilter->SetColormap( VectorFilterType::Blue ); } else if ( colormapString == "grey" ) { rgbfilter->SetColormap( RGBFilterType::Grey ); vfilter->SetColormap( VectorFilterType::Grey ); } else if ( colormapString == "cool" ) { rgbfilter->SetColormap( RGBFilterType::Cool ); vfilter->SetColormap( VectorFilterType::Cool ); } else if ( colormapString == "hot" ) { rgbfilter->SetColormap( RGBFilterType::Hot ); vfilter->SetColormap( VectorFilterType::Hot ); } else if ( colormapString == "spring" ) { rgbfilter->SetColormap( RGBFilterType::Spring ); vfilter->SetColormap( VectorFilterType::Spring ); } else if ( colormapString == "autumn" ) { rgbfilter->SetColormap( RGBFilterType::Autumn ); vfilter->SetColormap( VectorFilterType::Autumn ); } else if ( colormapString == "winter" ) { rgbfilter->SetColormap( RGBFilterType::Winter ); vfilter->SetColormap( VectorFilterType::Winter ); } else if ( colormapString == "copper" ) { rgbfilter->SetColormap( RGBFilterType::Copper ); vfilter->SetColormap( VectorFilterType::Copper ); } else if ( colormapString == "summer" ) { rgbfilter->SetColormap( RGBFilterType::Summer ); vfilter->SetColormap( VectorFilterType::Summer ); } else if ( colormapString == "jet" ) { typedef itk::Function::JetColormapFunction< ImageType::PixelType, RGBImageType::PixelType> ColormapType; ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); typedef itk::Function::JetColormapFunction< ImageType::PixelType, VectorImageType::PixelType> VectorColormapType; VectorColormapType::Pointer vcolormap = VectorColormapType::New(); vfilter->SetColormap( vcolormap ); } else if ( colormapString == "hsv" ) { typedef itk::Function::HSVColormapFunction< ImageType::PixelType, RGBImageType::PixelType> ColormapType; ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); typedef itk::Function::HSVColormapFunction< ImageType::PixelType, VectorImageType::PixelType> VectorColormapType; VectorColormapType::Pointer vcolormap = VectorColormapType::New(); vfilter->SetColormap( vcolormap ); } else if ( colormapString == "overunder" ) { rgbfilter->SetColormap( RGBFilterType::OverUnder ); vfilter->SetColormap( VectorFilterType::OverUnder ); } else if ( colormapString == "custom" ) { typedef itk::Function::CustomColormapFunction< ImageType::PixelType, RGBImageType::PixelType> ColormapType; ColormapType::Pointer colormap = ColormapType::New(); typedef itk::Function::CustomColormapFunction< ImageType::PixelType, VectorImageType::PixelType> VectorColormapType; VectorColormapType::Pointer vcolormap = VectorColormapType::New(); std::ifstream str( argv[4] ); std::string line; float value; ColormapType::ChannelType channel; // Get red values std::getline( str, line ); std::istringstream issr( line ); while ( issr >> value ) { channel.push_back( value ); } colormap->SetRedChannel( channel ); vcolormap->SetRedChannel( channel ); // Get green values std::getline( str, line ); std::istringstream issg( line ); while ( issg >> value ) { channel.push_back( value ); } colormap->SetGreenChannel( channel ); vcolormap->SetGreenChannel( channel ); // Get blue values std::getline( str, line ); std::istringstream issb( line ); while ( issb >> value ) { channel.push_back( value ); } colormap->SetBlueChannel( channel ); vcolormap->SetBlueChannel( channel ); rgbfilter->SetColormap( colormap ); vfilter->SetColormap( vcolormap ); } rgbfilter->GetColormap()->SetMinimumRGBComponentValue( 0 ); rgbfilter->GetColormap()->SetMaximumRGBComponentValue( 255 ); typedef itk::Testing::HashImageFilter<RGBImageType> RGBHasher; RGBHasher::Pointer rgbhasher = RGBHasher::New(); rgbhasher->SetInput( rgbfilter->GetOutput() ); rgbhasher->InPlaceOff(); typedef itk::Testing::HashImageFilter<VectorImageType> VectorHasher; VectorHasher::Pointer vhasher = VectorHasher::New(); vhasher->SetInput( vfilter->GetOutput() ); try { rgbfilter->Update(); vfilter->Update(); rgbhasher->Update(); vhasher->Update(); } catch (...) { return EXIT_FAILURE; } typedef itk::ImageFileWriter<RGBImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput( rgbfilter->GetOutput() ); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* This file is part of the MinSG library extension BlueSurfels. Copyright (C) 2012-2013 Claudius Jhn <claudius@uni-paderborn.de> Copyright (C) 2013 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef MINSG_EXT_BLUE_SURFELS #include "E_SurfelGenerator.h" #include <EScript/Basics.h> #include <EScript/StdObjects.h> #include <E_Util/Graphics/E_PixelAccessor.h> #include <E_Rendering/Mesh/E_Mesh.h> #include <Util/Graphics/PixelAccessor.h> namespace E_MinSG{ namespace BlueSurfels{ //! (static) EScript::Type * E_SurfelGenerator::getTypeObject() { // E_SurfelGenerator ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! (static) init members void E_SurfelGenerator::init(EScript::Namespace & lib) { EScript::Type * typeObject = E_SurfelGenerator::getTypeObject(); declareConstant(&lib,getClassName(),typeObject); using namespace MinSG::BlueSurfels; //! [ESMF] SurfelGenerator new MinSG.SurfelGenerator ES_CTOR(typeObject,0,0,new E_SurfelGenerator(thisType)) //! [ESMF] self SurfelGenerator.clearBenchmarkResults() ES_MFUN(typeObject,SurfelGenerator,"clearBenchmarkResults",0,0, (thisObj->clearBenchmarkResults(),thisEObj)) //! [ESMF] ExtObject SurfelGenerator.createSurfels(PixelAccessor,PixelAccessor,PixelAccessor,PixelAccessor) ES_MFUNCTION(typeObject,SurfelGenerator,"createSurfels",4,4,{ const auto surfelResult = thisObj->createSurfels( parameter[0].to<Util::PixelAccessor&>(rt), parameter[1].to<Util::PixelAccessor&>(rt), parameter[2].to<Util::PixelAccessor&>(rt), parameter[3].to<Util::PixelAccessor&>(rt)); static const EScript::StringId meshAttr("mesh"); static const EScript::StringId relativeCoveringAttr("relativeCovering"); EScript::ExtObject * result = new EScript::ExtObject; result->setAttribute(meshAttr, EScript::create(surfelResult.first.get())); result->setAttribute(relativeCoveringAttr, EScript::Number::create(surfelResult.second)); return result; }) //! [ESMF] Map SurfelGenerator.getBenchmarkResults() ES_MFUNCTION(typeObject,const SurfelGenerator,"getBenchmarkResults",0,0,{ EScript::Map* m = new EScript::Map; for(const auto& entry : thisObj->getBenchmarkResults()) // string -> number m->setValue( EScript::create(entry.first), EScript::create(entry.second) ); return m; }) //! [ESMF] Number SurfelGenerator.getReusalRate() ES_MFUN(typeObject,const SurfelGenerator,"getReusalRate",0,0, thisObj->getReusalRate()) //! [ESMF] Number SurfelGenerator.getMaxAbsSurfels() ES_MFUN(typeObject,const SurfelGenerator,"getMaxAbsSurfels",0,0, thisObj->getMaxAbsSurfels()) //! [ESMF] self SurfelGenerator.setMaxAbsSurfels(Number) ES_MFUN(typeObject,SurfelGenerator,"setMaxAbsSurfels",1,1, (thisObj->setMaxAbsSurfels(parameter[0].toUInt()),thisEObj)) //! [ESMF] self SurfelGenerator.setReusalRate(Number) ES_MFUN(typeObject,SurfelGenerator,"setReusalRate",1,1, (thisObj->setReusalRate(parameter[0].toFloat()),thisEObj)) //! [ESMF] self SurfelGenerator.setBenchmarkingEnabled(Bool) ES_MFUN(typeObject,SurfelGenerator,"setBenchmarkingEnabled",1,1, (thisObj->setBenchmarkingEnabled(parameter[0].toBool()),thisEObj)) } } } #endif // MINSG_EXT_BLUE_SURFELS <commit_msg>E_SurfelGenerator: removed old bindings.<commit_after>/* This file is part of the MinSG library extension BlueSurfels. Copyright (C) 2012-2013 Claudius Jhn <claudius@uni-paderborn.de> Copyright (C) 2013 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef MINSG_EXT_BLUE_SURFELS #include "E_SurfelGenerator.h" #include <EScript/Basics.h> #include <EScript/StdObjects.h> #include <E_Util/Graphics/E_PixelAccessor.h> #include <E_Rendering/Mesh/E_Mesh.h> #include <Util/Graphics/PixelAccessor.h> namespace E_MinSG{ namespace BlueSurfels{ //! (static) EScript::Type * E_SurfelGenerator::getTypeObject() { // E_SurfelGenerator ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! (static) init members void E_SurfelGenerator::init(EScript::Namespace & lib) { EScript::Type * typeObject = E_SurfelGenerator::getTypeObject(); declareConstant(&lib,getClassName(),typeObject); using namespace MinSG::BlueSurfels; //! [ESMF] SurfelGenerator new MinSG.SurfelGenerator ES_CTOR(typeObject,0,0,new E_SurfelGenerator(thisType)) //! [ESMF] self SurfelGenerator.clearBenchmarkResults() ES_MFUN(typeObject,SurfelGenerator,"clearBenchmarkResults",0,0, (thisObj->clearBenchmarkResults(),thisEObj)) //! [ESMF] ExtObject SurfelGenerator.createSurfels(PixelAccessor,PixelAccessor,PixelAccessor,PixelAccessor) ES_MFUNCTION(typeObject,SurfelGenerator,"createSurfels",4,4,{ const auto surfelResult = thisObj->createSurfels( parameter[0].to<Util::PixelAccessor&>(rt), parameter[1].to<Util::PixelAccessor&>(rt), parameter[2].to<Util::PixelAccessor&>(rt), parameter[3].to<Util::PixelAccessor&>(rt)); static const EScript::StringId meshAttr("mesh"); static const EScript::StringId relativeCoveringAttr("relativeCovering"); EScript::ExtObject * result = new EScript::ExtObject; result->setAttribute(meshAttr, EScript::create(surfelResult.first.get())); result->setAttribute(relativeCoveringAttr, EScript::Number::create(surfelResult.second)); return result; }) //! [ESMF] Map SurfelGenerator.getBenchmarkResults() ES_MFUNCTION(typeObject,const SurfelGenerator,"getBenchmarkResults",0,0,{ EScript::Map* m = new EScript::Map; for(const auto& entry : thisObj->getBenchmarkResults()) // string -> number m->setValue( EScript::create(entry.first), EScript::create(entry.second) ); return m; }) //! [ESMF] Number SurfelGenerator.getMaxAbsSurfels() ES_MFUN(typeObject,const SurfelGenerator,"getMaxAbsSurfels",0,0, thisObj->getMaxAbsSurfels()) //! [ESMF] self SurfelGenerator.setMaxAbsSurfels(Number) ES_MFUN(typeObject,SurfelGenerator,"setMaxAbsSurfels",1,1, (thisObj->setMaxAbsSurfels(parameter[0].toUInt()),thisEObj)) //! [ESMF] self SurfelGenerator.setBenchmarkingEnabled(Bool) ES_MFUN(typeObject,SurfelGenerator,"setBenchmarkingEnabled",1,1, (thisObj->setBenchmarkingEnabled(parameter[0].toBool()),thisEObj)) } } } #endif // MINSG_EXT_BLUE_SURFELS <|endoftext|>
<commit_before>6570eb76-2e4e-11e5-9284-b827eb9e62be<commit_msg>6576005c-2e4e-11e5-9284-b827eb9e62be<commit_after>6576005c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>75461fcc-2e4d-11e5-9284-b827eb9e62be<commit_msg>754b102c-2e4d-11e5-9284-b827eb9e62be<commit_after>754b102c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* Copyright (c) 2014, Patricio Gonzalez Vivo 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 copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/shm.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <map> #include "app.h" #include "utils.h" #include "gl/shader.h" #include "gl/vbo.h" #include "gl/texture.h" #include "3d/camera.h" #include "types/shapes.h" #include "ui/cursor.h" // GLOBAL VARIABLES //============================================================================ // static bool bPlay = true; // List of FILES to watch and the variable to communicate that between process struct WatchFile { std::string type; std::string path; int lastChange; }; std::vector<WatchFile> files; int* iHasChanged; // SHADER Shader shader; int iFrag = -1; std::string fragSource = ""; int iVert = -1; std::string vertSource = ""; // CAMERA Camera cam; float lat = 180.0; float lon = 0.0; // ASSETS Vbo* vbo; int iGeom = -1; glm::mat4 model_matrix = glm::mat4(1.); std::map<std::string,Texture*> textures; std::string outputFile = ""; // CURSOR Cursor cursor; bool bCursor = false; // Time limit float timeLimit = 0.0f; //================================================================= Functions void watchThread(); void onFileChange(); void renderThread(int argc, char **argv); void setup(); void draw(); void onExit(); // Main program //============================================================================ int main(int argc, char **argv){ // Load files to watch struct stat st; for (uint i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if ( iFrag == -1 && ( haveExt(argument,"frag") || haveExt(argument,"fs") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argv[i] << std::endl; } else { WatchFile file; file.type = "fragment"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iFrag = files.size()-1; } } else if ( iVert == -1 && ( haveExt(argument,"vert") || haveExt(argument,"vs") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "vertex"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iVert = files.size()-1; } } else if ( iGeom == -1 && ( haveExt(argument,"ply") || haveExt(argument,"PLY") || haveExt(argument,"obj") || haveExt(argument,"OBJ") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "geometry"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iGeom = files.size()-1; } } else if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ){ int ierr = stat(argument.c_str(), &st); if (ierr != 0) { // std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "image"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); } } } // If no shader if( iFrag == -1 && iVert == -1 && iGeom == -1) { std::cerr << "Usage: " << argv[0] << " shader.frag [shader.vert] [mesh.(obj/.ply)] [texture.(png/jpg)] [-textureNameA texture.(png/jpg)] [-u] [-x x] [-y y] [-w width] [-h height] [-l/--livecoding] [--square] [-s seconds] [-o screenshot.png]\n"; return EXIT_FAILURE; } // Fork process with a shared variable // int shmId = shmget(IPC_PRIVATE, sizeof(bool), 0666); pid_t pid = fork(); iHasChanged = (int *) shmat(shmId, NULL, 0); switch(pid) { case -1: //error break; case 0: // child { *iHasChanged = -1; watchThread(); } break; default: { // Initialize openGL context initGL(argc,argv); // OpenGL Render Loop renderThread(argc,argv); // Kill the iNotify watcher once you finish kill(pid, SIGKILL); onExit(); } break; } shmctl(shmId, IPC_RMID, NULL); return 0; } // Watching Thread //============================================================================ void watchThread() { struct stat st; while(1){ for(uint i = 0; i < files.size(); i++){ if( *iHasChanged == -1 ){ stat(files[i].path.c_str(), &st); int date = st.st_mtime; if (date != files[i].lastChange ){ *iHasChanged = i; files[i].lastChange = date; } usleep(500000); } } } } void renderThread(int argc, char **argv) { // Prepare viewport glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); // Setup setup(); // Turn on Alpha blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); // Clear the background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); int textureCounter = 0; //Load the the resources (textures) for (uint i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if (argument == "-x" || argument == "-y" || argument == "-w" || argument == "--width" || argument == "-h" || argument == "--height" ) { i++; } else if ( argument == "--square" || argument == "-l" || argument == "--life-coding" ) { } else if ( argument == "-m" ) { bCursor = true; cursor.init(); } else if ( argument == "-s" || argument == "--sec") { i++; argument = std::string(argv[i]); timeLimit = getFloat(argument); std::cout << "Will exit in " << timeLimit << " seconds." << std::endl; } else if ( argument == "-o" ){ i++; argument = std::string(argv[i]); if( haveExt(argument,"png") ){ outputFile = argument; std::cout << "Will save screenshot to " << outputFile << " on exit." << std::endl; } else { std::cout << "At the moment screenshots only support PNG formats" << std::endl; } } else if (argument.find("-") == 0) { std::string parameterPair = argument.substr(argument.find_last_of('-')+1); i++; argument = std::string(argv[i]); Texture* tex = new Texture(); if( tex->load(argument) ){ textures[parameterPair] = tex; std::cout << "Loading " << argument << " as the following uniform: " << std::endl; std::cout << " uniform sampler2D " << parameterPair << "; // loaded"<< std::endl; std::cout << " uniform vec2 " << parameterPair << "Resolution;"<< std::endl; } } else if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ) { Texture* tex = new Texture(); if( tex->load(argument) ){ std::string name = "u_tex"+getString(textureCounter); textures[name] = tex; std::cout << "Loading " << argument << " as the following uniform: " << std::endl; std::cout << " uniform sampler2D " << name << "; // loaded"<< std::endl; std::cout << " uniform vec2 " << name << "Resolution;"<< std::endl; textureCounter++; } } } // Render Loop while (isGL() && bPlay) { // Update updateGL(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw draw(); // Swap the buffers renderGL(); if ( timeLimit > 0.0 && getTime() > timeLimit ) { onKeyPress('s'); bPlay = false; } } } void setup() { glEnable(GL_DEPTH_TEST); glFrontFace(GL_CCW); // Load Geometry // if ( iGeom == -1 ){ vbo = rect(0.0,0.0,1.0,1.0).getVbo(); } else { Mesh model; model.load(files[iGeom].path); vbo = model.getVbo(); glm::vec3 toCentroid = getCentroid(model.getVertices()); // model_matrix = glm::scale(glm::vec3(0.001)); model_matrix = glm::translate(-toCentroid); } // Build shader; // if ( iFrag != -1 ) { fragSource = ""; if(!loadFromPath(files[iFrag].path, &fragSource)) { return; } } else { fragSource = vbo->getVertexLayout()->getDefaultFragShader(); } if ( iVert != -1 ) { vertSource = ""; loadFromPath(files[iVert].path, &vertSource); } else { vertSource = vbo->getVertexLayout()->getDefaultVertShader(); } shader.load(fragSource,vertSource); cam.setViewport(getWindowWidth(),getWindowHeight()); cam.setPosition(glm::vec3(0.0,0.0,-3.)); } void draw(){ // Something change?? if(*iHasChanged != -1) { onFileChange(); *iHasChanged = -1; } shader.use(); shader.setUniform("u_time", getTime()); shader.setUniform("u_mouse", getMouseX(), getMouseY()); shader.setUniform("u_resolution",getWindowWidth(), getWindowHeight()); glm::mat4 mvp = glm::mat4(1.); if (iGeom != -1) { shader.setUniform("u_eye", -cam.getPosition()); shader.setUniform("u_normalMatrix", cam.getNormalMatrix()); shader.setUniform("u_modelMatrix", model_matrix); shader.setUniform("u_viewMatrix", cam.getViewMatrix()); shader.setUniform("u_projectionMatrix", cam.getProjectionMatrix()); mvp = cam.getProjectionViewMatrix() * model_matrix; } shader.setUniform("u_modelViewProjectionMatrix", mvp); unsigned int index = 0; for (std::map<std::string,Texture*>::iterator it = textures.begin(); it!=textures.end(); ++it) { shader.setUniform(it->first,it->second,index); shader.setUniform(it->first+"Resolution",it->second->getWidth(),it->second->getHeight()); index++; } vbo->draw(&shader); if(bCursor){ cursor.draw(); } } // Rendering Thread //============================================================================ void onFileChange(){ std::string type = files[*iHasChanged].type; std::string path = files[*iHasChanged].path; if ( type == "fragment" ){ fragSource = ""; if(loadFromPath(path, &fragSource)){ shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER); shader.load(fragSource,vertSource); } } else if ( type == "vertex" ){ vertSource = ""; if(loadFromPath(path, &vertSource)){ shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER); shader.load(fragSource,vertSource); } } else if ( type == "geometry" ){ // TODO } else if ( type == "image" ){ for (std::map<std::string,Texture*>::iterator it = textures.begin(); it!=textures.end(); ++it) { if ( path == it->second->getFilePath() ){ it->second->load(path); break; } } } } void onKeyPress(int _key) { if( _key == 'q' || _key == 'Q' || _key == 's' || _key == 'S' ){ if (outputFile != "") { unsigned char* pixels = new unsigned char[getWindowWidth()*getWindowHeight()*4]; glReadPixels(0, 0, getWindowWidth(), getWindowHeight(), GL_RGBA, GL_UNSIGNED_BYTE, pixels); Texture::savePixels(outputFile, pixels, getWindowWidth(), getWindowHeight()); } } if ( _key == 'q' || _key == 'Q' || _key == GLFW_KEY_ESCAPE){ bPlay = false; } } void onMouseMove(float _x, float _y) { } void onMouseClick(float _x, float _y, int _button) { } void onMouseDrag(float _x, float _y, int _button) { if (_button == 1){ float dist = glm::length(cam.getPosition()); lat -= getMouseVelX(); lon -= getMouseVelY()*0.5; cam.orbit(lat,lon,dist); cam.lookAt(glm::vec3(0.0)); } else { float dist = glm::length(cam.getPosition()); dist += (-.008f * getMouseVelY()); if(dist > 0.0f){ cam.setPosition( -dist * cam.getZAxis() ); cam.lookAt(glm::vec3(0.0)); } } } void onViewportResize(int _newWidth, int _newHeight) { cam.setViewport(_newWidth,_newHeight); } void onExit() { // clear screen glClear( GL_COLOR_BUFFER_BIT ); // close openGL instance closeGL(); // DELETE RESOURCES for (std::map<std::string,Texture*>::iterator i = textures.begin(); i != textures.end(); ++i) { delete i->second; i->second = NULL; } textures.clear(); delete vbo; } <commit_msg>add RPI macro on esc to close the app.<commit_after>/* Copyright (c) 2014, Patricio Gonzalez Vivo 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 copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/shm.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <map> #include "app.h" #include "utils.h" #include "gl/shader.h" #include "gl/vbo.h" #include "gl/texture.h" #include "3d/camera.h" #include "types/shapes.h" #include "ui/cursor.h" // GLOBAL VARIABLES //============================================================================ // static bool bPlay = true; // List of FILES to watch and the variable to communicate that between process struct WatchFile { std::string type; std::string path; int lastChange; }; std::vector<WatchFile> files; int* iHasChanged; // SHADER Shader shader; int iFrag = -1; std::string fragSource = ""; int iVert = -1; std::string vertSource = ""; // CAMERA Camera cam; float lat = 180.0; float lon = 0.0; // ASSETS Vbo* vbo; int iGeom = -1; glm::mat4 model_matrix = glm::mat4(1.); std::map<std::string,Texture*> textures; std::string outputFile = ""; // CURSOR Cursor cursor; bool bCursor = false; // Time limit float timeLimit = 0.0f; //================================================================= Functions void watchThread(); void onFileChange(); void renderThread(int argc, char **argv); void setup(); void draw(); void onExit(); // Main program //============================================================================ int main(int argc, char **argv){ // Load files to watch struct stat st; for (uint i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if ( iFrag == -1 && ( haveExt(argument,"frag") || haveExt(argument,"fs") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argv[i] << std::endl; } else { WatchFile file; file.type = "fragment"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iFrag = files.size()-1; } } else if ( iVert == -1 && ( haveExt(argument,"vert") || haveExt(argument,"vs") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "vertex"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iVert = files.size()-1; } } else if ( iGeom == -1 && ( haveExt(argument,"ply") || haveExt(argument,"PLY") || haveExt(argument,"obj") || haveExt(argument,"OBJ") ) ) { int ierr = stat(argument.c_str(), &st); if (ierr != 0) { std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "geometry"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); iGeom = files.size()-1; } } else if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ){ int ierr = stat(argument.c_str(), &st); if (ierr != 0) { // std::cerr << "Error watching file " << argument << std::endl; } else { WatchFile file; file.type = "image"; file.path = argument; file.lastChange = st.st_mtime; files.push_back(file); } } } // If no shader if( iFrag == -1 && iVert == -1 && iGeom == -1) { std::cerr << "Usage: " << argv[0] << " shader.frag [shader.vert] [mesh.(obj/.ply)] [texture.(png/jpg)] [-textureNameA texture.(png/jpg)] [-u] [-x x] [-y y] [-w width] [-h height] [-l/--livecoding] [--square] [-s seconds] [-o screenshot.png]\n"; return EXIT_FAILURE; } // Fork process with a shared variable // int shmId = shmget(IPC_PRIVATE, sizeof(bool), 0666); pid_t pid = fork(); iHasChanged = (int *) shmat(shmId, NULL, 0); switch(pid) { case -1: //error break; case 0: // child { *iHasChanged = -1; watchThread(); } break; default: { // Initialize openGL context initGL(argc,argv); // OpenGL Render Loop renderThread(argc,argv); // Kill the iNotify watcher once you finish kill(pid, SIGKILL); onExit(); } break; } shmctl(shmId, IPC_RMID, NULL); return 0; } // Watching Thread //============================================================================ void watchThread() { struct stat st; while(1){ for(uint i = 0; i < files.size(); i++){ if( *iHasChanged == -1 ){ stat(files[i].path.c_str(), &st); int date = st.st_mtime; if (date != files[i].lastChange ){ *iHasChanged = i; files[i].lastChange = date; } usleep(500000); } } } } void renderThread(int argc, char **argv) { // Prepare viewport glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); // Setup setup(); // Turn on Alpha blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); // Clear the background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); int textureCounter = 0; //Load the the resources (textures) for (uint i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if (argument == "-x" || argument == "-y" || argument == "-w" || argument == "--width" || argument == "-h" || argument == "--height" ) { i++; } else if ( argument == "--square" || argument == "-l" || argument == "--life-coding" ) { } else if ( argument == "-m" ) { bCursor = true; cursor.init(); } else if ( argument == "-s" || argument == "--sec") { i++; argument = std::string(argv[i]); timeLimit = getFloat(argument); std::cout << "Will exit in " << timeLimit << " seconds." << std::endl; } else if ( argument == "-o" ){ i++; argument = std::string(argv[i]); if( haveExt(argument,"png") ){ outputFile = argument; std::cout << "Will save screenshot to " << outputFile << " on exit." << std::endl; } else { std::cout << "At the moment screenshots only support PNG formats" << std::endl; } } else if (argument.find("-") == 0) { std::string parameterPair = argument.substr(argument.find_last_of('-')+1); i++; argument = std::string(argv[i]); Texture* tex = new Texture(); if( tex->load(argument) ){ textures[parameterPair] = tex; std::cout << "Loading " << argument << " as the following uniform: " << std::endl; std::cout << " uniform sampler2D " << parameterPair << "; // loaded"<< std::endl; std::cout << " uniform vec2 " << parameterPair << "Resolution;"<< std::endl; } } else if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ) { Texture* tex = new Texture(); if( tex->load(argument) ){ std::string name = "u_tex"+getString(textureCounter); textures[name] = tex; std::cout << "Loading " << argument << " as the following uniform: " << std::endl; std::cout << " uniform sampler2D " << name << "; // loaded"<< std::endl; std::cout << " uniform vec2 " << name << "Resolution;"<< std::endl; textureCounter++; } } } // Render Loop while (isGL() && bPlay) { // Update updateGL(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw draw(); // Swap the buffers renderGL(); if ( timeLimit > 0.0 && getTime() > timeLimit ) { onKeyPress('s'); bPlay = false; } } } void setup() { glEnable(GL_DEPTH_TEST); glFrontFace(GL_CCW); // Load Geometry // if ( iGeom == -1 ){ vbo = rect(0.0,0.0,1.0,1.0).getVbo(); } else { Mesh model; model.load(files[iGeom].path); vbo = model.getVbo(); glm::vec3 toCentroid = getCentroid(model.getVertices()); // model_matrix = glm::scale(glm::vec3(0.001)); model_matrix = glm::translate(-toCentroid); } // Build shader; // if ( iFrag != -1 ) { fragSource = ""; if(!loadFromPath(files[iFrag].path, &fragSource)) { return; } } else { fragSource = vbo->getVertexLayout()->getDefaultFragShader(); } if ( iVert != -1 ) { vertSource = ""; loadFromPath(files[iVert].path, &vertSource); } else { vertSource = vbo->getVertexLayout()->getDefaultVertShader(); } shader.load(fragSource,vertSource); cam.setViewport(getWindowWidth(),getWindowHeight()); cam.setPosition(glm::vec3(0.0,0.0,-3.)); } void draw(){ // Something change?? if(*iHasChanged != -1) { onFileChange(); *iHasChanged = -1; } shader.use(); shader.setUniform("u_time", getTime()); shader.setUniform("u_mouse", getMouseX(), getMouseY()); shader.setUniform("u_resolution",getWindowWidth(), getWindowHeight()); glm::mat4 mvp = glm::mat4(1.); if (iGeom != -1) { shader.setUniform("u_eye", -cam.getPosition()); shader.setUniform("u_normalMatrix", cam.getNormalMatrix()); shader.setUniform("u_modelMatrix", model_matrix); shader.setUniform("u_viewMatrix", cam.getViewMatrix()); shader.setUniform("u_projectionMatrix", cam.getProjectionMatrix()); mvp = cam.getProjectionViewMatrix() * model_matrix; } shader.setUniform("u_modelViewProjectionMatrix", mvp); unsigned int index = 0; for (std::map<std::string,Texture*>::iterator it = textures.begin(); it!=textures.end(); ++it) { shader.setUniform(it->first,it->second,index); shader.setUniform(it->first+"Resolution",it->second->getWidth(),it->second->getHeight()); index++; } vbo->draw(&shader); if(bCursor){ cursor.draw(); } } // Rendering Thread //============================================================================ void onFileChange(){ std::string type = files[*iHasChanged].type; std::string path = files[*iHasChanged].path; if ( type == "fragment" ){ fragSource = ""; if(loadFromPath(path, &fragSource)){ shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER); shader.load(fragSource,vertSource); } } else if ( type == "vertex" ){ vertSource = ""; if(loadFromPath(path, &vertSource)){ shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER); shader.load(fragSource,vertSource); } } else if ( type == "geometry" ){ // TODO } else if ( type == "image" ){ for (std::map<std::string,Texture*>::iterator it = textures.begin(); it!=textures.end(); ++it) { if ( path == it->second->getFilePath() ){ it->second->load(path); break; } } } } void onKeyPress(int _key) { if( _key == 'q' || _key == 'Q' || _key == 's' || _key == 'S' ){ if (outputFile != "") { unsigned char* pixels = new unsigned char[getWindowWidth()*getWindowHeight()*4]; glReadPixels(0, 0, getWindowWidth(), getWindowHeight(), GL_RGBA, GL_UNSIGNED_BYTE, pixels); Texture::savePixels(outputFile, pixels, getWindowWidth(), getWindowHeight()); } } #ifdef PLATFORM_RPI _key = getchar(); if (_key == 27) { bPlay = false; } #else if ( _key == 'q' || _key == 'Q' || _key == GLFW_KEY_ESCAPE){ bPlay = false; } #endif } void onMouseMove(float _x, float _y) { } void onMouseClick(float _x, float _y, int _button) { } void onMouseDrag(float _x, float _y, int _button) { if (_button == 1){ float dist = glm::length(cam.getPosition()); lat -= getMouseVelX(); lon -= getMouseVelY()*0.5; cam.orbit(lat,lon,dist); cam.lookAt(glm::vec3(0.0)); } else { float dist = glm::length(cam.getPosition()); dist += (-.008f * getMouseVelY()); if(dist > 0.0f){ cam.setPosition( -dist * cam.getZAxis() ); cam.lookAt(glm::vec3(0.0)); } } } void onViewportResize(int _newWidth, int _newHeight) { cam.setViewport(_newWidth,_newHeight); } void onExit() { // clear screen glClear( GL_COLOR_BUFFER_BIT ); // close openGL instance closeGL(); // DELETE RESOURCES for (std::map<std::string,Texture*>::iterator i = textures.begin(); i != textures.end(); ++i) { delete i->second; i->second = NULL; } textures.clear(); delete vbo; } <|endoftext|>
<commit_before>1e40c612-2e4f-11e5-9284-b827eb9e62be<commit_msg>1e45b9b0-2e4f-11e5-9284-b827eb9e62be<commit_after>1e45b9b0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b131ad1c-2e4d-11e5-9284-b827eb9e62be<commit_msg>b136a75e-2e4d-11e5-9284-b827eb9e62be<commit_after>b136a75e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include <cstdio> #include <SDL2/SDL.h> #include "draw.hpp" #include "font.hpp" const char * game_name = "Game Of Life On Surface"; const wchar_t tmp_str[] = L"FPS: %.2f; theta: %.2f; phi: %.2f"; int screen_width = 640; int screen_height = 640; float R = 200; int px, py; vec3s delta = { 0, 0, 0 }; vec3s view_direction = {1, M_PI / 4, 0 }; field f(16, 32); bool quit_flag = false; bool button_set = false; SDL_Window * window = NULL; SDL_Renderer * render = NULL; SDL_Event event; font_table_t * ft = NULL; void game_send_error( int code ) { printf( "[error]: %s\n", SDL_GetError() ); exit( code ); } float get_fps( void ) { static float NewCount = 0.0f, LastCount = 0.0f, FpsRate = 0.0f; static int FrameCount = 0; NewCount = (float) SDL_GetTicks(); if ( ( NewCount - LastCount ) > 1000.0f ) { FpsRate = ( FrameCount * 1000.0f ) / ( NewCount - LastCount ); LastCount = NewCount; FrameCount = 0; } FrameCount++; return FpsRate; } void game_event( SDL_Event * event ) { SDL_PollEvent( event ); switch ( event->type ) { case SDL_QUIT: quit_flag = true; break; case SDL_WINDOWEVENT: if ( event->window.event == SDL_WINDOWEVENT_RESIZED ) { screen_width = event->window.data1; screen_height = event->window.data2; } break; case SDL_KEYDOWN: switch ( event->key.keysym.sym ) { case SDLK_ESCAPE: quit_flag = true; break; case SDLK_UP: view_direction.theta -= 0.01f; break; case SDLK_DOWN: view_direction.theta += 0.01f; break; case SDLK_LEFT: view_direction.phi -= 0.01f; break; case SDLK_RIGHT: view_direction.phi += 0.01f; break; default: break; } case SDL_MOUSEMOTION: if ( button_set ) { delta.phi = ( event->button.x - px ) / 100.0f; delta.theta = ( event->button.y - py ) / 100.0f; px = event->button.x; py = event->button.y; view_direction -= delta; } break; case SDL_MOUSEBUTTONDOWN: switch ( event->button.button ) { case SDL_BUTTON_LEFT: if ( button_set == false ) { px = event->button.x; py = event->button.y; } break; default: break; } button_set = true; break; case SDL_MOUSEBUTTONUP: button_set = false; break; default: break; } } void game_loop( void ) { // insert code } void game_render( void ) { const std::size_t BUFFER_SIZE = 128; wchar_t buffer[BUFFER_SIZE]; SDL_RenderClear( render ); set_coloru( COLOR_WHITE ); draw_sphere( view_direction, {screen_width / 2, screen_height / 2}, R, f ); swprintf( buffer, BUFFER_SIZE, tmp_str, get_fps(), view_direction.theta, view_direction.phi ); font_draw( render, ft, buffer, 5, screen_height - 16 ); set_coloru( COLOR_BLACK ); SDL_RenderPresent( render ); } void game_destroy( void ) { font_destroy( ft ); SDL_DestroyRenderer( render ); SDL_DestroyWindow( window ); SDL_Quit(); } void game_init( void ) { SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ); window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE ); if ( window == NULL ) { game_send_error( EXIT_FAILURE ); } render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE ); if ( render == NULL ) { game_send_error( EXIT_FAILURE ); } SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND ); draw_init( render ); font_load( render, &ft, "./data/font.cfg" ); // тестовое заполнение for ( size_t i = 0; i < 100; i++ ) { f.f[rand()%16][rand()%32] = true; } } int main( int argc, char * argv[] ) { game_init(); while ( quit_flag == false ) { game_event( &event ); game_loop(); game_render(); } game_destroy(); return EXIT_SUCCESS; } <commit_msg>[add] help menu, random_fill, game_loop<commit_after>#include <cstdio> #include <ctime> #include <SDL2/SDL.h> #include "draw.hpp" #include "font.hpp" #include "logics.hpp" const char * game_name = "Game Of Life On Surface"; const wchar_t tmp_str[] = L"(%s) FPS: %.2f; theta: %.2f; phi: %.2f; delay %d"; const wchar_t * game_status[] = { (const wchar_t *) "pause", (const wchar_t *) "play" }; const wchar_t help_info[] = L"help menu:\n\n" L" F1 -- this menu\n" L" ESC -- quit\n" L"SPACE -- play/pause\n" L" F -- random fill\n" L" > -- speed up\n" L" < -- speed down\n" L" []{} -- rotate"; int game_counter = 0, MAX_COUNT = 5; int screen_width = 640; int screen_height = 640; const int border_size = 24; const int help_box_width = 200; const int help_box_height = 80; float R = 200; int px, py; vec3s delta = { 0, 0, 0 }; vec3s view_direction = {1, M_PI / 4, 0 }; field f(16, 32); bool quit_flag = false; bool button_set = false; bool game_step = false; bool help_flag = false; SDL_Window * window = NULL; SDL_Renderer * render = NULL; SDL_Event event; font_table_t * ft = NULL; void game_send_error( int code ) { printf( "[error]: %s\n", SDL_GetError() ); exit( code ); } float get_fps( void ) { static float NewCount = 0.0f, LastCount = 0.0f, FpsRate = 0.0f; static int FrameCount = 0; NewCount = (float) SDL_GetTicks(); if ( ( NewCount - LastCount ) > 1000.0f ) { FpsRate = ( FrameCount * 1000.0f ) / ( NewCount - LastCount ); LastCount = NewCount; FrameCount = 0; } FrameCount++; return FpsRate; } void random_fill( void ) { for ( size_t i = 0; i < 128; i++ ) { f.f[rand()%16][rand()%32] = true; } } void game_event( SDL_Event * event ) { SDL_PollEvent( event ); switch ( event->type ) { case SDL_QUIT: quit_flag = true; break; case SDL_WINDOWEVENT: if ( event->window.event == SDL_WINDOWEVENT_RESIZED ) { screen_width = event->window.data1; screen_height = event->window.data2; } break; case SDL_KEYDOWN: switch ( event->key.keysym.sym ) { case SDLK_ESCAPE: quit_flag = true; break; case SDLK_SPACE: game_step = !game_step; break; case SDLK_F1: help_flag = !help_flag; event->key.keysym.sym = 0; break; case SDLK_UP: view_direction.theta -= 0.01f; break; case SDLK_DOWN: view_direction.theta += 0.01f; break; case SDLK_LEFT: view_direction.phi -= 0.01f; break; case SDLK_RIGHT: view_direction.phi += 0.01f; break; case SDLK_PERIOD: if ( MAX_COUNT > 0 ) { MAX_COUNT -= 1; } break; case SDLK_COMMA: MAX_COUNT += 1; break; case SDLK_f: random_fill(); break; default: break; } break; case SDL_MOUSEMOTION: if ( button_set ) { delta.phi = ( event->button.x - px ) / 100.0f; delta.theta = ( event->button.y - py ) / 100.0f; px = event->button.x; py = event->button.y; view_direction -= delta; } break; case SDL_MOUSEBUTTONDOWN: switch ( event->button.button ) { case SDL_BUTTON_LEFT: if ( button_set == false ) { px = event->button.x; py = event->button.y; } break; default: break; } button_set = true; break; case SDL_MOUSEBUTTONUP: button_set = false; break; default: break; } } void game_loop( void ) { if ( game_step && game_counter >= MAX_COUNT ) { nextStep( f ); game_counter = 0; } else { game_counter++; } } void game_render( void ) { const std::size_t BUFFER_SIZE = 128; wchar_t buffer[BUFFER_SIZE]; SDL_RenderClear( render ); set_coloru( COLOR_WHITE ); draw_sphere( view_direction, {screen_width / 2, screen_height / 2}, R, f ); swprintf( buffer, BUFFER_SIZE, tmp_str, game_status[int(game_step)], get_fps(), view_direction.theta, view_direction.phi, MAX_COUNT ); font_draw( render, ft, buffer, 5, screen_height - 16 ); if ( help_flag ) { set_color4u( 0x00, 0x00, 0xff, 0x96 ); draw_rectangle_param( ( screen_width - help_box_width ) / 2, ( screen_height - help_box_height ) / 2, help_box_width, help_box_height, true ); font_draw( render, ft, help_info, ( screen_width - help_box_width ) / 2, ( screen_height - help_box_height ) / 2 + 4 ); } set_coloru( COLOR_BLACK ); SDL_RenderPresent( render ); } void game_destroy( void ) { font_destroy( ft ); SDL_DestroyRenderer( render ); SDL_DestroyWindow( window ); SDL_Quit(); } void game_init( void ) { SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ); window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE ); if ( window == NULL ) { game_send_error( EXIT_FAILURE ); } render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE ); if ( render == NULL ) { game_send_error( EXIT_FAILURE ); } SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND ); draw_init( render ); font_load( render, &ft, "./data/font.cfg" ); srand( time( NULL ) ); random_fill(); } int main( int argc, char * argv[] ) { game_init(); while ( quit_flag == false ) { game_event( &event ); game_loop(); game_render(); } game_destroy(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>dc05cdb0-2e4e-11e5-9284-b827eb9e62be<commit_msg>dc0ace5a-2e4e-11e5-9284-b827eb9e62be<commit_after>dc0ace5a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3b801f34-2e4f-11e5-9284-b827eb9e62be<commit_msg>3b851dc2-2e4f-11e5-9284-b827eb9e62be<commit_after>3b851dc2-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b06e6b50-2e4c-11e5-9284-b827eb9e62be<commit_msg>b0851bd4-2e4c-11e5-9284-b827eb9e62be<commit_after>b0851bd4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>de5951b8-2e4e-11e5-9284-b827eb9e62be<commit_msg>de5e58fc-2e4e-11e5-9284-b827eb9e62be<commit_after>de5e58fc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f48e11fa-2e4c-11e5-9284-b827eb9e62be<commit_msg>f4931b46-2e4c-11e5-9284-b827eb9e62be<commit_after>f4931b46-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ebcac49e-2e4e-11e5-9284-b827eb9e62be<commit_msg>ebcff900-2e4e-11e5-9284-b827eb9e62be<commit_after>ebcff900-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>69c0d3a8-2e4e-11e5-9284-b827eb9e62be<commit_msg>69c5ccf0-2e4e-11e5-9284-b827eb9e62be<commit_after>69c5ccf0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>34296990-2e4d-11e5-9284-b827eb9e62be<commit_msg>342e7bba-2e4d-11e5-9284-b827eb9e62be<commit_after>342e7bba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b244db10-2e4e-11e5-9284-b827eb9e62be<commit_msg>b249ccec-2e4e-11e5-9284-b827eb9e62be<commit_after>b249ccec-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c2277eb6-2e4e-11e5-9284-b827eb9e62be<commit_msg>c22c8136-2e4e-11e5-9284-b827eb9e62be<commit_after>c22c8136-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>97c54b80-2e4e-11e5-9284-b827eb9e62be<commit_msg>97ca9748-2e4e-11e5-9284-b827eb9e62be<commit_after>97ca9748-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e25c57fc-2e4d-11e5-9284-b827eb9e62be<commit_msg>e2616c92-2e4d-11e5-9284-b827eb9e62be<commit_after>e2616c92-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e6f4c67c-2e4e-11e5-9284-b827eb9e62be<commit_msg>e6f9f43a-2e4e-11e5-9284-b827eb9e62be<commit_after>e6f9f43a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include "lexer/lexer.hpp" #include <iostream> #include "utils/debug.hpp" #include "parser/parser.hpp" using namespace lambda; int main(int argc, char const *argv[]) { Parser par; // i'll add value-blocks later. so '{...}' would be <expression> too. using namespace Syntax; // <if> ::= 'if' <expression> '{' <expression> '}' 'else' '{' <expression> '}' par.defExpr(L"if-then-else", defSyntax( (L"if"), expr, (L"{"), expr, (L"}"), (L"else"), (L"{"), expr, (L"}") ), [](Parser::ParseInfo & info ){ return new Expression(); } ); // <when> ::= 'when' <expression> '{' <statement> '}' par.defStmt(L"when", defSyntax( (L"when"), expr, (L"{"), stmt, (L"}") ), [](Parser::ParseInfo & info ){ std::wcerr << L"when alloc\n"; return new Statement(); } ); // like <when>, but condition must be false. // <unless> ::= 'when' <expression> '{' <statement> '}' par.defStmt(L"unless", defSyntax( (L"unless"), expr, (L"{"), stmt, (L"}") ), [](Parser::ParseInfo & info ){ return new Statement(); } ); // new syntax :) // <let> ::= 'let' <identifer> '=' <expression> auto let = par.defStmt(L"let", defSyntax(L"let",id,L"=",expr), [](Parser::ParseInfo&){ std::wcerr << L"let alloc\n"; return new Statement(); } ); // now looks like BNF // <def> ::= 'def' <identifer> '=' <expression> par.defStmt(L"def", defSyntax(L"def",id,L"=",expr), [](Parser::ParseInfo&){ return new Statement(); } ); // <block> ::= '{' <statement>* '}' par.defStmt(L"block",ParseVal::Token(L"{"), [](Parser& par,Lexer& lex){ auto end = lex.TryRecognize(L"}"); while(lex.nextTok().id!=end){ par.expectStatement(); } std::wcerr << L"block alloc\n"; return new Statement(); }); // <for> ::= 'for' <let> ('let' <identifer> '=' <expression>) 'to' <expression> 'do' <statement> par.defStmt(L"for", defSyntax(L"for",let,L"to",expr,L"do",stmt), [](Parser::ParseInfo&){std::wcerr<<L"for alloc\n";return new Statement();}); par.addData(L"for let i = 1 to 10 do { when a b let c = 10 }", L"test"); par.Parse(); par.showRules(); par.showError(); return 0; }<commit_msg>Update main.cpp<commit_after>#include "lexer/lexer.hpp" #include <iostream> #include "utils/debug.hpp" #include "parser/parser.hpp" using namespace lambda; int main(int argc, char const *argv[]) { Parser par; // i'll add value-blocks later. so '{...}' would be <expression> too. using namespace Syntax; // <block> ::= '{' <statement>* '}' auto block = par.defStmt(L"block", defSyntax( (L"{"),infstmts, (L"}") ), [](Parser::ParseInfo&){std::wcerr << L"block alloc\n"; return new Statement();} ); // ParsedInfo.size == Syntax.size. so, ParsedInfo[x].pv == Rule[x], if Rule[x] <: <expression> or <statement> then ParsedInfo[x].expr or ParsedInfo[x].stmt != nullptr. And if you want to extract data from ParsedInfo for your AST node - feel free. // <if> ::= 'if' <expression> '{' <expression> '}' 'else' '{' <expression> '}' par.defExpr(L"if-then-else", defSyntax( (L"if"), expr, (L"{"), expr, (L"}"), (L"else"), (L"{"), expr, (L"}") ), [](Parser::ParseInfo & info ){ return new Expression(); } ); // <when> ::= 'when' <expression> '{' <statement> '}' par.defStmt(L"when", defSyntax( (L"when"), expr,block ), [](Parser::ParseInfo & info ){ std::wcerr << L"when alloc\n"; return new Statement(); } ); // like <when>, but condition must be false. // <unless> ::= 'when' <expression> '{' <statement> '}' par.defStmt(L"unless", defSyntax( (L"unless"), expr,block ), [](Parser::ParseInfo & info ){ std::wcerr << L"unless alloc\n"; return new Statement(); } ); // new syntax :) // <let> ::= 'let' <identifer> '=' <expression> auto let = par.defStmt(L"let", defSyntax( (L"let"),id,(L"="),expr ), [](Parser::ParseInfo&){ std::wcerr << L"let alloc\n"; return new Statement(); } ); // <def> ::= 'def' <identifer> '=' <expression> par.defStmt(L"def", defSyntax( (L"def"),id,(L"="),expr ), [](Parser::ParseInfo&){ return new Statement(); } ); // <for> ::= 'for' <let> ('let' <identifer> '=' <expression>) 'to' <expression> 'do' <statement> par.defStmt(L"for", defSyntax( (L"for"),let,(L"to"),expr,(L"do"),block ), [](Parser::ParseInfo&){std::wcerr<<L"for alloc\n";return new Statement();}); par.addData(L"for let i = 1 to 10 do { when a { unless a {let c = 10.1} } let c = 10 }", L"test"); par.Parse(); par.showRules(); par.showError(); return 0; } <|endoftext|>
<commit_before>27e15868-2e4e-11e5-9284-b827eb9e62be<commit_msg>27e66948-2e4e-11e5-9284-b827eb9e62be<commit_after>27e66948-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include <cv.h> #include <highgui.h> #include <iostream> #include <gflags/gflags.h> #include <cstdlib> #include <list> using namespace std; using namespace cv; DEFINE_bool(display, true, "Display video in window."); DEFINE_bool(quiet, false, "Suppress terminal output."); DEFINE_string(save, "", "Save output to file."); DEFINE_string(axis, "y", "Axis of rotation."); DEFINE_bool(live, false, "Use live feed."); enum axis_enum { AXIS_X, AXIS_Y, AXIS_T }; typedef struct options_struct { enum axis_enum axis; Size size; int frame_count; VideoCapture *video_src; VideoWriter *video_dst; bool live; } options_type; int video_file_filter(options_type *o, char *window_name); int video_live_filter(options_type *o, char *window_name); options_type * create_options(int *argc, char ***argv) { google::ParseCommandLineFlags(argc, argv, true); options_type *o = (options_type *) calloc(1, sizeof(options_type)); if (FLAGS_live && *argc == 1) { o->live = true; } else if (*argc != 2) { o->live = false; cout << "usage: " << *argv[0] << " input-video" << endl; free(o); return NULL; } // open input video if (o->live) { o->video_src = new VideoCapture(0); } else { string input_file = (*argv)[(*argc) - 1]; o->video_src = new VideoCapture(input_file); } if(!o->video_src->isOpened()) return NULL; // get axis if (FLAGS_axis == "x") { o->axis = AXIS_X; } else if (FLAGS_axis == "y") { o->axis = AXIS_Y; } else if (FLAGS_axis == "t") { o->axis = AXIS_T; } else { free(o); return NULL; } // get size of output video int width = o->video_src->get(CV_CAP_PROP_FRAME_WIDTH); int height = o->video_src->get(CV_CAP_PROP_FRAME_HEIGHT); int frame_count = o->video_src->get(CV_CAP_PROP_FRAME_COUNT); if (o->live) { o->size = Size(width, height); o->frame_count = FLAGS_axis == "x" ? height : width; } else if (FLAGS_axis == "x") { o->size = Size(width, frame_count); o->frame_count = height; } else if (FLAGS_axis == "y") { o->size = Size(frame_count, height); o->frame_count = width; } else { free(o); return NULL; } // get output video if (!FLAGS_save.empty()) { o->video_dst = new VideoWriter; int ex = CV_FOURCC('I', 'Y', 'U', 'V'); o->video_dst->open( FLAGS_save, ex, o->video_src->get(CV_CAP_PROP_FPS), o->size); } return o; } int main(int argc, char **argv) { options_type *o = create_options(&argc, &argv); if (o == NULL) return -1; if (FLAGS_display) { namedWindow(argv[0],CV_WINDOW_NORMAL); setWindowProperty(argv[0], CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN); } if (o->live) video_live_filter(o, argv[0]); else video_file_filter(o, argv[0]); delete o->video_src; delete o->video_dst; free(o); return 0; } int video_live_filter(options_type *o, char *window_name) { Mat frame_in; *(o->video_src) >> frame_in; Mat frame_out(o->size, frame_in.type()); list<Mat> frame_list; for (int i = 0; i < o->frame_count; i++) { cout << "Frame " << i+1 << " of " << o->frame_count << endl; if (waitKey(1) == '') return 0; *(o->video_src) >> frame_in; frame_list.push_back(frame_in.clone()); } int j = 0; int d = 1; for (;;) { int i = 0; for (list<Mat>::iterator it = frame_list.begin(); it != frame_list.end(); it++) { switch (o->axis) { case AXIS_X: it->row(j).copyTo(frame_out.row(i)); break; case AXIS_Y: it->col(j).copyTo(frame_out.col(i)); break; default: cout << "UNIMPLEMENTED" << endl; return -1; } i++; } if (j == o->frame_count - 1) { d = -1; } else if (j == 0) { d = 1; } j += d; imshow(window_name, frame_out); if (waitKey(1) == '') return 0; *(o->video_src) >> frame_in; frame_list.push_back(frame_in.clone()); frame_list.pop_front(); } } int video_file_filter(options_type *o, char *window_name) { Mat frame_in; *(o->video_src) >> frame_in; Mat frame_out(o->size, frame_in.type()); int frame_count_src = o->video_src->get(CV_CAP_PROP_FRAME_COUNT); for (int j = 0; j < o->frame_count; j++) { // Output status to console if (!FLAGS_quiet) cout << "Frame " << j+1 << " of " << o->frame_count << "." << endl; // Create a new frame. o->video_src->set(CV_CAP_PROP_POS_FRAMES, 0); for (int i = 0; i < frame_count_src; i++) { *(o->video_src) >> frame_in; switch (o->axis) { case AXIS_X: frame_in.row(j).copyTo(frame_out.row(i)); break; case AXIS_Y: frame_in.col(j).copyTo(frame_out.col(i)); break; default: cout << "UNIMPLEMENTED" << endl; return -1; } } // Display window if (FLAGS_display) { imshow(window_name, frame_out); if (waitKey(1) == '') return 0; } // Save frame to file if (!FLAGS_save.empty()) o->video_dst->write(frame_out); } } <commit_msg>Force ignore of control-c to keep webcam from getting messed up<commit_after>#include <signal.h> #include <cv.h> #include <highgui.h> #include <iostream> #include <gflags/gflags.h> #include <cstdlib> #include <list> using namespace std; using namespace cv; DEFINE_bool(display, true, "Display video in window."); DEFINE_bool(quiet, false, "Suppress terminal output."); DEFINE_string(save, "", "Save output to file."); DEFINE_string(axis, "y", "Axis of rotation."); DEFINE_bool(live, false, "Use live feed."); enum axis_enum { AXIS_X, AXIS_Y, AXIS_T }; typedef struct options_struct { enum axis_enum axis; Size size; int frame_count; VideoCapture *video_src; VideoWriter *video_dst; bool live; } options_type; int video_file_filter(options_type *o, char *window_name); int video_live_filter(options_type *o, char *window_name); options_type * create_options(int *argc, char ***argv) { google::ParseCommandLineFlags(argc, argv, true); options_type *o = (options_type *) calloc(1, sizeof(options_type)); if (FLAGS_live && *argc == 1) { o->live = true; } else if (*argc != 2) { o->live = false; cout << "usage: " << *argv[0] << " input-video" << endl; free(o); return NULL; } // open input video if (o->live) { o->video_src = new VideoCapture(0); } else { string input_file = (*argv)[(*argc) - 1]; o->video_src = new VideoCapture(input_file); } if(!o->video_src->isOpened()) return NULL; // get axis if (FLAGS_axis == "x") { o->axis = AXIS_X; } else if (FLAGS_axis == "y") { o->axis = AXIS_Y; } else if (FLAGS_axis == "t") { o->axis = AXIS_T; } else { free(o); return NULL; } // get size of output video int width = o->video_src->get(CV_CAP_PROP_FRAME_WIDTH); int height = o->video_src->get(CV_CAP_PROP_FRAME_HEIGHT); int frame_count = o->video_src->get(CV_CAP_PROP_FRAME_COUNT); if (o->live) { o->size = Size(width, height); o->frame_count = FLAGS_axis == "x" ? height : width; } else if (FLAGS_axis == "x") { o->size = Size(width, frame_count); o->frame_count = height; } else if (FLAGS_axis == "y") { o->size = Size(frame_count, height); o->frame_count = width; } else { free(o); return NULL; } // get output video if (!FLAGS_save.empty()) { o->video_dst = new VideoWriter; int ex = CV_FOURCC('I', 'Y', 'U', 'V'); o->video_dst->open( FLAGS_save, ex, o->video_src->get(CV_CAP_PROP_FPS), o->size); } return o; } int main(int argc, char **argv) { signal(SIGINT, SIG_IGN); options_type *o = create_options(&argc, &argv); if (o == NULL) return -1; if (FLAGS_display) { namedWindow(argv[0],CV_WINDOW_NORMAL); setWindowProperty(argv[0], CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN); } if (o->live) video_live_filter(o, argv[0]); else video_file_filter(o, argv[0]); delete o->video_src; delete o->video_dst; free(o); return 0; } int video_live_filter(options_type *o, char *window_name) { Mat frame_in; *(o->video_src) >> frame_in; Mat frame_out(o->size, frame_in.type()); list<Mat> frame_list; for (int i = 0; i < o->frame_count; i++) { cout << "Frame " << i+1 << " of " << o->frame_count << endl; if (waitKey(1) == '') return 0; *(o->video_src) >> frame_in; frame_list.push_back(frame_in.clone()); } int j = 0; int d = 1; for (;;) { int i = 0; for (list<Mat>::iterator it = frame_list.begin(); it != frame_list.end(); it++) { switch (o->axis) { case AXIS_X: it->row(j).copyTo(frame_out.row(i)); break; case AXIS_Y: it->col(j).copyTo(frame_out.col(i)); break; default: cout << "UNIMPLEMENTED" << endl; return -1; } i++; } if (j == o->frame_count - 1) { d = -1; } else if (j == 0) { d = 1; } j += d; imshow(window_name, frame_out); if (waitKey(1) == '') return 0; *(o->video_src) >> frame_in; frame_list.push_back(frame_in.clone()); frame_list.pop_front(); } } int video_file_filter(options_type *o, char *window_name) { Mat frame_in; *(o->video_src) >> frame_in; Mat frame_out(o->size, frame_in.type()); int frame_count_src = o->video_src->get(CV_CAP_PROP_FRAME_COUNT); for (int j = 0; j < o->frame_count; j++) { // Output status to console if (!FLAGS_quiet) cout << "Frame " << j+1 << " of " << o->frame_count << "." << endl; // Create a new frame. o->video_src->set(CV_CAP_PROP_POS_FRAMES, 0); for (int i = 0; i < frame_count_src; i++) { *(o->video_src) >> frame_in; switch (o->axis) { case AXIS_X: frame_in.row(j).copyTo(frame_out.row(i)); break; case AXIS_Y: frame_in.col(j).copyTo(frame_out.col(i)); break; default: cout << "UNIMPLEMENTED" << endl; return -1; } } // Display window if (FLAGS_display) { imshow(window_name, frame_out); if (waitKey(1) == '') return 0; } // Save frame to file if (!FLAGS_save.empty()) o->video_dst->write(frame_out); } } <|endoftext|>