text
stringlengths
54
60.6k
<commit_before>/* ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <map> #include <boost/algorithm/string.hpp> #include <gtest/gtest.h> #include <qi/application.hpp> #include <qi/anyobject.hpp> #include <qi/type/dynamicobjectbuilder.hpp> #include <qi/type/detail/traceanalyzer.hpp> qiLogCategory("test"); class TestObject : public ::testing::Test { public: virtual void SetUp() { lastPayload = 0; } void onFire(int pl); int lastPayload; qi::Promise<int> pPayload; }; void TestObject::onFire(int pl) { lastPayload = pl; pPayload.setValue(pl); } TEST_F(TestObject, Simple) { qi::DynamicObjectBuilder ob; ob.advertiseSignal<int>("fire"); qi::AnyObject obj(ob.object()); EXPECT_LE(1U, obj.metaObject().signalMap().size()); qi::SignalLink linkId = obj.connect("fire", qi::bind<void(int)>(&TestObject::onFire, this, _1)); obj.post("fire", 42); EXPECT_TRUE(pPayload.future().wait() != qi::FutureState_Running); EXPECT_EQ(42, lastPayload); pPayload.reset(); obj.post("fire", 51); EXPECT_TRUE(pPayload.future().wait() != qi::FutureState_Running); EXPECT_EQ(51, lastPayload); pPayload.reset(); obj.disconnect(linkId); obj.post("fire", 42); EXPECT_FALSE(pPayload.future().wait(0) != qi::FutureState_Running); EXPECT_EQ(51, lastPayload); } void readString(const std::string&) { } TEST_F(TestObject, ConnectBind) { qi::DynamicObjectBuilder ob; ob.advertiseSignal<int>("fire"); ob.advertiseSignal<int, int>("fire2"); qi::AnyObject obj(ob.object()); qi::SignalLink link = obj.connect("fire", qi::bind<void(int)>(&TestObject::onFire, this, _1)); obj.post("fire", 42); EXPECT_TRUE(pPayload.future().wait() != qi::FutureState_Running); EXPECT_EQ(42, lastPayload); obj.disconnect(link); // The boost bind without _1 gives us a void (void) signature that does not match fire EXPECT_ANY_THROW( obj.connect("fire", boost::bind<void>(&TestObject::onFire, this, 51)).value() ); // Argument type mismatch EXPECT_ANY_THROW( obj.connect("fire", boost::bind<void>(&readString, _1)).value() ); link = obj.connect("fire2", qi::bind<void(int, int)>(&TestObject::onFire, this, _2)); EXPECT_TRUE(link != 0); pPayload.reset(); obj.post("fire2", 40, 41); EXPECT_TRUE(pPayload.future().wait() != qi::FutureState_Running); EXPECT_EQ(41, lastPayload); obj.disconnect(link); } TEST_F(TestObject, EmitMethod) { lastPayload = 0; qi::DynamicObjectBuilder ob; ob.advertiseMethod("fire", qi::bind<void(int)>(&TestObject::onFire, this, _1)); qi::AnyObject obj(ob.object()); pPayload.reset(); obj.post("fire", 23); EXPECT_TRUE(pPayload.future().wait() != qi::FutureState_Running); EXPECT_EQ(23, pPayload.future().value()); } using qi::EventTrace; inline qi::os::timeval ts(qi::int64_t v) { qi::os::timeval res; res.tv_sec = v / 1000000; res.tv_usec = v % 1000000; return res; } std::string sort(const std::string& input) { std::vector<std::string> s; boost::algorithm::split(s, input, boost::algorithm::is_any_of("\n")); if (s.back().empty()) s.pop_back(); std::sort(s.begin(), s.end()); return boost::algorithm::join(s, "\n") + "\n"; } TEST(TestTraceAnalyzer, Basic) { qi::TraceAnalyzer ta; qi::AnyValue noargs; EXPECT_EQ(ta.dumpTraces(), ""); ta.addTrace(qi::EventTrace(10, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 50, 50), 1); ta.addTrace(qi::EventTrace(10, EventTrace::Event_Result, 100, noargs, ts(11), 0, 0, 50, 50), 1); EXPECT_EQ(ta.dumpTraces(), "50 10:1.100\n"); ta.clear(); ta.addTrace(qi::EventTrace(10, EventTrace::Event_Result, 100, noargs, ts(11), 0, 0, 50, 50), 1); ta.addTrace(qi::EventTrace(10, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 50, 50), 1); EXPECT_EQ(ta.dumpTraces(), "50 10:1.100\n"); ta.addTrace(qi::EventTrace(11, EventTrace::Event_Result, 100, noargs, ts(13), 0, 0, 50, 50), 1); ta.addTrace(qi::EventTrace(11, EventTrace::Event_Call, 100, noargs, ts(12), 0, 0, 50, 50), 1); EXPECT_EQ(ta.dumpTraces(), "50 10:1.100 11:1.100\n"); ta.addTrace(qi::EventTrace(12, EventTrace::Event_Result, 100, noargs, ts(11), 0, 0, 51, 51), 1); ta.addTrace(qi::EventTrace(12, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 51, 51), 1); EXPECT_EQ(ta.dumpTraces(), "51 12:1.100\n50 10:1.100 11:1.100\n"); ta.clear(); } TEST(TestTraceAnalyzer, Children) { qi::TraceAnalyzer ta; qi::AnyValue noargs; // try all possible orders std::vector<qi::EventTrace> v; v.push_back(qi::EventTrace(10, EventTrace::Event_Result, 100, noargs, ts(20), 0, 0, 50, 50)); v.push_back(qi::EventTrace(10, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 50, 50)); v.push_back(qi::EventTrace(11, EventTrace::Event_Result, 101, noargs, ts(14), 0, 0, 50, 50)); v.push_back(qi::EventTrace(11, EventTrace::Event_Call, 101, noargs, ts(12), 0, 0, 50, 50)); int permutator[] = { 0,1,2,3}; unsigned count = 0; do { ++count; ta.clear(); for (unsigned i=0; i<4; ++i) ta.addTrace(v[permutator[i]], 1); std::set<qi::TraceAnalyzer::FlowLink> fl; ta.analyze(fl); EXPECT_EQ(ta.dumpTraces(), "50 10:1.100< 11:1.101>\n"); } while (std::next_permutation(permutator, permutator + 4)); EXPECT_EQ(24U, count); } TEST(TestTraceAnalyzer, AsyncChildren) { qi::TraceAnalyzer ta; qi::AnyValue noargs; std::vector<qi::EventTrace> v; v.push_back(qi::EventTrace(10, EventTrace::Event_Result, 100, noargs, ts(20), 0, 0, 50, 50)); v.push_back(qi::EventTrace(10, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 50, 50)); v.push_back(qi::EventTrace(11, EventTrace::Event_Result, 101, noargs, ts(25), 0, 0, 50, 51)); v.push_back(qi::EventTrace(11, EventTrace::Event_Call, 101, noargs, ts(21), 0, 0, 50, 51, ts(12))); int permutator[] = { 0,1,2,3}; unsigned count = 0; do { ++count; ta.clear(); qiLogDebug() << "New iteration"; for (unsigned i=0; i<4; ++i) ta.addTrace(v[permutator[i]], 1); std::set<qi::TraceAnalyzer::FlowLink> fl; ta.analyze(fl); ASSERT_EQ(sort(ta.dumpTraces()), "50 10:1.100{11,}\n51 11:1.101\n"); } while (std::next_permutation(permutator, permutator + 4)); EXPECT_EQ(24U, count); } TEST(TestTraceAnalyzer, BogusChildren) { qi::TraceAnalyzer ta; qi::AnyValue noargs; std::vector<qi::EventTrace> v; v.push_back(qi::EventTrace(10, EventTrace::Event_Result, 100, noargs, ts(20), 0, 0, 50, 50)); v.push_back(qi::EventTrace(10, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 50, 50)); v.push_back(qi::EventTrace(11, EventTrace::Event_Result, 101, noargs, ts(30), 0, 0, 50, 50)); v.push_back(qi::EventTrace(11, EventTrace::Event_Call, 101, noargs, ts(21), 0, 0, 50, 50)); int permutator[] = { 0,1,2,3}; unsigned count = 0; do { ++count; ta.clear(); qiLogDebug() << "New iteration"; for (unsigned i=0; i<4; ++i) ta.addTrace(v[permutator[i]], 1); std::set<qi::TraceAnalyzer::FlowLink> fl; ta.analyze(fl); ASSERT_EQ(sort(ta.dumpTraces()), "50 10:1.100 11:1.101\n"); } while (std::next_permutation(permutator, permutator + 4)); EXPECT_EQ(24U, count); } int main(int argc, char **argv) { qi::Application app(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>test_event: do not use promise.reset()<commit_after>/* ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <map> #include <boost/algorithm/string.hpp> #include <gtest/gtest.h> #include <qi/application.hpp> #include <qi/anyobject.hpp> #include <qi/type/dynamicobjectbuilder.hpp> #include <qi/type/detail/traceanalyzer.hpp> qiLogCategory("test"); class TestObject : public ::testing::Test { public: virtual void SetUp() { lastPayload = 0; } void onFire(int pl); int lastPayload; qi::Promise<int> pPayload; }; void TestObject::onFire(int pl) { lastPayload = pl; pPayload.setValue(pl); } TEST_F(TestObject, Simple) { qi::DynamicObjectBuilder ob; ob.advertiseSignal<int>("fire"); qi::AnyObject obj(ob.object()); EXPECT_LE(1U, obj.metaObject().signalMap().size()); qi::SignalLink linkId = obj.connect("fire", qi::bind<void(int)>(&TestObject::onFire, this, _1)); obj.post("fire", 42); EXPECT_TRUE(pPayload.future().wait() != qi::FutureState_Running); EXPECT_EQ(42, lastPayload); pPayload = qi::Promise<int>(); obj.post("fire", 51); EXPECT_TRUE(pPayload.future().wait() != qi::FutureState_Running); EXPECT_EQ(51, lastPayload); pPayload = qi::Promise<int>(); obj.disconnect(linkId); obj.post("fire", 42); EXPECT_FALSE(pPayload.future().wait(0) != qi::FutureState_Running); EXPECT_EQ(51, lastPayload); } void readString(const std::string&) { } TEST_F(TestObject, ConnectBind) { qi::DynamicObjectBuilder ob; ob.advertiseSignal<int>("fire"); ob.advertiseSignal<int, int>("fire2"); qi::AnyObject obj(ob.object()); qi::SignalLink link = obj.connect("fire", qi::bind<void(int)>(&TestObject::onFire, this, _1)); obj.post("fire", 42); EXPECT_TRUE(pPayload.future().wait() != qi::FutureState_Running); EXPECT_EQ(42, lastPayload); obj.disconnect(link); // The boost bind without _1 gives us a void (void) signature that does not match fire EXPECT_ANY_THROW( obj.connect("fire", boost::bind<void>(&TestObject::onFire, this, 51)).value() ); // Argument type mismatch EXPECT_ANY_THROW( obj.connect("fire", boost::bind<void>(&readString, _1)).value() ); link = obj.connect("fire2", qi::bind<void(int, int)>(&TestObject::onFire, this, _2)); EXPECT_TRUE(link != 0); pPayload = qi::Promise<int>(); obj.post("fire2", 40, 41); EXPECT_TRUE(pPayload.future().wait() != qi::FutureState_Running); EXPECT_EQ(41, lastPayload); obj.disconnect(link); } TEST_F(TestObject, EmitMethod) { lastPayload = 0; qi::DynamicObjectBuilder ob; ob.advertiseMethod("fire", qi::bind<void(int)>(&TestObject::onFire, this, _1)); qi::AnyObject obj(ob.object()); pPayload = qi::Promise<int>(); obj.post("fire", 23); EXPECT_TRUE(pPayload.future().wait() != qi::FutureState_Running); EXPECT_EQ(23, pPayload.future().value()); } using qi::EventTrace; inline qi::os::timeval ts(qi::int64_t v) { qi::os::timeval res; res.tv_sec = v / 1000000; res.tv_usec = v % 1000000; return res; } std::string sort(const std::string& input) { std::vector<std::string> s; boost::algorithm::split(s, input, boost::algorithm::is_any_of("\n")); if (s.back().empty()) s.pop_back(); std::sort(s.begin(), s.end()); return boost::algorithm::join(s, "\n") + "\n"; } TEST(TestTraceAnalyzer, Basic) { qi::TraceAnalyzer ta; qi::AnyValue noargs; EXPECT_EQ(ta.dumpTraces(), ""); ta.addTrace(qi::EventTrace(10, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 50, 50), 1); ta.addTrace(qi::EventTrace(10, EventTrace::Event_Result, 100, noargs, ts(11), 0, 0, 50, 50), 1); EXPECT_EQ(ta.dumpTraces(), "50 10:1.100\n"); ta.clear(); ta.addTrace(qi::EventTrace(10, EventTrace::Event_Result, 100, noargs, ts(11), 0, 0, 50, 50), 1); ta.addTrace(qi::EventTrace(10, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 50, 50), 1); EXPECT_EQ(ta.dumpTraces(), "50 10:1.100\n"); ta.addTrace(qi::EventTrace(11, EventTrace::Event_Result, 100, noargs, ts(13), 0, 0, 50, 50), 1); ta.addTrace(qi::EventTrace(11, EventTrace::Event_Call, 100, noargs, ts(12), 0, 0, 50, 50), 1); EXPECT_EQ(ta.dumpTraces(), "50 10:1.100 11:1.100\n"); ta.addTrace(qi::EventTrace(12, EventTrace::Event_Result, 100, noargs, ts(11), 0, 0, 51, 51), 1); ta.addTrace(qi::EventTrace(12, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 51, 51), 1); EXPECT_EQ(ta.dumpTraces(), "51 12:1.100\n50 10:1.100 11:1.100\n"); ta.clear(); } TEST(TestTraceAnalyzer, Children) { qi::TraceAnalyzer ta; qi::AnyValue noargs; // try all possible orders std::vector<qi::EventTrace> v; v.push_back(qi::EventTrace(10, EventTrace::Event_Result, 100, noargs, ts(20), 0, 0, 50, 50)); v.push_back(qi::EventTrace(10, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 50, 50)); v.push_back(qi::EventTrace(11, EventTrace::Event_Result, 101, noargs, ts(14), 0, 0, 50, 50)); v.push_back(qi::EventTrace(11, EventTrace::Event_Call, 101, noargs, ts(12), 0, 0, 50, 50)); int permutator[] = { 0,1,2,3}; unsigned count = 0; do { ++count; ta.clear(); for (unsigned i=0; i<4; ++i) ta.addTrace(v[permutator[i]], 1); std::set<qi::TraceAnalyzer::FlowLink> fl; ta.analyze(fl); EXPECT_EQ(ta.dumpTraces(), "50 10:1.100< 11:1.101>\n"); } while (std::next_permutation(permutator, permutator + 4)); EXPECT_EQ(24U, count); } TEST(TestTraceAnalyzer, AsyncChildren) { qi::TraceAnalyzer ta; qi::AnyValue noargs; std::vector<qi::EventTrace> v; v.push_back(qi::EventTrace(10, EventTrace::Event_Result, 100, noargs, ts(20), 0, 0, 50, 50)); v.push_back(qi::EventTrace(10, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 50, 50)); v.push_back(qi::EventTrace(11, EventTrace::Event_Result, 101, noargs, ts(25), 0, 0, 50, 51)); v.push_back(qi::EventTrace(11, EventTrace::Event_Call, 101, noargs, ts(21), 0, 0, 50, 51, ts(12))); int permutator[] = { 0,1,2,3}; unsigned count = 0; do { ++count; ta.clear(); qiLogDebug() << "New iteration"; for (unsigned i=0; i<4; ++i) ta.addTrace(v[permutator[i]], 1); std::set<qi::TraceAnalyzer::FlowLink> fl; ta.analyze(fl); ASSERT_EQ(sort(ta.dumpTraces()), "50 10:1.100{11,}\n51 11:1.101\n"); } while (std::next_permutation(permutator, permutator + 4)); EXPECT_EQ(24U, count); } TEST(TestTraceAnalyzer, BogusChildren) { qi::TraceAnalyzer ta; qi::AnyValue noargs; std::vector<qi::EventTrace> v; v.push_back(qi::EventTrace(10, EventTrace::Event_Result, 100, noargs, ts(20), 0, 0, 50, 50)); v.push_back(qi::EventTrace(10, EventTrace::Event_Call, 100, noargs, ts(10), 0, 0, 50, 50)); v.push_back(qi::EventTrace(11, EventTrace::Event_Result, 101, noargs, ts(30), 0, 0, 50, 50)); v.push_back(qi::EventTrace(11, EventTrace::Event_Call, 101, noargs, ts(21), 0, 0, 50, 50)); int permutator[] = { 0,1,2,3}; unsigned count = 0; do { ++count; ta.clear(); qiLogDebug() << "New iteration"; for (unsigned i=0; i<4; ++i) ta.addTrace(v[permutator[i]], 1); std::set<qi::TraceAnalyzer::FlowLink> fl; ta.analyze(fl); ASSERT_EQ(sort(ta.dumpTraces()), "50 10:1.100 11:1.101\n"); } while (std::next_permutation(permutator, permutator + 4)); EXPECT_EQ(24U, count); } int main(int argc, char **argv) { qi::Application app(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "Halide.h" #include <tiramisu/utils.h> #include <cstdlib> #include <iostream> #include "wrapper_test_21.h" #ifdef __cplusplus extern "C" { #endif uint8_t my_external(halide_buffer_t *buf0) { return 0; //buf0->host[0]; } #ifdef __cplusplus } // extern "C" #endif int main(int, char**) { buffer_t reference_buf = allocate_2D_buffer(SIZE0, SIZE1); init_2D_buffer_val(&reference_buf, SIZE0, SIZE1, 1); buffer_t output_buf1 = allocate_2D_buffer(SIZE0, SIZE1); init_2D_buffer_val(&output_buf1, SIZE0, SIZE1, 1); buffer_t output_buf2 = allocate_2D_buffer(SIZE0, SIZE1); init_2D_buffer_val(&output_buf2, SIZE0, SIZE1, 99); Halide::Buffer<uint8_t> halide_output_buf1(output_buf1); Halide::Buffer<uint8_t> halide_output_buf2(output_buf2); // Call the Tiramisu generated code tiramisu_generated_code(halide_output_buf1.raw_buffer(), halide_output_buf2.raw_buffer()); compare_2_2D_arrays("test_"+std::string(TEST_NAME_STR), halide_output_buf1.data(), reference_buf.host, SIZE0, SIZE1); return 0; } <commit_msg>Fix segfault in test_21<commit_after>#include "Halide.h" #include <tiramisu/utils.h> #include <cstdlib> #include <iostream> #include "wrapper_test_21.h" #ifdef __cplusplus extern "C" { #endif uint8_t my_external(halide_buffer_t *buf0) { return buf0->host[0]; } #ifdef __cplusplus } // extern "C" #endif int main(int, char**) { buffer_t reference_buf = allocate_2D_buffer(SIZE0, SIZE1); init_2D_buffer_val(&reference_buf, SIZE0, SIZE1, 1); buffer_t output_buf1 = allocate_2D_buffer(SIZE0, SIZE1); init_2D_buffer_val(&output_buf1, SIZE0, SIZE1, 1); buffer_t output_buf2 = allocate_2D_buffer(SIZE0, SIZE1); init_2D_buffer_val(&output_buf2, SIZE0, SIZE1, 99); Halide::Buffer<uint8_t> halide_output_buf1(output_buf1); Halide::Buffer<uint8_t> halide_output_buf2(output_buf2); // Call the Tiramisu generated code tiramisu_generated_code(halide_output_buf1.raw_buffer(), halide_output_buf2.raw_buffer()); compare_2_2D_arrays("test_"+std::string(TEST_NAME_STR), halide_output_buf1.data(), reference_buf.host, SIZE0, SIZE1); return 0; } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2018 Intel Corporation // // // // 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. // // ======================================================================== // #undef NDEBUG // ospray #include "Instance.h" #include "common/Model.h" // ispc exports #include "Instance_ispc.h" namespace ospray { Instance::Instance() { this->ispcEquivalent = ispc::InstanceGeometry_create(this); } std::string Instance::toString() const { return "ospray::Instance"; } void Instance::finalize(Model *model) { xfm.l.vx = getParam3f("xfm.l.vx",vec3f(1.f,0.f,0.f)); xfm.l.vy = getParam3f("xfm.l.vy",vec3f(0.f,1.f,0.f)); xfm.l.vz = getParam3f("xfm.l.vz",vec3f(0.f,0.f,1.f)); xfm.p = getParam3f("xfm.p",vec3f(0.f,0.f,0.f)); instancedScene = (Model *)getParamObject("model", nullptr); assert(instancedScene); if (!instancedScene->embreeSceneHandle) { instancedScene->commit(); } #if USE_EMBREE3 RTCGeometry embreeGeom = rtcNewGeometry(ispc_embreeDevice,RTC_GEOMETRY_TYPE_INSTANCE); embreeGeomID = rtcAttachGeometry(model->embreeSceneHandle,embreeGeom); rtcReleaseGeometry(embreeGeom); rtcSetGeometryInstancedScene(embreeGeom,instancedScene->embreeSceneHandle); #else embreeGeomID = rtcNewInstance2(model->embreeSceneHandle, instancedScene->embreeSceneHandle); #endif const box3f b = instancedScene->bounds; if (b.empty()) { // for now, let's just issue a warning since not all ospray // geometries do properly set the boudning box yet. as soon as // this gets fixed we will actually switch to reporting an error static WarnOnce warning("creating an instance to a model that does not" " have a valid bounding box. epsilons for" " ray offsets may be wrong"); } const vec3f v000(b.lower.x,b.lower.y,b.lower.z); const vec3f v001(b.upper.x,b.lower.y,b.lower.z); const vec3f v010(b.lower.x,b.upper.y,b.lower.z); const vec3f v011(b.upper.x,b.upper.y,b.lower.z); const vec3f v100(b.lower.x,b.lower.y,b.upper.z); const vec3f v101(b.upper.x,b.lower.y,b.upper.z); const vec3f v110(b.lower.x,b.upper.y,b.upper.z); const vec3f v111(b.upper.x,b.upper.y,b.upper.z); bounds = empty; bounds.extend(xfmPoint(xfm,v000)); bounds.extend(xfmPoint(xfm,v001)); bounds.extend(xfmPoint(xfm,v010)); bounds.extend(xfmPoint(xfm,v011)); bounds.extend(xfmPoint(xfm,v100)); bounds.extend(xfmPoint(xfm,v101)); bounds.extend(xfmPoint(xfm,v110)); bounds.extend(xfmPoint(xfm,v111)); #if USE_EMBREE3 rtcSetGeometryTransform(embreeGeom,0,RTC_FORMAT_FLOAT3X4_COLUMN_MAJOR,&xfm); #else rtcSetTransform2(model->embreeSceneHandle,embreeGeomID, RTC_MATRIX_COLUMN_MAJOR, (const float *)&xfm); #endif AffineSpace3f rcp_xfm = rcp(xfm); areaPDF.resize(instancedScene->geometry.size()); ispc::InstanceGeometry_set(getIE(), (ispc::AffineSpace3f&)xfm, (ispc::AffineSpace3f&)rcp_xfm, instancedScene->getIE(), &areaPDF[0]); for (auto volume : instancedScene->volume) { ospSet3f((OSPObject)volume.ptr, "xfm.l.vx", xfm.l.vx.x, xfm.l.vx.y, xfm.l.vx.z); ospSet3f((OSPObject)volume.ptr, "xfm.l.vy", xfm.l.vy.x, xfm.l.vy.y, xfm.l.vy.z); ospSet3f((OSPObject)volume.ptr, "xfm.l.vz", xfm.l.vz.x, xfm.l.vz.y, xfm.l.vz.z); ospSet3f((OSPObject)volume.ptr, "xfm.p", xfm.p.x, xfm.p.y, xfm.p.z); } } OSP_REGISTER_GEOMETRY(Instance,instance); } // ::ospray <commit_msg>bugfix: now committing instance geom<commit_after>// ======================================================================== // // Copyright 2009-2018 Intel Corporation // // // // 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. // // ======================================================================== // #undef NDEBUG // ospray #include "Instance.h" #include "common/Model.h" // ispc exports #include "Instance_ispc.h" namespace ospray { Instance::Instance() { this->ispcEquivalent = ispc::InstanceGeometry_create(this); } std::string Instance::toString() const { return "ospray::Instance"; } void Instance::finalize(Model *model) { xfm.l.vx = getParam3f("xfm.l.vx",vec3f(1.f,0.f,0.f)); xfm.l.vy = getParam3f("xfm.l.vy",vec3f(0.f,1.f,0.f)); xfm.l.vz = getParam3f("xfm.l.vz",vec3f(0.f,0.f,1.f)); xfm.p = getParam3f("xfm.p",vec3f(0.f,0.f,0.f)); instancedScene = (Model *)getParamObject("model", nullptr); assert(instancedScene); if (!instancedScene->embreeSceneHandle) { instancedScene->commit(); } #if USE_EMBREE3 RTCGeometry embreeGeom = rtcNewGeometry(ispc_embreeDevice,RTC_GEOMETRY_TYPE_INSTANCE); embreeGeomID = rtcAttachGeometry(model->embreeSceneHandle,embreeGeom); rtcSetGeometryInstancedScene(embreeGeom,instancedScene->embreeSceneHandle); #else embreeGeomID = rtcNewInstance2(model->embreeSceneHandle, instancedScene->embreeSceneHandle); #endif const box3f b = instancedScene->bounds; if (b.empty()) { // for now, let's just issue a warning since not all ospray // geometries do properly set the boudning box yet. as soon as // this gets fixed we will actually switch to reporting an error static WarnOnce warning("creating an instance to a model that does not" " have a valid bounding box. epsilons for" " ray offsets may be wrong"); } const vec3f v000(b.lower.x,b.lower.y,b.lower.z); const vec3f v001(b.upper.x,b.lower.y,b.lower.z); const vec3f v010(b.lower.x,b.upper.y,b.lower.z); const vec3f v011(b.upper.x,b.upper.y,b.lower.z); const vec3f v100(b.lower.x,b.lower.y,b.upper.z); const vec3f v101(b.upper.x,b.lower.y,b.upper.z); const vec3f v110(b.lower.x,b.upper.y,b.upper.z); const vec3f v111(b.upper.x,b.upper.y,b.upper.z); bounds = empty; bounds.extend(xfmPoint(xfm,v000)); bounds.extend(xfmPoint(xfm,v001)); bounds.extend(xfmPoint(xfm,v010)); bounds.extend(xfmPoint(xfm,v011)); bounds.extend(xfmPoint(xfm,v100)); bounds.extend(xfmPoint(xfm,v101)); bounds.extend(xfmPoint(xfm,v110)); bounds.extend(xfmPoint(xfm,v111)); #if USE_EMBREE3 rtcSetGeometryTransform(embreeGeom,0,RTC_FORMAT_FLOAT3X4_COLUMN_MAJOR,&xfm); rtcCommitGeometry(embreeGeom); rtcReleaseGeometry(embreeGeom); #else rtcSetTransform2(model->embreeSceneHandle,embreeGeomID, RTC_MATRIX_COLUMN_MAJOR, (const float *)&xfm); #endif AffineSpace3f rcp_xfm = rcp(xfm); areaPDF.resize(instancedScene->geometry.size()); ispc::InstanceGeometry_set(getIE(), (ispc::AffineSpace3f&)xfm, (ispc::AffineSpace3f&)rcp_xfm, instancedScene->getIE(), &areaPDF[0]); for (auto volume : instancedScene->volume) { ospSet3f((OSPObject)volume.ptr, "xfm.l.vx", xfm.l.vx.x, xfm.l.vx.y, xfm.l.vx.z); ospSet3f((OSPObject)volume.ptr, "xfm.l.vy", xfm.l.vy.x, xfm.l.vy.y, xfm.l.vy.z); ospSet3f((OSPObject)volume.ptr, "xfm.l.vz", xfm.l.vz.x, xfm.l.vz.y, xfm.l.vz.z); ospSet3f((OSPObject)volume.ptr, "xfm.p", xfm.p.x, xfm.p.y, xfm.p.z); } } OSP_REGISTER_GEOMETRY(Instance,instance); } // ::ospray <|endoftext|>
<commit_before>#include "thread.h" #include <QtWidgets/QApplication> using namespace qReal; using namespace interpreters::robots; using namespace interpreters::robots::details; Id const startingElementType = Id("RobotsMetamodel", "RobotsDiagram", "InitialNode"); Thread::Thread(GraphicalModelAssistInterface const *graphicalModelApi , gui::MainWindowInterpretersInterface &interpretersInterface , BlocksTable &blocksTable, Id const &initialNode) : mGraphicalModelApi(graphicalModelApi) , mInterpretersInterface(interpretersInterface) , mBlocksTable(blocksTable) , mCurrentBlock(mBlocksTable.block(initialNode)) { } Thread::Thread(GraphicalModelAssistInterface const *graphicalModelApi , gui::MainWindowInterpretersInterface &interpretersInterface , Id const &diagramToInterpret, BlocksTable &blocksTable) : mGraphicalModelApi(graphicalModelApi) , mInterpretersInterface(interpretersInterface) , mBlocksTable(blocksTable) , mCurrentBlock(NULL) , mInitialDiagram(diagramToInterpret) { } Thread::~Thread() { foreach (blocks::Block *block, mStack) { if (block) { mInterpretersInterface.dehighlight(block->id()); } } } void Thread::interpret() { if (mCurrentBlock) { turnOn(mCurrentBlock); } else { stepInto(mInitialDiagram); } } void Thread::nextBlock(blocks::Block * const block) { turnOff(mCurrentBlock); turnOn(block); } void Thread::stepInto(Id const &diagram) { Id const initialNode = findStartingElement(diagram); blocks::Block *block = mBlocksTable.block(initialNode); if (!block) { error(tr("No entry point found, please add Initial Node to a diagram"), diagram); return; } if (mStack.count() >= SettingsManager::value("robotsInterpreterStackSize").toInt()) { error(tr("Stack overflow")); return; } turnOn(block); } void Thread::finishedSteppingInto() { if (mStack.isEmpty()) { emit stopped(); return; } mCurrentBlock = mStack.top(); // Execution must proceed here mCurrentBlock->finishedSteppingInto(); } void Thread::failure() { emit stopped(); } void Thread::error(QString const &message, Id const &source) { mInterpretersInterface.errorReporter()->addError(message, source); failure(); } Id Thread::findStartingElement(Id const &diagram) const { IdList const children = mGraphicalModelApi->graphicalRepoApi().children(diagram); foreach (Id const &child, children) { if (child.type() == startingElementType) { return child; } } return Id(); } void Thread::turnOn(blocks::Block * const block) { mCurrentBlock = block; if (!mCurrentBlock) { finishedSteppingInto(); return; } mInterpretersInterface.highlight(mCurrentBlock->id(), false); connect(mCurrentBlock, SIGNAL(done(blocks::Block * const)), this, SLOT(nextBlock(blocks::Block * const))); connect(mCurrentBlock, SIGNAL(newThread(details::blocks::Block*const)), this, SIGNAL(newThread(details::blocks::Block*const))); connect(mCurrentBlock, SIGNAL(failure()), this, SLOT(failure())); connect(mCurrentBlock, SIGNAL(stepInto(Id const &)), this, SLOT(stepInto(Id const &))); mStack.push(mCurrentBlock); // After QApplication::processEvents() call thread can be destroyed, so we can not access fields, but can access // variables on a stack. Kind of hack, but quite an easy way to not suspend everything if interpreted program // has an infinite loop without timers. blocks::Block *currentBlock = mCurrentBlock; QApplication::processEvents(); currentBlock->interpret(); } void Thread::turnOff(blocks::Block * const block) { // This is a signal not from a current block of this thread. // Other thread shall process it, we will just ignore. if (sender() && sender() != block) { return; } if (sender()) { sender()->disconnect(this); } mStack.pop(); mInterpretersInterface.dehighlight(block->id()); } <commit_msg>grammar<commit_after>#include "thread.h" #include <QtWidgets/QApplication> using namespace qReal; using namespace interpreters::robots; using namespace interpreters::robots::details; Id const startingElementType = Id("RobotsMetamodel", "RobotsDiagram", "InitialNode"); Thread::Thread(GraphicalModelAssistInterface const *graphicalModelApi , gui::MainWindowInterpretersInterface &interpretersInterface , BlocksTable &blocksTable, Id const &initialNode) : mGraphicalModelApi(graphicalModelApi) , mInterpretersInterface(interpretersInterface) , mBlocksTable(blocksTable) , mCurrentBlock(mBlocksTable.block(initialNode)) { } Thread::Thread(GraphicalModelAssistInterface const *graphicalModelApi , gui::MainWindowInterpretersInterface &interpretersInterface , Id const &diagramToInterpret, BlocksTable &blocksTable) : mGraphicalModelApi(graphicalModelApi) , mInterpretersInterface(interpretersInterface) , mBlocksTable(blocksTable) , mCurrentBlock(NULL) , mInitialDiagram(diagramToInterpret) { } Thread::~Thread() { foreach (blocks::Block *block, mStack) { if (block) { mInterpretersInterface.dehighlight(block->id()); } } } void Thread::interpret() { if (mCurrentBlock) { turnOn(mCurrentBlock); } else { stepInto(mInitialDiagram); } } void Thread::nextBlock(blocks::Block * const block) { turnOff(mCurrentBlock); turnOn(block); } void Thread::stepInto(Id const &diagram) { Id const initialNode = findStartingElement(diagram); blocks::Block *block = mBlocksTable.block(initialNode); if (!block) { error(tr("No entry point found, please add Initial Node to a diagram"), diagram); return; } if (mStack.count() >= SettingsManager::value("robotsInterpreterStackSize").toInt()) { error(tr("Stack overflow")); return; } turnOn(block); } void Thread::finishedSteppingInto() { if (mStack.isEmpty()) { emit stopped(); return; } mCurrentBlock = mStack.top(); // Execution must proceed here mCurrentBlock->finishedSteppingInto(); } void Thread::failure() { emit stopped(); } void Thread::error(QString const &message, Id const &source) { mInterpretersInterface.errorReporter()->addError(message, source); failure(); } Id Thread::findStartingElement(Id const &diagram) const { IdList const children = mGraphicalModelApi->graphicalRepoApi().children(diagram); foreach (Id const &child, children) { if (child.type() == startingElementType) { return child; } } return Id(); } void Thread::turnOn(blocks::Block * const block) { mCurrentBlock = block; if (!mCurrentBlock) { finishedSteppingInto(); return; } mInterpretersInterface.highlight(mCurrentBlock->id(), false); connect(mCurrentBlock, SIGNAL(done(blocks::Block * const)), this, SLOT(nextBlock(blocks::Block * const))); connect(mCurrentBlock, SIGNAL(newThread(details::blocks::Block*const)), this, SIGNAL(newThread(details::blocks::Block*const))); connect(mCurrentBlock, SIGNAL(failure()), this, SLOT(failure())); connect(mCurrentBlock, SIGNAL(stepInto(Id const &)), this, SLOT(stepInto(Id const &))); mStack.push(mCurrentBlock); // After QApplication::processEvents() call thread can be destroyed, so we can not access fields, but can access // variables on a stack. Kind of hack, but quite an easy way not to suspend everything if interpreted program // has an infinite loop without timers. blocks::Block *currentBlock = mCurrentBlock; QApplication::processEvents(); currentBlock->interpret(); } void Thread::turnOff(blocks::Block * const block) { // This is a signal not from a current block of this thread. // Other thread shall process it, we will just ignore. if (sender() && sender() != block) { return; } if (sender()) { sender()->disconnect(this); } mStack.pop(); mInterpretersInterface.dehighlight(block->id()); } <|endoftext|>
<commit_before>// Time: ctor: O(n), // query: O(logn) // Space: O(n) /** * Definition of Interval: * classs Interval { * int start, end; * Interval(int start, int end) { * this->start = start; * this->end = end; * } */ // Segment Tree solution. class SegmentTreeSumNode { public: int start, end; long long sum; SegmentTreeSumNode *left, *right; SegmentTreeSumNode(int start, int end, long long sum) { this->start = start; this->end = end; this->sum = sum; this->left = this->right = NULL; } }; class Solution { public: /** *@param A, queries: Given an integer array and an query list *@return: The result list */ vector<long long> intervalSum(vector<int> &A, vector<Interval> &queries) { vector<long long> res; // Build segment tree. SegmentTreeSumNode *root = build(A, 0, A.size() - 1); // Do each query. for (const auto& q : queries) { res.emplace_back(query(root, q.start, q.end)); } return res; } // Build segment tree. SegmentTreeSumNode *build(vector<int> &A, int start, int end) { if (start > end) { return nullptr; } // The root's start and end is given by build method. SegmentTreeSumNode *root = new SegmentTreeSumNode(start, end, 0); // If start equals to end, there will be no children for this node. if (start == end) { root->sum = A[start]; return root; } // Left child: start=A.left, end=(A.left + A.right) / 2. root->left = build(A, start, (start + end) / 2); // Right child: start=(A.left + A.right) / 2 + 1, end=A.right. root->right = build(A, (start + end) / 2 + 1, end); long long left_sum = root->left != nullptr? root->left->sum : 0; long long right_sum = root->right != nullptr? root->right->sum : 0; // Update sum. root->sum = left_sum + right_sum; return root; } // Query sum in given range. long long query(SegmentTreeSumNode *root, int start, int end) { // Out of range. if (root == nullptr || root->start > end || root->end < start) { return 0; } // Current segment is totally within range [start, end] if (root->start >= start && root->end <= end) { return root->sum; } long long left = query(root->left, start, end); long long right = query(root->right, start, end); // Find sum in the children. return left + right; } }; // Time: ctor: O(nlogn), // query: O(logn) // Space: O(n) // Binary Indexed Tree (BIT) solution. class Solution2 { public: /** *@param A, queries: Given an integer array and an query list *@return: The result list */ vector<long long> intervalSum(vector<int> &A, vector<Interval> &queries) { nums_ = A; vector<long long> res; bit_ = vector<long long>(nums_.size() + 1); for (int i = 0; i < nums_.size(); ++i) { add(i, nums_[i]); } for (const auto& q : queries) { res.emplace_back(query(q.start, q.end)); } return res; } private: vector<int> nums_; vector<long long> bit_; long long query(int start, int end) { long long sum = sumRegion_bit(end); if (start > 0) { sum -= sumRegion_bit(start - 1); } return sum; } long long sumRegion_bit(long long i) { ++i; long long sum = 0; for (; i > 0; i -= lower_bit(i)) { sum += bit_[i]; } return sum; } void add(int i, int val) { ++i; for (; i <= nums_.size(); i += lower_bit(i)) { bit_[i] += val; } } int lower_bit(int i) { return i & -i; } }; <commit_msg>Update interval-sum.cpp<commit_after>// Time: ctor: O(n), // query: O(logn) // Space: O(n) /** * Definition of Interval: * classs Interval { * int start, end; * Interval(int start, int end) { * this->start = start; * this->end = end; * } */ // Segment Tree solution. class SegmentTreeSumNode { public: int start, end; long long sum; SegmentTreeSumNode *left, *right; SegmentTreeSumNode(int start, int end, long long sum) { this->start = start; this->end = end; this->sum = sum; this->left = this->right = NULL; } }; class Solution { public: /** *@param A, queries: Given an integer array and an query list *@return: The result list */ vector<long long> intervalSum(vector<int> &A, vector<Interval> &queries) { vector<long long> res; // Build segment tree. SegmentTreeSumNode *root = build(A, 0, A.size() - 1); // Do each query. for (const auto& q : queries) { res.emplace_back(query(root, q.start, q.end)); } return res; } // Build segment tree. SegmentTreeSumNode *build(vector<int> &A, int start, int end) { if (start > end) { return nullptr; } // The root's start and end is given by build method. SegmentTreeSumNode *root = new SegmentTreeSumNode(start, end, 0); // If start equals to end, there will be no children for this node. if (start == end) { root->sum = A[start]; return root; } // Left child: start=A.left, end=(A.left + A.right) / 2. root->left = build(A, start, (start + end) / 2); // Right child: start=(A.left + A.right) / 2 + 1, end=A.right. root->right = build(A, (start + end) / 2 + 1, end); long long left_sum = root->left != nullptr? root->left->sum : 0; long long right_sum = root->right != nullptr? root->right->sum : 0; // Update sum. root->sum = left_sum + right_sum; return root; } // Query sum in given range. long long query(SegmentTreeSumNode *root, int start, int end) { // Out of range. if (root == nullptr || root->start > end || root->end < start) { return 0; } // Current segment is totally within range [start, end] if (root->start >= start && root->end <= end) { return root->sum; } long long left = query(root->left, start, end); long long right = query(root->right, start, end); // Find sum in the children. return left + right; } }; // Time: ctor: O(n), // query: O(logn) // Space: O(n) // Binary Indexed Tree (BIT) solution. class Solution2 { public: /** *@param A, queries: Given an integer array and an query list *@return: The result list */ vector<long long> intervalSum(vector<int> &A, vector<Interval> &queries) { nums_ = A; vector<long long> res; bit_ = vector<long long>(nums_.size() + 1); for (int i = 1; i < bit_.size(); ++i) { bit_[i] = A[i - 1] + bit_[i - 1]; } for (int i = bit_.size() - 1; i >= 1; --i) { int last_i = i - (i & -i); bit_[i] -= bit_[last_i]; } for (const auto& q : queries) { res.emplace_back(query(q.start, q.end)); } return res; } private: vector<int> nums_; vector<long long> bit_; long long query(int start, int end) { long long sum = sumRegion_bit(end); if (start > 0) { sum -= sumRegion_bit(start - 1); } return sum; } long long sumRegion_bit(long long i) { ++i; long long sum = 0; for (; i > 0; i -= lower_bit(i)) { sum += bit_[i]; } return sum; } void add(int i, int val) { ++i; for (; i <= nums_.size(); i += lower_bit(i)) { bit_[i] += val; } } int lower_bit(int i) { return i & -i; } }; <|endoftext|>
<commit_before>#include "Halide.h" using namespace Halide; #include "../png.h" #include <iostream> #include <limits> #include <sys/time.h> double now() { struct timeval tv; gettimeofday(&tv, NULL); static bool first_call = true; static time_t first_sec = 0; if (first_call) { first_call = false; first_sec = tv.tv_sec; } assert(tv.tv_sec >= first_sec); return (tv.tv_sec - first_sec) + (tv.tv_usec / 1000000.0); } int main(int argc, char **argv) { if (argc < 3) { std::cerr << "Usage:\n\t./interpolate in.png out.png\n" << std::endl; return 1; } UniformImage input(Float(32), 3); unsigned int levels = 10; Func downsampled[levels]; Func interpolated[levels]; Uniform< unsigned int > level_widths[levels]; Uniform< unsigned int > level_heights[levels]; Var x,y,c; downsampled[0](x,y) = ( input(x,y,0) * input(x,y,3), input(x,y,1) * input(x,y,3), input(x,y,2) * input(x,y,3), input(x,y,3)); //generate downsample levels: for (unsigned int l = 1; l < levels; ++l) { Func clamped; clamped(x,y,c) = downsampled[l-1](clamp(x,0,level_widths[l-1]-1), clamp(y,0,level_heights[l-1]-1), c); Func downx; downx(x,y,c) = (clamped(x*2-1,y,c) + 2.0f * clamped(x*2,y,c) + clamped(x*2+1,y,c)) / 4.0f; downsampled[l](x,y,c) = (downx(x,y*2-1,c) + 2.0f * downx(x,y*2,c) + downx(x,y*2+1,c)) / 4.0f; } interpolated[levels-1](x,y,c) = downsampled[levels-1](x,y,c); //generate interpolated levels: for (unsigned int l = levels-2; l < levels; --l) { Func upsampledx, upsampled; upsampledx(x,y,c) = 0.5f * (interpolated[l+1](x/2 + (x%2),y,c) + interpolated[l+1](x/2,y,c)); upsampled(x,y,c) = 0.5f * (upsampledx(x, y/2 + (y%2),c) + upsampledx(x,y/2,c)); interpolated[l](x,y,c) = downsampled[l](x,y,c) + (1.0 - downsampled[l](x,y,3)) * upsampled(x,y,c); } Func final; final(x,y) = ( interpolated[0](x,y,0) / interpolated[0](x,y,3), interpolated[0](x,y,1) / interpolated[0](x,y,3), interpolated[0](x,y,2) / interpolated[0](x,y,3), 1.0f/*interpolated[0](x,y,3)*/); std::cout << "Finished function setup." << std::endl; int sched = 3; switch (sched) { case 0: { std::cout << "Flat schedule." << std::endl; //schedule: for (unsigned int l = 0; l < levels; ++l) { downsampled[l].root(); interpolated[l].root(); } final.root(); break; } case 1: { std::cout << "Flat schedule with vectorization." << std::endl; for (unsigned int l = 0; l < levels; ++l) { downsampled[l].root().vectorize(x,4); interpolated[l].root().vectorize(x,4); } final.root(); break; } case 2: { std::cout << "Flat schedule with parallelization + vectorization." << std::endl; for (unsigned int l = 0; l < levels; ++l) { if (l + 2 < levels) { Var yo,yi; downsampled[l].root().split(y,yo,yi,4).parallel(yo).vectorize(x,4); interpolated[l].root().split(y,yo,yi,4).parallel(yo).vectorize(x,4); } else { downsampled[l].root(); interpolated[l].root(); } } final.root(); break; } case 3: { std::cout << "Flat schedule with vectorization sometimes." << std::endl; for (unsigned int l = 0; l < levels; ++l) { if (l + 4 < levels) { Var yo,yi; downsampled[l].root().vectorize(x,4); interpolated[l].root().vectorize(x,4); } else { downsampled[l].root(); interpolated[l].root(); } } final.root(); break; } default: assert(0 && "No schedule with this number."); } final.compileJIT(); std::cout << "Running... " << std::endl; double min = std::numeric_limits< double >::infinity(); const unsigned int Iters = 20; for (unsigned int x = 0; x < Iters; ++x) { Image< float > in_png = load< float >(argv[1]); assert(in_png.channels() == 4); input = in_png; { //set up level sizes: unsigned int width = in_png.width(); unsigned int height = in_png.height(); for (unsigned int l = 0; l < levels; ++l) { level_widths[l] = width; level_heights[l] = height; width = width / 2 + 1; height = height / 2 + 1; } } double before = now(); Image< float > out = final.realize(in_png.width(), in_png.height(), 4); double after = now(); double amt = after - before; std::cout << " " << amt * 1000 << std::endl; if (amt < min) min = amt; if (x + 1 == Iters) { Image< float > out = final.realize(in_png.width(), in_png.height(), 4); save(out, argv[2]); } } std::cout << " took " << min * 1000 << " msec." << std::endl; } <commit_msg>fix Jim's interpolator<commit_after>#include "Halide.h" using namespace Halide; #include "../png.h" #include <iostream> #include <limits> #include <sys/time.h> double now() { struct timeval tv; gettimeofday(&tv, NULL); static bool first_call = true; static time_t first_sec = 0; if (first_call) { first_call = false; first_sec = tv.tv_sec; } assert(tv.tv_sec >= first_sec); return (tv.tv_sec - first_sec) + (tv.tv_usec / 1000000.0); } int main(int argc, char **argv) { if (argc < 3) { std::cerr << "Usage:\n\t./interpolate in.png out.png\n" << std::endl; return 1; } UniformImage input(Float(32), 3); unsigned int levels = 10; Func downsampled[levels]; Func interpolated[levels]; Uniform< unsigned int > level_widths[levels]; Uniform< unsigned int > level_heights[levels]; Var x,y,c; downsampled[0](x,y) = ( input(x,y,0) * input(x,y,3), input(x,y,1) * input(x,y,3), input(x,y,2) * input(x,y,3), input(x,y,3)); //generate downsample levels: for (unsigned int l = 1; l < levels; ++l) { Func clamped; clamped(x,y,c) = downsampled[l-1](clamp(cast<int>(x),cast<int>(0),cast<int>(level_widths[l-1]-1)), clamp(cast<int>(y),cast<int>(0),cast<int>(level_heights[l-1]-1)), c); Func downx; downx(x,y,c) = (clamped(x*2-1,y,c) + 2.0f * clamped(x*2,y,c) + clamped(x*2+1,y,c)) / 4.0f; downsampled[l](x,y,c) = (downx(x,y*2-1,c) + 2.0f * downx(x,y*2,c) + downx(x,y*2+1,c)) / 4.0f; } interpolated[levels-1](x,y,c) = downsampled[levels-1](x,y,c); //generate interpolated levels: for (unsigned int l = levels-2; l < levels; --l) { Func upsampledx, upsampled; upsampledx(x,y,c) = 0.5f * (interpolated[l+1](x/2 + (x%2),y,c) + interpolated[l+1](x/2,y,c)); upsampled(x,y,c) = 0.5f * (upsampledx(x, y/2 + (y%2),c) + upsampledx(x,y/2,c)); interpolated[l](x,y,c) = downsampled[l](x,y,c) + (1.0f - downsampled[l](x,y,3)) * upsampled(x,y,c); } Func final; final(x,y) = ( interpolated[0](x,y,0) / interpolated[0](x,y,3), interpolated[0](x,y,1) / interpolated[0](x,y,3), interpolated[0](x,y,2) / interpolated[0](x,y,3), 1.0f/*interpolated[0](x,y,3)*/); std::cout << "Finished function setup." << std::endl; int sched = 3; switch (sched) { case 0: { std::cout << "Flat schedule." << std::endl; //schedule: for (unsigned int l = 0; l < levels; ++l) { downsampled[l].root(); interpolated[l].root(); } final.root(); break; } case 1: { std::cout << "Flat schedule with vectorization." << std::endl; for (unsigned int l = 0; l < levels; ++l) { downsampled[l].root().vectorize(x,4); interpolated[l].root().vectorize(x,4); } final.root(); break; } case 2: { std::cout << "Flat schedule with parallelization + vectorization." << std::endl; for (unsigned int l = 0; l < levels; ++l) { if (l + 2 < levels) { Var yo,yi; downsampled[l].root().split(y,yo,yi,4).parallel(yo).vectorize(x,4); interpolated[l].root().split(y,yo,yi,4).parallel(yo).vectorize(x,4); } else { downsampled[l].root(); interpolated[l].root(); } } final.root(); break; } case 3: { std::cout << "Flat schedule with vectorization sometimes." << std::endl; for (unsigned int l = 0; l < levels; ++l) { if (l + 4 < levels) { Var yo,yi; downsampled[l].root().vectorize(x,4); interpolated[l].root().vectorize(x,4); } else { downsampled[l].root(); interpolated[l].root(); } } final.root(); break; } default: assert(0 && "No schedule with this number."); } final.compileJIT(); std::cout << "Running... " << std::endl; double min = std::numeric_limits< double >::infinity(); const unsigned int Iters = 20; for (unsigned int x = 0; x < Iters; ++x) { Image< float > in_png = load< float >(argv[1]); assert(in_png.channels() == 4); input = in_png; { //set up level sizes: unsigned int width = in_png.width(); unsigned int height = in_png.height(); for (unsigned int l = 0; l < levels; ++l) { level_widths[l] = width; level_heights[l] = height; width = width / 2 + 1; height = height / 2 + 1; } } double before = now(); Image< float > out = final.realize(in_png.width(), in_png.height(), 4); double after = now(); double amt = after - before; std::cout << " " << amt * 1000 << std::endl; if (amt < min) min = amt; if (x + 1 == Iters) { Image< float > out = final.realize(in_png.width(), in_png.height(), 4); save(out, argv[2]); } } std::cout << " took " << min * 1000 << " msec." << std::endl; } <|endoftext|>
<commit_before>#include "qspiaccessibleinterface.h" #include <qdebug.h> #include <qdbusmessage.h> #include <dbusconnection.h> #include <qaccessible.h> #include "constant_mappings.h" QSpiAccessibleInterface::QSpiAccessibleInterface() { } bool QSpiAccessibleInterface::handleMessage(QAccessibleInterface *interface, int child, const QString &function, const QDBusMessage &message, const QDBusConnection &connection) { if (function == "GetRole") { QVariant v; v.setValue((uint) qSpiRoleMapping[interface->role(child)].spiRole()); QDBusMessage reply = message.createReply(v); connection.send(reply); return true; } else if (function == "GetName") { sendReply(connection, message, interface->text(QAccessible::Name, child)); return true; } else if (function == "GetRoleName") { QVariant v; v.setValue(qSpiRoleMapping[interface->role(child)].name()); QDBusMessage reply = message.createReply(v); connection.send(reply); return true; } else if (function == "GetLocalizedRoleName") { QVariant v; v.setValue(qSpiRoleMapping[interface->role(child)].localizedName()); QDBusMessage reply = message.createReply(v); connection.send(reply); return true; } else if (function == "GetChildCount") { int childCount = child ? 0 : interface->childCount(); sendReply(connection, message, childCount); return true; } else if (function == "GetIndexInParent") { int childIndex = -1; if (child) { childIndex = child; } else { QAccessibleInterface *parent = accessibleParent(interface, child); if (parent) childIndex = parent->indexOfChild(interface); delete parent; } sendReply(connection, message, childIndex); return true; } else if (function == "GetParent") { QAccessibleInterface *parent = accessibleParent(interface, child); if (!parent || parent->role(0) == QAccessible::Application) { QVariant ref; QSpiObjectReference v(connection, QDBusObjectPath(QSPI_OBJECT_PATH_ROOT)); ref.setValue(v); sendReply(connection, message, ref); return true; } return false; // QString path = pathForInterface(parent, 0); // QVariantList v; // v.append(connection.baseService()); // v.append(QVariant::fromValue(QDBusObjectPath(path))); // sendReply(connection, message, v); // if (parent != interface) // delete parent; // return true; } else if (function == "GetChildAtIndex") { QString path; if (child) { path = pathForInterface(interface, child + 1); } else { QAccessibleInterface *childInterface = 0; int childIndex = interface->navigate(QAccessible::Child, child + 1, &childInterface); if (childIndex < 0) return false; path = pathForInterface(childInterface, childIndex); delete childInterface; } QVariant ref; QSpiObjectReference v(connection, QDBusObjectPath(path)); ref.setValue(v); QDBusMessage reply = message.createReply(ref); connection.send(reply); return true; } else if (function == "GetInterfaces") { QStringList ifaces; ifaces << QSPI_INTERFACE_ACCESSIBLE; QVariant v; v.setValue(ifaces); QDBusMessage reply = message.createReply(v); connection.send(reply); return true; } else if (function == "GetDescription") { sendReply(connection, message, interface->text(QAccessible::Description, child)); return true; } else if (function == "GetState") { quint64 spiState = spiStatesFromQState(interface->state(child)); if (interface->table2Interface()) { setSpiStateBit(&spiState, ATSPI_STATE_MANAGES_DESCENDANTS); } QVariant v; QSpiUIntList l = spiStateSetFromSpiStates(spiState); v.setValue(l); QDBusMessage reply = message.createReply(v); connection.send(reply); return true; } else if (function == "GetAttributes") { return true; } else if (function == "GetRelationSet") { return true; } else { qWarning() << "WARNING: QSpiAccessibleInterface::handleMessage does not implement " << function << message.path(); } return false; } void QSpiAccessibleInterface::sendReply(const QDBusConnection &connection, const QDBusMessage &message, const QVariant &argument) { sendReply(connection, message, QDBusVariant(argument)); } void QSpiAccessibleInterface::sendReply(const QDBusConnection &connection, const QDBusMessage &message, const QDBusVariant &argument) { QDBusMessage reply = message.createReply(QVariant::fromValue(argument)); connection.send(reply); // qDebug() << "SIGNATURE " << message.member() << reply.signature() << message.signature(); } QAccessibleInterface *QSpiAccessibleInterface::accessibleParent(QAccessibleInterface *iface, int child) { if (child) return iface; QAccessibleInterface *parent = 0; iface->navigate(QAccessible::Ancestor, 1, &parent); return parent; } QString QSpiAccessibleInterface::pathForObject(QObject *object) { Q_ASSERT(object); return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object)); } QString QSpiAccessibleInterface::pathForInterface(QAccessibleInterface *interface, int childIndex) { QString path; QAccessibleInterface* interfaceWithObject = interface; while(!interfaceWithObject->object()) { QAccessibleInterface* parentInterface; interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface); Q_ASSERT(parentInterface->isValid()); int index = parentInterface->indexOfChild(interfaceWithObject); //Q_ASSERT(index >= 0); // FIXME: This should never happen! if (index < 0) { index = 999; path.prepend("/BROKEN_OBJECT_HIERARCHY"); qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object(); qDebug() << "Original interface: " << interface->object() << index; qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount(); QObject* p = parentInterface->object(); qDebug() << p->children(); QAccessibleInterface* tttt; int id = parentInterface->navigate(QAccessible::Child, 1, &tttt); qDebug() << "Nav child: " << id << tttt->object(); } path.prepend('/' + QString::number(index)); interfaceWithObject = parentInterface; } path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object()))); if (childIndex > 0) { path.append('/' + QString::number(childIndex)); } return path; } <commit_msg>Fix parent path.<commit_after>#include "qspiaccessibleinterface.h" #include <qdebug.h> #include <qdbusmessage.h> #include <dbusconnection.h> #include <qaccessible.h> #include "constant_mappings.h" QSpiAccessibleInterface::QSpiAccessibleInterface() { } bool QSpiAccessibleInterface::handleMessage(QAccessibleInterface *interface, int child, const QString &function, const QDBusMessage &message, const QDBusConnection &connection) { if (function == "GetRole") { QVariant v; v.setValue((uint) qSpiRoleMapping[interface->role(child)].spiRole()); QDBusMessage reply = message.createReply(v); connection.send(reply); return true; } else if (function == "GetName") { sendReply(connection, message, interface->text(QAccessible::Name, child)); return true; } else if (function == "GetRoleName") { QVariant v; v.setValue(qSpiRoleMapping[interface->role(child)].name()); QDBusMessage reply = message.createReply(v); connection.send(reply); return true; } else if (function == "GetLocalizedRoleName") { QVariant v; v.setValue(qSpiRoleMapping[interface->role(child)].localizedName()); QDBusMessage reply = message.createReply(v); connection.send(reply); return true; } else if (function == "GetChildCount") { int childCount = child ? 0 : interface->childCount(); sendReply(connection, message, childCount); return true; } else if (function == "GetIndexInParent") { int childIndex = -1; if (child) { childIndex = child; } else { QAccessibleInterface *parent = accessibleParent(interface, child); if (parent) childIndex = parent->indexOfChild(interface); delete parent; } sendReply(connection, message, childIndex); return true; } else if (function == "GetParent") { QAccessibleInterface *parent = accessibleParent(interface, child); QString path; if (!parent || parent->role(0) == QAccessible::Application) { path = QSPI_OBJECT_PATH_ROOT; } else { path = pathForInterface(parent, 0); } if (parent != interface) delete parent; QVariant ref; QSpiObjectReference v(connection, QDBusObjectPath(path)); ref.setValue(v); sendReply(connection, message, ref); return true; } else if (function == "GetChildAtIndex") { QString path; if (child) { path = pathForInterface(interface, child + 1); } else { QAccessibleInterface *childInterface = 0; int childIndex = interface->navigate(QAccessible::Child, child + 1, &childInterface); if (childIndex < 0) return false; path = pathForInterface(childInterface, childIndex); delete childInterface; } QVariant ref; QSpiObjectReference v(connection, QDBusObjectPath(path)); ref.setValue(v); QDBusMessage reply = message.createReply(ref); connection.send(reply); return true; } else if (function == "GetInterfaces") { QStringList ifaces; ifaces << QSPI_INTERFACE_ACCESSIBLE; QVariant v; v.setValue(ifaces); QDBusMessage reply = message.createReply(v); connection.send(reply); return true; } else if (function == "GetDescription") { sendReply(connection, message, interface->text(QAccessible::Description, child)); return true; } else if (function == "GetState") { quint64 spiState = spiStatesFromQState(interface->state(child)); if (interface->table2Interface()) { setSpiStateBit(&spiState, ATSPI_STATE_MANAGES_DESCENDANTS); } QVariant v; QSpiUIntList l = spiStateSetFromSpiStates(spiState); v.setValue(l); QDBusMessage reply = message.createReply(v); connection.send(reply); return true; } else if (function == "GetAttributes") { return true; } else if (function == "GetRelationSet") { return true; } else { qWarning() << "WARNING: QSpiAccessibleInterface::handleMessage does not implement " << function << message.path(); } return false; } void QSpiAccessibleInterface::sendReply(const QDBusConnection &connection, const QDBusMessage &message, const QVariant &argument) { sendReply(connection, message, QDBusVariant(argument)); } void QSpiAccessibleInterface::sendReply(const QDBusConnection &connection, const QDBusMessage &message, const QDBusVariant &argument) { QDBusMessage reply = message.createReply(QVariant::fromValue(argument)); connection.send(reply); // qDebug() << "SIGNATURE " << message.member() << reply.signature() << message.signature(); } QAccessibleInterface *QSpiAccessibleInterface::accessibleParent(QAccessibleInterface *iface, int child) { if (child) return iface; QAccessibleInterface *parent = 0; iface->navigate(QAccessible::Ancestor, 1, &parent); return parent; } QString QSpiAccessibleInterface::pathForObject(QObject *object) { Q_ASSERT(object); return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object)); } QString QSpiAccessibleInterface::pathForInterface(QAccessibleInterface *interface, int childIndex) { QString path; QAccessibleInterface* interfaceWithObject = interface; while(!interfaceWithObject->object()) { QAccessibleInterface* parentInterface; interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface); Q_ASSERT(parentInterface->isValid()); int index = parentInterface->indexOfChild(interfaceWithObject); //Q_ASSERT(index >= 0); // FIXME: This should never happen! if (index < 0) { index = 999; path.prepend("/BROKEN_OBJECT_HIERARCHY"); qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object(); qDebug() << "Original interface: " << interface->object() << index; qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount(); QObject* p = parentInterface->object(); qDebug() << p->children(); QAccessibleInterface* tttt; int id = parentInterface->navigate(QAccessible::Child, 1, &tttt); qDebug() << "Nav child: " << id << tttt->object(); } path.prepend('/' + QString::number(index)); interfaceWithObject = parentInterface; } path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object()))); if (childIndex > 0) { path.append('/' + QString::number(childIndex)); } return path; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Nagoya University * 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 Autoware 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 "waypoint_loader_core.h" namespace waypoint_maker { // Constructor WaypointLoaderNode::WaypointLoaderNode() : private_nh_("~") { initPubSub(); } // Destructor WaypointLoaderNode::~WaypointLoaderNode() { } void WaypointLoaderNode::initPubSub() { // setup publisher if (disable_decision_maker_) { lane_pub_ = nh_.advertise<autoware_msgs::LaneArray>("/lane_waypoints_array", 10, true); } else { lane_pub_ = nh_.advertise<autoware_msgs::LaneArray>("/based/lane_waypoints_array", 10, true); } config_sub_ = nh_.subscribe("/config/waypoint_loader", 1, &WaypointLoaderNode::configCallback, this); output_cmd_sub_ = nh_.subscribe("/config/waypoint_loader_output", 1, &WaypointLoaderNode::outputCommandCallback, this); } void WaypointLoaderNode::initParameter(const autoware_msgs::ConfigWaypointLoader::ConstPtr& conf) { // parameter settings disable_decision_maker_ = conf->disable_decision_maker; filtering_mode_ = conf->filtering_mode; multi_lane_csv_ = conf->multi_lane_csv; } void WaypointLoaderNode::configCallback(const autoware_msgs::ConfigWaypointLoader::ConstPtr& conf) { filter_.initParameter(conf); initParameter(conf); parseColumns(multi_lane_csv_, &multi_file_path_); autoware_msgs::LaneArray lane_array; createLaneArray(multi_file_path_, &lane_array); lane_pub_.publish(lane_array); output_lane_array_ = lane_array; } void WaypointLoaderNode::outputCommandCallback(const std_msgs::Bool::ConstPtr& output_cmd) { std::vector<std::string> dst_multi_file_path = multi_file_path_; for (auto& el : dst_multi_file_path) el = addFileSuffix(el, "_filtered"); saveLaneArray(dst_multi_file_path, output_lane_array_); } const std::string addFileSuffix(std::string file_path, std::string suffix) { std::string output_file_path, tmp; std::string directory_path, filename, extension; tmp = file_path; const std::string::size_type idx_slash = tmp.find_last_of("/"); if (idx_slash != std::string::npos) tmp.erase(0, idx_slash); const std::string::size_type idx_dot = tmp.find_last_of("."); const std::string::size_type idx_dot_allpath = file_path.find_last_of("."); if (idx_dot != std::string::npos && idx_dot != tmp.size() - 1) file_path.erase(idx_dot_allpath, file_path.size() - 1); file_path += suffix + ".csv"; return file_path; } void WaypointLoaderNode::createLaneArray(const std::vector<std::string>& paths, autoware_msgs::LaneArray* lane_array) { for (const auto& el : paths) { autoware_msgs::lane lane; createLaneWaypoint(el, &lane); if (filtering_mode_) filter_.filterLaneWaypoint(&lane); lane_array->lanes.push_back(lane); } } void WaypointLoaderNode::saveLaneArray(const std::vector<std::string>& paths, const autoware_msgs::LaneArray& lane_array) { unsigned long idx = 0; for (const auto& file_path : paths) { std::ofstream ofs(file_path.c_str()); ofs << "x,y,z,yaw,velocity,change_flag,steering_flag,accel_flag,stop_flag,event_flag" << std::endl; for (const auto& el : lane_array.lanes[idx].waypoints) { ofs << std::fixed << std::setprecision(4) << el.pose.pose.position.x << "," << el.pose.pose.position.y << "," << el.pose.pose.position.z << "," << tf::getYaw(el.pose.pose.orientation) << "," << mps2kmph(el.twist.twist.linear.x) << "," << (int)el.change_flag << "," << (int)el.wpstate.steering_state << "," << (int)el.wpstate.accel_state << "," << (int)el.wpstate.stopline_state << "," << (int)el.wpstate.event_state << std::endl; } idx++; } } void WaypointLoaderNode::createLaneWaypoint(const std::string& file_path, autoware_msgs::lane* lane) { if (!verifyFileConsistency(file_path.c_str())) { ROS_ERROR("lane data is something wrong..."); return; } ROS_INFO("lane data is valid. publishing..."); FileFormat format = checkFileFormat(file_path.c_str()); std::vector<autoware_msgs::waypoint> wps; if (format == FileFormat::ver1) loadWaypointsForVer1(file_path.c_str(), &wps); else if (format == FileFormat::ver2) loadWaypointsForVer2(file_path.c_str(), &wps); else loadWaypointsForVer3(file_path.c_str(), &wps); lane->header.frame_id = "/map"; lane->header.stamp = ros::Time(0); lane->waypoints = wps; } void WaypointLoaderNode::loadWaypointsForVer1(const char* filename, std::vector<autoware_msgs::waypoint>* wps) { std::ifstream ifs(filename); if (!ifs) return; std::string line; std::getline(ifs, line); // Remove first line while (std::getline(ifs, line)) { autoware_msgs::waypoint wp; parseWaypointForVer1(line, &wp); wps->push_back(wp); } size_t last = wps->size() - 1; for (size_t i = 0; i < wps->size(); ++i) { if (i != last) { double yaw = atan2(wps->at(i + 1).pose.pose.position.y - wps->at(i).pose.pose.position.y, wps->at(i + 1).pose.pose.position.x - wps->at(i).pose.pose.position.x); wps->at(i).pose.pose.orientation = tf::createQuaternionMsgFromYaw(yaw); } else { wps->at(i).pose.pose.orientation = wps->at(i - 1).pose.pose.orientation; } } } void WaypointLoaderNode::parseWaypointForVer1(const std::string& line, autoware_msgs::waypoint* wp) { std::vector<std::string> columns; parseColumns(line, &columns); wp->pose.pose.position.x = std::stod(columns[0]); wp->pose.pose.position.y = std::stod(columns[1]); wp->pose.pose.position.z = std::stod(columns[2]); wp->twist.twist.linear.x = kmph2mps(std::stod(columns[3])); } void WaypointLoaderNode::loadWaypointsForVer2(const char* filename, std::vector<autoware_msgs::waypoint>* wps) { std::ifstream ifs(filename); if (!ifs) return; std::string line; std::getline(ifs, line); // Remove first line while (std::getline(ifs, line)) { autoware_msgs::waypoint wp; parseWaypointForVer2(line, &wp); wps->push_back(wp); } } void WaypointLoaderNode::parseWaypointForVer2(const std::string& line, autoware_msgs::waypoint* wp) { std::vector<std::string> columns; parseColumns(line, &columns); wp->pose.pose.position.x = std::stod(columns[0]); wp->pose.pose.position.y = std::stod(columns[1]); wp->pose.pose.position.z = std::stod(columns[2]); wp->pose.pose.orientation = tf::createQuaternionMsgFromYaw(std::stod(columns[3])); wp->twist.twist.linear.x = kmph2mps(std::stod(columns[4])); } void WaypointLoaderNode::loadWaypointsForVer3(const char* filename, std::vector<autoware_msgs::waypoint>* wps) { std::ifstream ifs(filename); if (!ifs) return; std::string line; std::getline(ifs, line); // get first line std::vector<std::string> contents; parseColumns(line, &contents); // std::getline(ifs, line); // remove second line while (std::getline(ifs, line)) { autoware_msgs::waypoint wp; parseWaypointForVer3(line, contents, &wp); wps->push_back(wp); } } void WaypointLoaderNode::parseWaypointForVer3(const std::string& line, const std::vector<std::string>& contents, autoware_msgs::waypoint* wp) { std::vector<std::string> columns; parseColumns(line, &columns); std::unordered_map<std::string, std::string> map; for (size_t i = 0; i < contents.size(); i++) { map[contents.at(i)] = columns.at(i); } wp->pose.pose.position.x = std::stod(map["x"]); wp->pose.pose.position.y = std::stod(map["y"]); wp->pose.pose.position.z = std::stod(map["z"]); wp->pose.pose.orientation = tf::createQuaternionMsgFromYaw(std::stod(map["yaw"])); wp->twist.twist.linear.x = kmph2mps(std::stod(map["velocity"])); wp->change_flag = std::stoi(map["change_flag"]); wp->wpstate.steering_state = (map.find("steering_flag") != map.end()) ? std::stoi(map["steering_flag"]) : 0; wp->wpstate.accel_state = (map.find("accel_flag") != map.end()) ? std::stoi(map["accel_flag"]) : 0; wp->wpstate.stopline_state = (map.find("stop_flag") != map.end()) ? std::stoi(map["stop_flag"]) : 0; wp->wpstate.event_state = (map.find("event_flag") != map.end()) ? std::stoi(map["event_flag"]) : 0; } FileFormat WaypointLoaderNode::checkFileFormat(const char* filename) { std::ifstream ifs(filename); if (!ifs) { return FileFormat::unknown; } // get first line std::string line; std::getline(ifs, line); // parse first line std::vector<std::string> parsed_columns; parseColumns(line, &parsed_columns); // check if first element in the first column does not include digit if (!std::any_of(parsed_columns.at(0).cbegin(), parsed_columns.at(0).cend(), isdigit)) { return FileFormat::ver3; } // if element consists only digit int num_of_columns = countColumns(line); ROS_INFO("columns size: %d", num_of_columns); return (num_of_columns == 3 ? FileFormat::ver1 // if data consists "x y z (velocity)" : num_of_columns == 4 ? FileFormat::ver2 // if data consists "x y z yaw (velocity) : FileFormat::unknown); } bool WaypointLoaderNode::verifyFileConsistency(const char* filename) { ROS_INFO("verify..."); std::ifstream ifs(filename); if (!ifs) return false; FileFormat format = checkFileFormat(filename); ROS_INFO("format: %d", static_cast<FileFormat>(format)); if (format == FileFormat::unknown) { ROS_ERROR("unknown file format"); return false; } std::string line; std::getline(ifs, line); // remove first line size_t ncol = format == FileFormat::ver1 ? 4 // x,y,z,velocity : format == FileFormat::ver2 ? 5 // x,y,z,yaw,velocity : countColumns(line); while (std::getline(ifs, line)) // search from second line { if (countColumns(line) != ncol) return false; } return true; } void parseColumns(const std::string& line, std::vector<std::string>* columns) { std::istringstream ss(line); std::string column; while (std::getline(ss, column, ',')) { while (1) { auto res = std::find(column.begin(), column.end(), ' '); if (res == column.end()) break; column.erase(res); } if (!column.empty()) columns->push_back(column); } } size_t countColumns(const std::string& line) { std::istringstream ss(line); size_t ncol = 0; std::string column; while (std::getline(ss, column, ',')) { ++ncol; } return ncol; } } // waypoint_maker <commit_msg>Fix bug, increasing path size for each loop<commit_after>/* * Copyright (c) 2015, Nagoya University * 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 Autoware 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 "waypoint_loader_core.h" namespace waypoint_maker { // Constructor WaypointLoaderNode::WaypointLoaderNode() : private_nh_("~") { initPubSub(); } // Destructor WaypointLoaderNode::~WaypointLoaderNode() { } void WaypointLoaderNode::initPubSub() { // setup publisher if (disable_decision_maker_) { lane_pub_ = nh_.advertise<autoware_msgs::LaneArray>("/lane_waypoints_array", 10, true); } else { lane_pub_ = nh_.advertise<autoware_msgs::LaneArray>("/based/lane_waypoints_array", 10, true); } config_sub_ = nh_.subscribe("/config/waypoint_loader", 1, &WaypointLoaderNode::configCallback, this); output_cmd_sub_ = nh_.subscribe("/config/waypoint_loader_output", 1, &WaypointLoaderNode::outputCommandCallback, this); } void WaypointLoaderNode::initParameter(const autoware_msgs::ConfigWaypointLoader::ConstPtr& conf) { // parameter settings disable_decision_maker_ = conf->disable_decision_maker; filtering_mode_ = conf->filtering_mode; multi_lane_csv_ = conf->multi_lane_csv; } void WaypointLoaderNode::configCallback(const autoware_msgs::ConfigWaypointLoader::ConstPtr& conf) { initParameter(conf); filter_.initParameter(conf); multi_file_path_.clear(); parseColumns(multi_lane_csv_, &multi_file_path_); autoware_msgs::LaneArray lane_array; createLaneArray(multi_file_path_, &lane_array); lane_pub_.publish(lane_array); output_lane_array_ = lane_array; } void WaypointLoaderNode::outputCommandCallback(const std_msgs::Bool::ConstPtr& output_cmd) { std::vector<std::string> dst_multi_file_path = multi_file_path_; for (auto& el : dst_multi_file_path) el = addFileSuffix(el, "_filtered"); saveLaneArray(dst_multi_file_path, output_lane_array_); } const std::string addFileSuffix(std::string file_path, std::string suffix) { std::string output_file_path, tmp; std::string directory_path, filename, extension; tmp = file_path; const std::string::size_type idx_slash = tmp.find_last_of("/"); if (idx_slash != std::string::npos) tmp.erase(0, idx_slash); const std::string::size_type idx_dot = tmp.find_last_of("."); const std::string::size_type idx_dot_allpath = file_path.find_last_of("."); if (idx_dot != std::string::npos && idx_dot != tmp.size() - 1) file_path.erase(idx_dot_allpath, file_path.size() - 1); file_path += suffix + ".csv"; return file_path; } void WaypointLoaderNode::createLaneArray(const std::vector<std::string>& paths, autoware_msgs::LaneArray* lane_array) { for (const auto& el : paths) { autoware_msgs::lane lane; createLaneWaypoint(el, &lane); if (filtering_mode_) filter_.filterLaneWaypoint(&lane); lane_array->lanes.push_back(lane); } } void WaypointLoaderNode::saveLaneArray(const std::vector<std::string>& paths, const autoware_msgs::LaneArray& lane_array) { unsigned long idx = 0; for (const auto& file_path : paths) { std::ofstream ofs(file_path.c_str()); ofs << "x,y,z,yaw,velocity,change_flag,steering_flag,accel_flag,stop_flag,event_flag" << std::endl; for (const auto& el : lane_array.lanes[idx].waypoints) { ofs << std::fixed << std::setprecision(4) << el.pose.pose.position.x << "," << el.pose.pose.position.y << "," << el.pose.pose.position.z << "," << tf::getYaw(el.pose.pose.orientation) << "," << mps2kmph(el.twist.twist.linear.x) << "," << (int)el.change_flag << "," << (int)el.wpstate.steering_state << "," << (int)el.wpstate.accel_state << "," << (int)el.wpstate.stopline_state << "," << (int)el.wpstate.event_state << std::endl; } idx++; } } void WaypointLoaderNode::createLaneWaypoint(const std::string& file_path, autoware_msgs::lane* lane) { if (!verifyFileConsistency(file_path.c_str())) { ROS_ERROR("lane data is something wrong..."); return; } ROS_INFO("lane data is valid. publishing..."); FileFormat format = checkFileFormat(file_path.c_str()); std::vector<autoware_msgs::waypoint> wps; if (format == FileFormat::ver1) loadWaypointsForVer1(file_path.c_str(), &wps); else if (format == FileFormat::ver2) loadWaypointsForVer2(file_path.c_str(), &wps); else loadWaypointsForVer3(file_path.c_str(), &wps); lane->header.frame_id = "/map"; lane->header.stamp = ros::Time(0); lane->waypoints = wps; } void WaypointLoaderNode::loadWaypointsForVer1(const char* filename, std::vector<autoware_msgs::waypoint>* wps) { std::ifstream ifs(filename); if (!ifs) return; std::string line; std::getline(ifs, line); // Remove first line while (std::getline(ifs, line)) { autoware_msgs::waypoint wp; parseWaypointForVer1(line, &wp); wps->push_back(wp); } size_t last = wps->size() - 1; for (size_t i = 0; i < wps->size(); ++i) { if (i != last) { double yaw = atan2(wps->at(i + 1).pose.pose.position.y - wps->at(i).pose.pose.position.y, wps->at(i + 1).pose.pose.position.x - wps->at(i).pose.pose.position.x); wps->at(i).pose.pose.orientation = tf::createQuaternionMsgFromYaw(yaw); } else { wps->at(i).pose.pose.orientation = wps->at(i - 1).pose.pose.orientation; } } } void WaypointLoaderNode::parseWaypointForVer1(const std::string& line, autoware_msgs::waypoint* wp) { std::vector<std::string> columns; parseColumns(line, &columns); wp->pose.pose.position.x = std::stod(columns[0]); wp->pose.pose.position.y = std::stod(columns[1]); wp->pose.pose.position.z = std::stod(columns[2]); wp->twist.twist.linear.x = kmph2mps(std::stod(columns[3])); } void WaypointLoaderNode::loadWaypointsForVer2(const char* filename, std::vector<autoware_msgs::waypoint>* wps) { std::ifstream ifs(filename); if (!ifs) return; std::string line; std::getline(ifs, line); // Remove first line while (std::getline(ifs, line)) { autoware_msgs::waypoint wp; parseWaypointForVer2(line, &wp); wps->push_back(wp); } } void WaypointLoaderNode::parseWaypointForVer2(const std::string& line, autoware_msgs::waypoint* wp) { std::vector<std::string> columns; parseColumns(line, &columns); wp->pose.pose.position.x = std::stod(columns[0]); wp->pose.pose.position.y = std::stod(columns[1]); wp->pose.pose.position.z = std::stod(columns[2]); wp->pose.pose.orientation = tf::createQuaternionMsgFromYaw(std::stod(columns[3])); wp->twist.twist.linear.x = kmph2mps(std::stod(columns[4])); } void WaypointLoaderNode::loadWaypointsForVer3(const char* filename, std::vector<autoware_msgs::waypoint>* wps) { std::ifstream ifs(filename); if (!ifs) return; std::string line; std::getline(ifs, line); // get first line std::vector<std::string> contents; parseColumns(line, &contents); // std::getline(ifs, line); // remove second line while (std::getline(ifs, line)) { autoware_msgs::waypoint wp; parseWaypointForVer3(line, contents, &wp); wps->push_back(wp); } } void WaypointLoaderNode::parseWaypointForVer3(const std::string& line, const std::vector<std::string>& contents, autoware_msgs::waypoint* wp) { std::vector<std::string> columns; parseColumns(line, &columns); std::unordered_map<std::string, std::string> map; for (size_t i = 0; i < contents.size(); i++) { map[contents.at(i)] = columns.at(i); } wp->pose.pose.position.x = std::stod(map["x"]); wp->pose.pose.position.y = std::stod(map["y"]); wp->pose.pose.position.z = std::stod(map["z"]); wp->pose.pose.orientation = tf::createQuaternionMsgFromYaw(std::stod(map["yaw"])); wp->twist.twist.linear.x = kmph2mps(std::stod(map["velocity"])); wp->change_flag = std::stoi(map["change_flag"]); wp->wpstate.steering_state = (map.find("steering_flag") != map.end()) ? std::stoi(map["steering_flag"]) : 0; wp->wpstate.accel_state = (map.find("accel_flag") != map.end()) ? std::stoi(map["accel_flag"]) : 0; wp->wpstate.stopline_state = (map.find("stop_flag") != map.end()) ? std::stoi(map["stop_flag"]) : 0; wp->wpstate.event_state = (map.find("event_flag") != map.end()) ? std::stoi(map["event_flag"]) : 0; } FileFormat WaypointLoaderNode::checkFileFormat(const char* filename) { std::ifstream ifs(filename); if (!ifs) { return FileFormat::unknown; } // get first line std::string line; std::getline(ifs, line); // parse first line std::vector<std::string> parsed_columns; parseColumns(line, &parsed_columns); // check if first element in the first column does not include digit if (!std::any_of(parsed_columns.at(0).cbegin(), parsed_columns.at(0).cend(), isdigit)) { return FileFormat::ver3; } // if element consists only digit int num_of_columns = countColumns(line); ROS_INFO("columns size: %d", num_of_columns); return (num_of_columns == 3 ? FileFormat::ver1 // if data consists "x y z (velocity)" : num_of_columns == 4 ? FileFormat::ver2 // if data consists "x y z yaw (velocity) : FileFormat::unknown); } bool WaypointLoaderNode::verifyFileConsistency(const char* filename) { ROS_INFO("verify..."); std::ifstream ifs(filename); if (!ifs) return false; FileFormat format = checkFileFormat(filename); ROS_INFO("format: %d", static_cast<FileFormat>(format)); if (format == FileFormat::unknown) { ROS_ERROR("unknown file format"); return false; } std::string line; std::getline(ifs, line); // remove first line size_t ncol = format == FileFormat::ver1 ? 4 // x,y,z,velocity : format == FileFormat::ver2 ? 5 // x,y,z,yaw,velocity : countColumns(line); while (std::getline(ifs, line)) // search from second line { if (countColumns(line) != ncol) return false; } return true; } void parseColumns(const std::string& line, std::vector<std::string>* columns) { std::istringstream ss(line); std::string column; while (std::getline(ss, column, ',')) { while (1) { auto res = std::find(column.begin(), column.end(), ' '); if (res == column.end()) break; column.erase(res); } if (!column.empty()) columns->push_back(column); } } size_t countColumns(const std::string& line) { std::istringstream ss(line); size_t ncol = 0; std::string column; while (std::getline(ss, column, ',')) { ++ncol; } return ncol; } } // waypoint_maker <|endoftext|>
<commit_before>#ifndef INC_IO_HPP #define INC_IO_HPP #include <iostream> #include <string> #include <utility> #include <vector> namespace io { template<typename T> class basic_formatter { public: basic_formatter(const T &fmt) { size_t start = 0; for(size_t i = 0; i < fmt.size(); i++) { // Jesus Christ how horrifying if(fmt[i] == '{') { strings_.push_back(fmt.substr(start, i-start)); placeholders_.push_back(fmt[i+1] - '0'); i += 2; // Skip the number and the '}' start = i + 1; } } strings_.push_back(fmt.substr(start)); } std::vector<T> strings_; std::vector<size_t> placeholders_; }; typedef basic_formatter<char> formatter; template<typename T, typename String = std::string> class has_tostring { // It might be possible to simplify this, but it works. template<typename U> static constexpr auto has_tostring_(int, int, int, int, int, int) -> decltype( tostring<String>(std::declval<U>(), std::declval<const char*>()), tostring<String>(std::declval<U>()), int()) { static_assert(std::is_convertible<String, decltype( tostring<String>(std::declval<U>(), std::declval<const char*>()) )>::value, "unexpected return type for tostring"); static_assert(std::is_convertible<String, decltype( tostring<String>(std::declval<U>()) )>::value, "unexpected return type for tostring"); return 4 | 2 | 1; } template<typename U> static constexpr auto has_tostring_(int, int, int, int, int, ...) -> decltype( tostring(std::declval<U>(), std::declval<const char*>()), tostring(std::declval<U>()), int()) { static_assert(std::is_convertible<String, decltype( tostring(std::declval<U>(), std::declval<const char*>()) )>::value, "unexpected return type for tostring"); static_assert(std::is_convertible<String, decltype( tostring(std::declval<U>()) )>::value, "unexpected return type for tostring"); return 2 | 1; } template<typename U> static constexpr auto has_tostring_(int, int, int, int, ...) -> decltype( tostring<String>(std::declval<U>(), std::declval<const char*>()), int()) { static_assert(std::is_convertible<String, decltype( tostring<String>(std::declval<U>(), std::declval<const char*>()) )>::value, "unexpected return type for tostring"); return 4 | 2; } template<typename U> static constexpr auto has_tostring_(int, int, int, ...) -> decltype( tostring(std::declval<U>(), std::declval<const char*>()), int()) { static_assert(std::is_convertible<String, decltype( tostring(std::declval<U>(), std::declval<const char*>()) )>::value, "unexpected return type for tostring"); return 2; } template<typename U> static constexpr auto has_tostring_(int, int, ...) -> decltype( tostring<String>(std::declval<U>()), int()) { static_assert(std::is_convertible<String, decltype( tostring<String>(std::declval<U>()) )>::value, "unexpected return type for tostring"); return 4 | 1; } template<typename U> static constexpr auto has_tostring_(int, ...) -> decltype( tostring(std::declval<U>()), int()) { static_assert(std::is_convertible<String, decltype( tostring(std::declval<U>()) )>::value, "unexpected return type for tostring"); return 1; } template<typename U> static constexpr auto has_tostring_(...) -> int { return 0; } public: // value is a bitfield describing what kind of tostring function we have: // 4 = tostring accepts a template for the return type // 2 = tostring accepts a format string // 1 = tostring accepts no format string enum { value = has_tostring_<T>(0, 0, 0, 0, 0, 0) }; }; namespace detail { // First, some helpers to call tostring whether or not it takes a template to // define the return type. template<typename String, typename T> inline auto tostring_(T &&t) -> typename std::enable_if< (has_tostring<T, String>::value & 4) == 0, decltype(tostring( std::declval<T>() )) >::type { return tostring(std::forward<T>(t)); } template<typename String, typename T> inline auto tostring_(T &&t) -> typename std::enable_if< has_tostring<T, String>::value & 4, decltype(tostring<String>( std::declval<T>() )) >::type { return tostring<String>(std::forward<T>(t)); } // Next, some helpers to delegate to the proper tostring based on whether // format args were provided and whether tostring accepts them. template<typename Char, typename Traits, typename T> inline typename std::enable_if< has_tostring<T, std::basic_string<Char, Traits>>::value == 0, void >::type try_format(std::basic_ostream<Char, Traits> &o, T &&t, const char *fmt = 0) { static_assert(has_tostring<T, std::basic_string<Char, Traits>>::value, "no tostring function found"); } template<typename Char, typename Traits, typename T> inline typename std::enable_if< has_tostring<T, std::basic_string<Char, Traits>>::value & 1, void >::type try_format(std::basic_ostream<Char, Traits> &o, T &&t) { o << tostring_<std::basic_string<Char, Traits>>(t); } template<typename Char, typename Traits, typename T> inline typename std::enable_if< (has_tostring<T, std::basic_string<Char, Traits>>::value & 3) == 2, void >::type try_format(std::basic_ostream<Char, Traits> &o, T &&t) { o << tostring_<std::basic_string<Char, Traits>>(t, ""); } template<typename Char, typename Traits, typename T> inline typename std::enable_if< (has_tostring<T, std::basic_string<Char, Traits>>::value & 3) == 1, void >::type try_format(std::basic_ostream<Char, Traits> &o, T &&t, const char *fmt) { o << tostring_<std::basic_string<Char, Traits>>(t); } template<typename Char, typename Traits, typename T> inline typename std::enable_if< has_tostring<T, std::basic_string<Char, Traits>>::value & 2, void >::type try_format(std::basic_ostream<Char, Traits> &o, T &&t, const char *fmt) { o << tostring_<std::basic_string<Char, Traits>>(t, fmt); } // Finally, some helpers to return a formatted version of the i'th argument // in a template parameter pack. template<typename Char, typename Traits, typename ...Rest> inline void format_one(std::basic_ostream<Char, Traits> &o, int i, Rest &&...args) { // This should never actually be called. } template<typename Char, typename Traits, typename T, typename ...Rest> inline void format_one(std::basic_ostream<Char, Traits> &o, int i, T &&x, Rest &&...args) { if(i == 0) try_format(o, x); else format_one(o, i-1, args...); } template<typename Char, typename Traits, typename ...Rest> inline void format_one(std::basic_ostream<Char, Traits> &o, const char *fmt, int i, Rest &&...args) { // This should never actually be called. } template<typename Char, typename Traits, typename T, typename ...Rest> inline void format_one(std::basic_ostream<Char, Traits> &o, const char *fmt, int i, T &&x, Rest &&...args) { if(i == 0) try_format(o, x, fmt); else format_one(o, i-1, args...); } } // Not sure why I need this overload... you'd think the next one would be // deduceable. template<typename Char, typename Traits, typename ...T> inline void format(std::basic_ostream<Char, Traits> &o, const Char *fmt, T &&...args) { format(o, basic_formatter<std::basic_string<Char, Traits>>(fmt), args...); } template<typename Char, typename Traits, typename ...T> inline void format(std::basic_ostream<Char, Traits> &o, const std::basic_string<Char, Traits> &fmt, T &&...args) { format(o, basic_formatter<std::basic_string<Char, Traits>>(fmt), args...); } template<typename Char, typename Traits, typename ...T> void format(std::basic_ostream<Char, Traits> &o, const basic_formatter<std::basic_string<Char, Traits>> &fmt, T &&...args) { auto str = fmt.strings_.begin(); for(auto i : fmt.placeholders_) { o << *str; ++str; detail::format_one(o, i, args...); } o << *str; } } // namespace io #endif <commit_msg>Don't static_assert in a type_traits-ish function; that's rude<commit_after>#ifndef INC_IO_HPP #define INC_IO_HPP #include <iostream> #include <string> #include <utility> #include <vector> namespace io { template<typename T> class basic_formatter { public: basic_formatter(const T &fmt) { size_t start = 0; for(size_t i = 0; i < fmt.size(); i++) { // Jesus Christ how horrifying if(fmt[i] == '{') { strings_.push_back(fmt.substr(start, i-start)); placeholders_.push_back(fmt[i+1] - '0'); i += 2; // Skip the number and the '}' start = i + 1; } } strings_.push_back(fmt.substr(start)); } std::vector<T> strings_; std::vector<size_t> placeholders_; }; typedef basic_formatter<char> formatter; template<typename T, typename String = std::string> class has_tostring { // It might be possible to simplify this, but it works. template<typename U> static constexpr auto has_tostring_(int, int, int, int, int, int) -> decltype( String(tostring<String>(std::declval<U>(), std::declval<const char*>())), String(tostring<String>(std::declval<U>())), int()) { return 4 | 2 | 1; } template<typename U> static constexpr auto has_tostring_(int, int, int, int, int, ...) -> decltype( String(tostring(std::declval<U>(), std::declval<const char*>())), String(tostring(std::declval<U>())), int()) { return 2 | 1; } template<typename U> static constexpr auto has_tostring_(int, int, int, int, ...) -> decltype( String(tostring<String>(std::declval<U>(), std::declval<const char*>())), int()) { return 4 | 2; } template<typename U> static constexpr auto has_tostring_(int, int, int, ...) -> decltype( String(tostring(std::declval<U>(), std::declval<const char*>())), int()) { return 2; } template<typename U> static constexpr auto has_tostring_(int, int, ...) -> decltype( String(tostring<String>(std::declval<U>())), int()) { return 4 | 1; } template<typename U> static constexpr auto has_tostring_(int, ...) -> decltype( String(tostring(std::declval<U>())), int()) { return 1; } template<typename U> static constexpr auto has_tostring_(...) -> int { return 0; } public: // value is a bitfield describing what kind of tostring function we have: // 4 = tostring accepts a template for the return type // 2 = tostring accepts a format string // 1 = tostring accepts no format string enum { value = has_tostring_<T>(0, 0, 0, 0, 0, 0) }; }; namespace detail { // First, some helpers to call tostring whether or not it takes a template to // define the return type. template<typename String, typename T> inline auto tostring_(T &&t) -> typename std::enable_if< (has_tostring<T, String>::value & 4) == 0, decltype(tostring( std::declval<T>() )) >::type { return tostring(std::forward<T>(t)); } template<typename String, typename T> inline auto tostring_(T &&t) -> typename std::enable_if< has_tostring<T, String>::value & 4, decltype(tostring<String>( std::declval<T>() )) >::type { return tostring<String>(std::forward<T>(t)); } // Next, some helpers to delegate to the proper tostring based on whether // format args were provided and whether tostring accepts them. template<typename Char, typename Traits, typename T> inline typename std::enable_if< has_tostring<T, std::basic_string<Char, Traits>>::value == 0, void >::type try_format(std::basic_ostream<Char, Traits> &o, T &&t, const char *fmt = 0) { static_assert(has_tostring<T, std::basic_string<Char, Traits>>::value, "no valid tostring function found"); } template<typename Char, typename Traits, typename T> inline typename std::enable_if< has_tostring<T, std::basic_string<Char, Traits>>::value & 1, void >::type try_format(std::basic_ostream<Char, Traits> &o, T &&t) { o << tostring_<std::basic_string<Char, Traits>>(t); } template<typename Char, typename Traits, typename T> inline typename std::enable_if< (has_tostring<T, std::basic_string<Char, Traits>>::value & 3) == 2, void >::type try_format(std::basic_ostream<Char, Traits> &o, T &&t) { o << tostring_<std::basic_string<Char, Traits>>(t, ""); } template<typename Char, typename Traits, typename T> inline typename std::enable_if< (has_tostring<T, std::basic_string<Char, Traits>>::value & 3) == 1, void >::type try_format(std::basic_ostream<Char, Traits> &o, T &&t, const char *fmt) { o << tostring_<std::basic_string<Char, Traits>>(t); } template<typename Char, typename Traits, typename T> inline typename std::enable_if< has_tostring<T, std::basic_string<Char, Traits>>::value & 2, void >::type try_format(std::basic_ostream<Char, Traits> &o, T &&t, const char *fmt) { o << tostring_<std::basic_string<Char, Traits>>(t, fmt); } // Finally, some helpers to return a formatted version of the i'th argument // in a template parameter pack. template<typename Char, typename Traits, typename ...Rest> inline void format_one(std::basic_ostream<Char, Traits> &o, int i, Rest &&...args) { // This should never actually be called. } template<typename Char, typename Traits, typename T, typename ...Rest> inline void format_one(std::basic_ostream<Char, Traits> &o, int i, T &&x, Rest &&...args) { if(i == 0) try_format(o, x); else format_one(o, i-1, args...); } template<typename Char, typename Traits, typename ...Rest> inline void format_one(std::basic_ostream<Char, Traits> &o, const char *fmt, int i, Rest &&...args) { // This should never actually be called. } template<typename Char, typename Traits, typename T, typename ...Rest> inline void format_one(std::basic_ostream<Char, Traits> &o, const char *fmt, int i, T &&x, Rest &&...args) { if(i == 0) try_format(o, x, fmt); else format_one(o, i-1, args...); } } // Not sure why I need this overload... you'd think the next one would be // deduceable. template<typename Char, typename Traits, typename ...T> inline void format(std::basic_ostream<Char, Traits> &o, const Char *fmt, T &&...args) { format(o, basic_formatter<std::basic_string<Char, Traits>>(fmt), args...); } template<typename Char, typename Traits, typename ...T> inline void format(std::basic_ostream<Char, Traits> &o, const std::basic_string<Char, Traits> &fmt, T &&...args) { format(o, basic_formatter<std::basic_string<Char, Traits>>(fmt), args...); } template<typename Char, typename Traits, typename ...T> void format(std::basic_ostream<Char, Traits> &o, const basic_formatter<std::basic_string<Char, Traits>> &fmt, T &&...args) { auto str = fmt.strings_.begin(); for(auto i : fmt.placeholders_) { o << *str; ++str; detail::format_one(o, i, args...); } o << *str; } } // namespace io #endif <|endoftext|>
<commit_before>/* -*- mode: C++; c-file-style: "gnu" -*- * * Copyright (c) 2001-2003 Carsten Pfeiffer <pfeiffer@kde.org> * Copyright (c) 2003 Zack Rusin <zack@kde.org> * * KMail is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. * * KMail is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "recentaddresses.h" #include <kstaticdeleter.h> #include <kconfig.h> #include <kglobal.h> #include <kdebug.h> #include <klocale.h> #include <keditlistbox.h> #include <qlayout.h> //Added by qt3to4: #include <QVBoxLayout> using namespace KRecentAddress; static KStaticDeleter<RecentAddresses> sd; RecentAddresses * RecentAddresses::s_self = 0; RecentAddresses * RecentAddresses::self( KConfig *config) { if ( !s_self ) sd.setObject( s_self, new RecentAddresses(config) ); return s_self; } RecentAddresses::RecentAddresses(KConfig * config) { if ( !config ) load( KGlobal::config() ); else load( config ); } RecentAddresses::~RecentAddresses() { // if you want this destructor to get called, use a KStaticDeleter // on s_self } void RecentAddresses::load( KConfig *config ) { QStringList addresses; QString name; QString email; m_addresseeList.clear(); KConfigGroupSaver cs( config, "General" ); m_maxCount = config->readNumEntry( "Maximum Recent Addresses", 40 ); addresses = config->readListEntry( "Recent Addresses" ); for ( QStringList::Iterator it = addresses.begin(); it != addresses.end(); ++it ) { KABC::Addressee::parseEmailAddress( *it, name, email ); if ( !email.isEmpty() ) { KABC::Addressee addr; addr.setNameFromString( name ); addr.insertEmail( email, true ); m_addresseeList.append( addr ); } } adjustSize(); } void RecentAddresses::save( KConfig *config ) { KConfigGroupSaver cs( config, "General" ); config->writeEntry( "Recent Addresses", addresses() ); } void RecentAddresses::add( const QString& entry ) { if ( !entry.isEmpty() && m_maxCount > 0 ) { QString email; QString fullName; KABC::Addressee addr; KABC::Addressee::parseEmailAddress( entry, fullName, email ); for ( KABC::Addressee::List::Iterator it = m_addresseeList.begin(); it != m_addresseeList.end(); ++it ) { if ( email == (*it).preferredEmail() ) return;//already inside } addr.setNameFromString( fullName ); addr.insertEmail( email, true ); m_addresseeList.prepend( addr ); adjustSize(); } } void RecentAddresses::setMaxCount( int count ) { m_maxCount = count; adjustSize(); } void RecentAddresses::adjustSize() { while ( m_addresseeList.count() > m_maxCount ) m_addresseeList.remove( m_addresseeList.fromLast() ); } void RecentAddresses::clear() { m_addresseeList.clear(); adjustSize(); } QStringList RecentAddresses::addresses() const { QStringList addresses; for ( KABC::Addressee::List::ConstIterator it = m_addresseeList.begin(); it != m_addresseeList.end(); ++it ) { addresses.append( (*it).fullEmail() ); } return addresses; } RecentAddressDialog::RecentAddressDialog( QWidget *parent, const char *name ) : KDialogBase( Plain, i18n( "Edit Recent Addresses" ), Ok | Cancel, Ok, parent, name, true, true ) { QWidget *page = plainPage(); QVBoxLayout *layout = new QVBoxLayout( page, marginHint(), spacingHint() ); mEditor = new KEditListBox( i18n( "Recent Addresses" ), page, "", false, KEditListBox::Add | KEditListBox::Remove ); layout->addWidget( mEditor ); } void RecentAddressDialog::setAddresses( const QStringList &addrs ) { mEditor->clear(); mEditor->insertStringList( addrs ); } QStringList RecentAddressDialog::addresses() const { return mEditor->items(); } <commit_msg>forward port. Fix this dialog -- nhasan<commit_after>/* -*- mode: C++; c-file-style: "gnu" -*- * * Copyright (c) 2001-2003 Carsten Pfeiffer <pfeiffer@kde.org> * Copyright (c) 2003 Zack Rusin <zack@kde.org> * * KMail is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. * * KMail is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "recentaddresses.h" #include <kstaticdeleter.h> #include <kconfig.h> #include <kglobal.h> #include <kdebug.h> #include <klocale.h> #include <keditlistbox.h> #include <qlayout.h> //Added by qt3to4: #include <QVBoxLayout> using namespace KRecentAddress; static KStaticDeleter<RecentAddresses> sd; RecentAddresses * RecentAddresses::s_self = 0; RecentAddresses * RecentAddresses::self( KConfig *config) { if ( !s_self ) sd.setObject( s_self, new RecentAddresses(config) ); return s_self; } RecentAddresses::RecentAddresses(KConfig * config) { if ( !config ) load( KGlobal::config() ); else load( config ); } RecentAddresses::~RecentAddresses() { // if you want this destructor to get called, use a KStaticDeleter // on s_self } void RecentAddresses::load( KConfig *config ) { QStringList addresses; QString name; QString email; m_addresseeList.clear(); KConfigGroupSaver cs( config, "General" ); m_maxCount = config->readNumEntry( "Maximum Recent Addresses", 40 ); addresses = config->readListEntry( "Recent Addresses" ); for ( QStringList::Iterator it = addresses.begin(); it != addresses.end(); ++it ) { KABC::Addressee::parseEmailAddress( *it, name, email ); if ( !email.isEmpty() ) { KABC::Addressee addr; addr.setNameFromString( name ); addr.insertEmail( email, true ); m_addresseeList.append( addr ); } } adjustSize(); } void RecentAddresses::save( KConfig *config ) { KConfigGroupSaver cs( config, "General" ); config->writeEntry( "Recent Addresses", addresses() ); } void RecentAddresses::add( const QString& entry ) { if ( !entry.isEmpty() && m_maxCount > 0 ) { QString email; QString fullName; KABC::Addressee addr; KABC::Addressee::parseEmailAddress( entry, fullName, email ); for ( KABC::Addressee::List::Iterator it = m_addresseeList.begin(); it != m_addresseeList.end(); ++it ) { if ( email == (*it).preferredEmail() ) return;//already inside } addr.setNameFromString( fullName ); addr.insertEmail( email, true ); m_addresseeList.prepend( addr ); adjustSize(); } } void RecentAddresses::setMaxCount( int count ) { m_maxCount = count; adjustSize(); } void RecentAddresses::adjustSize() { while ( m_addresseeList.count() > m_maxCount ) m_addresseeList.remove( m_addresseeList.fromLast() ); } void RecentAddresses::clear() { m_addresseeList.clear(); adjustSize(); } QStringList RecentAddresses::addresses() const { QStringList addresses; for ( KABC::Addressee::List::ConstIterator it = m_addresseeList.begin(); it != m_addresseeList.end(); ++it ) { addresses.append( (*it).fullEmail() ); } return addresses; } RecentAddressDialog::RecentAddressDialog( QWidget *parent, const char *name ) : KDialogBase( Plain, i18n( "Edit Recent Addresses" ), Ok | Cancel, Ok, parent, name, true ) { QWidget *page = plainPage(); QVBoxLayout *layout = new QVBoxLayout( page, 0, spacingHint() ); mEditor = new KEditListBox( i18n( "Recent Addresses" ), page, "", false, KEditListBox::Add | KEditListBox::Remove ); layout->addWidget( mEditor ); } void RecentAddressDialog::setAddresses( const QStringList &addrs ) { mEditor->clear(); mEditor->insertStringList( addrs ); } QStringList RecentAddressDialog::addresses() const { return mEditor->items(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2001 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) #ident "$Id: symbols.cc,v 1.4 2001/11/02 04:48:03 steve Exp $" #endif # include "symbols.h" # include <string.h> # include <assert.h> struct symbol_table_s { struct tree_node_*root; }; /* * This is a B-Tree data structure, where there are nodes and * leaves. * * Nodes have a bunch of pointers to children. Each child pointer has * associated with it a key that is the largest key referenced by that * child. So, if the key being searched for has a value <= the first * key of a node, then the value is in the first child. * * leaves have a sorted table of key-value pairs. The search can use a * simple binary search to find an item. Each key represents an item. */ const unsigned leaf_width = 511; const unsigned node_width = 511; struct tree_node_ { bool leaf_flag; unsigned count; struct tree_node_*parent; union { struct { char*key; symbol_value_t val; } leaf[leaf_width]; struct tree_node_*child[node_width]; }; }; static inline char* node_last_key(struct tree_node_*node) { while (node->leaf_flag == false) node = node->child[node->count-1]; return node->leaf[node->count-1].key; } /* * Allocate a new symbol table means creating the table structure and * a root node, and initializing the pointers and members of the root * node. */ symbol_table_t new_symbol_table(void) { symbol_table_t tbl = new struct symbol_table_s; tbl->root = new struct tree_node_; tbl->root->leaf_flag = false; tbl->root->count = 0; tbl->root->parent = 0; return tbl; } /* Do as split_leaf_ do, but for nodes. */ static void split_node_(struct tree_node_*cur) { unsigned int idx, idx1, idx2, tmp; struct tree_node_ *new_node; assert(!cur->leaf_flag); if (cur->parent) assert(! cur->parent->leaf_flag); while (cur->count == node_width) { /* Create a new node to hold half the data from the old node. */ new_node = new struct tree_node_; new_node->leaf_flag = false; new_node->count = cur->count / 2; if (cur->parent) /* cur is not root; new_node becomes sibling. */ new_node->parent = cur->parent; else /* cur is root; new_node becomes child. */ /* And. move the first half of child to another new node later */ new_node->parent = cur; /* Move the last half of the data from the end of the old node to the beggining of the new node. At the same time, reduce the size of the old node. */ idx1 = new_node->count; idx2 = cur->count; while (idx1 > 0) { idx1 -= 1; idx2 -= 1; new_node->child[idx1] = cur->child[idx2]; new_node->child[idx1]->parent = new_node; cur->count -= 1; } assert(new_node->count > 0); assert(cur->count > 0); if (cur->parent == 0) { /* cur is root. Move first half of children to another new node, and put the two new nodes in cur. */ cur->child[cur->count] /* used as tmep var */ = new_node; new_node = new struct tree_node_; new_node->leaf_flag = false; new_node->count = cur->count; for (idx = 0; idx < cur->count; idx ++) { new_node->child[idx] = cur->child[idx]; new_node->child[idx]->parent = new_node; } cur->child[0] = new_node; cur->child[1] = cur->child[cur->count]; cur->count = 2; /* no more ancestors, stop the while loop */ break; } /* cur is not root. hook new_node to cur->parent. */ idx = 0; while (cur->parent->child[idx] != cur) { assert(idx < cur->parent->count); idx += 1; } idx += 1; for (tmp = cur->parent->count ; tmp > idx ; tmp -= 1) cur->parent->child[tmp] = cur->parent->child[tmp-1]; cur->parent->child[idx] = new_node; cur->parent->count += 1; /* check the ancestor */ cur = cur->parent; } } /* * This function takes a leaf node and splits in into two. Move half * the leaf keys into the new node, and add the new leaf into the * parent node. */ static struct tree_node_* split_leaf_(struct tree_node_*cur) { assert(cur->leaf_flag); assert(cur->parent); assert(! cur->parent->leaf_flag); /* Create a new leaf to hold half the data from the old leaf. */ struct tree_node_*new_leaf = new struct tree_node_; new_leaf->leaf_flag = true; new_leaf->count = cur->count / 2; new_leaf->parent = cur->parent; /* Move the last half of the data from the end of the old leaf to the beggining of the new leaf. At the same time, reduce the size of the old leaf. */ unsigned idx1 = new_leaf->count; unsigned idx2 = cur->count; while (idx1 > 0) { idx1 -= 1; idx2 -= 1; new_leaf->leaf[idx1] = cur->leaf[idx2]; cur->count -= 1; } assert(new_leaf->count > 0); assert(cur->count > 0); unsigned idx = 0; while (cur->parent->child[idx] != cur) { assert(idx < cur->parent->count); idx += 1; } idx += 1; for (unsigned tmp = cur->parent->count ; tmp > idx ; tmp -= 1) cur->parent->child[tmp] = cur->parent->child[tmp-1]; cur->parent->child[idx] = new_leaf; cur->parent->count += 1; if (cur->parent->count == node_width) split_node_(cur->parent); return new_leaf; } /* * This function searches tree recursively for the key. If the value * is not found (and we are at a leaf) then set the key with the given * value. If the key is found, set the value only if the force_flag is * true. */ static symbol_value_t find_value_(symbol_table_t tbl, struct tree_node_*cur, const char*key, symbol_value_t val, bool force_flag) { if (cur->leaf_flag) { unsigned idx = 0; for (;;) { /* If we run out of keys in the leaf, then add this at the end of the leaf. */ if (idx == cur->count) { cur->leaf[idx].key = strdup(key); cur->leaf[idx].val = val; cur->count += 1; if (cur->count == leaf_width) split_leaf_(cur); return val; } int rc = strcmp(key, cur->leaf[idx].key); /* If we found the key already in the table, then set the new value and break. */ if (rc == 0) { if (force_flag) cur->leaf[idx].val = val; return cur->leaf[idx].val; } /* If this key goes before the current key, then push all the following entries back and add this key here. */ if (rc < 0) { for (unsigned tmp = cur->count; tmp > idx; tmp -= 1) cur->leaf[tmp] = cur->leaf[tmp-1]; cur->leaf[idx].key = strdup(key); cur->leaf[idx].val = val; cur->count += 1; if (cur->count == leaf_width) split_leaf_(cur); return val; } idx += 1; } } else { unsigned idx = 0; for (;;) { if (idx == cur->count) { idx -= 1; return find_value_(tbl, cur->child[idx], key, val, force_flag); } int rc = strcmp(key, node_last_key(cur->child[idx])); if (rc <= 0) { return find_value_(tbl, cur->child[idx], key, val, force_flag); } idx += 1; } } assert(0); { symbol_value_t tmp; tmp.num = 0; return tmp; } } void sym_set_value(symbol_table_t tbl, const char*key, symbol_value_t val) { if (tbl->root->count == 0) { /* Handle the special case that this is the very first value in the symbol table. Create the first leaf node and initialize the pointers. */ struct tree_node_*cur = new struct tree_node_; cur->leaf_flag = true; cur->parent = tbl->root; cur->count = 1; cur->leaf[0].key = strdup(key); cur->leaf[0].val = val; tbl->root->count = 1; tbl->root->child[0] = cur; } else { find_value_(tbl, tbl->root, key, val, true); } } symbol_value_t sym_get_value(symbol_table_t tbl, const char*key) { symbol_value_t def; def.num = 0; if (tbl->root->count == 0) { /* Handle the special case that this is the very first value in the symbol table. Create the first leaf node and initialize the pointers. */ struct tree_node_*cur = new struct tree_node_; cur->leaf_flag = true; cur->parent = tbl->root; cur->count = 1; cur->leaf[0].key = strdup(key); cur->leaf[0].val = def; tbl->root->count = 1; tbl->root->child[0] = cur; return cur->leaf[0].val; } else { return find_value_(tbl, tbl->root, key, def, false); } } /* * $Log: symbols.cc,v $ * Revision 1.4 2001/11/02 04:48:03 steve * Implement split_node for symbol table (hendrik) * * Revision 1.3 2001/05/09 04:23:19 steve * Now that the interactive debugger exists, * there is no use for the output dump. * * Revision 1.2 2001/03/18 00:37:55 steve * Add support for vpi scopes. * * Revision 1.1 2001/03/11 00:29:39 steve * Add the vvp engine to cvs. * */ <commit_msg> Use binary search to speed up deep lookups.<commit_after>/* * Copyright (c) 2001 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) #ident "$Id: symbols.cc,v 1.5 2002/05/29 05:37:35 steve Exp $" #endif # include "symbols.h" # include <string.h> # include <assert.h> struct symbol_table_s { struct tree_node_*root; }; /* * This is a B-Tree data structure, where there are nodes and * leaves. * * Nodes have a bunch of pointers to children. Each child pointer has * associated with it a key that is the largest key referenced by that * child. So, if the key being searched for has a value <= the first * key of a node, then the value is in the first child. * * leaves have a sorted table of key-value pairs. The search can use a * simple binary search to find an item. Each key represents an item. */ const unsigned leaf_width = 254; const unsigned node_width = 508; struct tree_node_ { bool leaf_flag; unsigned count; struct tree_node_*parent; union { struct { char*key; symbol_value_t val; } leaf[leaf_width]; struct tree_node_*child[node_width]; }; }; static inline char* node_last_key(struct tree_node_*node) { while (node->leaf_flag == false) node = node->child[node->count-1]; return node->leaf[node->count-1].key; } /* * Allocate a new symbol table means creating the table structure and * a root node, and initializing the pointers and members of the root * node. */ symbol_table_t new_symbol_table(void) { symbol_table_t tbl = new struct symbol_table_s; tbl->root = new struct tree_node_; tbl->root->leaf_flag = false; tbl->root->count = 0; tbl->root->parent = 0; return tbl; } /* Do as split_leaf_ do, but for nodes. */ static void split_node_(struct tree_node_*cur) { unsigned int idx, idx1, idx2, tmp; struct tree_node_ *new_node; assert(!cur->leaf_flag); if (cur->parent) assert(! cur->parent->leaf_flag); while (cur->count == node_width) { /* Create a new node to hold half the data from the old node. */ new_node = new struct tree_node_; new_node->leaf_flag = false; new_node->count = cur->count / 2; if (cur->parent) /* cur is not root; new_node becomes sibling. */ new_node->parent = cur->parent; else /* cur is root; new_node becomes child. */ /* And. move the first half of child to another new node later */ new_node->parent = cur; /* Move the last half of the data from the end of the old node to the beggining of the new node. At the same time, reduce the size of the old node. */ idx1 = new_node->count; idx2 = cur->count; while (idx1 > 0) { idx1 -= 1; idx2 -= 1; new_node->child[idx1] = cur->child[idx2]; new_node->child[idx1]->parent = new_node; cur->count -= 1; } assert(new_node->count > 0); assert(cur->count > 0); if (cur->parent == 0) { /* cur is root. Move first half of children to another new node, and put the two new nodes in cur. */ cur->child[cur->count] /* used as tmep var */ = new_node; new_node = new struct tree_node_; new_node->leaf_flag = false; new_node->count = cur->count; for (idx = 0; idx < cur->count; idx ++) { new_node->child[idx] = cur->child[idx]; new_node->child[idx]->parent = new_node; } cur->child[0] = new_node; cur->child[1] = cur->child[cur->count]; cur->count = 2; /* no more ancestors, stop the while loop */ break; } /* cur is not root. hook new_node to cur->parent. */ idx = 0; while (cur->parent->child[idx] != cur) { assert(idx < cur->parent->count); idx += 1; } idx += 1; for (tmp = cur->parent->count ; tmp > idx ; tmp -= 1) cur->parent->child[tmp] = cur->parent->child[tmp-1]; cur->parent->child[idx] = new_node; cur->parent->count += 1; /* check the ancestor */ cur = cur->parent; } } /* * This function takes a leaf node and splits in into two. Move half * the leaf keys into the new node, and add the new leaf into the * parent node. */ static struct tree_node_* split_leaf_(struct tree_node_*cur) { assert(cur->leaf_flag); assert(cur->parent); assert(! cur->parent->leaf_flag); /* Create a new leaf to hold half the data from the old leaf. */ struct tree_node_*new_leaf = new struct tree_node_; new_leaf->leaf_flag = true; new_leaf->count = cur->count / 2; new_leaf->parent = cur->parent; /* Move the last half of the data from the end of the old leaf to the beggining of the new leaf. At the same time, reduce the size of the old leaf. */ unsigned idx1 = new_leaf->count; unsigned idx2 = cur->count; while (idx1 > 0) { idx1 -= 1; idx2 -= 1; new_leaf->leaf[idx1] = cur->leaf[idx2]; cur->count -= 1; } assert(new_leaf->count > 0); assert(cur->count > 0); unsigned idx = 0; while (cur->parent->child[idx] != cur) { assert(idx < cur->parent->count); idx += 1; } idx += 1; for (unsigned tmp = cur->parent->count ; tmp > idx ; tmp -= 1) cur->parent->child[tmp] = cur->parent->child[tmp-1]; cur->parent->child[idx] = new_leaf; cur->parent->count += 1; if (cur->parent->count == node_width) split_node_(cur->parent); return new_leaf; } /* * This function searches tree recursively for the key. If the value * is not found (and we are at a leaf) then set the key with the given * value. If the key is found, set the value only if the force_flag is * true. */ static symbol_value_t find_value_(symbol_table_t tbl, struct tree_node_*cur, const char*key, symbol_value_t val, bool force_flag) { if (cur->leaf_flag) { unsigned idx = 0; for (;;) { /* If we run out of keys in the leaf, then add this at the end of the leaf. */ if (idx == cur->count) { cur->leaf[idx].key = strdup(key); cur->leaf[idx].val = val; cur->count += 1; if (cur->count == leaf_width) split_leaf_(cur); return val; } int rc = strcmp(key, cur->leaf[idx].key); /* If we found the key already in the table, then set the new value and break. */ if (rc == 0) { if (force_flag) cur->leaf[idx].val = val; return cur->leaf[idx].val; } /* If this key goes before the current key, then push all the following entries back and add this key here. */ if (rc < 0) { for (unsigned tmp = cur->count; tmp > idx; tmp -= 1) cur->leaf[tmp] = cur->leaf[tmp-1]; cur->leaf[idx].key = strdup(key); cur->leaf[idx].val = val; cur->count += 1; if (cur->count == leaf_width) split_leaf_(cur); return val; } idx += 1; } } else { /* Do a binary search within the inner node. */ unsigned min = 0; unsigned max = cur->count; unsigned idx = max/2; for (;;) { int rc = strcmp(key, node_last_key(cur->child[idx])); if (rc == 0) { return find_value_(tbl, cur->child[idx], key, val, force_flag); } if (rc > 0) { min = idx + 1; if (min == cur->count) return find_value_(tbl, cur->child[idx], key, val, force_flag); if (min == max) return find_value_(tbl, cur->child[max], key, val, force_flag); idx = min + (max-min)/2; } else { max = idx; if (idx == min) return find_value_(tbl, cur->child[idx], key, val, force_flag); idx = min + (max-min)/2; } } } assert(0); { symbol_value_t tmp; tmp.num = 0; return tmp; } } void sym_set_value(symbol_table_t tbl, const char*key, symbol_value_t val) { if (tbl->root->count == 0) { /* Handle the special case that this is the very first value in the symbol table. Create the first leaf node and initialize the pointers. */ struct tree_node_*cur = new struct tree_node_; cur->leaf_flag = true; cur->parent = tbl->root; cur->count = 1; cur->leaf[0].key = strdup(key); cur->leaf[0].val = val; tbl->root->count = 1; tbl->root->child[0] = cur; } else { find_value_(tbl, tbl->root, key, val, true); } } symbol_value_t sym_get_value(symbol_table_t tbl, const char*key) { symbol_value_t def; def.num = 0; if (tbl->root->count == 0) { /* Handle the special case that this is the very first value in the symbol table. Create the first leaf node and initialize the pointers. */ struct tree_node_*cur = new struct tree_node_; cur->leaf_flag = true; cur->parent = tbl->root; cur->count = 1; cur->leaf[0].key = strdup(key); cur->leaf[0].val = def; tbl->root->count = 1; tbl->root->child[0] = cur; return cur->leaf[0].val; } else { return find_value_(tbl, tbl->root, key, def, false); } } /* * $Log: symbols.cc,v $ * Revision 1.5 2002/05/29 05:37:35 steve * Use binary search to speed up deep lookups. * * Revision 1.4 2001/11/02 04:48:03 steve * Implement split_node for symbol table (hendrik) * * Revision 1.3 2001/05/09 04:23:19 steve * Now that the interactive debugger exists, * there is no use for the output dump. * * Revision 1.2 2001/03/18 00:37:55 steve * Add support for vpi scopes. * * Revision 1.1 2001/03/11 00:29:39 steve * Add the vvp engine to cvs. * */ <|endoftext|>
<commit_before>#include "SecIdentity.hpp" #include "Util.hpp" SecurityIdentity::SecurityIdentity(const SID * sid) { SecurityIdentity(reinterpret_cast<const unsigned char*>(sid), sizeof(SID)); } SecurityIdentity::SecurityIdentity(const unsigned char * sid, unsigned short sid_size) { this->raw_sid = new unsigned char[sid_size]; this->sid_size = sid_size; this->sid_type = SID_NAME_USE::SidTypeUnknown; memcpy(this->raw_sid, sid, sid_size); } SecurityIdentity::~SecurityIdentity() { delete[] this->raw_sid; } void SecurityIdentity::HexString(wstring & s) { BinaryToString(this->raw_sid, this->sid_size, s); } void SecurityIdentity::GetName(wstring & n) { n.assign(this->name); } void SecurityIdentity::ResolveName(LSA_HANDLE lsa) { if(this->name.size() != 0) { return; } void * sidss[1]; sidss[0] = this->raw_sid; LSA_REFERENCED_DOMAIN_LIST * domains = nullptr; LSA_TRANSLATED_NAME * names = nullptr; auto lsa_result = LsaLookupSids2(lsa,LSA_LOOKUP_DISALLOW_CONNECTED_ACCOUNT_INTERNET_SID , 1, sidss, &domains, &names); if(lsa_result != STATUS_SUCCESS) { if(lsa_result == STATUS_NONE_MAPPED) { this->name.assign(L"<NONE>"); } else { wchar_t fail[32]; swprintf_s(fail, 32, L"!!FAILED 0x%08X", lsa_result); this->name.assign(fail); } if(domains) { LsaFreeMemory(domains); } if(names) { LsaFreeMemory(names); } return; } UNICODE_STRING u; switch(names->Use) { case SID_NAME_USE::SidTypeDomain: this->name.assign(L"!!THIS WAS DOMAIN SID!!"); break; case SID_NAME_USE::SidTypeInvalid: case SID_NAME_USE::SidTypeUnknown: this->name.assign(L"!!INVALID OR UNKNOWN NAME!!"); break; default: u.Buffer = names->Name.Buffer; u.Length = names->Name.Length; u.MaximumLength = names->Name.MaximumLength; this->name.assign(u.Buffer, u.Length / sizeof(wchar_t)); this->sid_type = names->Use; break; } LsaFreeMemory(domains); LsaFreeMemory(names); } NtAccounts::NtAccounts() { LSA_OBJECT_ATTRIBUTES oa; memset(&oa, 0, sizeof(LSA_OBJECT_ATTRIBUTES)); if(LsaOpenPolicy(nullptr, &oa, POLICY_LOOKUP_NAMES, &this->lsa) != STATUS_SUCCESS) { DebugPrint(L"LsaOpenPolicy failed."); this->lsa = nullptr; return; } this->EnumerateSecurityIdentities(); } NtAccounts::~NtAccounts() { while(this->sid_list.size() != 0) { delete this->sid_list.back(); this->sid_list.pop_back(); } if(this->lsa) { LsaClose(this->lsa); } } void NtAccounts::GetUserAccounts(vector<SecurityIdentity*> & l) { l.clear(); for(auto i = this->sid_list.begin(), e = this->sid_list.end(); i != e; i++) { if((*i)->IsUser()) { l.push_back(*i); } } } void NtAccounts::GetAll(vector<SecurityIdentity*> & l) { l.clear(); l.assign(this->sid_list.begin(), this->sid_list.end()); } void NtAccounts::EnumerateSecurityIdentities() { if(!this->lsa) { DebugPrint(L"No LSA policy."); return; } while(this->sid_list.size() != 0) { delete this->sid_list.back(); this->sid_list.pop_back(); } LSTATUS reg_result; HKEY accounts; reg_result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, LR"(SECURITY\Policy\Accounts)", 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &accounts); if(reg_result != ERROR_SUCCESS) { DebugPrint(L"RegOpenKeyEx failed. 0x%08X", reg_result); LsaClose(lsa); return; } DWORD subkeys; DWORD key_name_size; FILETIME time; RegQueryInfoKeyW(accounts, nullptr, nullptr, nullptr, &subkeys, &key_name_size, nullptr, nullptr, nullptr, nullptr, nullptr, &time); wchar_t * key_name = new wchar_t[++key_name_size]; // null文字を含まない文字数なのでそれを考慮 for(DWORD i = 0; i < subkeys; i++) { memset(key_name, 0, sizeof(wchar_t) * key_name_size); DWORD key_name_size_cur = key_name_size; reg_result = RegEnumKeyExW(accounts, i, key_name, &key_name_size_cur, nullptr, nullptr, 0, &time); if(reg_result != ERROR_SUCCESS) { break; } HKEY sid_key; { wstring reg_path(key_name); reg_path.append(L"\\Sid"); reg_result = RegOpenKeyExW(accounts, reg_path.c_str(), 0, KEY_QUERY_VALUE, &sid_key); } if(reg_result != ERROR_SUCCESS) { break; } DWORD sid_s; reg_result = RegQueryValueExW(sid_key, nullptr, nullptr, nullptr, nullptr, &sid_s); if((reg_result != ERROR_SUCCESS) || (sid_s == 0)) { RegCloseKey(sid_key); break; } auto sid = new unsigned char[sid_s]; RegQueryValueExW(sid_key, nullptr, nullptr, nullptr, sid, &sid_s); RegCloseKey(sid_key); auto sid_cls = new SecurityIdentity(sid, static_cast<unsigned short>(sid_s)); this->sid_list.push_back(sid_cls); sid_cls->ResolveName(lsa); delete[] sid; } delete[] key_name; RegCloseKey(accounts); } <commit_msg>LsaOpenPolicy関数の引数に管理者権限を必要とする項目を追加<commit_after>#include "SecIdentity.hpp" #include "Util.hpp" SecurityIdentity::SecurityIdentity(const SID * sid) { SecurityIdentity(reinterpret_cast<const unsigned char*>(sid), sizeof(SID)); } SecurityIdentity::SecurityIdentity(const unsigned char * sid, unsigned short sid_size) { this->raw_sid = new unsigned char[sid_size]; this->sid_size = sid_size; this->sid_type = SID_NAME_USE::SidTypeUnknown; memcpy(this->raw_sid, sid, sid_size); } SecurityIdentity::~SecurityIdentity() { delete[] this->raw_sid; } void SecurityIdentity::HexString(wstring & s) { BinaryToString(this->raw_sid, this->sid_size, s); } void SecurityIdentity::GetName(wstring & n) { n.assign(this->name); } void SecurityIdentity::ResolveName(LSA_HANDLE lsa) { if(this->name.size() != 0) { return; } void * sidss[1]; sidss[0] = this->raw_sid; LSA_REFERENCED_DOMAIN_LIST * domains = nullptr; LSA_TRANSLATED_NAME * names = nullptr; auto lsa_result = LsaLookupSids2(lsa,LSA_LOOKUP_DISALLOW_CONNECTED_ACCOUNT_INTERNET_SID , 1, sidss, &domains, &names); if(lsa_result != STATUS_SUCCESS) { if(lsa_result == STATUS_NONE_MAPPED) { this->name.assign(L"<NONE>"); } else { wchar_t fail[32]; swprintf_s(fail, 32, L"!!FAILED 0x%08X", lsa_result); this->name.assign(fail); } if(domains) { LsaFreeMemory(domains); } if(names) { LsaFreeMemory(names); } return; } UNICODE_STRING u; switch(names->Use) { case SID_NAME_USE::SidTypeDomain: this->name.assign(L"!!THIS WAS DOMAIN SID!!"); break; case SID_NAME_USE::SidTypeInvalid: case SID_NAME_USE::SidTypeUnknown: this->name.assign(L"!!INVALID OR UNKNOWN NAME!!"); break; default: u.Buffer = names->Name.Buffer; u.Length = names->Name.Length; u.MaximumLength = names->Name.MaximumLength; this->name.assign(u.Buffer, u.Length / sizeof(wchar_t)); this->sid_type = names->Use; break; } LsaFreeMemory(domains); LsaFreeMemory(names); } NtAccounts::NtAccounts() { LSA_OBJECT_ATTRIBUTES oa; memset(&oa, 0, sizeof(LSA_OBJECT_ATTRIBUTES)); // 管理者権限がない状態でLsaOpenPolicy関数を呼び出したときのハンドルを // LsaClose関数に渡すと、LsaClose関数内部のHeapFree呼び出しで二重解放になる // そのため、POLICY_LOOKUP_NAMESを指定しているところに // 本来不要であるPOLICY_WRITEを追加して管理者権限を必要とするようにする if(LsaOpenPolicy(nullptr, &oa, POLICY_LOOKUP_NAMES | POLICY_WRITE, &this->lsa) != STATUS_SUCCESS) { DebugPrint(L"LsaOpenPolicy failed."); this->lsa = nullptr; return; } this->EnumerateSecurityIdentities(); } NtAccounts::~NtAccounts() { while(this->sid_list.size() != 0) { delete this->sid_list.back(); this->sid_list.pop_back(); } if(this->lsa) { LsaClose(this->lsa); } } void NtAccounts::GetUserAccounts(vector<SecurityIdentity*> & l) { l.clear(); for(auto i = this->sid_list.begin(), e = this->sid_list.end(); i != e; i++) { if((*i)->IsUser()) { l.push_back(*i); } } } void NtAccounts::GetAll(vector<SecurityIdentity*> & l) { l.clear(); l.assign(this->sid_list.begin(), this->sid_list.end()); } void NtAccounts::EnumerateSecurityIdentities() { if(!this->lsa) { DebugPrint(L"No LSA policy."); return; } while(this->sid_list.size() != 0) { delete this->sid_list.back(); this->sid_list.pop_back(); } LSTATUS reg_result; HKEY accounts; reg_result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, LR"(SECURITY\Policy\Accounts)", 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &accounts); if(reg_result != ERROR_SUCCESS) { DebugPrint(L"RegOpenKeyEx failed. 0x%08X", reg_result); LsaClose(lsa); return; } DWORD subkeys; DWORD key_name_size; FILETIME time; RegQueryInfoKeyW(accounts, nullptr, nullptr, nullptr, &subkeys, &key_name_size, nullptr, nullptr, nullptr, nullptr, nullptr, &time); wchar_t * key_name = new wchar_t[++key_name_size]; // null文字を含まない文字数なのでそれを考慮 for(DWORD i = 0; i < subkeys; i++) { memset(key_name, 0, sizeof(wchar_t) * key_name_size); DWORD key_name_size_cur = key_name_size; reg_result = RegEnumKeyExW(accounts, i, key_name, &key_name_size_cur, nullptr, nullptr, 0, &time); if(reg_result != ERROR_SUCCESS) { break; } HKEY sid_key; { wstring reg_path(key_name); reg_path.append(L"\\Sid"); reg_result = RegOpenKeyExW(accounts, reg_path.c_str(), 0, KEY_QUERY_VALUE, &sid_key); } if(reg_result != ERROR_SUCCESS) { break; } DWORD sid_s; reg_result = RegQueryValueExW(sid_key, nullptr, nullptr, nullptr, nullptr, &sid_s); if((reg_result != ERROR_SUCCESS) || (sid_s == 0)) { RegCloseKey(sid_key); break; } auto sid = new unsigned char[sid_s]; RegQueryValueExW(sid_key, nullptr, nullptr, nullptr, sid, &sid_s); RegCloseKey(sid_key); auto sid_cls = new SecurityIdentity(sid, static_cast<unsigned short>(sid_s)); this->sid_list.push_back(sid_cls); sid_cls->ResolveName(lsa); delete[] sid; } delete[] key_name; RegCloseKey(accounts); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <iomanip> #include <cmath> #include <string> #include <algorithm> using namespace std; double logsumexp(double x1, double x2) { if(x1 > x2) return x1 + log(1. + exp(x2 - x1)); return x2 + log(1. + exp(x1 - x2)); } int main() { // Temperatures double T1 = 0.3; double T2 = 0.3; // Normalising constant for prior weights double logC = -1E300; // Prior weights (relative) and 'likelihoods' vector<double> logw, logL; bool save = false; vector<string> directories; directories.push_back(string("mcmc_2000/8.1")); directories.push_back(string("mcmc_2000/8.2")); directories.push_back(string("mcmc_2000/8.3")); directories.push_back(string("mcmc_2000/8.4")); directories.push_back(string("mcmc_2000/8.5")); directories.push_back(string("mcmc_2000/8.6")); directories.push_back(string("mcmc_2000/8.7")); fstream fout1, fout2; if(save) { fout1.open("logw.txt", ios::out); fout2.open("scalars.txt", ios::out); } int k = 0; for(size_t i=0; i<directories.size(); i++) { string filename1 = directories[i] + string("/logw.txt"); fstream fin1(filename1.c_str(), ios::in); string filename2 = directories[i] + string("/scalars.txt"); fstream fin2(filename2.c_str(), ios::in); double temp1, temp2, temp3; while(fin1>>temp1 && fin2>>temp2 && fin2>>temp3) { if(save) { fout1<<temp1<<endl; fout2<<temp2<<' '<<temp3<<endl; } logC = logsumexp(logC, temp1); logw.push_back(temp1); logL.push_back(temp2/T1 + temp3/T2); k++; } fin1.close(); fin2.close(); cout<<"# Loaded "<<k<<" points."<<endl; } if(save) { fout1.close(); fout2.close(); } // Calculate log(Z) double logZ = -1E300; for(size_t i=0; i<logL.size(); i++) logZ = logsumexp(logZ, (logw[i] - logC) + logL[i]); // Calculate partial log(Z)s from each run double logw_max = *max_element(logw.begin(), logw.end()); vector<double> logZ_partial, logC_partial; for(size_t i=0; i<logL.size(); i++) { if(logw[i] == logw_max) { logZ_partial.push_back(-1E300); logC_partial.push_back(-1E300); } logZ_partial[logZ_partial.size() - 1] = logsumexp(logZ_partial[logZ_partial.size() - 1], logw[i] + logL[i]); logC_partial[logC_partial.size() - 1] = logsumexp(logC_partial[logC_partial.size() - 1], logw[i]); } // Normalise within each run for(size_t i=0; i<logZ_partial.size(); i++) logZ_partial[i] -= logC_partial[i]; double max = *max_element(logZ_partial.begin(), logZ_partial.end()); vector<double> Z(logZ_partial.size()); double tot = 0.; for(size_t i=0; i<logZ_partial.size(); i++) { Z[i] = exp(logZ_partial[i] - max); tot += Z[i]; } for(size_t i=0; i<logZ_partial.size(); i++) Z[i] /= tot; // Effective number of runs double ENR = 0.; for(size_t i=0; i<Z.size(); i++) ENR += -Z[i]*log(Z[i] + 1E-300); ENR = exp(ENR); cout<<"# Effective number of contributing runs = "<<ENR<<"."<<endl; // Calculate H double H = 0.; double logP; for(size_t i=0; i<logL.size(); i++) { // Posterior weight logP = logw[i] - logC + logL[i] - logZ; H += exp(logP)*logL[i]; } H -= logZ; // Output cout<<setprecision(8); cout<<"# ln(Z) = "<<logZ<<"."<<endl; cout<<"# H = "<<H<<" nats."<<endl; return 0; } <commit_msg>Print number of runs<commit_after>#include <iostream> #include <fstream> #include <vector> #include <iomanip> #include <cmath> #include <string> #include <algorithm> using namespace std; double logsumexp(double x1, double x2) { if(x1 > x2) return x1 + log(1. + exp(x2 - x1)); return x2 + log(1. + exp(x1 - x2)); } int main() { // Temperatures double T1 = 0.3; double T2 = 0.3; // Normalising constant for prior weights double logC = -1E300; // Prior weights (relative) and 'likelihoods' vector<double> logw, logL; bool save = false; vector<string> directories; directories.push_back(string("mcmc_2000/8.1")); directories.push_back(string("mcmc_2000/8.2")); directories.push_back(string("mcmc_2000/8.3")); directories.push_back(string("mcmc_2000/8.4")); directories.push_back(string("mcmc_2000/8.5")); directories.push_back(string("mcmc_2000/8.6")); directories.push_back(string("mcmc_2000/8.7")); fstream fout1, fout2; if(save) { fout1.open("logw.txt", ios::out); fout2.open("scalars.txt", ios::out); } int k = 0; for(size_t i=0; i<directories.size(); i++) { string filename1 = directories[i] + string("/logw.txt"); fstream fin1(filename1.c_str(), ios::in); string filename2 = directories[i] + string("/scalars.txt"); fstream fin2(filename2.c_str(), ios::in); double temp1, temp2, temp3; while(fin1>>temp1 && fin2>>temp2 && fin2>>temp3) { if(save) { fout1<<temp1<<endl; fout2<<temp2<<' '<<temp3<<endl; } logC = logsumexp(logC, temp1); logw.push_back(temp1); logL.push_back(temp2/T1 + temp3/T2); k++; } fin1.close(); fin2.close(); cout<<"# Loaded "<<k<<" points."<<endl; } if(save) { fout1.close(); fout2.close(); } // Calculate log(Z) double logZ = -1E300; for(size_t i=0; i<logL.size(); i++) logZ = logsumexp(logZ, (logw[i] - logC) + logL[i]); // Calculate partial log(Z)s from each run double logw_max = *max_element(logw.begin(), logw.end()); vector<double> logZ_partial, logC_partial; for(size_t i=0; i<logL.size(); i++) { if(logw[i] == logw_max) { logZ_partial.push_back(-1E300); logC_partial.push_back(-1E300); } logZ_partial[logZ_partial.size() - 1] = logsumexp(logZ_partial[logZ_partial.size() - 1], logw[i] + logL[i]); logC_partial[logC_partial.size() - 1] = logsumexp(logC_partial[logC_partial.size() - 1], logw[i]); } // Normalise within each run for(size_t i=0; i<logZ_partial.size(); i++) logZ_partial[i] -= logC_partial[i]; double max = *max_element(logZ_partial.begin(), logZ_partial.end()); vector<double> Z(logZ_partial.size()); double tot = 0.; for(size_t i=0; i<logZ_partial.size(); i++) { Z[i] = exp(logZ_partial[i] - max); tot += Z[i]; } for(size_t i=0; i<logZ_partial.size(); i++) Z[i] /= tot; // Effective number of runs double ENR = 0.; for(size_t i=0; i<Z.size(); i++) ENR += -Z[i]*log(Z[i] + 1E-300); ENR = exp(ENR); cout<<"# Number of runs = "<<Z.size()<<"."<<endl; cout<<"# Effective number of contributing runs = "<<ENR<<"."<<endl; // Calculate H double H = 0.; double logP; for(size_t i=0; i<logL.size(); i++) { // Posterior weight logP = logw[i] - logC + logL[i] - logZ; H += exp(logP)*logL[i]; } H -= logZ; // Output cout<<setprecision(8); cout<<"# ln(Z) = "<<logZ<<"."<<endl; cout<<"# H = "<<H<<" nats."<<endl; return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "amr_forestclaw.H" #include "amr_waveprop.H" #include "swirl_user.H" #ifdef __cplusplus extern "C" { #if 0 } #endif #endif void swirl_link_solvers(fclaw2d_domain_t *domain) { fclaw2d_solver_functions_t* sf = get_solver_functions(domain); sf->use_single_step_update = fclaw_true; sf->use_mol_update = fclaw_false; sf->f_patch_setup = &swirl_patch_setup; sf->f_patch_initialize = &swirl_patch_initialize; sf->f_patch_physical_bc = &swirl_patch_physical_bc; sf->f_patch_single_step_update = &swirl_patch_single_step_update; amr_waveprop_link_to_clawpatch(); } void swirl_problem_setup(fclaw2d_domain_t* domain) { /* Setup any fortran common blocks for general problem and any other general problem specific things that only needs to be done once. */ amr_waveprop_setprob(domain); } void swirl_patch_setup(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx) { /* Set velocity data */ amr_waveprop_setaux(domain,this_patch,this_block_idx,this_patch_idx); /* Set up diffusion coefficients? Read in velocity data? Material properties? */ } void swirl_patch_initialize(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx) { amr_waveprop_qinit(domain,this_patch,this_block_idx,this_patch_idx); } void swirl_patch_physical_bc(fclaw2d_domain *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, double t, double dt, fclaw_bool intersects_bc[]) { amr_waveprop_bc2(domain,this_patch,this_block_idx,this_patch_idx, t,dt,intersects_bc); } double swirl_patch_single_step_update(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, double t, double dt) { amr_waveprop_b4step2(domain,this_patch,this_block_idx,this_patch_idx,t,dt); double maxcfl = amr_waveprop_step2(domain,this_patch,this_block_idx, this_patch_idx,t,dt); return maxcfl; } /* ----------------------------------------------------------------- Default routine for tagging patches for refinement and coarsening ----------------------------------------------------------------- */ fclaw_bool swirl_patch_tag4refinement(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, int initflag) { /* ----------------------------------------------------------- */ // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; /* ----------------------------------------------------------- */ // Patch specific parameters ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); /* ------------------------------------------------------------ */ // Pointers needed to pass to Fortran double* q = cp->q(); int tag_patch = 0; swirl_tag4refinement_(mx,my,mbc,meqn,xlower,ylower,dx,dy,q,initflag,tag_patch); return tag_patch == 1; } fclaw_bool swirl_patch_tag4coarsening(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int blockno, int patchno) { /* ----------------------------------------------------------- */ // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; /* ----------------------------------------------------------- */ // Patch specific parameters ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); /* ------------------------------------------------------------ */ // Pointers needed to pass to Fortran double* qcoarse = cp->q(); int tag_patch = 1; // == 0 or 1 swirl_tag4coarsening_(mx,my,mbc,meqn,xlower,ylower,dx,dy,qcoarse,tag_patch); return tag_patch == 0; } #ifdef __cplusplus #if 0 { #endif } #endif <commit_msg>Removed extern C statements.<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "amr_forestclaw.H" #include "amr_waveprop.H" #include "swirl_user.H" void swirl_link_solvers(fclaw2d_domain_t *domain) { fclaw2d_solver_functions_t* sf = get_solver_functions(domain); sf->use_single_step_update = fclaw_true; sf->use_mol_update = fclaw_false; sf->f_patch_setup = &swirl_patch_setup; sf->f_patch_initialize = &swirl_patch_initialize; sf->f_patch_physical_bc = &swirl_patch_physical_bc; sf->f_patch_single_step_update = &swirl_patch_single_step_update; amr_waveprop_link_to_clawpatch(); } void swirl_problem_setup(fclaw2d_domain_t* domain) { /* Setup any fortran common blocks for general problem and any other general problem specific things that only needs to be done once. */ amr_waveprop_setprob(domain); } void swirl_patch_setup(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx) { /* Set velocity data */ amr_waveprop_setaux(domain,this_patch,this_block_idx,this_patch_idx); /* Set up diffusion coefficients? Read in velocity data? Material properties? */ } void swirl_patch_initialize(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx) { amr_waveprop_qinit(domain,this_patch,this_block_idx,this_patch_idx); } void swirl_patch_physical_bc(fclaw2d_domain *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, double t, double dt, fclaw_bool intersects_bc[]) { amr_waveprop_bc2(domain,this_patch,this_block_idx,this_patch_idx, t,dt,intersects_bc); } double swirl_patch_single_step_update(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, double t, double dt) { amr_waveprop_b4step2(domain,this_patch,this_block_idx,this_patch_idx,t,dt); double maxcfl = amr_waveprop_step2(domain,this_patch,this_block_idx, this_patch_idx,t,dt); return maxcfl; } /* ----------------------------------------------------------------- Default routine for tagging patches for refinement and coarsening ----------------------------------------------------------------- */ fclaw_bool swirl_patch_tag4refinement(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, int initflag) { /* ----------------------------------------------------------- */ // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; /* ----------------------------------------------------------- */ // Patch specific parameters ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); /* ------------------------------------------------------------ */ // Pointers needed to pass to Fortran double* q = cp->q(); int tag_patch = 0; swirl_tag4refinement_(mx,my,mbc,meqn,xlower,ylower,dx,dy,q,initflag,tag_patch); return tag_patch == 1; } fclaw_bool swirl_patch_tag4coarsening(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int blockno, int patchno) { /* ----------------------------------------------------------- */ // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; /* ----------------------------------------------------------- */ // Patch specific parameters ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); /* ------------------------------------------------------------ */ // Pointers needed to pass to Fortran double* qcoarse = cp->q(); int tag_patch = 1; // == 0 or 1 swirl_tag4coarsening_(mx,my,mbc,meqn,xlower,ylower,dx,dy,qcoarse,tag_patch); return tag_patch == 0; } <|endoftext|>
<commit_before> #include <Grappa.hpp> #include <ParallelLoop.hpp> #include <GlobalVector.hpp> #include <Array.hpp> using namespace Grappa; DEFINE_uint64(log_vertices, 8, "log2(total number of vertices)"); #define NUM_VERTICES (1L << FLAGS_log_vertices) DEFINE_uint64(max_children, -1, "max number of children"); DEFINE_uint64(max_color, 10, "'colors' will be in the range [0, max_color)"); DEFINE_uint64(search_color, 0, "which 'color' to look for"); #include <random> long next_random(long max) { static std::default_random_engine e(12345L*mycore()); static std::uniform_int_distribution<int64_t> dist(0, 1L << 48); return dist(e) % max; } inline long random_num_children() { if (FLAGS_max_children == -1) FLAGS_max_children = NUM_VERTICES / 4; return next_random(FLAGS_max_children); } inline long random_color() { return next_random(FLAGS_max_color); } //////////////////////////// // Types using index_t = uint64_t; class Vertex; //////////////////////////// // Globals GlobalAddress<Vertex> vertex_array; GlobalAddress<index_t> counter; GlobalAddress<GlobalVector<index_t>> results; struct Vertex { index_t id; index_t num_children; index_t first_child; long color; void init(index_t index) { id = index; color = random_color(); num_children = random_num_children(); first_child = delegate::fetch_and_add(counter, num_children); if (first_child >= NUM_VERTICES) { num_children = 0; } else if (first_child + num_children > NUM_VERTICES) { num_children = NUM_VERTICES - first_child; } forall_public_async(first_child, num_children, [](index_t i){ Vertex child; child.init(i); delegate::write(vertex_array+i, child); }); } void print(int depth = 0) { std::stringstream s; for (int i=0; i<depth; i++) s << " "; if (num_children == 0) { LOG(INFO) << s.str() << "node(id: " << id << ")"; } else { LOG(INFO) << s.str() << "node(id: " << id << ", first_child: " << first_child << ", num_children: " << num_children << ""; for (int i=0; i<num_children; i++) { Vertex v = delegate::read(vertex_array+first_child+i); v.print(depth+1); } LOG(INFO) << s.str() << ")"; } } }; void create_tree() { auto _vertex_array = global_alloc<Vertex>(NUM_VERTICES); auto child_count = make_global(new index_t[1]); delegate::write(child_count, 1); on_all_cores([child_count, _vertex_array]{ counter = child_count; vertex_array = _vertex_array; }); auto root = vertex_array+0; Vertex v; v.init(0); delegate::write(root, v); default_gce().wait(); } void search(index_t vertex_index, long color, bool should_wait = true) { Vertex v = delegate::read(vertex_array + vertex_index); if (v.color == color) { results->push(v.id); } // search children forall_public_async(v.first_child, v.num_children, [color](index_t i){ search(i, color, false); }); if (should_wait) default_gce().wait(); } int main( int argc, char * argv[] ) { init( &argc, &argv ); run( [] { create_tree(); index_t root = 0; delegate::read(vertex_array+root).print(); auto results_vector = GlobalVector<index_t>::create(NUM_VERTICES); on_all_cores([results_vector]{ results = results_vector; }); search(root, FLAGS_search_color); // print results size_t n = std::max(results->size(), (size_t)10); LOG(INFO) << util::array_str("results", results->begin(), n); } ); finalize(); return 0; } <commit_msg>fix tree search, less recursiion<commit_after> #include <Grappa.hpp> #include <ParallelLoop.hpp> #include <GlobalVector.hpp> #include <Array.hpp> using namespace Grappa; DEFINE_uint64(log_vertices, 8, "log2(total number of vertices)"); #define NUM_VERTICES (1L << FLAGS_log_vertices) DEFINE_uint64(max_children, -1, "max number of children"); DEFINE_uint64(max_color, 10, "'colors' will be in the range [0, max_color)"); DEFINE_uint64(search_color, 0, "which 'color' to look for"); #include <random> long next_random(long max) { static std::default_random_engine e(12345L*mycore()); static std::uniform_int_distribution<int64_t> dist(0, 1L << 48); return dist(e) % max; } inline long random_num_children() { if (FLAGS_max_children == -1) FLAGS_max_children = NUM_VERTICES / 4; return next_random(FLAGS_max_children); } inline long random_color() { return next_random(FLAGS_max_color); } //////////////////////////// // Types using index_t = uint64_t; class Vertex; //////////////////////////// // Globals GlobalAddress< Vertex > vertex_array; GlobalAddress< index_t > counter; GlobalAddress< GlobalVector<index_t> > results; struct Vertex { index_t id; index_t num_children; index_t first_child; long color; void init(index_t index) { id = index; color = random_color(); num_children = random_num_children(); first_child = delegate::fetch_and_add(counter, num_children); if (first_child >= NUM_VERTICES) { num_children = 0; } else if (first_child + num_children > NUM_VERTICES) { num_children = NUM_VERTICES - first_child; } forall_public_async(first_child, num_children, [](index_t i){ Vertex child; child.init(i); delegate::write(vertex_array+i, child); }); } }; void create_tree() { auto _vertex_array = global_alloc<Vertex>(NUM_VERTICES); auto vertex_count = make_global(new index_t[1]); delegate::write(vertex_count, 1); on_all_cores([vertex_count, _vertex_array]{ counter = vertex_count; vertex_array = _vertex_array; }); auto root = vertex_array+0; Vertex v; v.init(0); delegate::write(root, v); default_gce().wait(); } void search(index_t vertex_index, long color) { Vertex v = delegate::read(vertex_array + vertex_index); if (v.color == color) { results->push(v.id); } // search children forall_public_async(v.first_child, v.num_children, [color](index_t i){ search(i, color); }); } int main( int argc, char * argv[] ) { init( &argc, &argv ); run( [] { create_tree(); auto results_vector = GlobalVector<index_t>::create(NUM_VERTICES); on_all_cores([results_vector]{ results = results_vector; }); { index_t root = 0; search(root, FLAGS_search_color); default_gce().wait(); } // print first 10 results LOG(INFO) << util::array_str("results", results->begin(), std::max(results->size(), (size_t)10)); } ); finalize(); return 0; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006-2007 by Rajko Albrecht * * ral@alwins-world.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "svnqt/repositorydata.hpp" #include "svnqt/svnqt_defines.hpp" #include "svnqt/exception.hpp" #include "svnqt/repositorylistener.hpp" #include "svnqt/svnfilestream.hpp" #include <svn_fs.h> #include <svn_path.h> #include <svn_config.h> namespace svn { namespace repository { class RepoOutStream:public stream::SvnStream { public: RepoOutStream(RepositoryData*); virtual ~RepoOutStream(){} virtual bool isOk()const{return true;} virtual long write(const char*data,const unsigned long max); protected: RepositoryData*m_Back; }; RepoOutStream::RepoOutStream(RepositoryData*aBack) : SvnStream(false,true) { m_Back = aBack; } long RepoOutStream::write(const char*data,const unsigned long max) { if (m_Back) { QString msg = QString::FROMUTF8(data,max); m_Back->reposFsWarning(msg); } return max; } RepositoryData::RepositoryData(RepositoryListener*aListener) { m_Repository = 0; m_Listener = aListener; } RepositoryData::~RepositoryData() { } void RepositoryData::warning_func(void *baton, svn_error_t *err) { RepositoryData*_r = (RepositoryData*)baton; if (_r) { QString msg = svn::Exception::error2msg(err); svn_error_clear(err); _r->reposFsWarning(msg); } } void RepositoryData::reposFsWarning(const QString&msg) { if (m_Listener) { m_Listener->sendWarning(msg); } } svn_error_t*RepositoryData::cancel_func(void*baton) { RepositoryListener*m_L = (RepositoryListener*)baton; if (m_L && m_L->isCanceld()) { return svn_error_create (SVN_ERR_CANCELLED, 0, QString::FROMUTF8("Cancelled by user.").TOUTF8()); } return SVN_NO_ERROR; } /*! \fn svn::RepositoryData::close() */ void RepositoryData::Close() { m_Pool.renew(); m_Repository = 0; } /*! \fn svn::RepositoryData::Open(const QString&) */ svn_error_t * RepositoryData::Open(const QString&path) { Close(); svn_error_t * error = svn_repos_open(&m_Repository,path.TOUTF8(),m_Pool); if (error!=0L) { m_Repository=0; return error; } svn_fs_set_warning_func(svn_repos_fs(m_Repository), RepositoryData::warning_func, this); return SVN_NO_ERROR; } /*! \fn svn::RepositoryData::CreateOpen(const QString&path, const QString&fstype, bool _bdbnosync = false, bool _bdbautologremove = true, bool nosvn1diff=false) */ svn_error_t * RepositoryData::CreateOpen(const QString&path, const QString&fstype, bool _bdbnosync, bool _bdbautologremove, bool _pre_1_4_compat, bool _pre_1_5_compat) { Close(); const char* _type; if (fstype.toLower()=="bdb") { _type="bdb"; } else { _type="fsfs"; } apr_hash_t *config; apr_hash_t *fs_config = apr_hash_make(m_Pool); apr_hash_set(fs_config, SVN_FS_CONFIG_BDB_TXN_NOSYNC, APR_HASH_KEY_STRING, (_bdbnosync ? "1" : "0")); apr_hash_set(fs_config, SVN_FS_CONFIG_BDB_LOG_AUTOREMOVE, APR_HASH_KEY_STRING, (_bdbautologremove ? "1" : "0")); apr_hash_set(fs_config, SVN_FS_CONFIG_FS_TYPE, APR_HASH_KEY_STRING, _type); #if ((SVN_VER_MAJOR == 1) && (SVN_VER_MINOR >= 4) || SVN_VER_MAJOR>1) if (_pre_1_4_compat) { //qDebug("Pre 14"); apr_hash_set(fs_config, SVN_FS_CONFIG_PRE_1_4_COMPATIBLE, APR_HASH_KEY_STRING,"1"); } #else Q_UNUSED(_pre_1_4_compat); #endif #if ((SVN_VER_MAJOR == 1) && (SVN_VER_MINOR >= 5) || SVN_VER_MAJOR>1) if (_pre_1_5_compat) { //qDebug("Pre 15"); apr_hash_set(fs_config, SVN_FS_CONFIG_PRE_1_5_COMPATIBLE, APR_HASH_KEY_STRING,"1"); } #else Q_UNUSED(_pre_1_5_compat); #endif /// @todo config as extra paramter? Meanwhile default config only /// (see svn::ContextData) SVN_ERR(svn_config_get_config(&config, 0, m_Pool)); const char*repository_path = apr_pstrdup (m_Pool,path.TOUTF8()); repository_path = svn_path_internal_style(repository_path, m_Pool); if (svn_path_is_url(repository_path)) { return svn_error_createf(SVN_ERR_CL_ARG_PARSING_ERROR, NULL, "'%s' is an URL when it should be a path",repository_path); } SVN_ERR(svn_repos_create(&m_Repository, repository_path, NULL, NULL,config, fs_config,m_Pool)); svn_fs_set_warning_func(svn_repos_fs(m_Repository), RepositoryData::warning_func, this); return SVN_NO_ERROR; } /*! \fn svn::RepositoryData::dump(const QString&output,const svn::Revision&start,const svn::Revision&end, bool incremental, bool use_deltas) */ svn_error_t* RepositoryData::dump(const QString&output,const svn::Revision&start,const svn::Revision&end, bool incremental, bool use_deltas) { if (!m_Repository) { return svn_error_create(SVN_ERR_CANCELLED,0,"No repository selected."); } Pool pool; svn::stream::SvnFileOStream out(output); RepoOutStream backstream(this); svn_revnum_t _s,_e; _s = start.revnum(); _e = end.revnum(); SVN_ERR(svn_repos_dump_fs2(m_Repository,out,backstream,_s,_e,incremental,use_deltas, RepositoryData::cancel_func,m_Listener,pool)); return SVN_NO_ERROR; } svn_error_t* RepositoryData::loaddump(const QString&dump,svn_repos_load_uuid uuida, const QString&parentFolder, bool usePre, bool usePost) { if (!m_Repository) { return svn_error_create(SVN_ERR_CANCELLED,0,"No repository selected."); } svn::stream::SvnFileIStream infile(dump); RepoOutStream backstream(this); Pool pool; const char*src_path = apr_pstrdup (pool,dump.TOUTF8()); const char*dest_path; if (parentFolder.isEmpty()) { dest_path=0; } else { dest_path=apr_pstrdup (pool,parentFolder.TOUTF8()); } src_path = svn_path_internal_style(src_path, pool); SVN_ERR(svn_repos_load_fs2(m_Repository,infile,backstream,uuida,dest_path,usePre?1:0,usePost?1:0,RepositoryData::cancel_func,m_Listener,pool)); return SVN_NO_ERROR; } svn_error_t* RepositoryData::hotcopy(const QString&src,const QString&dest,bool cleanlogs) { Pool pool; const char*src_path = apr_pstrdup (pool,src.TOUTF8()); const char*dest_path = apr_pstrdup (pool,dest.TOUTF8()); src_path = svn_path_internal_style(src_path, pool); dest_path = svn_path_internal_style(dest_path, pool); SVN_ERR(svn_repos_hotcopy(src_path,dest_path,cleanlogs?1:0,pool)); return SVN_NO_ERROR; } } } <commit_msg>fix a small visibility error in svnqt library<commit_after>/*************************************************************************** * Copyright (C) 2006-2007 by Rajko Albrecht * * ral@alwins-world.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "svnqt/repositorydata.hpp" #include "svnqt/svnqt_defines.hpp" #include "svnqt/exception.hpp" #include "svnqt/repositorylistener.hpp" #include "svnqt/svnfilestream.hpp" #include <svn_fs.h> #include <svn_path.h> #include <svn_config.h> namespace svn { namespace repository { class SVNQT_NOEXPORT RepoOutStream:public stream::SvnStream { public: RepoOutStream(RepositoryData*); virtual ~RepoOutStream(){} virtual bool isOk()const{return true;} virtual long write(const char*data,const unsigned long max); protected: RepositoryData*m_Back; }; RepoOutStream::RepoOutStream(RepositoryData*aBack) : SvnStream(false,true) { m_Back = aBack; } long RepoOutStream::write(const char*data,const unsigned long max) { if (m_Back) { QString msg = QString::FROMUTF8(data,max); m_Back->reposFsWarning(msg); } return max; } RepositoryData::RepositoryData(RepositoryListener*aListener) { m_Repository = 0; m_Listener = aListener; } RepositoryData::~RepositoryData() { } void RepositoryData::warning_func(void *baton, svn_error_t *err) { RepositoryData*_r = (RepositoryData*)baton; if (_r) { QString msg = svn::Exception::error2msg(err); svn_error_clear(err); _r->reposFsWarning(msg); } } void RepositoryData::reposFsWarning(const QString&msg) { if (m_Listener) { m_Listener->sendWarning(msg); } } svn_error_t*RepositoryData::cancel_func(void*baton) { RepositoryListener*m_L = (RepositoryListener*)baton; if (m_L && m_L->isCanceld()) { return svn_error_create (SVN_ERR_CANCELLED, 0, QString::FROMUTF8("Cancelled by user.").TOUTF8()); } return SVN_NO_ERROR; } /*! \fn svn::RepositoryData::close() */ void RepositoryData::Close() { m_Pool.renew(); m_Repository = 0; } /*! \fn svn::RepositoryData::Open(const QString&) */ svn_error_t * RepositoryData::Open(const QString&path) { Close(); svn_error_t * error = svn_repos_open(&m_Repository,path.TOUTF8(),m_Pool); if (error!=0L) { m_Repository=0; return error; } svn_fs_set_warning_func(svn_repos_fs(m_Repository), RepositoryData::warning_func, this); return SVN_NO_ERROR; } /*! \fn svn::RepositoryData::CreateOpen(const QString&path, const QString&fstype, bool _bdbnosync = false, bool _bdbautologremove = true, bool nosvn1diff=false) */ svn_error_t * RepositoryData::CreateOpen(const QString&path, const QString&fstype, bool _bdbnosync, bool _bdbautologremove, bool _pre_1_4_compat, bool _pre_1_5_compat) { Close(); const char* _type; if (fstype.toLower()=="bdb") { _type="bdb"; } else { _type="fsfs"; } apr_hash_t *config; apr_hash_t *fs_config = apr_hash_make(m_Pool); apr_hash_set(fs_config, SVN_FS_CONFIG_BDB_TXN_NOSYNC, APR_HASH_KEY_STRING, (_bdbnosync ? "1" : "0")); apr_hash_set(fs_config, SVN_FS_CONFIG_BDB_LOG_AUTOREMOVE, APR_HASH_KEY_STRING, (_bdbautologremove ? "1" : "0")); apr_hash_set(fs_config, SVN_FS_CONFIG_FS_TYPE, APR_HASH_KEY_STRING, _type); #if ((SVN_VER_MAJOR == 1) && (SVN_VER_MINOR >= 4) || SVN_VER_MAJOR>1) if (_pre_1_4_compat) { //qDebug("Pre 14"); apr_hash_set(fs_config, SVN_FS_CONFIG_PRE_1_4_COMPATIBLE, APR_HASH_KEY_STRING,"1"); } #else Q_UNUSED(_pre_1_4_compat); #endif #if ((SVN_VER_MAJOR == 1) && (SVN_VER_MINOR >= 5) || SVN_VER_MAJOR>1) if (_pre_1_5_compat) { //qDebug("Pre 15"); apr_hash_set(fs_config, SVN_FS_CONFIG_PRE_1_5_COMPATIBLE, APR_HASH_KEY_STRING,"1"); } #else Q_UNUSED(_pre_1_5_compat); #endif /// @todo config as extra paramter? Meanwhile default config only /// (see svn::ContextData) SVN_ERR(svn_config_get_config(&config, 0, m_Pool)); const char*repository_path = apr_pstrdup (m_Pool,path.TOUTF8()); repository_path = svn_path_internal_style(repository_path, m_Pool); if (svn_path_is_url(repository_path)) { return svn_error_createf(SVN_ERR_CL_ARG_PARSING_ERROR, NULL, "'%s' is an URL when it should be a path",repository_path); } SVN_ERR(svn_repos_create(&m_Repository, repository_path, NULL, NULL,config, fs_config,m_Pool)); svn_fs_set_warning_func(svn_repos_fs(m_Repository), RepositoryData::warning_func, this); return SVN_NO_ERROR; } /*! \fn svn::RepositoryData::dump(const QString&output,const svn::Revision&start,const svn::Revision&end, bool incremental, bool use_deltas) */ svn_error_t* RepositoryData::dump(const QString&output,const svn::Revision&start,const svn::Revision&end, bool incremental, bool use_deltas) { if (!m_Repository) { return svn_error_create(SVN_ERR_CANCELLED,0,"No repository selected."); } Pool pool; svn::stream::SvnFileOStream out(output); RepoOutStream backstream(this); svn_revnum_t _s,_e; _s = start.revnum(); _e = end.revnum(); SVN_ERR(svn_repos_dump_fs2(m_Repository,out,backstream,_s,_e,incremental,use_deltas, RepositoryData::cancel_func,m_Listener,pool)); return SVN_NO_ERROR; } svn_error_t* RepositoryData::loaddump(const QString&dump,svn_repos_load_uuid uuida, const QString&parentFolder, bool usePre, bool usePost) { if (!m_Repository) { return svn_error_create(SVN_ERR_CANCELLED,0,"No repository selected."); } svn::stream::SvnFileIStream infile(dump); RepoOutStream backstream(this); Pool pool; const char*src_path = apr_pstrdup (pool,dump.TOUTF8()); const char*dest_path; if (parentFolder.isEmpty()) { dest_path=0; } else { dest_path=apr_pstrdup (pool,parentFolder.TOUTF8()); } src_path = svn_path_internal_style(src_path, pool); SVN_ERR(svn_repos_load_fs2(m_Repository,infile,backstream,uuida,dest_path,usePre?1:0,usePost?1:0,RepositoryData::cancel_func,m_Listener,pool)); return SVN_NO_ERROR; } svn_error_t* RepositoryData::hotcopy(const QString&src,const QString&dest,bool cleanlogs) { Pool pool; const char*src_path = apr_pstrdup (pool,src.TOUTF8()); const char*dest_path = apr_pstrdup (pool,dest.TOUTF8()); src_path = svn_path_internal_style(src_path, pool); dest_path = svn_path_internal_style(dest_path, pool); SVN_ERR(svn_repos_hotcopy(src_path,dest_path,cleanlogs?1:0,pool)); return SVN_NO_ERROR; } } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com) * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/filters/ScalingFilter.hpp> #include <pdal/Dimension.hpp> #include <pdal/Schema.hpp> #include <pdal/exceptions.hpp> #include <pdal/PointBuffer.hpp> #include <pdal/filters/ScalingFilterIterator.hpp> namespace pdal { namespace filters { ScalingFilter::ScalingFilter(const Stage& prevStage, bool forward) : Filter(prevStage, Options::none()) , m_customScaleOffset(false) , m_scaleX(0.0) , m_scaleY(0.0) , m_scaleZ(0.0) , m_offsetX(0.0) , m_offsetY(0.0) , m_offsetZ(0.0) , m_forward(forward) { checkImpedance(); initialize(); return; } ScalingFilter::ScalingFilter(const Stage& prevStage, double scaleX, double offsetX, double scaleY, double offsetY, double scaleZ, double offsetZ, bool forward) : Filter(prevStage, Options::none()) , m_customScaleOffset(true) , m_scaleX(scaleX) , m_scaleY(scaleY) , m_scaleZ(scaleZ) , m_offsetX(offsetX) , m_offsetY(offsetY) , m_offsetZ(offsetZ) , m_forward(forward) { checkImpedance(); initialize(); return; } void ScalingFilter::checkImpedance() { Schema& schema = this->getSchemaRef(); if (m_forward) { // doubles --> ints const int indexXd = schema.getDimensionIndex(Dimension::Field_X, Dimension::Double); const int indexYd = schema.getDimensionIndex(Dimension::Field_Y, Dimension::Double); const int indexZd = schema.getDimensionIndex(Dimension::Field_Z, Dimension::Double); const Dimension dimXd = schema.getDimension(indexXd); const Dimension dimYd = schema.getDimension(indexYd); const Dimension dimZd = schema.getDimension(indexZd); Dimension dimXi(Dimension::Field_X, Dimension::Int32); Dimension dimYi(Dimension::Field_Y, Dimension::Int32); Dimension dimZi(Dimension::Field_Z, Dimension::Int32); if (!schema.hasDimension(dimXd) || !schema.hasDimension(dimYd) || !schema.hasDimension(dimZd)) { throw impedance_invalid("Scaling filter requires X,Y,Z dimensions as doubles (forward direction)"); } if (schema.hasDimension(dimXi) || schema.hasDimension(dimYi) || schema.hasDimension(dimZi)) { throw impedance_invalid("Scaling filter requires X,Y,Z dimensions as ints not be initially present (forward direction)"); } schema.removeDimension(dimXd); schema.removeDimension(dimYd); schema.removeDimension(dimZd); if (m_customScaleOffset) { dimXi.setNumericScale(m_scaleX); dimXi.setNumericOffset(m_offsetX); dimYi.setNumericScale(m_scaleY); dimYi.setNumericOffset(m_offsetY); dimZi.setNumericScale(m_scaleZ); dimZi.setNumericOffset(m_offsetZ); } else { dimXi.setNumericScale(dimXd.getNumericScale()); dimXi.setNumericOffset(dimXd.getNumericOffset()); dimYi.setNumericScale(dimYd.getNumericScale()); dimYi.setNumericOffset(dimYd.getNumericOffset()); dimZi.setNumericScale(dimZd.getNumericScale()); dimZi.setNumericOffset(dimZd.getNumericOffset()); } schema.addDimension(dimXi); schema.addDimension(dimYi); schema.addDimension(dimZi); } else { const int indexXi = schema.getDimensionIndex(Dimension::Field_X, Dimension::Int32); const int indexYi = schema.getDimensionIndex(Dimension::Field_Y, Dimension::Int32); const int indexZi = schema.getDimensionIndex(Dimension::Field_Z, Dimension::Int32); const Dimension dimXi = schema.getDimension(indexXi); const Dimension dimYi = schema.getDimension(indexYi); const Dimension dimZi = schema.getDimension(indexZi); Dimension dimXd(Dimension::Field_X, Dimension::Double); Dimension dimYd(Dimension::Field_Y, Dimension::Double); Dimension dimZd(Dimension::Field_Z, Dimension::Double); // ints --> doubles if (!schema.hasDimension(dimXi) || !schema.hasDimension(dimYi) || !schema.hasDimension(dimZi)) { throw impedance_invalid("Scaling filter requires X,Y,Z dimensions as int32s (reverse direction)"); } if (schema.hasDimension(dimXd) || schema.hasDimension(dimYd) || schema.hasDimension(dimZd)) { throw impedance_invalid("Scaling filter requires X,Y,Z dimensions as int32s not be initially present (reverse direction)"); } if (m_customScaleOffset) { dimXd.setNumericScale(m_scaleX); dimXd.setNumericOffset(m_offsetX); dimYd.setNumericScale(m_scaleY); dimYd.setNumericOffset(m_offsetY); dimZd.setNumericScale(m_scaleZ); dimZd.setNumericOffset(m_offsetZ); } else { dimXd.setNumericScale(dimXi.getNumericScale()); dimXd.setNumericOffset(dimXi.getNumericOffset()); dimYd.setNumericScale(dimYi.getNumericScale()); dimYd.setNumericOffset(dimYi.getNumericOffset()); dimZd.setNumericScale(dimZi.getNumericScale()); dimZd.setNumericOffset(dimZi.getNumericOffset()); } schema.removeDimension(dimXi); schema.removeDimension(dimYi); schema.removeDimension(dimZi); schema.addDimension(dimXd); schema.addDimension(dimYd); schema.addDimension(dimZd); } return; } void ScalingFilter::initialize() { return; } const std::string& ScalingFilter::getDescription() const { static std::string name("Scaling Filter"); return name; } const std::string& ScalingFilter::getName() const { static std::string name("filters.scaling"); return name; } void ScalingFilter::processBuffer(const PointBuffer& srcData, PointBuffer& dstData) const { const boost::uint32_t numPoints = srcData.getNumPoints(); const SchemaLayout& srcSchemaLayout = srcData.getSchemaLayout(); const Schema& srcSchema = srcSchemaLayout.getSchema(); const SchemaLayout& dstSchemaLayout = dstData.getSchemaLayout(); const Schema& dstSchema = dstSchemaLayout.getSchema(); // rather than think about "src/dst", we will think in terms of "doubles" and "ints" const Schema& schemaD = (m_forward ? srcSchema : dstSchema); const Schema& schemaI = (m_forward ? dstSchema : srcSchema); assert(schemaD.hasDimension(Dimension::Field_X, Dimension::Double)); assert(schemaI.hasDimension(Dimension::Field_X, Dimension::Int32)); const int indexXd = schemaD.getDimensionIndex(Dimension::Field_X, Dimension::Double); const int indexYd = schemaD.getDimensionIndex(Dimension::Field_Y, Dimension::Double); const int indexZd = schemaD.getDimensionIndex(Dimension::Field_Z, Dimension::Double); const int indexXi = schemaI.getDimensionIndex(Dimension::Field_X, Dimension::Int32); const int indexYi = schemaI.getDimensionIndex(Dimension::Field_Y, Dimension::Int32); const int indexZi = schemaI.getDimensionIndex(Dimension::Field_Z, Dimension::Int32); const Dimension& dimXd = schemaD.getDimension(indexXd); const Dimension& dimYd = schemaD.getDimension(indexYd); const Dimension& dimZd = schemaD.getDimension(indexZd); const Dimension& dimXi = schemaI.getDimension(indexXi); const Dimension& dimYi = schemaI.getDimension(indexYi); const Dimension& dimZi = schemaI.getDimension(indexZi); for (boost::uint32_t pointIndex=0; pointIndex<numPoints; pointIndex++) { if (m_forward) { // doubles --> ints (removeScaling) const double xd = srcData.getField<double>(pointIndex, indexXd); const double yd = srcData.getField<double>(pointIndex, indexYd); const double zd = srcData.getField<double>(pointIndex, indexZd); const boost::int32_t xi = dimXi.removeScaling<boost::int32_t>(xd); const boost::int32_t yi = dimYi.removeScaling<boost::int32_t>(yd); const boost::int32_t zi = dimZi.removeScaling<boost::int32_t>(zd); dstData.setField<boost::int32_t>(pointIndex, indexXi, xi); dstData.setField<boost::int32_t>(pointIndex, indexYi, yi); dstData.setField<boost::int32_t>(pointIndex, indexZi, zi); } else { // ints --> doubles (applyScaling) const boost::int32_t xi = srcData.getField<boost::int32_t>(pointIndex, indexXi); const boost::int32_t yi = srcData.getField<boost::int32_t>(pointIndex, indexYi); const boost::int32_t zi = srcData.getField<boost::int32_t>(pointIndex, indexZi); const double xd = dimXd.applyScaling(xi); const double yd = dimYd.applyScaling(yi); const double zd = dimZd.applyScaling(zi); dstData.setField<double>(pointIndex, indexXd, xd); dstData.setField<double>(pointIndex, indexYd, yd); dstData.setField<double>(pointIndex, indexZd, zd); } dstData.setNumPoints(pointIndex+1); } return; } pdal::StageSequentialIterator* ScalingFilter::createSequentialIterator() const { return new ScalingFilterSequentialIterator(*this); } } } // namespaces <commit_msg>start on raw field copying -- doesn't work yet though<commit_after>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com) * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/filters/ScalingFilter.hpp> #include <pdal/Dimension.hpp> #include <pdal/Schema.hpp> #include <pdal/SchemaLayout.hpp> #include <pdal/exceptions.hpp> #include <pdal/PointBuffer.hpp> #include <pdal/filters/ScalingFilterIterator.hpp> #include <iostream> namespace pdal { namespace filters { ScalingFilter::ScalingFilter(const Stage& prevStage, bool forward) : Filter(prevStage, Options::none()) , m_customScaleOffset(false) , m_scaleX(0.0) , m_scaleY(0.0) , m_scaleZ(0.0) , m_offsetX(0.0) , m_offsetY(0.0) , m_offsetZ(0.0) , m_forward(forward) { checkImpedance(); initialize(); return; } ScalingFilter::ScalingFilter(const Stage& prevStage, double scaleX, double offsetX, double scaleY, double offsetY, double scaleZ, double offsetZ, bool forward) : Filter(prevStage, Options::none()) , m_customScaleOffset(true) , m_scaleX(scaleX) , m_scaleY(scaleY) , m_scaleZ(scaleZ) , m_offsetX(offsetX) , m_offsetY(offsetY) , m_offsetZ(offsetZ) , m_forward(forward) { checkImpedance(); initialize(); return; } void ScalingFilter::checkImpedance() { Schema& schema = this->getSchemaRef(); if (m_forward) { // doubles --> ints const int indexXd = schema.getDimensionIndex(Dimension::Field_X, Dimension::Double); const int indexYd = schema.getDimensionIndex(Dimension::Field_Y, Dimension::Double); const int indexZd = schema.getDimensionIndex(Dimension::Field_Z, Dimension::Double); const Dimension dimXd = schema.getDimension(indexXd); const Dimension dimYd = schema.getDimension(indexYd); const Dimension dimZd = schema.getDimension(indexZd); Dimension dimXi(Dimension::Field_X, Dimension::Int32); Dimension dimYi(Dimension::Field_Y, Dimension::Int32); Dimension dimZi(Dimension::Field_Z, Dimension::Int32); if (!schema.hasDimension(dimXd) || !schema.hasDimension(dimYd) || !schema.hasDimension(dimZd)) { throw impedance_invalid("Scaling filter requires X,Y,Z dimensions as doubles (forward direction)"); } if (schema.hasDimension(dimXi) || schema.hasDimension(dimYi) || schema.hasDimension(dimZi)) { throw impedance_invalid("Scaling filter requires X,Y,Z dimensions as ints not be initially present (forward direction)"); } schema.removeDimension(dimXd); schema.removeDimension(dimYd); schema.removeDimension(dimZd); if (m_customScaleOffset) { dimXi.setNumericScale(m_scaleX); dimXi.setNumericOffset(m_offsetX); dimYi.setNumericScale(m_scaleY); dimYi.setNumericOffset(m_offsetY); dimZi.setNumericScale(m_scaleZ); dimZi.setNumericOffset(m_offsetZ); } else { dimXi.setNumericScale(dimXd.getNumericScale()); dimXi.setNumericOffset(dimXd.getNumericOffset()); dimYi.setNumericScale(dimYd.getNumericScale()); dimYi.setNumericOffset(dimYd.getNumericOffset()); dimZi.setNumericScale(dimZd.getNumericScale()); dimZi.setNumericOffset(dimZd.getNumericOffset()); } schema.addDimension(dimXi); schema.addDimension(dimYi); schema.addDimension(dimZi); } else { const int indexXi = schema.getDimensionIndex(Dimension::Field_X, Dimension::Int32); const int indexYi = schema.getDimensionIndex(Dimension::Field_Y, Dimension::Int32); const int indexZi = schema.getDimensionIndex(Dimension::Field_Z, Dimension::Int32); const Dimension dimXi = schema.getDimension(indexXi); const Dimension dimYi = schema.getDimension(indexYi); const Dimension dimZi = schema.getDimension(indexZi); Dimension dimXd(Dimension::Field_X, Dimension::Double); Dimension dimYd(Dimension::Field_Y, Dimension::Double); Dimension dimZd(Dimension::Field_Z, Dimension::Double); // ints --> doubles if (!schema.hasDimension(dimXi) || !schema.hasDimension(dimYi) || !schema.hasDimension(dimZi)) { throw impedance_invalid("Scaling filter requires X,Y,Z dimensions as int32s (reverse direction)"); } if (schema.hasDimension(dimXd) || schema.hasDimension(dimYd) || schema.hasDimension(dimZd)) { throw impedance_invalid("Scaling filter requires X,Y,Z dimensions as int32s not be initially present (reverse direction)"); } if (m_customScaleOffset) { dimXd.setNumericScale(m_scaleX); dimXd.setNumericOffset(m_offsetX); dimYd.setNumericScale(m_scaleY); dimYd.setNumericOffset(m_offsetY); dimZd.setNumericScale(m_scaleZ); dimZd.setNumericOffset(m_offsetZ); } else { dimXd.setNumericScale(dimXi.getNumericScale()); dimXd.setNumericOffset(dimXi.getNumericOffset()); dimYd.setNumericScale(dimYi.getNumericScale()); dimYd.setNumericOffset(dimYi.getNumericOffset()); dimZd.setNumericScale(dimZi.getNumericScale()); dimZd.setNumericOffset(dimZi.getNumericOffset()); } schema.removeDimension(dimXi); schema.removeDimension(dimYi); schema.removeDimension(dimZi); schema.addDimension(dimXd); schema.addDimension(dimYd); schema.addDimension(dimZd); } return; } void ScalingFilter::initialize() { return; } const std::string& ScalingFilter::getDescription() const { static std::string name("Scaling Filter"); return name; } const std::string& ScalingFilter::getName() const { static std::string name("filters.scaling"); return name; } void ScalingFilter::processBuffer(const PointBuffer& srcData, PointBuffer& dstData) const { const boost::uint32_t numPoints = srcData.getNumPoints(); const SchemaLayout& srcSchemaLayout = srcData.getSchemaLayout(); const Schema& srcSchema = srcSchemaLayout.getSchema(); const SchemaLayout& dstSchemaLayout = dstData.getSchemaLayout(); const Schema& dstSchema = dstSchemaLayout.getSchema(); // rather than think about "src/dst", we will think in terms of "doubles" and "ints" const Schema& schemaD = (m_forward ? srcSchema : dstSchema); const Schema& schemaI = (m_forward ? dstSchema : srcSchema); // std::cout << " Source Schema: " << std::endl << srcSchema << std::endl; // std::cout << " DST Schema: " << std::endl << dstSchema << std::endl; assert(schemaD.hasDimension(Dimension::Field_X, Dimension::Double)); assert(schemaI.hasDimension(Dimension::Field_X, Dimension::Int32)); const int indexXd = schemaD.getDimensionIndex(Dimension::Field_X, Dimension::Double); const int indexYd = schemaD.getDimensionIndex(Dimension::Field_Y, Dimension::Double); const int indexZd = schemaD.getDimensionIndex(Dimension::Field_Z, Dimension::Double); const int indexXi = schemaI.getDimensionIndex(Dimension::Field_X, Dimension::Int32); const int indexYi = schemaI.getDimensionIndex(Dimension::Field_Y, Dimension::Int32); const int indexZi = schemaI.getDimensionIndex(Dimension::Field_Z, Dimension::Int32); const Dimension& dimXd = schemaD.getDimension(indexXd); const Dimension& dimYd = schemaD.getDimension(indexYd); const Dimension& dimZd = schemaD.getDimension(indexZd); const Dimension& dimXi = schemaI.getDimension(indexXi); const Dimension& dimYi = schemaI.getDimension(indexYi); const Dimension& dimZi = schemaI.getDimension(indexZi); std::vector<DimensionLayout> const& src_layouts = srcSchemaLayout.getDimensionLayouts(); std::vector<DimensionLayout> const& dst_layouts = dstSchemaLayout.getDimensionLayouts(); for (boost::uint32_t pointIndex=0; pointIndex<numPoints; pointIndex++) { if (m_forward) { // doubles --> ints (removeScaling) const double xd = srcData.getField<double>(pointIndex, indexXd); const double yd = srcData.getField<double>(pointIndex, indexYd); const double zd = srcData.getField<double>(pointIndex, indexZd); const boost::int32_t xi = dimXi.removeScaling<boost::int32_t>(xd); const boost::int32_t yi = dimYi.removeScaling<boost::int32_t>(yd); const boost::int32_t zi = dimZi.removeScaling<boost::int32_t>(zd); dstData.setField<boost::int32_t>(pointIndex, indexXi, xi); dstData.setField<boost::int32_t>(pointIndex, indexYi, yi); dstData.setField<boost::int32_t>(pointIndex, indexZi, zi); } else { // ints --> doubles (applyScaling) const boost::int32_t xi = srcData.getField<boost::int32_t>(pointIndex, indexXi); const boost::int32_t yi = srcData.getField<boost::int32_t>(pointIndex, indexYi); const boost::int32_t zi = srcData.getField<boost::int32_t>(pointIndex, indexZi); const double xd = dimXd.applyScaling(xi); const double yd = dimYd.applyScaling(yi); const double zd = dimZd.applyScaling(zi); const boost::uint8_t* src_raw_data = srcData.getData(pointIndex); boost::uint8_t* dst_raw_data = dstData.getData(pointIndex); std::size_t src_position = 0; std::size_t dst_position = 0; boost::uint32_t srcFieldIndex = 0; boost::uint32_t dstFieldIndex = 0; for (std::vector<DimensionLayout>::const_iterator i = src_layouts.begin(); i != src_layouts.end(); ++i) { Dimension const& d = i->getDimension(); std::size_t src_offset = i->getByteOffset(); if (d != dimXi && d != dimYi && d != dimZi) { dstFieldIndex = dstSchemaLayout.getSchema().getDimensionIndex(d); srcFieldIndex = srcSchemaLayout.getSchema().getDimensionIndex(d); std::size_t size = d.getDataTypeSize(d.getDataType()); std::cout << " src osffset: " << src_offset << " srcFieldIndex: " << srcFieldIndex << " dstFieldIndex: " << dstFieldIndex << std::endl; dstData.setFieldData(pointIndex, dstFieldIndex, src_raw_data+src_offset); } } dstData.setField<double>(pointIndex, indexXd, xd); dstData.setField<double>(pointIndex, indexYd, yd); dstData.setField<double>(pointIndex, indexZd, zd); } dstData.setNumPoints(pointIndex+1); } return; } pdal::StageSequentialIterator* ScalingFilter::createSequentialIterator() const { return new ScalingFilterSequentialIterator(*this); } } } // namespaces <|endoftext|>
<commit_before>#ifndef __AXIS_HPP #define __AXIS_HPP #ifndef __ODRIVE_MAIN_H #error "This file should not be included directly. Include odrive_main.h instead." #endif class Axis { public: enum Error_t { ERROR_NONE = 0x00, ERROR_INVALID_STATE = 0x01, //<! an invalid state was requested ERROR_DC_BUS_UNDER_VOLTAGE = 0x02, ERROR_DC_BUS_OVER_VOLTAGE = 0x04, ERROR_CURRENT_MEASUREMENT_TIMEOUT = 0x08, ERROR_BRAKE_RESISTOR_DISARMED = 0x10, //<! the brake resistor was unexpectedly disarmed ERROR_MOTOR_DISARMED = 0x20, //<! the motor was unexpectedly disarmed ERROR_MOTOR_FAILED = 0x40, // Go to motor.hpp for information, check odrvX.axisX.motor.error for error value ERROR_SENSORLESS_ESTIMATOR_FAILED = 0x80, ERROR_ENCODER_FAILED = 0x100, // Go to encoder.hpp for information, check odrvX.axisX.encoder.error for error value ERROR_CONTROLLER_FAILED = 0x200, ERROR_POS_CTRL_DURING_SENSORLESS = 0x400, ERROR_ESTOP_REQUESTED = 0x800 }; enum State_t { AXIS_STATE_UNDEFINED = 0, //<! will fall through to idle AXIS_STATE_IDLE = 1, //<! disable PWM and do nothing AXIS_STATE_STARTUP_SEQUENCE = 2, //<! the actual sequence is defined by the config.startup_... flags AXIS_STATE_FULL_CALIBRATION_SEQUENCE = 3, //<! run all calibration procedures, then idle AXIS_STATE_MOTOR_CALIBRATION = 4, //<! run motor calibration AXIS_STATE_SENSORLESS_CONTROL = 5, //<! run sensorless control AXIS_STATE_ENCODER_INDEX_SEARCH = 6, //<! run encoder index search AXIS_STATE_ENCODER_OFFSET_CALIBRATION = 7, //<! run encoder offset calibration AXIS_STATE_CLOSED_LOOP_CONTROL = 8, //<! run closed loop control AXIS_STATE_LOCKIN_SPIN = 9, //<! run lockin spin AXIS_STATE_ENCODER_DIR_FIND = 10, }; struct LockinConfig_t { float current = 10.0f; // [A] float ramp_time = 0.4f; // [s] float ramp_distance = 1 * M_PI; // [rad] float accel = 20.0f; // [rad/s^2] float vel = 40.0f; // [rad/s] float finish_distance = 100.0f; // [rad] bool finish_on_vel = false; bool finish_on_distance = false; bool finish_on_enc_idx = false; }; struct Config_t { bool startup_motor_calibration = false; //<! run motor calibration at startup, skip otherwise bool startup_encoder_index_search = false; //<! run encoder index search after startup, skip otherwise // this only has an effect if encoder.config.use_index is also true bool startup_encoder_offset_calibration = false; //<! run encoder offset calibration after startup, skip otherwise bool startup_closed_loop_control = false; //<! enable closed loop control after calibration/startup bool startup_sensorless_control = false; //<! enable sensorless control after calibration/startup bool enable_step_dir = false; //<! enable step/dir input after calibration // For M0 this has no effect if enable_uart is true float counts_per_step = 2.0f; // Defaults loaded from hw_config in load_configuration in main.cpp uint16_t step_gpio_pin = 0; uint16_t dir_gpio_pin = 0; LockinConfig_t lockin; uint8_t can_node_id = 0; // Both axes will have the same id to start uint32_t can_heartbeat_rate_ms = 100; }; enum thread_signals { M_SIGNAL_PH_CURRENT_MEAS = 1u << 0 }; enum LockinState_t { LOCKIN_STATE_INACTIVE, LOCKIN_STATE_RAMP, LOCKIN_STATE_ACCELERATE, LOCKIN_STATE_CONST_VEL, }; Axis(const AxisHardwareConfig_t& hw_config, Config_t& config, Encoder& encoder, SensorlessEstimator& sensorless_estimator, Controller& controller, Motor& motor, TrapezoidalTrajectory& trap); void setup(); void start_thread(); void signal_current_meas(); bool wait_for_current_meas(); void step_cb(); void set_step_dir_active(bool enable); void decode_step_dir_pins(); static void load_default_step_dir_pin_config( const AxisHardwareConfig_t& hw_config, Config_t* config); static void load_default_can_id(const int& id, Config_t& config); bool check_DRV_fault(); bool check_PSU_brownout(); bool do_checks(); bool do_updates(); // True if there are no errors bool inline check_for_errors() { return error_ == ERROR_NONE; } // @brief Runs the specified update handler at the frequency of the current measurements. // // The loop runs until one of the following conditions: // - update_handler returns false // - the current measurement times out // - the health checks fail (brownout, driver fault line) // - update_handler doesn't update the modulation timings in time // This criterion is ignored if current_state is AXIS_STATE_IDLE // // If update_handler is going to update the motor timings, you must call motor.arm() // shortly before this function. // // If the function returns, it is guaranteed that error is non-zero, except if the cause // for the exit was a negative return value of update_handler or an external // state change request (requested_state != AXIS_STATE_DONT_CARE). // Under all exit conditions the motor is disarmed and the brake current set to zero. // Furthermore, if the update_handler does not set the phase voltages in time, they will // go to zero. // // @tparam T Must be a callable type that takes no arguments and returns a bool template<typename T> void run_control_loop(const T& update_handler) { while (requested_state_ == AXIS_STATE_UNDEFINED) { // look for errors at axis level and also all subcomponents bool checks_ok = do_checks(); // Update all estimators // Note: updates run even if checks fail bool updates_ok = do_updates(); if (!checks_ok || !updates_ok) { // It's not useful to quit idle since that is the safe action // Also leaving idle would rearm the motors if (current_state_ != AXIS_STATE_IDLE) break; } // Run main loop function, defer quitting for after wait // TODO: change arming logic to arm after waiting bool main_continue = update_handler(); // Check we meet deadlines after queueing ++loop_counter_; // Wait until the current measurement interrupt fires if (!wait_for_current_meas()) { // maybe the interrupt handler is dead, let's be // safe and float the phases safety_critical_disarm_motor_pwm(motor_); update_brake_current(); error_ |= ERROR_CURRENT_MEASUREMENT_TIMEOUT; break; } if (!main_continue) break; } } bool run_lockin_spin(); bool run_sensorless_control_loop(); bool run_closed_loop_control_loop(); bool run_idle_loop(); void run_state_machine_loop(); const AxisHardwareConfig_t& hw_config_; Config_t& config_; Encoder& encoder_; SensorlessEstimator& sensorless_estimator_; Controller& controller_; Motor& motor_; TrapezoidalTrajectory& trap_; osThreadId thread_id_; volatile bool thread_id_valid_ = false; // variables exposed on protocol Error_t error_ = ERROR_NONE; bool step_dir_active_ = false; // auto enabled after calibration, based on config.enable_step_dir // updated from config in constructor, and on protocol hook GPIO_TypeDef* step_port_; uint16_t step_pin_; GPIO_TypeDef* dir_port_; uint16_t dir_pin_; State_t requested_state_ = AXIS_STATE_STARTUP_SEQUENCE; State_t task_chain_[10] = { AXIS_STATE_UNDEFINED }; State_t& current_state_ = task_chain_[0]; uint32_t loop_counter_ = 0; LockinState_t lockin_state_ = LOCKIN_STATE_INACTIVE; uint32_t last_heartbeat_ = 0; // Communication protocol definitions auto make_protocol_definitions() { return make_protocol_member_list( make_protocol_property("error", &error_), make_protocol_ro_property("step_dir_active", &step_dir_active_), make_protocol_ro_property("current_state", &current_state_), make_protocol_property("requested_state", &requested_state_), make_protocol_ro_property("loop_counter", &loop_counter_), make_protocol_ro_property("lockin_state", &lockin_state_), make_protocol_object("config", make_protocol_property("startup_motor_calibration", &config_.startup_motor_calibration), make_protocol_property("startup_encoder_index_search", &config_.startup_encoder_index_search), make_protocol_property("startup_encoder_offset_calibration", &config_.startup_encoder_offset_calibration), make_protocol_property("startup_closed_loop_control", &config_.startup_closed_loop_control), make_protocol_property("startup_sensorless_control", &config_.startup_sensorless_control), make_protocol_property("enable_step_dir", &config_.enable_step_dir), make_protocol_property("counts_per_step", &config_.counts_per_step), make_protocol_property("step_gpio_pin", &config_.step_gpio_pin, [](void* ctx) { static_cast<Axis*>(ctx)->decode_step_dir_pins(); }, this), make_protocol_property("dir_gpio_pin", &config_.dir_gpio_pin, [](void* ctx) { static_cast<Axis*>(ctx)->decode_step_dir_pins(); }, this), make_protocol_object("lockin", make_protocol_property("current", &config_.lockin.current), make_protocol_property("ramp_time", &config_.lockin.ramp_time), make_protocol_property("ramp_distance", &config_.lockin.ramp_distance), make_protocol_property("accel", &config_.lockin.accel), make_protocol_property("vel", &config_.lockin.vel), make_protocol_property("finish_distance", &config_.lockin.finish_distance), make_protocol_property("finish_on_vel", &config_.lockin.finish_on_vel), make_protocol_property("finish_on_distance", &config_.lockin.finish_on_distance), make_protocol_property("finish_on_enc_idx", &config_.lockin.finish_on_enc_idx) ), make_protocol_property("can_node_id", &config_.can_node_id) ), make_protocol_object("motor", motor_.make_protocol_definitions()), make_protocol_object("controller", controller_.make_protocol_definitions()), make_protocol_object("encoder", encoder_.make_protocol_definitions()), make_protocol_object("sensorless_estimator", sensorless_estimator_.make_protocol_definitions()), make_protocol_object("trap_traj", trap_.make_protocol_definitions()) ); } }; DEFINE_ENUM_FLAG_OPERATORS(Axis::Error_t) #endif /* __AXIS_HPP */ <commit_msg>Add heartbeat_rate to config protocol<commit_after>#ifndef __AXIS_HPP #define __AXIS_HPP #ifndef __ODRIVE_MAIN_H #error "This file should not be included directly. Include odrive_main.h instead." #endif class Axis { public: enum Error_t { ERROR_NONE = 0x00, ERROR_INVALID_STATE = 0x01, //<! an invalid state was requested ERROR_DC_BUS_UNDER_VOLTAGE = 0x02, ERROR_DC_BUS_OVER_VOLTAGE = 0x04, ERROR_CURRENT_MEASUREMENT_TIMEOUT = 0x08, ERROR_BRAKE_RESISTOR_DISARMED = 0x10, //<! the brake resistor was unexpectedly disarmed ERROR_MOTOR_DISARMED = 0x20, //<! the motor was unexpectedly disarmed ERROR_MOTOR_FAILED = 0x40, // Go to motor.hpp for information, check odrvX.axisX.motor.error for error value ERROR_SENSORLESS_ESTIMATOR_FAILED = 0x80, ERROR_ENCODER_FAILED = 0x100, // Go to encoder.hpp for information, check odrvX.axisX.encoder.error for error value ERROR_CONTROLLER_FAILED = 0x200, ERROR_POS_CTRL_DURING_SENSORLESS = 0x400, ERROR_ESTOP_REQUESTED = 0x800 }; enum State_t { AXIS_STATE_UNDEFINED = 0, //<! will fall through to idle AXIS_STATE_IDLE = 1, //<! disable PWM and do nothing AXIS_STATE_STARTUP_SEQUENCE = 2, //<! the actual sequence is defined by the config.startup_... flags AXIS_STATE_FULL_CALIBRATION_SEQUENCE = 3, //<! run all calibration procedures, then idle AXIS_STATE_MOTOR_CALIBRATION = 4, //<! run motor calibration AXIS_STATE_SENSORLESS_CONTROL = 5, //<! run sensorless control AXIS_STATE_ENCODER_INDEX_SEARCH = 6, //<! run encoder index search AXIS_STATE_ENCODER_OFFSET_CALIBRATION = 7, //<! run encoder offset calibration AXIS_STATE_CLOSED_LOOP_CONTROL = 8, //<! run closed loop control AXIS_STATE_LOCKIN_SPIN = 9, //<! run lockin spin AXIS_STATE_ENCODER_DIR_FIND = 10, }; struct LockinConfig_t { float current = 10.0f; // [A] float ramp_time = 0.4f; // [s] float ramp_distance = 1 * M_PI; // [rad] float accel = 20.0f; // [rad/s^2] float vel = 40.0f; // [rad/s] float finish_distance = 100.0f; // [rad] bool finish_on_vel = false; bool finish_on_distance = false; bool finish_on_enc_idx = false; }; struct Config_t { bool startup_motor_calibration = false; //<! run motor calibration at startup, skip otherwise bool startup_encoder_index_search = false; //<! run encoder index search after startup, skip otherwise // this only has an effect if encoder.config.use_index is also true bool startup_encoder_offset_calibration = false; //<! run encoder offset calibration after startup, skip otherwise bool startup_closed_loop_control = false; //<! enable closed loop control after calibration/startup bool startup_sensorless_control = false; //<! enable sensorless control after calibration/startup bool enable_step_dir = false; //<! enable step/dir input after calibration // For M0 this has no effect if enable_uart is true float counts_per_step = 2.0f; // Defaults loaded from hw_config in load_configuration in main.cpp uint16_t step_gpio_pin = 0; uint16_t dir_gpio_pin = 0; LockinConfig_t lockin; uint8_t can_node_id = 0; // Both axes will have the same id to start uint32_t can_heartbeat_rate_ms = 100; }; enum thread_signals { M_SIGNAL_PH_CURRENT_MEAS = 1u << 0 }; enum LockinState_t { LOCKIN_STATE_INACTIVE, LOCKIN_STATE_RAMP, LOCKIN_STATE_ACCELERATE, LOCKIN_STATE_CONST_VEL, }; Axis(const AxisHardwareConfig_t& hw_config, Config_t& config, Encoder& encoder, SensorlessEstimator& sensorless_estimator, Controller& controller, Motor& motor, TrapezoidalTrajectory& trap); void setup(); void start_thread(); void signal_current_meas(); bool wait_for_current_meas(); void step_cb(); void set_step_dir_active(bool enable); void decode_step_dir_pins(); static void load_default_step_dir_pin_config( const AxisHardwareConfig_t& hw_config, Config_t* config); static void load_default_can_id(const int& id, Config_t& config); bool check_DRV_fault(); bool check_PSU_brownout(); bool do_checks(); bool do_updates(); // True if there are no errors bool inline check_for_errors() { return error_ == ERROR_NONE; } // @brief Runs the specified update handler at the frequency of the current measurements. // // The loop runs until one of the following conditions: // - update_handler returns false // - the current measurement times out // - the health checks fail (brownout, driver fault line) // - update_handler doesn't update the modulation timings in time // This criterion is ignored if current_state is AXIS_STATE_IDLE // // If update_handler is going to update the motor timings, you must call motor.arm() // shortly before this function. // // If the function returns, it is guaranteed that error is non-zero, except if the cause // for the exit was a negative return value of update_handler or an external // state change request (requested_state != AXIS_STATE_DONT_CARE). // Under all exit conditions the motor is disarmed and the brake current set to zero. // Furthermore, if the update_handler does not set the phase voltages in time, they will // go to zero. // // @tparam T Must be a callable type that takes no arguments and returns a bool template<typename T> void run_control_loop(const T& update_handler) { while (requested_state_ == AXIS_STATE_UNDEFINED) { // look for errors at axis level and also all subcomponents bool checks_ok = do_checks(); // Update all estimators // Note: updates run even if checks fail bool updates_ok = do_updates(); if (!checks_ok || !updates_ok) { // It's not useful to quit idle since that is the safe action // Also leaving idle would rearm the motors if (current_state_ != AXIS_STATE_IDLE) break; } // Run main loop function, defer quitting for after wait // TODO: change arming logic to arm after waiting bool main_continue = update_handler(); // Check we meet deadlines after queueing ++loop_counter_; // Wait until the current measurement interrupt fires if (!wait_for_current_meas()) { // maybe the interrupt handler is dead, let's be // safe and float the phases safety_critical_disarm_motor_pwm(motor_); update_brake_current(); error_ |= ERROR_CURRENT_MEASUREMENT_TIMEOUT; break; } if (!main_continue) break; } } bool run_lockin_spin(); bool run_sensorless_control_loop(); bool run_closed_loop_control_loop(); bool run_idle_loop(); void run_state_machine_loop(); const AxisHardwareConfig_t& hw_config_; Config_t& config_; Encoder& encoder_; SensorlessEstimator& sensorless_estimator_; Controller& controller_; Motor& motor_; TrapezoidalTrajectory& trap_; osThreadId thread_id_; volatile bool thread_id_valid_ = false; // variables exposed on protocol Error_t error_ = ERROR_NONE; bool step_dir_active_ = false; // auto enabled after calibration, based on config.enable_step_dir // updated from config in constructor, and on protocol hook GPIO_TypeDef* step_port_; uint16_t step_pin_; GPIO_TypeDef* dir_port_; uint16_t dir_pin_; State_t requested_state_ = AXIS_STATE_STARTUP_SEQUENCE; State_t task_chain_[10] = { AXIS_STATE_UNDEFINED }; State_t& current_state_ = task_chain_[0]; uint32_t loop_counter_ = 0; LockinState_t lockin_state_ = LOCKIN_STATE_INACTIVE; uint32_t last_heartbeat_ = 0; // Communication protocol definitions auto make_protocol_definitions() { return make_protocol_member_list( make_protocol_property("error", &error_), make_protocol_ro_property("step_dir_active", &step_dir_active_), make_protocol_ro_property("current_state", &current_state_), make_protocol_property("requested_state", &requested_state_), make_protocol_ro_property("loop_counter", &loop_counter_), make_protocol_ro_property("lockin_state", &lockin_state_), make_protocol_object("config", make_protocol_property("startup_motor_calibration", &config_.startup_motor_calibration), make_protocol_property("startup_encoder_index_search", &config_.startup_encoder_index_search), make_protocol_property("startup_encoder_offset_calibration", &config_.startup_encoder_offset_calibration), make_protocol_property("startup_closed_loop_control", &config_.startup_closed_loop_control), make_protocol_property("startup_sensorless_control", &config_.startup_sensorless_control), make_protocol_property("enable_step_dir", &config_.enable_step_dir), make_protocol_property("counts_per_step", &config_.counts_per_step), make_protocol_property("step_gpio_pin", &config_.step_gpio_pin, [](void* ctx) { static_cast<Axis*>(ctx)->decode_step_dir_pins(); }, this), make_protocol_property("dir_gpio_pin", &config_.dir_gpio_pin, [](void* ctx) { static_cast<Axis*>(ctx)->decode_step_dir_pins(); }, this), make_protocol_object("lockin", make_protocol_property("current", &config_.lockin.current), make_protocol_property("ramp_time", &config_.lockin.ramp_time), make_protocol_property("ramp_distance", &config_.lockin.ramp_distance), make_protocol_property("accel", &config_.lockin.accel), make_protocol_property("vel", &config_.lockin.vel), make_protocol_property("finish_distance", &config_.lockin.finish_distance), make_protocol_property("finish_on_vel", &config_.lockin.finish_on_vel), make_protocol_property("finish_on_distance", &config_.lockin.finish_on_distance), make_protocol_property("finish_on_enc_idx", &config_.lockin.finish_on_enc_idx) ), make_protocol_property("can_node_id", &config_.can_node_id), make_protocol_property("can_heartbeat_rate_ms", &config_.can_heartbeat_rate_ms) ), make_protocol_object("motor", motor_.make_protocol_definitions()), make_protocol_object("controller", controller_.make_protocol_definitions()), make_protocol_object("encoder", encoder_.make_protocol_definitions()), make_protocol_object("sensorless_estimator", sensorless_estimator_.make_protocol_definitions()), make_protocol_object("trap_traj", trap_.make_protocol_definitions()) ); } }; DEFINE_ENUM_FLAG_OPERATORS(Axis::Error_t) #endif /* __AXIS_HPP */ <|endoftext|>
<commit_before>#include "PictureRenderer.h" #include "SamplePipeControllers.h" #include "SkCanvas.h" #include "SkDevice.h" #include "SkGPipe.h" #include "SkPicture.h" #include "SkTDArray.h" #include "SkTypes.h" #include "picture_utils.h" #if SK_SUPPORT_GPU #include "SkGpuDevice.h" #endif namespace sk_tools { enum { kDefaultTileWidth = 256, kDefaultTileHeight = 256 }; void PictureRenderer::init(SkPicture* pict) { SkASSERT(NULL == fPicture); SkASSERT(NULL == fCanvas.get()); if (fPicture != NULL || NULL != fCanvas.get()) { return; } SkASSERT(pict != NULL); if (NULL == pict) { return; } fPicture = pict; fCanvas.reset(this->setupCanvas()); } SkCanvas* PictureRenderer::setupCanvas() { return this->setupCanvas(fPicture->width(), fPicture->height()); } SkCanvas* PictureRenderer::setupCanvas(int width, int height) { switch(fDeviceType) { case kBitmap_DeviceType: { SkBitmap bitmap; sk_tools::setup_bitmap(&bitmap, width, height); return SkNEW_ARGS(SkCanvas, (bitmap)); break; } #if SK_SUPPORT_GPU case kGPU_DeviceType: { SkAutoTUnref<SkGpuDevice> device(SkNEW_ARGS(SkGpuDevice, (fGrContext, SkBitmap::kARGB_8888_Config, width, height))); return SkNEW_ARGS(SkCanvas, (device.get())); break; } #endif default: SkASSERT(0); } return NULL; } void PictureRenderer::end() { this->resetState(); fPicture = NULL; fCanvas.reset(NULL); } void PictureRenderer::resetState() { #if SK_SUPPORT_GPU if (this->isUsingGpuDevice()) { SkGLContext* glContext = fGrContextFactory.getGLContext( GrContextFactory::kNative_GLContextType); SK_GL(*glContext, Finish()); } #endif } void PictureRenderer::finishDraw() { SkASSERT(fCanvas.get() != NULL); if (NULL == fCanvas.get()) { return; } fCanvas->flush(); #if SK_SUPPORT_GPU if (this->isUsingGpuDevice()) { SkGLContext* glContext = fGrContextFactory.getGLContext( GrContextFactory::kNative_GLContextType); SkASSERT(glContext != NULL); if (NULL == glContext) { return; } SK_GL(*glContext, Finish()); } #endif } void PipePictureRenderer::render() { SkASSERT(fCanvas.get() != NULL); SkASSERT(fPicture != NULL); if (NULL == fCanvas.get() || NULL == fPicture) { return; } PipeController pipeController(fCanvas.get()); SkGPipeWriter writer; SkCanvas* pipeCanvas = writer.startRecording(&pipeController); pipeCanvas->drawPicture(*fPicture); writer.endRecording(); this->finishDraw(); } void SimplePictureRenderer::render() { SkASSERT(fCanvas.get() != NULL); SkASSERT(fPicture != NULL); if (NULL == fCanvas.get() || NULL == fPicture) { return; } fCanvas->drawPicture(*fPicture); this->finishDraw(); } TiledPictureRenderer::TiledPictureRenderer() : fTileWidth(kDefaultTileWidth) , fTileHeight(kDefaultTileHeight) {} void TiledPictureRenderer::init(SkPicture* pict) { SkASSERT(pict != NULL); SkASSERT(0 == fTiles.count()); if (NULL == pict || fTiles.count() != 0) { return; } this->INHERITED::init(pict); if (fTileWidthPercentage > 0) { fTileWidth = sk_float_ceil2int(float(fTileWidthPercentage * fPicture->width() / 100)); } if (fTileHeightPercentage > 0) { fTileHeight = sk_float_ceil2int(float(fTileHeightPercentage * fPicture->height() / 100)); } this->setupTiles(); } void TiledPictureRenderer::render() { SkASSERT(fCanvas.get() != NULL); SkASSERT(fPicture != NULL); if (NULL == fCanvas.get() || NULL == fPicture) { return; } this->drawTiles(); this->copyTilesToCanvas(); this->finishDraw(); } void TiledPictureRenderer::end() { this->deleteTiles(); this->INHERITED::end(); } TiledPictureRenderer::~TiledPictureRenderer() { this->deleteTiles(); } void TiledPictureRenderer::clipTile(const TileInfo& tile) { SkRect clip = SkRect::MakeWH(SkIntToScalar(fPicture->width()), SkIntToScalar(fPicture->height())); tile.fCanvas->clipRect(clip); } void TiledPictureRenderer::addTile(int tile_x_start, int tile_y_start) { TileInfo* tile = fTiles.push(); tile->fCanvas = this->setupCanvas(fTileWidth, fTileHeight); tile->fCanvas->translate(SkIntToScalar(-tile_x_start), SkIntToScalar(-tile_y_start)); this->clipTile(*tile); } void TiledPictureRenderer::setupTiles() { for (int tile_y_start = 0; tile_y_start < fPicture->height(); tile_y_start += fTileHeight) { for (int tile_x_start = 0; tile_x_start < fPicture->width(); tile_x_start += fTileWidth) { this->addTile(tile_x_start, tile_y_start); } } } void TiledPictureRenderer::deleteTiles() { for (int i = 0; i < fTiles.count(); ++i) { SkDELETE(fTiles[i].fCanvas); } fTiles.reset(); } void TiledPictureRenderer::drawTiles() { for (int i = 0; i < fTiles.count(); ++i) { fTiles[i].fCanvas->drawPicture(*(fPicture)); } } void TiledPictureRenderer::finishDraw() { for (int i = 0; i < fTiles.count(); ++i) { fTiles[i].fCanvas->flush(); } #if SK_SUPPORT_GPU if (this->isUsingGpuDevice()) { SkGLContext* glContext = fGrContextFactory.getGLContext( GrContextFactory::kNative_GLContextType); SkASSERT(glContext != NULL); if (NULL == glContext) { return; } SK_GL(*glContext, Finish()); } #endif } void TiledPictureRenderer::copyTilesToCanvas() { int tile_index = 0; for (int tile_y_start = 0; tile_y_start < fPicture->height(); tile_y_start += fTileHeight) { for (int tile_x_start = 0; tile_x_start < fPicture->width(); tile_x_start += fTileWidth) { SkASSERT(tile_index < fTiles.count()); SkBitmap source = fTiles[tile_index].fCanvas->getDevice()->accessBitmap(false); fCanvas->drawBitmap(source, SkIntToScalar(tile_x_start), SkIntToScalar(tile_y_start)); ++tile_index; } } } } <commit_msg>Added copyright notice to PictureRenderer.cpp<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "PictureRenderer.h" #include "SamplePipeControllers.h" #include "SkCanvas.h" #include "SkDevice.h" #include "SkGPipe.h" #include "SkPicture.h" #include "SkTDArray.h" #include "SkTypes.h" #include "picture_utils.h" #if SK_SUPPORT_GPU #include "SkGpuDevice.h" #endif namespace sk_tools { enum { kDefaultTileWidth = 256, kDefaultTileHeight = 256 }; void PictureRenderer::init(SkPicture* pict) { SkASSERT(NULL == fPicture); SkASSERT(NULL == fCanvas.get()); if (fPicture != NULL || NULL != fCanvas.get()) { return; } SkASSERT(pict != NULL); if (NULL == pict) { return; } fPicture = pict; fCanvas.reset(this->setupCanvas()); } SkCanvas* PictureRenderer::setupCanvas() { return this->setupCanvas(fPicture->width(), fPicture->height()); } SkCanvas* PictureRenderer::setupCanvas(int width, int height) { switch(fDeviceType) { case kBitmap_DeviceType: { SkBitmap bitmap; sk_tools::setup_bitmap(&bitmap, width, height); return SkNEW_ARGS(SkCanvas, (bitmap)); break; } #if SK_SUPPORT_GPU case kGPU_DeviceType: { SkAutoTUnref<SkGpuDevice> device(SkNEW_ARGS(SkGpuDevice, (fGrContext, SkBitmap::kARGB_8888_Config, width, height))); return SkNEW_ARGS(SkCanvas, (device.get())); break; } #endif default: SkASSERT(0); } return NULL; } void PictureRenderer::end() { this->resetState(); fPicture = NULL; fCanvas.reset(NULL); } void PictureRenderer::resetState() { #if SK_SUPPORT_GPU if (this->isUsingGpuDevice()) { SkGLContext* glContext = fGrContextFactory.getGLContext( GrContextFactory::kNative_GLContextType); SK_GL(*glContext, Finish()); } #endif } void PictureRenderer::finishDraw() { SkASSERT(fCanvas.get() != NULL); if (NULL == fCanvas.get()) { return; } fCanvas->flush(); #if SK_SUPPORT_GPU if (this->isUsingGpuDevice()) { SkGLContext* glContext = fGrContextFactory.getGLContext( GrContextFactory::kNative_GLContextType); SkASSERT(glContext != NULL); if (NULL == glContext) { return; } SK_GL(*glContext, Finish()); } #endif } void PipePictureRenderer::render() { SkASSERT(fCanvas.get() != NULL); SkASSERT(fPicture != NULL); if (NULL == fCanvas.get() || NULL == fPicture) { return; } PipeController pipeController(fCanvas.get()); SkGPipeWriter writer; SkCanvas* pipeCanvas = writer.startRecording(&pipeController); pipeCanvas->drawPicture(*fPicture); writer.endRecording(); this->finishDraw(); } void SimplePictureRenderer::render() { SkASSERT(fCanvas.get() != NULL); SkASSERT(fPicture != NULL); if (NULL == fCanvas.get() || NULL == fPicture) { return; } fCanvas->drawPicture(*fPicture); this->finishDraw(); } TiledPictureRenderer::TiledPictureRenderer() : fTileWidth(kDefaultTileWidth) , fTileHeight(kDefaultTileHeight) {} void TiledPictureRenderer::init(SkPicture* pict) { SkASSERT(pict != NULL); SkASSERT(0 == fTiles.count()); if (NULL == pict || fTiles.count() != 0) { return; } this->INHERITED::init(pict); if (fTileWidthPercentage > 0) { fTileWidth = sk_float_ceil2int(float(fTileWidthPercentage * fPicture->width() / 100)); } if (fTileHeightPercentage > 0) { fTileHeight = sk_float_ceil2int(float(fTileHeightPercentage * fPicture->height() / 100)); } this->setupTiles(); } void TiledPictureRenderer::render() { SkASSERT(fCanvas.get() != NULL); SkASSERT(fPicture != NULL); if (NULL == fCanvas.get() || NULL == fPicture) { return; } this->drawTiles(); this->copyTilesToCanvas(); this->finishDraw(); } void TiledPictureRenderer::end() { this->deleteTiles(); this->INHERITED::end(); } TiledPictureRenderer::~TiledPictureRenderer() { this->deleteTiles(); } void TiledPictureRenderer::clipTile(const TileInfo& tile) { SkRect clip = SkRect::MakeWH(SkIntToScalar(fPicture->width()), SkIntToScalar(fPicture->height())); tile.fCanvas->clipRect(clip); } void TiledPictureRenderer::addTile(int tile_x_start, int tile_y_start) { TileInfo* tile = fTiles.push(); tile->fCanvas = this->setupCanvas(fTileWidth, fTileHeight); tile->fCanvas->translate(SkIntToScalar(-tile_x_start), SkIntToScalar(-tile_y_start)); this->clipTile(*tile); } void TiledPictureRenderer::setupTiles() { for (int tile_y_start = 0; tile_y_start < fPicture->height(); tile_y_start += fTileHeight) { for (int tile_x_start = 0; tile_x_start < fPicture->width(); tile_x_start += fTileWidth) { this->addTile(tile_x_start, tile_y_start); } } } void TiledPictureRenderer::deleteTiles() { for (int i = 0; i < fTiles.count(); ++i) { SkDELETE(fTiles[i].fCanvas); } fTiles.reset(); } void TiledPictureRenderer::drawTiles() { for (int i = 0; i < fTiles.count(); ++i) { fTiles[i].fCanvas->drawPicture(*(fPicture)); } } void TiledPictureRenderer::finishDraw() { for (int i = 0; i < fTiles.count(); ++i) { fTiles[i].fCanvas->flush(); } #if SK_SUPPORT_GPU if (this->isUsingGpuDevice()) { SkGLContext* glContext = fGrContextFactory.getGLContext( GrContextFactory::kNative_GLContextType); SkASSERT(glContext != NULL); if (NULL == glContext) { return; } SK_GL(*glContext, Finish()); } #endif } void TiledPictureRenderer::copyTilesToCanvas() { int tile_index = 0; for (int tile_y_start = 0; tile_y_start < fPicture->height(); tile_y_start += fTileHeight) { for (int tile_x_start = 0; tile_x_start < fPicture->width(); tile_x_start += fTileWidth) { SkASSERT(tile_index < fTiles.count()); SkBitmap source = fTiles[tile_index].fCanvas->getDevice()->accessBitmap(false); fCanvas->drawBitmap(source, SkIntToScalar(tile_x_start), SkIntToScalar(tile_y_start)); ++tile_index; } } } } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // LLVM 'Analyze' UTILITY // // This utility is designed to print out the results of running various analysis // passes on a program. This is useful for understanding a program, or for // debugging an analysis pass. // // analyze --help - Output information about command line switches // analyze --quiet - Do not print analysis name before output // //===----------------------------------------------------------------------===// #include "llvm/Instruction.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/iPHINode.h" #include "llvm/PassManager.h" #include "llvm/Bytecode/Reader.h" #include "llvm/Assembly/Parser.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Analysis/Writer.h" #include "llvm/Analysis/InstForest.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/IntervalPartition.h" #include "llvm/Analysis/Expressions.h" #include "llvm/Analysis/InductionVariable.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/FindUnsafePointerTypes.h" #include "llvm/Analysis/FindUsedTypes.h" #include "Support/CommandLine.h" #include <algorithm> #include <iostream> using std::cout; using std::ostream; using std::string; static Module *CurrentModule; static void operator<<(ostream &O, const FindUsedTypes &FUT) { FUT.printTypes(cout, CurrentModule); } static void operator<<(ostream &O, const FindUnsafePointerTypes &FUPT) { FUPT.printResults(CurrentModule, cout); } template <class PassType, class PassName> class PassPrinter; // Do not implement template <class PassName> class PassPrinter<Pass, PassName> : public Pass { const string Message; const AnalysisID ID; public: PassPrinter(const string &M, AnalysisID id) : Message(M), ID(id) {} virtual bool run(Module *M) { cout << Message << "\n" << getAnalysis<PassName>(ID); return false; } virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required, Pass::AnalysisSet &Destroyed, Pass::AnalysisSet &Provided) { Required.push_back(ID); } }; template <class PassName> class PassPrinter<MethodPass, PassName> : public MethodPass { const string Message; const AnalysisID ID; public: PassPrinter(const string &M, AnalysisID id) : Message(M), ID(id) {} virtual bool runOnMethod(Method *M) { cout << Message << " on method '" << M->getName() << "'\n" << getAnalysis<PassName>(ID); return false; } virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required, Pass::AnalysisSet &Destroyed, Pass::AnalysisSet &Provided) { Required.push_back(ID); } }; template <class PassType, class PassName, AnalysisID &ID> Pass *New(const string &Message) { return new PassPrinter<PassType, PassName>(Message, ID); } template <class PassType, class PassName> Pass *New(const string &Message) { return new PassPrinter<PassType, PassName>(Message, PassName::ID); } Pass *NewPrintMethod(const string &Message) { return new PrintMethodPass(Message, &std::cout); } Pass *NewPrintModule(const string &Message) { return new PrintModulePass(&std::cout); } struct InstForest : public MethodPass { void doit(Method *M) { cout << analysis::InstForest<char>(M); } }; struct IndVars : public MethodPass { void doit(Method *M) { cfg::LoopInfo &LI = getAnalysis<cfg::LoopInfo>(); for (Method::inst_iterator I = M->inst_begin(), E = M->inst_end(); I != E; ++I) if (PHINode *PN = dyn_cast<PHINode>(*I)) { InductionVariable IV(PN, &LI); if (IV.InductionType != InductionVariable::Unknown) cout << IV; } } void getAnalysisUsageInfo(Pass::AnalysisSet &Req, Pass::AnalysisSet &, Pass::AnalysisSet &) { Req.push_back(cfg::LoopInfo::ID); } }; struct Exprs : public MethodPass { static void doit(Method *M) { cout << "Classified expressions for: " << M->getName() << "\n"; Method::inst_iterator I = M->inst_begin(), E = M->inst_end(); for (; I != E; ++I) { cout << *I; if ((*I)->getType() == Type::VoidTy) continue; analysis::ExprType R = analysis::ClassifyExpression(*I); if (R.Var == *I) continue; // Doesn't tell us anything cout << "\t\tExpr ="; switch (R.ExprTy) { case analysis::ExprType::ScaledLinear: WriteAsOperand(cout << "(", (Value*)R.Scale) << " ) *"; // fall through case analysis::ExprType::Linear: WriteAsOperand(cout << "(", R.Var) << " )"; if (R.Offset == 0) break; else cout << " +"; // fall through case analysis::ExprType::Constant: if (R.Offset) WriteAsOperand(cout, (Value*)R.Offset); else cout << " 0"; break; } cout << "\n\n"; } } }; template<class TraitClass> class PrinterPass : public TraitClass { const string Message; public: PrinterPass(const string &M) : Message(M) {} virtual bool runOnMethod(Method *M) { cout << Message << " on method '" << M->getName() << "'\n"; TraitClass::doit(M); return false; } }; template<class PassClass> Pass *Create(const string &Message) { return new PassClass(Message); } enum Ans { // global analyses print, intervals, exprs, instforest, loops, indvars, // ip analyses printmodule, callgraph, printusedtypes, unsafepointertypes, domset, idom, domtree, domfrontier, postdomset, postidom, postdomtree, postdomfrontier, }; cl::String InputFilename ("", "Load <arg> file to analyze", cl::NoFlags, "-"); cl::Flag Quiet ("q", "Don't print analysis pass names"); cl::Alias QuietA ("quiet", "Alias for -q", cl::NoFlags, Quiet); cl::EnumList<enum Ans> AnalysesList(cl::NoFlags, clEnumVal(print , "Print each method"), clEnumVal(intervals , "Print Interval Partitions"), clEnumVal(exprs , "Classify Expressions"), clEnumVal(instforest , "Print Instruction Forest"), clEnumVal(loops , "Print Loops"), clEnumVal(indvars , "Print Induction Variables"), clEnumVal(printmodule , "Print entire module"), clEnumVal(callgraph , "Print Call Graph"), clEnumVal(printusedtypes , "Print Types Used by Module"), clEnumVal(unsafepointertypes, "Print Unsafe Pointer Types"), clEnumVal(domset , "Print Dominator Sets"), clEnumVal(idom , "Print Immediate Dominators"), clEnumVal(domtree , "Print Dominator Tree"), clEnumVal(domfrontier , "Print Dominance Frontier"), clEnumVal(postdomset , "Print Postdominator Sets"), clEnumVal(postidom , "Print Immediate Postdominators"), clEnumVal(postdomtree , "Print Post Dominator Tree"), clEnumVal(postdomfrontier, "Print Postdominance Frontier"), 0); struct { enum Ans AnID; Pass *(*PassConstructor)(const string &Message); } AnTable[] = { // Global analyses { print , NewPrintMethod }, { intervals , New<MethodPass, cfg::IntervalPartition> }, { loops , New<MethodPass, cfg::LoopInfo> }, { instforest , Create<PrinterPass<InstForest> > }, { indvars , Create<PrinterPass<IndVars> > }, { exprs , Create<PrinterPass<Exprs> > }, // IP Analyses... { printmodule , NewPrintModule }, { printusedtypes , New<Pass, FindUsedTypes> }, { callgraph , New<Pass, cfg::CallGraph> }, { unsafepointertypes, New<Pass, FindUnsafePointerTypes> }, // Dominator analyses { domset , New<MethodPass, cfg::DominatorSet> }, { idom , New<MethodPass, cfg::ImmediateDominators> }, { domtree , New<MethodPass, cfg::DominatorTree> }, { domfrontier , New<MethodPass, cfg::DominanceFrontier> }, { postdomset , New<MethodPass, cfg::DominatorSet, cfg::DominatorSet::PostDomID> }, { postidom , New<MethodPass, cfg::ImmediateDominators, cfg::ImmediateDominators::PostDomID> }, { postdomtree , New<MethodPass, cfg::DominatorTree, cfg::DominatorTree::PostDomID> }, { postdomfrontier , New<MethodPass, cfg::DominanceFrontier, cfg::DominanceFrontier::PostDomID> }, }; int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm analysis printer tool\n"); CurrentModule = ParseBytecodeFile(InputFilename); if (!CurrentModule && !(CurrentModule = ParseAssemblyFile(InputFilename))) { std::cerr << "Input file didn't read correctly.\n"; return 1; } // Create a PassManager to hold and optimize the collection of passes we are // about to build... // PassManager Analyses; // Loop over all of the analyses looking for analyses to run... for (unsigned i = 0; i < AnalysesList.size(); ++i) { enum Ans AnalysisPass = AnalysesList[i]; for (unsigned j = 0; j < sizeof(AnTable)/sizeof(AnTable[0]); ++j) { if (AnTable[j].AnID == AnalysisPass) { string Message; if (!Quiet) Message = "\nRunning: '" + string(AnalysesList.getArgDescription(AnalysisPass)) + "' analysis"; Analyses.add(AnTable[j].PassConstructor(Message)); break; // get an error later } } } Analyses.run(CurrentModule); delete CurrentModule; return 0; } <commit_msg>Catch the parse exception if bad input is provided. Much better than an abort<commit_after>//===----------------------------------------------------------------------===// // LLVM 'Analyze' UTILITY // // This utility is designed to print out the results of running various analysis // passes on a program. This is useful for understanding a program, or for // debugging an analysis pass. // // analyze --help - Output information about command line switches // analyze --quiet - Do not print analysis name before output // //===----------------------------------------------------------------------===// #include "llvm/Instruction.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/iPHINode.h" #include "llvm/PassManager.h" #include "llvm/Bytecode/Reader.h" #include "llvm/Assembly/Parser.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Analysis/Writer.h" #include "llvm/Analysis/InstForest.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/IntervalPartition.h" #include "llvm/Analysis/Expressions.h" #include "llvm/Analysis/InductionVariable.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/FindUnsafePointerTypes.h" #include "llvm/Analysis/FindUsedTypes.h" #include "Support/CommandLine.h" #include <algorithm> #include <iostream> using std::cout; using std::ostream; using std::string; static Module *CurrentModule; static void operator<<(ostream &O, const FindUsedTypes &FUT) { FUT.printTypes(cout, CurrentModule); } static void operator<<(ostream &O, const FindUnsafePointerTypes &FUPT) { FUPT.printResults(CurrentModule, cout); } template <class PassType, class PassName> class PassPrinter; // Do not implement template <class PassName> class PassPrinter<Pass, PassName> : public Pass { const string Message; const AnalysisID ID; public: PassPrinter(const string &M, AnalysisID id) : Message(M), ID(id) {} virtual bool run(Module *M) { cout << Message << "\n" << getAnalysis<PassName>(ID); return false; } virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required, Pass::AnalysisSet &Destroyed, Pass::AnalysisSet &Provided) { Required.push_back(ID); } }; template <class PassName> class PassPrinter<MethodPass, PassName> : public MethodPass { const string Message; const AnalysisID ID; public: PassPrinter(const string &M, AnalysisID id) : Message(M), ID(id) {} virtual bool runOnMethod(Method *M) { cout << Message << " on method '" << M->getName() << "'\n" << getAnalysis<PassName>(ID); return false; } virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required, Pass::AnalysisSet &Destroyed, Pass::AnalysisSet &Provided) { Required.push_back(ID); } }; template <class PassType, class PassName, AnalysisID &ID> Pass *New(const string &Message) { return new PassPrinter<PassType, PassName>(Message, ID); } template <class PassType, class PassName> Pass *New(const string &Message) { return new PassPrinter<PassType, PassName>(Message, PassName::ID); } Pass *NewPrintMethod(const string &Message) { return new PrintMethodPass(Message, &std::cout); } Pass *NewPrintModule(const string &Message) { return new PrintModulePass(&std::cout); } struct InstForest : public MethodPass { void doit(Method *M) { cout << analysis::InstForest<char>(M); } }; struct IndVars : public MethodPass { void doit(Method *M) { cfg::LoopInfo &LI = getAnalysis<cfg::LoopInfo>(); for (Method::inst_iterator I = M->inst_begin(), E = M->inst_end(); I != E; ++I) if (PHINode *PN = dyn_cast<PHINode>(*I)) { InductionVariable IV(PN, &LI); if (IV.InductionType != InductionVariable::Unknown) cout << IV; } } void getAnalysisUsageInfo(Pass::AnalysisSet &Req, Pass::AnalysisSet &, Pass::AnalysisSet &) { Req.push_back(cfg::LoopInfo::ID); } }; struct Exprs : public MethodPass { static void doit(Method *M) { cout << "Classified expressions for: " << M->getName() << "\n"; Method::inst_iterator I = M->inst_begin(), E = M->inst_end(); for (; I != E; ++I) { cout << *I; if ((*I)->getType() == Type::VoidTy) continue; analysis::ExprType R = analysis::ClassifyExpression(*I); if (R.Var == *I) continue; // Doesn't tell us anything cout << "\t\tExpr ="; switch (R.ExprTy) { case analysis::ExprType::ScaledLinear: WriteAsOperand(cout << "(", (Value*)R.Scale) << " ) *"; // fall through case analysis::ExprType::Linear: WriteAsOperand(cout << "(", R.Var) << " )"; if (R.Offset == 0) break; else cout << " +"; // fall through case analysis::ExprType::Constant: if (R.Offset) WriteAsOperand(cout, (Value*)R.Offset); else cout << " 0"; break; } cout << "\n\n"; } } }; template<class TraitClass> class PrinterPass : public TraitClass { const string Message; public: PrinterPass(const string &M) : Message(M) {} virtual bool runOnMethod(Method *M) { cout << Message << " on method '" << M->getName() << "'\n"; TraitClass::doit(M); return false; } }; template<class PassClass> Pass *Create(const string &Message) { return new PassClass(Message); } enum Ans { // global analyses print, intervals, exprs, instforest, loops, indvars, // ip analyses printmodule, callgraph, printusedtypes, unsafepointertypes, domset, idom, domtree, domfrontier, postdomset, postidom, postdomtree, postdomfrontier, }; cl::String InputFilename ("", "Load <arg> file to analyze", cl::NoFlags, "-"); cl::Flag Quiet ("q", "Don't print analysis pass names"); cl::Alias QuietA ("quiet", "Alias for -q", cl::NoFlags, Quiet); cl::EnumList<enum Ans> AnalysesList(cl::NoFlags, clEnumVal(print , "Print each method"), clEnumVal(intervals , "Print Interval Partitions"), clEnumVal(exprs , "Classify Expressions"), clEnumVal(instforest , "Print Instruction Forest"), clEnumVal(loops , "Print Loops"), clEnumVal(indvars , "Print Induction Variables"), clEnumVal(printmodule , "Print entire module"), clEnumVal(callgraph , "Print Call Graph"), clEnumVal(printusedtypes , "Print Types Used by Module"), clEnumVal(unsafepointertypes, "Print Unsafe Pointer Types"), clEnumVal(domset , "Print Dominator Sets"), clEnumVal(idom , "Print Immediate Dominators"), clEnumVal(domtree , "Print Dominator Tree"), clEnumVal(domfrontier , "Print Dominance Frontier"), clEnumVal(postdomset , "Print Postdominator Sets"), clEnumVal(postidom , "Print Immediate Postdominators"), clEnumVal(postdomtree , "Print Post Dominator Tree"), clEnumVal(postdomfrontier, "Print Postdominance Frontier"), 0); struct { enum Ans AnID; Pass *(*PassConstructor)(const string &Message); } AnTable[] = { // Global analyses { print , NewPrintMethod }, { intervals , New<MethodPass, cfg::IntervalPartition> }, { loops , New<MethodPass, cfg::LoopInfo> }, { instforest , Create<PrinterPass<InstForest> > }, { indvars , Create<PrinterPass<IndVars> > }, { exprs , Create<PrinterPass<Exprs> > }, // IP Analyses... { printmodule , NewPrintModule }, { printusedtypes , New<Pass, FindUsedTypes> }, { callgraph , New<Pass, cfg::CallGraph> }, { unsafepointertypes, New<Pass, FindUnsafePointerTypes> }, // Dominator analyses { domset , New<MethodPass, cfg::DominatorSet> }, { idom , New<MethodPass, cfg::ImmediateDominators> }, { domtree , New<MethodPass, cfg::DominatorTree> }, { domfrontier , New<MethodPass, cfg::DominanceFrontier> }, { postdomset , New<MethodPass, cfg::DominatorSet, cfg::DominatorSet::PostDomID> }, { postidom , New<MethodPass, cfg::ImmediateDominators, cfg::ImmediateDominators::PostDomID> }, { postdomtree , New<MethodPass, cfg::DominatorTree, cfg::DominatorTree::PostDomID> }, { postdomfrontier , New<MethodPass, cfg::DominanceFrontier, cfg::DominanceFrontier::PostDomID> }, }; int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm analysis printer tool\n"); try { CurrentModule = ParseBytecodeFile(InputFilename); if (!CurrentModule && !(CurrentModule = ParseAssemblyFile(InputFilename))){ std::cerr << "Input file didn't read correctly.\n"; return 1; } } catch (const ParseException &E) { cerr << E.getMessage() << endl; return 1; } // Create a PassManager to hold and optimize the collection of passes we are // about to build... // PassManager Analyses; // Loop over all of the analyses looking for analyses to run... for (unsigned i = 0; i < AnalysesList.size(); ++i) { enum Ans AnalysisPass = AnalysesList[i]; for (unsigned j = 0; j < sizeof(AnTable)/sizeof(AnTable[0]); ++j) { if (AnTable[j].AnID == AnalysisPass) { string Message; if (!Quiet) Message = "\nRunning: '" + string(AnalysesList.getArgDescription(AnalysisPass)) + "' analysis"; Analyses.add(AnTable[j].PassConstructor(Message)); break; // get an error later } } } Analyses.run(CurrentModule); delete CurrentModule; return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "rtc_base/numerics/samples_stats_counter.h" #include <math.h> #include <algorithm> #include <vector> #include "test/gtest.h" namespace webrtc { namespace { SamplesStatsCounter CreateStatsFilledWithIntsFrom1ToN(int n) { std::vector<double> data; for (int i = 1; i <= n; i++) { data.push_back(i); } std::random_shuffle(data.begin(), data.end()); SamplesStatsCounter stats; for (double v : data) { stats.AddSample(v); } return stats; } } // namespace TEST(SamplesStatsCounter, FullSimpleTest) { SamplesStatsCounter stats = CreateStatsFilledWithIntsFrom1ToN(100); EXPECT_TRUE(!stats.IsEmpty()); EXPECT_DOUBLE_EQ(stats.GetMin(), 1.0); EXPECT_DOUBLE_EQ(stats.GetMax(), 100.0); EXPECT_DOUBLE_EQ(stats.GetAverage(), 50.5); for (int i = 1; i <= 100; i++) { double p = i / 100.0; EXPECT_GE(stats.GetPercentile(p), i); EXPECT_LT(stats.GetPercentile(p), i + 1); } } TEST(SamplesStatsCounter, VarianceAndDeviation) { SamplesStatsCounter stats; stats.AddSample(2); stats.AddSample(2); stats.AddSample(-1); stats.AddSample(5); EXPECT_DOUBLE_EQ(stats.GetAverage(), 2.0); EXPECT_DOUBLE_EQ(stats.GetVariance(), 4.5); EXPECT_DOUBLE_EQ(stats.GetStandardDeviation(), sqrt(4.5)); } TEST(SamplesStatsCounter, FractionPercentile) { SamplesStatsCounter stats = CreateStatsFilledWithIntsFrom1ToN(5); EXPECT_DOUBLE_EQ(stats.GetPercentile(0.5), 3); } TEST(SamplesStatsCounter, TestBorderValues) { SamplesStatsCounter stats = CreateStatsFilledWithIntsFrom1ToN(5); EXPECT_GE(stats.GetPercentile(0.01), 1); EXPECT_LT(stats.GetPercentile(0.01), 2); EXPECT_DOUBLE_EQ(stats.GetPercentile(1.0), 5); } } // namespace webrtc <commit_msg>Switch from deprecated std::random_shuffle on std::shuffle<commit_after>/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "rtc_base/numerics/samples_stats_counter.h" #include <math.h> #include <algorithm> #include <random> #include <vector> #include "test/gtest.h" namespace webrtc { namespace { SamplesStatsCounter CreateStatsFilledWithIntsFrom1ToN(int n) { std::vector<double> data; for (int i = 1; i <= n; i++) { data.push_back(i); } std::shuffle(data.begin(), data.end(), std::mt19937(std::random_device()())); SamplesStatsCounter stats; for (double v : data) { stats.AddSample(v); } return stats; } } // namespace TEST(SamplesStatsCounter, FullSimpleTest) { SamplesStatsCounter stats = CreateStatsFilledWithIntsFrom1ToN(100); EXPECT_TRUE(!stats.IsEmpty()); EXPECT_DOUBLE_EQ(stats.GetMin(), 1.0); EXPECT_DOUBLE_EQ(stats.GetMax(), 100.0); EXPECT_DOUBLE_EQ(stats.GetAverage(), 50.5); for (int i = 1; i <= 100; i++) { double p = i / 100.0; EXPECT_GE(stats.GetPercentile(p), i); EXPECT_LT(stats.GetPercentile(p), i + 1); } } TEST(SamplesStatsCounter, VarianceAndDeviation) { SamplesStatsCounter stats; stats.AddSample(2); stats.AddSample(2); stats.AddSample(-1); stats.AddSample(5); EXPECT_DOUBLE_EQ(stats.GetAverage(), 2.0); EXPECT_DOUBLE_EQ(stats.GetVariance(), 4.5); EXPECT_DOUBLE_EQ(stats.GetStandardDeviation(), sqrt(4.5)); } TEST(SamplesStatsCounter, FractionPercentile) { SamplesStatsCounter stats = CreateStatsFilledWithIntsFrom1ToN(5); EXPECT_DOUBLE_EQ(stats.GetPercentile(0.5), 3); } TEST(SamplesStatsCounter, TestBorderValues) { SamplesStatsCounter stats = CreateStatsFilledWithIntsFrom1ToN(5); EXPECT_GE(stats.GetPercentile(0.01), 1); EXPECT_LT(stats.GetPercentile(0.01), 2); EXPECT_DOUBLE_EQ(stats.GetPercentile(1.0), 5); } } // namespace webrtc <|endoftext|>
<commit_before>#include <vector> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include "kdtree.h" void natural_neighbor(std::vector<double>& known_points); typedef boost::geometry::model::point <double, 3, boost::geometry::cs::cartesian> Point; using namespace spatial_index; std::vector<double> *natural_neighbor(std::vector<Point>& known_coordinates, std::vector<double>& known_values, std::vector<Point>& interpolation_points, int coord_max) { printf("Building KD-Tree\n"); // Build KD-Tree from known points kdtree<double> *tree = new kdtree<double>(); for (int i = 0; i < known_coordinates.size(); i ++) { tree->add(&known_coordinates[i], &known_values[i]); } tree->build(); std::vector<double> accumulator(interpolation_points.size()); std::vector<double> contribution_counter(interpolation_points.size()); for (int i = 0; i < interpolation_points.size(); i++) { accumulator[i] = 0; contribution_counter[i] = 0; } printf("Calculating scattered contributions\n"); int xscale = coord_max*coord_max; int yscale = coord_max; // Scatter method discrete Sibson for (int i = 0; i < interpolation_points.size(); i++) { if (i%10000 == 0){ printf("\tPoint %d of %d\n", i, interpolation_points.size()); } const QueryResult *q = tree->nearest_iterative(interpolation_points[i]); int r = (int) q->distance; double comparison_distance = r*r; int px = interpolation_points[i].get<0>(); int py = interpolation_points[i].get<1>(); int pz = interpolation_points[i].get<2>(); for (int x = px - r; x < px + r; x++) { if (x < 0) { continue; } for (int y = py - r; y < py + r; y++) { if (y < 0) { continue; } for (int z = pz - r; z < px + r; z++) { if (z < 0) { continue; } int idx = x*xscale + y*yscale + z; double distance_x = interpolation_points[idx].get<0>() - px; double distance_y = interpolation_points[idx].get<1>() - py; double distance_z = interpolation_points[idx].get<2>() - pz; if (distance_x*distance_x + distance_y*distance_y + distance_z*distance_z > comparison_distance){ continue; } accumulator[i] += q->value; contribution_counter[i] += 1; } } } } std::vector<double> interpolation_values(interpolation_points.size()); printf("Calculating final interpolation values (%d values)\n", (int) interpolation_values.size()); for (int i = 0; i < interpolation_values.size(); i++) { if (contribution_counter[i] != 0) { interpolation_values[i] = accumulator[i] / contribution_counter[i]; } else { interpolation_values[i] = NULL; //TODO: this is just 0, better way to mark NAN? } } delete tree; return new std::vector<double>(interpolation_values); } typedef boost::geometry::model::point <double, 3, boost::geometry::cs::cartesian> point; #define RAND_MAX 100 int main(int argc, char** argv) { printf("%d\n", RAND_MAX); int coord_max = 100; int num_known_points = 5000; std::vector<Point> known_points(num_known_points); std::vector<double> known_values(num_known_points); for (int i = 0; i < num_known_points; i++) { known_points[i] = Point(std::rand(), std::rand(), std::rand()); known_values[i] = std::rand(); } /* interpolation_points */ std::vector<Point> interpolation_points(coord_max*coord_max*coord_max); int idx = 0; for (int i = 0; i < coord_max; i++) { for (int j = 0; j < coord_max; j++) { for (int k = 0; k < coord_max; k++) { interpolation_points[idx] = Point(i, j, k); idx += 1; } } } std::vector<double>* interpolation_values = natural_neighbor(known_points, known_values, interpolation_points, coord_max); printf("Completed with %d interpolated values\n", (int) interpolation_values->size()); delete interpolation_values; } <commit_msg>Add more documentation comments<commit_after>#include <vector> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include "kdtree.h" void natural_neighbor(std::vector<double>& known_points); typedef boost::geometry::model::point <double, 3, boost::geometry::cs::cartesian> Point; using namespace spatial_index; std::vector<double> *natural_neighbor(std::vector<Point>& known_coordinates, std::vector<double>& known_values, std::vector<Point>& interpolation_points, int coord_max) { printf("Building KD-Tree\n"); kdtree<double> *tree = new kdtree<double>(); for (int i = 0; i < known_coordinates.size(); i ++) { tree->add(&known_coordinates[i], &known_values[i]); } tree->build(); std::vector<double> accumulator(interpolation_points.size()); std::vector<double> contribution_counter(interpolation_points.size()); for (int i = 0; i < interpolation_points.size(); i++) { accumulator[i] = 0; contribution_counter[i] = 0; } printf("Calculating scattered contributions\n"); int xscale = coord_max*coord_max; int yscale = coord_max; // Scatter method discrete Sibson for (int i = 0; i < interpolation_points.size(); i++) { if (i%10000 == 0){ printf("\tPoint %d of %d\n", i, interpolation_points.size()); } const QueryResult *q = tree->nearest_iterative(interpolation_points[i]); int r = (int) q->distance; double comparison_distance = r*r; int px = interpolation_points[i].get<0>(); int py = interpolation_points[i].get<1>(); int pz = interpolation_points[i].get<2>(); // Search neighboring interpolation points within a bounding box // of r indices. From this subset of points, calculate their distance // and tally the ones that fall within the sphere of radius r surrounding // interpolation_points[i]. for (int x = px - r; x < px + r; x++) { if (x < 0) { continue; } for (int y = py - r; y < py + r; y++) { if (y < 0) { continue; } for (int z = pz - r; z < px + r; z++) { if (z < 0) { continue; } int idx = x*xscale + y*yscale + z; double distance_x = interpolation_points[idx].get<0>() - px; double distance_y = interpolation_points[idx].get<1>() - py; double distance_z = interpolation_points[idx].get<2>() - pz; if (distance_x*distance_x + distance_y*distance_y + distance_z*distance_z > comparison_distance){ continue; } accumulator[i] += q->value; contribution_counter[i] += 1; } } } } std::vector<double> interpolation_values(interpolation_points.size()); printf("Calculating final interpolation values (%d values)\n", (int) interpolation_values.size()); for (int i = 0; i < interpolation_values.size(); i++) { if (contribution_counter[i] != 0) { interpolation_values[i] = accumulator[i] / contribution_counter[i]; } else { interpolation_values[i] = NULL; //TODO: this is just 0, better way to mark NAN? } } delete tree; return new std::vector<double>(interpolation_values); } typedef boost::geometry::model::point <double, 3, boost::geometry::cs::cartesian> point; #define RAND_MAX 300 int main(int argc, char** argv) { int coord_max = RAND_MAX; int num_known_points = 5000; std::vector<Point> known_points(num_known_points); std::vector<double> known_values(num_known_points); for (int i = 0; i < num_known_points; i++) { known_points[i] = Point(std::rand(), std::rand(), std::rand()); known_values[i] = std::rand(); } /* interpolation_points */ std::vector<Point> interpolation_points(coord_max*coord_max*coord_max); int idx = 0; for (int i = 0; i < coord_max; i++) { for (int j = 0; j < coord_max; j++) { for (int k = 0; k < coord_max; k++) { interpolation_points[idx] = Point(i, j, k); idx += 1; } } } std::vector<double>* interpolation_values = natural_neighbor(known_points, known_values, interpolation_points, coord_max); printf("Completed with %d interpolated values\n", (int) interpolation_values->size()); delete interpolation_values; } <|endoftext|>
<commit_before>/* Copyright (c) 2013 250bpm s.r.o. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NN_HPP_INCLUDED #define NN_HPP_INCLUDED #include <nanomsg/nn.h> #include <cassert> #include <cstring> #include <algorithm> #include <exception> #if defined __GNUC__ #define nn_slow(x) __builtin_expect ((x), 0) #else #define nn_slow(x) (x) #endif namespace nn { class exception : public std::exception { public: exception () : err (nn_errno ()) {} virtual const char *what () const throw () { return nn_strerror (err); } int num () const { return err; } private: int err; }; inline void version (int *major, int *minor, int *patch) { nn_version (major, minor, patch); } class context { public: inline context () { int rc = nn_init (); if (nn_slow (rc != 0)) throw nn::exception (); } inline ~context () { int rc = nn_term (); assert (rc == 0); } }; inline void *allocmsg (size_t size, int type) { void *msg = nn_allocmsg (size, type); if (nn_slow (!msg)) throw nn::exception (); } inline int freemsg (void *msg) { int rc = nn_freemsg (msg); if (nn_slow (rc != 0)) throw nn::exception (); } class socket { public: inline socket (int domain, int protocol) { s = nn_socket (domain, protocol); if (nn_slow (s < 0)) throw nn::exception (); } inline ~socket () { int rc = nn_close (s); assert (rc == 0); } inline void setsockopt (int level, int option, const void *optval, size_t optvallen) { int rc = nn_setsockopt (s, level, option, optval, optvallen); if (nn_slow (rc != 0)) throw nn::exception (); } inline void getsockopt (int level, int option, void *optval, size_t *optvallen) { int rc = nn_getsockopt (s, level, option, optval, optvallen); if (nn_slow (rc != 0)) throw nn::exception (); } inline int bind (const char *addr) { int rc = nn_bind (s, addr); if (nn_slow (rc < 0)) throw nn::exception (); return rc; } inline int connect (const char *addr) { int rc = nn_connect (s, addr); if (nn_slow (rc < 0)) throw nn::exception (); return rc; } inline void shutdown (int how) { int rc = nn_shutdown (s, how); if (nn_slow (rc != 0)) throw nn::exception (); } inline bool send (const void *buf, size_t len, int flags) { int rc = nn_send (s, buf, len, flags); if (nn_slow (rc < 0)) { if (nn_slow (nn_errno () != EAGAIN)) throw nn::exception (); return false; } return true; } inline bool recv (void *buf, size_t len, int flags) { int rc = nn_recv (s, buf, len, flags); if (nn_slow (rc < 0)) { if (nn_slow (nn_errno () != EAGAIN)) throw nn::exception (); return false; } return true; } inline bool sendmsg (const struct nn_msghdr *msghdr, int flags) { int rc = nn_sendmsg (s, msghdr, flags); if (nn_slow (rc < 0)) { if (nn_slow (nn_errno () != EAGAIN)) throw nn::exception (); return false; } return true; } inline bool recvmsg (struct nn_msghdr *msghdr, int flags) { int rc = nn_recvmsg (s, msghdr, flags); if (nn_slow (rc < 0)) { if (nn_slow (nn_errno () != EAGAIN)) throw nn::exception (); return false; } return true; } private: int s; /* Prevent making copies of the socket by accident. */ socket (const socket&); void operator = (const socket&); }; } #undef nn_slow #endif <commit_msg>send/recv functions return the size of the message<commit_after>/* Copyright (c) 2013 250bpm s.r.o. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NN_HPP_INCLUDED #define NN_HPP_INCLUDED #include <nanomsg/nn.h> #include <cassert> #include <cstring> #include <algorithm> #include <exception> #if defined __GNUC__ #define nn_slow(x) __builtin_expect ((x), 0) #else #define nn_slow(x) (x) #endif namespace nn { class exception : public std::exception { public: exception () : err (nn_errno ()) {} virtual const char *what () const throw () { return nn_strerror (err); } int num () const { return err; } private: int err; }; inline void version (int *major, int *minor, int *patch) { nn_version (major, minor, patch); } class context { public: inline context () { int rc = nn_init (); if (nn_slow (rc != 0)) throw nn::exception (); } inline ~context () { int rc = nn_term (); assert (rc == 0); } }; inline void *allocmsg (size_t size, int type) { void *msg = nn_allocmsg (size, type); if (nn_slow (!msg)) throw nn::exception (); } inline int freemsg (void *msg) { int rc = nn_freemsg (msg); if (nn_slow (rc != 0)) throw nn::exception (); } class socket { public: inline socket (int domain, int protocol) { s = nn_socket (domain, protocol); if (nn_slow (s < 0)) throw nn::exception (); } inline ~socket () { int rc = nn_close (s); assert (rc == 0); } inline void setsockopt (int level, int option, const void *optval, size_t optvallen) { int rc = nn_setsockopt (s, level, option, optval, optvallen); if (nn_slow (rc != 0)) throw nn::exception (); } inline void getsockopt (int level, int option, void *optval, size_t *optvallen) { int rc = nn_getsockopt (s, level, option, optval, optvallen); if (nn_slow (rc != 0)) throw nn::exception (); } inline int bind (const char *addr) { int rc = nn_bind (s, addr); if (nn_slow (rc < 0)) throw nn::exception (); return rc; } inline int connect (const char *addr) { int rc = nn_connect (s, addr); if (nn_slow (rc < 0)) throw nn::exception (); return rc; } inline void shutdown (int how) { int rc = nn_shutdown (s, how); if (nn_slow (rc != 0)) throw nn::exception (); } inline int send (const void *buf, size_t len, int flags) { int rc = nn_send (s, buf, len, flags); if (nn_slow (rc < 0)) { if (nn_slow (nn_errno () != EAGAIN)) throw nn::exception (); return -1; } return rc; } inline int recv (void *buf, size_t len, int flags) { int rc = nn_recv (s, buf, len, flags); if (nn_slow (rc < 0)) { if (nn_slow (nn_errno () != EAGAIN)) throw nn::exception (); return -1; } return rc; } inline int sendmsg (const struct nn_msghdr *msghdr, int flags) { int rc = nn_sendmsg (s, msghdr, flags); if (nn_slow (rc < 0)) { if (nn_slow (nn_errno () != EAGAIN)) throw nn::exception (); return -1; } return rc; } inline int recvmsg (struct nn_msghdr *msghdr, int flags) { int rc = nn_recvmsg (s, msghdr, flags); if (nn_slow (rc < 0)) { if (nn_slow (nn_errno () != EAGAIN)) throw nn::exception (); return -1; } return rc; } private: int s; /* Prevent making copies of the socket by accident. */ socket (const socket&); void operator = (const socket&); }; } #undef nn_slow #endif <|endoftext|>
<commit_before>#ifndef NETWORKING_H #define NETWORKING_H #include <iostream> #include <set> #ifdef _WIN32 #include <windows.h> #include <tchar.h> #include <stdio.h> #include <strsafe.h> #else #include <signal.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <unistd.h> #endif #include "../core/hlt.hpp" extern bool quiet_output; class Networking { public: void startAndConnectBot(std::string command); void handleInitNetworking(unsigned char playerTag, const hlt::Map & m, int * playerMillis, std::string * playerName); void handleFrameNetworking(unsigned char playerTag, const hlt::Map & m, int * playermillis, std::set<hlt::Move> * moves); void killPlayer(unsigned char playerTag); bool isProcessDead(unsigned char playerTag); int numberOfPlayers(); std::vector< std::string> player_logs; private: #ifdef _WIN32 struct WinConnection { HANDLE write, read; }; std::vector<WinConnection> connections; std::vector<HANDLE> processes; #else struct UniConnection { int read, write; }; std::vector< UniConnection > connections; std::vector<int> processes; #endif std::string serializeMap(const hlt::Map & map); std::set<hlt::Move> deserializeMoveSet(std::string & inputString, const hlt::Map & m); void sendString(unsigned char playerTag, std::string &sendString); std::string getString(unsigned char playerTag, unsigned int timoutMillis); }; #endif <commit_msg>In hpp, Fixed additional space<commit_after>#ifndef NETWORKING_H #define NETWORKING_H #include <iostream> #include <set> #ifdef _WIN32 #include <windows.h> #include <tchar.h> #include <stdio.h> #include <strsafe.h> #else #include <signal.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <unistd.h> #endif #include "../core/hlt.hpp" extern bool quiet_output; class Networking { public: void startAndConnectBot(std::string command); void handleInitNetworking(unsigned char playerTag, const hlt::Map & m, int * playerMillis, std::string * playerName); void handleFrameNetworking(unsigned char playerTag, const hlt::Map & m, int * playermillis, std::set<hlt::Move> * moves); void killPlayer(unsigned char playerTag); bool isProcessDead(unsigned char playerTag); int numberOfPlayers(); std::vector<std::string> player_logs; private: #ifdef _WIN32 struct WinConnection { HANDLE write, read; }; std::vector<WinConnection> connections; std::vector<HANDLE> processes; #else struct UniConnection { int read, write; }; std::vector< UniConnection > connections; std::vector<int> processes; #endif std::string serializeMap(const hlt::Map & map); std::set<hlt::Move> deserializeMoveSet(std::string & inputString, const hlt::Map & m); void sendString(unsigned char playerTag, std::string &sendString); std::string getString(unsigned char playerTag, unsigned int timoutMillis); }; #endif <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if defined(OS_WIN) #include <windows.h> #endif #include <stack> #include "chrome/common/ipc_sync_message.h" #include "base/logging.h" namespace IPC { uint32 SyncMessage::next_id_ = 0; #define kSyncMessageHeaderSize 4 #if defined(OS_WIN) // TODO(playmobil): reinstantiate once ObjectWatcher is ported. // A dummy handle used by EnableMessagePumping. HANDLE dummy_event = ::CreateEvent(NULL, TRUE, TRUE, NULL); #endif SyncMessage::SyncMessage( int32 routing_id, uint16 type, PriorityValue priority, MessageReplyDeserializer* deserializer) : Message(routing_id, type, priority), deserializer_(deserializer) #if defined(OS_WIN) // TODO(playmobil): reinstantiate once ObjectWatcher is ported. , pump_messages_event_(NULL) #endif { set_sync(); set_unblock(true); // Add synchronous message data before the message payload. SyncHeader header; header.message_id = ++next_id_; WriteSyncHeader(this, header); } MessageReplyDeserializer* SyncMessage::GetReplyDeserializer() { MessageReplyDeserializer* rv = deserializer_; DCHECK(rv); deserializer_ = NULL; return rv; } #if defined(OS_WIN) // TODO(playmobil): reinstantiate once ObjectWatcher is ported. void SyncMessage::EnableMessagePumping() { DCHECK(!pump_messages_event_); set_pump_messages_event(dummy_event); } #endif // defined(OS_WIN) bool SyncMessage::IsMessageReplyTo(const Message& msg, int request_id) { if (!msg.is_reply()) return false; return GetMessageId(msg) == request_id; } void* SyncMessage::GetDataIterator(const Message* msg) { void* iter = const_cast<char*>(msg->payload()); UpdateIter(&iter, kSyncMessageHeaderSize); return iter; } int SyncMessage::GetMessageId(const Message& msg) { if (!msg.is_sync() && !msg.is_reply()) return 0; SyncHeader header; if (!ReadSyncHeader(msg, &header)) return 0; return header.message_id; } Message* SyncMessage::GenerateReply(const Message* msg) { DCHECK(msg->is_sync()); Message* reply = new Message(msg->routing_id(), IPC_REPLY_ID, msg->priority()); reply->set_reply(); SyncHeader header; // use the same message id, but this time reply bit is set header.message_id = GetMessageId(*msg); WriteSyncHeader(reply, header); return reply; } bool SyncMessage::ReadSyncHeader(const Message& msg, SyncHeader* header) { DCHECK(msg.is_sync() || msg.is_reply()); void* iter = NULL; bool result = msg.ReadInt(&iter, &header->message_id); if (!result) { NOTREACHED(); return false; } return true; } bool SyncMessage::WriteSyncHeader(Message* msg, const SyncHeader& header) { DCHECK(msg->is_sync() || msg->is_reply()); DCHECK(msg->payload_size() == 0); bool result = msg->WriteInt(header.message_id); if (!result) { NOTREACHED(); return false; } // Note: if you add anything here, you need to update kSyncMessageHeaderSize. DCHECK(kSyncMessageHeaderSize == msg->payload_size()); return true; } bool MessageReplyDeserializer::SerializeOutputParameters(const Message& msg) { return SerializeOutputParameters(msg, SyncMessage::GetDataIterator(&msg)); } } // namespace IPC <commit_msg>Fix Win/Release build bustage.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include <stack> #include "chrome/common/ipc_sync_message.h" #include "base/logging.h" namespace IPC { uint32 SyncMessage::next_id_ = 0; #define kSyncMessageHeaderSize 4 #if defined(OS_WIN) // TODO(playmobil): reinstantiate once ObjectWatcher is ported. // A dummy handle used by EnableMessagePumping. HANDLE dummy_event = ::CreateEvent(NULL, TRUE, TRUE, NULL); #endif SyncMessage::SyncMessage( int32 routing_id, uint16 type, PriorityValue priority, MessageReplyDeserializer* deserializer) : Message(routing_id, type, priority), deserializer_(deserializer) #if defined(OS_WIN) // TODO(playmobil): reinstantiate once ObjectWatcher is ported. , pump_messages_event_(NULL) #endif { set_sync(); set_unblock(true); // Add synchronous message data before the message payload. SyncHeader header; header.message_id = ++next_id_; WriteSyncHeader(this, header); } MessageReplyDeserializer* SyncMessage::GetReplyDeserializer() { MessageReplyDeserializer* rv = deserializer_; DCHECK(rv); deserializer_ = NULL; return rv; } #if defined(OS_WIN) // TODO(playmobil): reinstantiate once ObjectWatcher is ported. void SyncMessage::EnableMessagePumping() { DCHECK(!pump_messages_event_); set_pump_messages_event(dummy_event); } #endif // defined(OS_WIN) bool SyncMessage::IsMessageReplyTo(const Message& msg, int request_id) { if (!msg.is_reply()) return false; return GetMessageId(msg) == request_id; } void* SyncMessage::GetDataIterator(const Message* msg) { void* iter = const_cast<char*>(msg->payload()); UpdateIter(&iter, kSyncMessageHeaderSize); return iter; } int SyncMessage::GetMessageId(const Message& msg) { if (!msg.is_sync() && !msg.is_reply()) return 0; SyncHeader header; if (!ReadSyncHeader(msg, &header)) return 0; return header.message_id; } Message* SyncMessage::GenerateReply(const Message* msg) { DCHECK(msg->is_sync()); Message* reply = new Message(msg->routing_id(), IPC_REPLY_ID, msg->priority()); reply->set_reply(); SyncHeader header; // use the same message id, but this time reply bit is set header.message_id = GetMessageId(*msg); WriteSyncHeader(reply, header); return reply; } bool SyncMessage::ReadSyncHeader(const Message& msg, SyncHeader* header) { DCHECK(msg.is_sync() || msg.is_reply()); void* iter = NULL; bool result = msg.ReadInt(&iter, &header->message_id); if (!result) { NOTREACHED(); return false; } return true; } bool SyncMessage::WriteSyncHeader(Message* msg, const SyncHeader& header) { DCHECK(msg->is_sync() || msg->is_reply()); DCHECK(msg->payload_size() == 0); bool result = msg->WriteInt(header.message_id); if (!result) { NOTREACHED(); return false; } // Note: if you add anything here, you need to update kSyncMessageHeaderSize. DCHECK(kSyncMessageHeaderSize == msg->payload_size()); return true; } bool MessageReplyDeserializer::SerializeOutputParameters(const Message& msg) { return SerializeOutputParameters(msg, SyncMessage::GetDataIterator(&msg)); } } // namespace IPC <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/environment.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/stringprintf.h" #include "base/string_number_conversions.h" #include "base/sys_info.h" #include "base/time.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "chrome/test/automation/automation_proxy.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/perf/perf_test.h" #include "chrome/test/ui/ui_perf_test.h" #include "net/base/net_util.h" using base::TimeDelta; namespace { class ShutdownTest : public UIPerfTest { public: ShutdownTest() { show_window_ = true; } void SetUp() {} void TearDown() {} enum TestSize { SIMPLE, // Runs with no command line arguments (loads about:blank). TWENTY_TABS, // Opens 5 copies of 4 different test pages. }; void SetUpTwentyTabs() { int window_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); ASSERT_EQ(1, window_count); scoped_refptr<BrowserProxy> browser_proxy( automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); const FilePath kFastShutdownDir(FILE_PATH_LITERAL("fast_shutdown")); const FilePath kCurrentDir(FilePath::kCurrentDirectory); const FilePath test_cases[] = { ui_test_utils::GetTestFilePath(kFastShutdownDir, FilePath(FILE_PATH_LITERAL("on_before_unloader.html"))), ui_test_utils::GetTestFilePath(kCurrentDir, FilePath(FILE_PATH_LITERAL("animated-gifs.html"))), ui_test_utils::GetTestFilePath(kCurrentDir, FilePath(FILE_PATH_LITERAL("french_page.html"))), ui_test_utils::GetTestFilePath(kCurrentDir, FilePath(FILE_PATH_LITERAL("onunload_cookie.html"))), }; for (size_t i = 0; i < arraysize(test_cases); i++) { ASSERT_TRUE(file_util::PathExists(test_cases[i])); for (size_t j = 0; j < 5; j++) { ASSERT_TRUE(browser_proxy->AppendTab( net::FilePathToFileURL(test_cases[i]))); } } } void RunShutdownTest(const char* graph, const char* trace, bool important, TestSize test_size, ProxyLauncher::ShutdownType shutdown_type) { const int kNumCyclesMax = 20; int numCycles = kNumCyclesMax; scoped_ptr<base::Environment> env(base::Environment::Create()); std::string numCyclesEnv; if (env->GetVar(env_vars::kStartupTestsNumCycles, &numCyclesEnv) && base::StringToInt(numCyclesEnv, &numCycles)) { if (numCycles <= kNumCyclesMax) { VLOG(1) << env_vars::kStartupTestsNumCycles << " set in environment, so setting numCycles to " << numCycles; } else { VLOG(1) << env_vars::kStartupTestsNumCycles << " is higher than the max, setting numCycles to " << kNumCyclesMax; numCycles = kNumCyclesMax; } } TimeDelta timings[kNumCyclesMax]; for (int i = 0; i < numCycles; ++i) { UITest::SetUp(); if (test_size == TWENTY_TABS) { SetUpTwentyTabs(); } set_shutdown_type(shutdown_type); UITest::TearDown(); timings[i] = browser_quit_time(); if (i == 0) { // Re-use the profile data after first run so that the noise from // creating databases doesn't impact all the runs. clear_profile_ = false; // Clear template_user_data_ so we don't try to copy it over each time // through. set_template_user_data(FilePath()); } } std::string times; for (int i = 0; i < numCycles; ++i) base::StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF()); perf_test::PrintResultList(graph, "", trace, times, "ms", important); } }; TEST_F(ShutdownTest, SimpleWindowClose) { RunShutdownTest("shutdown", "simple-window-close", true, /* important */ SIMPLE, ProxyLauncher::WINDOW_CLOSE); } TEST_F(ShutdownTest, SimpleUserQuit) { RunShutdownTest("shutdown", "simple-user-quit", true, /* important */ SIMPLE, ProxyLauncher::USER_QUIT); } TEST_F(ShutdownTest, SimpleSessionEnding) { RunShutdownTest("shutdown", "simple-session-ending", true, /* important */ SIMPLE, ProxyLauncher::SESSION_ENDING); } TEST_F(ShutdownTest, TwentyTabsWindowClose) { RunShutdownTest("shutdown", "twentytabs-window-close", true, /* important */ TWENTY_TABS, ProxyLauncher::WINDOW_CLOSE); } TEST_F(ShutdownTest, TwentyTabsUserQuit) { RunShutdownTest("shutdown", "twentytabs-user-quit", true, /* important */ TWENTY_TABS, ProxyLauncher::USER_QUIT); } // http://crbug.com/40671 #if defined(OS_WIN) && !defined(NDEBUG) #define MAYBE_TwentyTabsSessionEnding DISABLED_TwentyTabsSessionEnding #else #define MAYBE_TwentyTabsSessionEnding TwentyTabsSessionEnding #endif TEST_F(ShutdownTest, MAYBE_TwentyTabsSessionEnding) { RunShutdownTest("shutdown", "twentytabs-session-ending", true, /* important */ TWENTY_TABS, ProxyLauncher::SESSION_ENDING); } } // namespace <commit_msg>Mark TwentyTabsWindowClose on Windows debug disabled for now.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/environment.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/stringprintf.h" #include "base/string_number_conversions.h" #include "base/sys_info.h" #include "base/time.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "chrome/test/automation/automation_proxy.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/perf/perf_test.h" #include "chrome/test/ui/ui_perf_test.h" #include "net/base/net_util.h" using base::TimeDelta; namespace { class ShutdownTest : public UIPerfTest { public: ShutdownTest() { show_window_ = true; } void SetUp() {} void TearDown() {} enum TestSize { SIMPLE, // Runs with no command line arguments (loads about:blank). TWENTY_TABS, // Opens 5 copies of 4 different test pages. }; void SetUpTwentyTabs() { int window_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); ASSERT_EQ(1, window_count); scoped_refptr<BrowserProxy> browser_proxy( automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); const FilePath kFastShutdownDir(FILE_PATH_LITERAL("fast_shutdown")); const FilePath kCurrentDir(FilePath::kCurrentDirectory); const FilePath test_cases[] = { ui_test_utils::GetTestFilePath(kFastShutdownDir, FilePath(FILE_PATH_LITERAL("on_before_unloader.html"))), ui_test_utils::GetTestFilePath(kCurrentDir, FilePath(FILE_PATH_LITERAL("animated-gifs.html"))), ui_test_utils::GetTestFilePath(kCurrentDir, FilePath(FILE_PATH_LITERAL("french_page.html"))), ui_test_utils::GetTestFilePath(kCurrentDir, FilePath(FILE_PATH_LITERAL("onunload_cookie.html"))), }; for (size_t i = 0; i < arraysize(test_cases); i++) { ASSERT_TRUE(file_util::PathExists(test_cases[i])); for (size_t j = 0; j < 5; j++) { ASSERT_TRUE(browser_proxy->AppendTab( net::FilePathToFileURL(test_cases[i]))); } } } void RunShutdownTest(const char* graph, const char* trace, bool important, TestSize test_size, ProxyLauncher::ShutdownType shutdown_type) { const int kNumCyclesMax = 20; int numCycles = kNumCyclesMax; scoped_ptr<base::Environment> env(base::Environment::Create()); std::string numCyclesEnv; if (env->GetVar(env_vars::kStartupTestsNumCycles, &numCyclesEnv) && base::StringToInt(numCyclesEnv, &numCycles)) { if (numCycles <= kNumCyclesMax) { VLOG(1) << env_vars::kStartupTestsNumCycles << " set in environment, so setting numCycles to " << numCycles; } else { VLOG(1) << env_vars::kStartupTestsNumCycles << " is higher than the max, setting numCycles to " << kNumCyclesMax; numCycles = kNumCyclesMax; } } TimeDelta timings[kNumCyclesMax]; for (int i = 0; i < numCycles; ++i) { UITest::SetUp(); if (test_size == TWENTY_TABS) { SetUpTwentyTabs(); } set_shutdown_type(shutdown_type); UITest::TearDown(); timings[i] = browser_quit_time(); if (i == 0) { // Re-use the profile data after first run so that the noise from // creating databases doesn't impact all the runs. clear_profile_ = false; // Clear template_user_data_ so we don't try to copy it over each time // through. set_template_user_data(FilePath()); } } std::string times; for (int i = 0; i < numCycles; ++i) base::StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF()); perf_test::PrintResultList(graph, "", trace, times, "ms", important); } }; TEST_F(ShutdownTest, SimpleWindowClose) { RunShutdownTest("shutdown", "simple-window-close", true, /* important */ SIMPLE, ProxyLauncher::WINDOW_CLOSE); } TEST_F(ShutdownTest, SimpleUserQuit) { RunShutdownTest("shutdown", "simple-user-quit", true, /* important */ SIMPLE, ProxyLauncher::USER_QUIT); } TEST_F(ShutdownTest, SimpleSessionEnding) { RunShutdownTest("shutdown", "simple-session-ending", true, /* important */ SIMPLE, ProxyLauncher::SESSION_ENDING); } // http://crbug.com/110471 #if defined(OS_WIN) && !defined(NDEBUG) #define MAYBE_TwentyTabsWindowClose DISABLED_TwentyTabsWindowClose #else #define MAYBE_TwentyTabsWindowClose TwentyTabsWindowClose #endif TEST_F(ShutdownTest, MAYBE_TwentyTabsWindowClose) { RunShutdownTest("shutdown", "twentytabs-window-close", true, /* important */ TWENTY_TABS, ProxyLauncher::WINDOW_CLOSE); } TEST_F(ShutdownTest, TwentyTabsUserQuit) { RunShutdownTest("shutdown", "twentytabs-user-quit", true, /* important */ TWENTY_TABS, ProxyLauncher::USER_QUIT); } // http://crbug.com/40671 #if defined(OS_WIN) && !defined(NDEBUG) #define MAYBE_TwentyTabsSessionEnding DISABLED_TwentyTabsSessionEnding #else #define MAYBE_TwentyTabsSessionEnding TwentyTabsSessionEnding #endif TEST_F(ShutdownTest, MAYBE_TwentyTabsSessionEnding) { RunShutdownTest("shutdown", "twentytabs-session-ending", true, /* important */ TWENTY_TABS, ProxyLauncher::SESSION_ENDING); } } // namespace <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formstrings.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-16 13:18:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #ifndef _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_ #define PCR_IMPLEMENT_STRINGS #include "formstrings.hxx" #undef PCR_IMPLEMENT_STRINGS #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.276); FILE MERGED 2008/03/31 12:31:44 rt 1.4.276.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formstrings.cxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #ifndef _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_ #define PCR_IMPLEMENT_STRINGS #include "formstrings.hxx" #undef PCR_IMPLEMENT_STRINGS #endif <|endoftext|>
<commit_before>/* * * Copyright 2018 Asylo authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <memory> #include <regex> #include <string> #include <thread> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/memory/memory.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include "grpc_server/translator_server.grpc.pb.h" #include "gflags/gflags.h" #include "asylo/util/logging.h" #include "asylo/test/util/exec_tester.h" #include "asylo/test/util/status_matchers.h" #include "asylo/util/status.h" #include "include/grpcpp/grpcpp.h" #include "include/grpcpp/security/credentials.h" #include "include/grpcpp/security/server_credentials.h" DEFINE_string(enclave_path, "", "The path to the server enclave to pass to the enclave loader"); // The number of seconds to run the server for this test. constexpr int kServerLifetime = 1; // A regex matching the log message that contains the port. constexpr char kPortMessageRegex[] = "Server started on port [0-9]+"; namespace examples { namespace grpc_server { namespace { using asylo::IsOk; using asylo::StatusIs; // An ExecTester that scans stderr for the "Server started" log message from // the gRPC server enclave. If it finds the startup message, it writes the // server's port to an external buffer. class ServerEnclaveExecTester : public asylo::experimental::ExecTester { public: ServerEnclaveExecTester(const std::vector<std::string> &args, absl::Mutex *server_port_mutex, int *server_port) : ExecTester(args), server_port_found_(false), server_port_mutex_(server_port_mutex), server_port_(server_port) {} protected: bool CheckLine(const std::string &line) override LOCKS_EXCLUDED(*server_port_mutex_) { const std::regex port_message_regex(kPortMessageRegex); const std::regex port_regex("[0-9]+"); // Check if the line matches kPortMessageRegex. If so, put the port number // in |*server_port_|. std::cmatch port_message_match; if (std::regex_search(line.c_str(), port_message_match, port_message_regex)) { std::cmatch port_match; EXPECT_TRUE(std::regex_search(port_message_match.str().c_str(), port_match, port_regex)); server_port_found_ = true; absl::MutexLock lock(server_port_mutex_); EXPECT_TRUE(absl::SimpleAtoi(port_match.str(), server_port_)); } return true; } bool FinalCheck(bool accumulated) override LOCKS_EXCLUDED(*server_port_mutex_) { return accumulated && server_port_found_; } bool server_port_found_; absl::Mutex *server_port_mutex_; int *server_port_ PT_GUARDED_BY(*server_port_mutex_); }; class GrpcServerTest : public ::testing::Test { public: // Spawns the enclave loader subprocess and waits for it to log the port // number. Fails if the log message is never seen. void SetUp() override LOCKS_EXCLUDED(server_port_mutex_) { ASSERT_NE(FLAGS_enclave_path, ""); const std::vector<std::string> argv({ asylo::experimental::ExecTester::BuildSiblingPath( FLAGS_enclave_path, "grpc_server_host_loader"), absl::StrCat("--enclave_path=", FLAGS_enclave_path), absl::StrCat("--server_lifetime=", kServerLifetime), }); // Set server_port_ to -1 so that the Condition below knows when // server_port_ has changed. server_port_found_ = false; { absl::MutexLock lock(&server_port_mutex_); server_port_ = -1; } // Run the server ExecTester in a separate thread. server_thread_ = absl::make_unique<std::thread>( [this](const std::vector<std::string> &argv) { ServerEnclaveExecTester server_runner(argv, &server_port_mutex_, &server_port_); server_port_found_ = server_runner.Run(/*input=*/"", &server_exit_status_); }, argv); // Wait until server_thread_ sets server_port_ with a deadline of // kServerLifetime + 1 seconds. absl::Duration server_port_waiter_timeout = absl::Seconds(kServerLifetime + 1); int port = GetServerPort(server_port_waiter_timeout); // Set up the client stub. std::shared_ptr<::grpc::ChannelCredentials> credentials = ::grpc::InsecureChannelCredentials(); std::string server_address = absl::StrCat("dns:///localhost:", port); std::shared_ptr<::grpc::Channel> channel = ::grpc::CreateChannel(server_address, credentials); stub_ = Translator::NewStub(channel); } void TearDown() override { server_thread_->join(); ASSERT_TRUE(server_port_found_); EXPECT_EQ(server_exit_status_, 0); } // Sends a GetTranslation RPC to the server. Returns the same grpc::Status as // the stub function call. If the RPC is successful, then sets // |*translated_word| to the received translation. asylo::Status MakeRpc(const std::string &input_word, std::string *translated_word) { ::grpc::ClientContext context; GetTranslationRequest request; GetTranslationResponse response; request.set_input_word(input_word); ::grpc::Status status = stub_->GetTranslation(&context, request, &response); if (status.ok()) { *translated_word = response.translated_word(); } return asylo::Status(status); } private: int GetServerPort(absl::Duration timeout) { server_port_mutex_.LockWhenWithTimeout( absl::Condition(+[](int *server_port) { return *server_port != -1; }, &server_port_), timeout); int result = server_port_; server_port_mutex_.Unlock(); return result; } std::unique_ptr<std::thread> server_thread_; // These values don't need to be guarded by a mutex because they are not read // until the ExecTester thread (which writes to them) has been joined. bool server_port_found_; int server_exit_status_; absl::Mutex server_port_mutex_; int server_port_ GUARDED_BY(server_port_mutex_); std::unique_ptr<Translator::Stub> stub_; }; TEST_F(GrpcServerTest, AsyloTranslatesToSanctuary) { std::string asylo_translation; ASSERT_THAT(MakeRpc("asylo", &asylo_translation), IsOk()); EXPECT_EQ(asylo_translation, "sanctuary"); } TEST_F(GrpcServerTest, IstioTranslatesToSail) { std::string istio_translation; ASSERT_THAT(MakeRpc("istio", &istio_translation), IsOk()); EXPECT_EQ(istio_translation, "sail"); } TEST_F(GrpcServerTest, KubernetesTranslatesToHelmsman) { std::string kubernetes_translation; ASSERT_THAT(MakeRpc("kubernetes", &kubernetes_translation), IsOk()); EXPECT_EQ(kubernetes_translation, "helmsman"); } TEST_F(GrpcServerTest, OrkutTranslationNotFound) { std::string orkut_translation; asylo::Status status = MakeRpc("orkut", &orkut_translation); ASSERT_THAT(status, StatusIs(asylo::error::INVALID_ARGUMENT)); EXPECT_EQ(status.error_message(), "No known translation for \"orkut\""); } } // namespace } // namespace grpc_server } // namespace examples int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); ::google::ParseCommandLineFlags(&argc, &argv, /*remove_flags=*/ true); return RUN_ALL_TESTS(); } <commit_msg>Fix status check and flakes in gRPC example test<commit_after>/* * * Copyright 2018 Asylo authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <sys/wait.h> #include <memory> #include <regex> #include <string> #include <thread> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/memory/memory.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include "grpc_server/translator_server.grpc.pb.h" #include "gflags/gflags.h" #include "asylo/util/logging.h" #include "asylo/test/util/exec_tester.h" #include "asylo/test/util/status_matchers.h" #include "asylo/util/status.h" #include "include/grpcpp/grpcpp.h" #include "include/grpcpp/security/credentials.h" #include "include/grpcpp/security/server_credentials.h" DEFINE_string(enclave_path, "", "The path to the server enclave to pass to the enclave loader"); // The number of seconds to run the server for this test. constexpr int kServerLifetime = 1; // The number of seconds to wait for the server subprocess to print the server's // port number. constexpr int kServerPortDeadline = kServerLifetime + 3; // A regex matching the log message that contains the port. constexpr char kPortMessageRegex[] = "Server started on port [0-9]+"; namespace examples { namespace grpc_server { namespace { using asylo::IsOk; using asylo::StatusIs; // An ExecTester that scans stderr for the "Server started" log message from // the gRPC server enclave. If it finds the startup message, it writes the // server's port to an external buffer. class ServerEnclaveExecTester : public asylo::experimental::ExecTester { public: ServerEnclaveExecTester(const std::vector<std::string> &args, absl::Mutex *server_port_mutex, int *server_port) : ExecTester(args), server_port_found_(false), server_port_mutex_(server_port_mutex), server_port_(server_port) {} protected: bool CheckLine(const std::string &line) override LOCKS_EXCLUDED(*server_port_mutex_) { const std::regex port_message_regex(kPortMessageRegex); const std::regex port_regex("[0-9]+"); // Check if the line matches kPortMessageRegex. If so, put the port number // in |*server_port_|. std::cmatch port_message_match; if (std::regex_search(line.c_str(), port_message_match, port_message_regex)) { std::cmatch port_match; EXPECT_TRUE(std::regex_search(port_message_match.str().c_str(), port_match, port_regex)); server_port_found_ = true; absl::MutexLock lock(server_port_mutex_); EXPECT_TRUE(absl::SimpleAtoi(port_match.str(), server_port_)); } return true; } bool FinalCheck(bool accumulated) override LOCKS_EXCLUDED(*server_port_mutex_) { return accumulated && server_port_found_; } bool server_port_found_; absl::Mutex *server_port_mutex_; int *server_port_ PT_GUARDED_BY(*server_port_mutex_); }; class GrpcServerTest : public ::testing::Test { public: // Spawns the enclave loader subprocess and waits for it to log the port // number. Fails if the log message is never seen. void SetUp() override LOCKS_EXCLUDED(server_port_mutex_) { ASSERT_NE(FLAGS_enclave_path, ""); const std::vector<std::string> argv({ asylo::experimental::ExecTester::BuildSiblingPath( FLAGS_enclave_path, "grpc_server_host_loader"), absl::StrCat("--enclave_path=", FLAGS_enclave_path), absl::StrCat("--server_lifetime=", kServerLifetime), }); // Set server_port_ to -1 so that the Condition below knows when // server_port_ has changed. server_port_found_ = false; { absl::MutexLock lock(&server_port_mutex_); server_port_ = -1; } // Run the server ExecTester in a separate thread. server_thread_ = absl::make_unique<std::thread>( [this](const std::vector<std::string> &argv) { ServerEnclaveExecTester server_runner(argv, &server_port_mutex_, &server_port_); server_port_found_ = server_runner.Run(/*input=*/"", &server_exit_status_); }, argv); // Wait until server_thread_ sets server_port_ with a deadline of // kServerPortDeadline seconds. absl::Duration server_port_waiter_timeout = absl::Seconds(kServerPortDeadline); int port = GetServerPort(server_port_waiter_timeout); // Set up the client stub. std::shared_ptr<::grpc::ChannelCredentials> credentials = ::grpc::InsecureChannelCredentials(); std::string server_address = absl::StrCat("dns:///localhost:", port); std::shared_ptr<::grpc::Channel> channel = ::grpc::CreateChannel(server_address, credentials); stub_ = Translator::NewStub(channel); } void TearDown() override { server_thread_->join(); ASSERT_TRUE(server_port_found_); ASSERT_TRUE(WIFEXITED(server_exit_status_)); EXPECT_EQ(WEXITSTATUS(server_exit_status_), 0); } // Sends a GetTranslation RPC to the server. Returns the same grpc::Status as // the stub function call. If the RPC is successful, then sets // |*translated_word| to the received translation. asylo::Status MakeRpc(const std::string &input_word, std::string *translated_word) { ::grpc::ClientContext context; GetTranslationRequest request; GetTranslationResponse response; request.set_input_word(input_word); ::grpc::Status status = stub_->GetTranslation(&context, request, &response); if (status.ok()) { *translated_word = response.translated_word(); } return asylo::Status(status); } private: int GetServerPort(absl::Duration timeout) { server_port_mutex_.LockWhenWithTimeout( absl::Condition(+[](int *server_port) { return *server_port != -1; }, &server_port_), timeout); int result = server_port_; server_port_mutex_.Unlock(); return result; } std::unique_ptr<std::thread> server_thread_; // These values don't need to be guarded by a mutex because they are not read // until the ExecTester thread (which writes to them) has been joined. bool server_port_found_; int server_exit_status_; absl::Mutex server_port_mutex_; int server_port_ GUARDED_BY(server_port_mutex_); std::unique_ptr<Translator::Stub> stub_; }; TEST_F(GrpcServerTest, AsyloTranslatesToSanctuary) { std::string asylo_translation; ASSERT_THAT(MakeRpc("asylo", &asylo_translation), IsOk()); EXPECT_EQ(asylo_translation, "sanctuary"); } TEST_F(GrpcServerTest, IstioTranslatesToSail) { std::string istio_translation; ASSERT_THAT(MakeRpc("istio", &istio_translation), IsOk()); EXPECT_EQ(istio_translation, "sail"); } TEST_F(GrpcServerTest, KubernetesTranslatesToHelmsman) { std::string kubernetes_translation; ASSERT_THAT(MakeRpc("kubernetes", &kubernetes_translation), IsOk()); EXPECT_EQ(kubernetes_translation, "helmsman"); } TEST_F(GrpcServerTest, OrkutTranslationNotFound) { std::string orkut_translation; asylo::Status status = MakeRpc("orkut", &orkut_translation); ASSERT_THAT(status, StatusIs(asylo::error::INVALID_ARGUMENT)); EXPECT_EQ(status.error_message(), "No known translation for \"orkut\""); } } // namespace } // namespace grpc_server } // namespace examples int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); ::google::ParseCommandLineFlags(&argc, &argv, /*remove_flags=*/ true); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "imageprocessor.h" #include <QColor> ImageProcessor::ImageProcessor() { } // Private Methods QVector<double> ImageProcessor::histChannel(QImage image, QColor color) { QVector<double> histogram(256); int width = image.width(); int height = image.height(); for(int j = 0; j < height; j++) { QRgb* row = (QRgb*)image.scanLine(j); for(int i = 0; i < width; i++) { QRgb pixel = row[i]; int red = qRed(pixel); int green = qGreen(pixel); int blue = qBlue(pixel); if(color == QColor(Qt::red)) histogram[red] += 1; else if(color == QColor(Qt::green)) histogram[green] += 1; else if(color == QColor(Qt::blue)) histogram[blue] += 1; } } return histogram; } // Public Methods void ImageProcessor::setImage(QImage image) { this->image = image; } QImage ImageProcessor::getImage(){ return this->image; } QImage ImageProcessor::grayScale() { int width = this->image.width(); int height = this->image.height(); QImage gray(width, height, QImage::Format_ARGB32); for(int j = 0; j < height; j++) { QRgb* row = (QRgb*)this->image.scanLine(j); for(int i = 0; i < width; i++) { QRgb pixel = row[i]; int red = qRed(pixel); int green = qGreen(pixel); int blue = qBlue(pixel); double value = (0.299*red) + (0.587*green) + (0.14*blue); gray.setPixel(i, j, qRgb(value, value, value)); } } return gray; } QImage ImageProcessor::binarize(int t) { this->image = grayScale(); int width = this->image.width(); int height = this->image.height(); QImage binarized(width, height, QImage::Format_ARGB32); for(int j = 0; j < height; j++) { QRgb* row = (QRgb*)this->image.scanLine(j); for(int i = 0; i < width; i++) { QRgb pixel = row[i]; int gray = qRed(pixel); int value = gray < t ? 0 : 255; binarized.setPixel(i, j, qRgb(value, value, value)); } } return binarized; } int ImageProcessor::getOtsuThreshold(){ return 122; } // Get Histogram Methods QVector<double> ImageProcessor::histRed() { return this->histChannel(this->image, QColor(Qt::red)); } QVector<double> ImageProcessor::histGreen() { return this->histChannel(this->image, QColor(Qt::green)); } QVector<double> ImageProcessor::histBlue() { return this->histChannel(this->image, QColor(Qt::blue)); } QVector<double> ImageProcessor::histGray() { return this->histChannel(this->grayScale(), QColor(Qt::red)); } // Adjust Histogram Methods void ImageProcessor::adjustImageChannel(QVector<double> transform, QColor color) { int width = this->image.width(); int height = this->image.height(); for(int j = 0; j < height; j++) { QRgb* row = (QRgb*)this->image.scanLine(j); for(int i = 0; i < width; i++) { QRgb pixel = row[i]; int red = qRed(pixel); int green = qGreen(pixel); int blue = qBlue(pixel); if(color==Qt::red){ red = transform[red]; } else if(color==Qt::green){ green = transform[green]; } else if(color==Qt::blue){ blue = transform[blue]; } else if(color==Qt::gray){ red = transform[red]; green = transform[green]; blue = transform[blue]; } this->image.setPixel(i, j, qRgb(red, green, blue)); } } } void ImageProcessor::adjustChannel(QColor color, int Xmax, int Xmin) { QVector<double> histogram; if(color == Qt::red) histogram = this->histRed(); else if(color == Qt::green) histogram = this->histGreen(); else if(color == Qt::blue) histogram = this->histBlue(); else if(color == Qt::gray) histogram = this->histGray(); int size = histogram.size(); QVector<double> adjusted(size); QVector<double> transform(size); double xmax = 0; double xmin = 255; for(int i=0; i < size; i++) { double value = histogram.at(i); if(value == 0) continue; double x = i; if(x>xmax){ xmax = x; }if(x<xmin){ xmin = x; } } for(int i=0; i < size; i++) { double value = histogram.at(i); if(value == 0) continue; double x = i; int X = ((Xmax - Xmin)*(x - xmin)/(xmax - xmin)) + Xmin;// (xmax - xmin)/(x - xmin) = (Xmax - Xmin)/(X - Xmin) adjusted[X] = value; transform[i] = X; } this->adjustImageChannel(transform, color); } void ImageProcessor::adjustRed(int Xmax, int Xmin) { this->adjustChannel(Qt::red, Xmax, Xmin); } void ImageProcessor::adjustGreen(int Xmax, int Xmin) { this->adjustChannel(Qt::green, Xmax, Xmin); } void ImageProcessor::adjustBlue(int Xmax, int Xmin) { this->adjustChannel(Qt::blue, Xmax, Xmin); } void ImageProcessor::adjustGray(int Xmax, int Xmin) { this->adjustChannel(Qt::gray, Xmax, Xmin); } <commit_msg>ImageProcessor: Otsu threshold function implemented<commit_after>#include "imageprocessor.h" #include <QColor> #include <QtMath> ImageProcessor::ImageProcessor() { } // Private Methods QVector<double> ImageProcessor::histChannel(QImage image, QColor color) { QVector<double> histogram(256); int width = image.width(); int height = image.height(); for(int j = 0; j < height; j++) { QRgb* row = (QRgb*)image.scanLine(j); for(int i = 0; i < width; i++) { QRgb pixel = row[i]; int red = qRed(pixel); int green = qGreen(pixel); int blue = qBlue(pixel); if(color == QColor(Qt::red)) histogram[red] += 1; else if(color == QColor(Qt::green)) histogram[green] += 1; else if(color == QColor(Qt::blue)) histogram[blue] += 1; } } return histogram; } // Public Methods void ImageProcessor::setImage(QImage image) { this->image = image; } QImage ImageProcessor::getImage(){ return this->image; } QImage ImageProcessor::grayScale() { int width = this->image.width(); int height = this->image.height(); QImage gray(width, height, QImage::Format_ARGB32); for(int j = 0; j < height; j++) { QRgb* row = (QRgb*)this->image.scanLine(j); for(int i = 0; i < width; i++) { QRgb pixel = row[i]; int red = qRed(pixel); int green = qGreen(pixel); int blue = qBlue(pixel); double value = (0.299*red) + (0.587*green) + (0.14*blue); gray.setPixel(i, j, qRgb(value, value, value)); } } return gray; } QImage ImageProcessor::binarize(int t) { this->image = grayScale(); int width = this->image.width(); int height = this->image.height(); QImage binarized(width, height, QImage::Format_ARGB32); for(int j = 0; j < height; j++) { QRgb* row = (QRgb*)this->image.scanLine(j); for(int i = 0; i < width; i++) { QRgb pixel = row[i]; int gray = qRed(pixel); int value = gray < t ? 0 : 255; binarized.setPixel(i, j, qRgb(value, value, value)); } } return binarized; } int ImageProcessor::getOtsuThreshold(){ int threshold = 0; QVector<double> histogram = this->histGray(); int width = this->image.width(); int height = this->image.height(); int size = width * height; // P1, P2, M1, M2, P1*P2*(M2-M1)^2 QVector<double> p1(256); QVector<double> p2(256); QVector<double> m1(256); QVector<double> m2(256); QVector<double> p1_p2_m1_m2_2(256); double p1sum = 0; double p2sum = 0; double m1sum = 0; double m2sum = 0; for(int t = 0; t <= 255; t++){ double value = histogram[t]; p2sum += value; m2sum += t*value; } for(int t = 0; t <= 255; t++){ double value = histogram[t]; p1sum += value; p2sum -= value; p1[t] = p1sum/size; p2[t] = 1 - p1[t]; m1sum += t*value; m2sum -= t*value; m1[t] = p1sum ? m1sum/p1sum : 0; m2[t] = p2sum ? m2sum/p2sum : 0; p1_p2_m1_m2_2[t] = p1[t] * p2[t] * qPow(m2[t] - m1[t], 2); } // MAX P1*P2*(M2-M1)^2 double aux = 0; for(int t = 0; t <= 255; t++){ threshold = t; if(t==0){ aux = p1_p2_m1_m2_2[t]; continue; } if(p1_p2_m1_m2_2[t] >= aux){ aux = p1_p2_m1_m2_2[t]; continue; } break; } return threshold; } // Get Histogram Methods QVector<double> ImageProcessor::histRed() { return this->histChannel(this->image, QColor(Qt::red)); } QVector<double> ImageProcessor::histGreen() { return this->histChannel(this->image, QColor(Qt::green)); } QVector<double> ImageProcessor::histBlue() { return this->histChannel(this->image, QColor(Qt::blue)); } QVector<double> ImageProcessor::histGray() { return this->histChannel(this->grayScale(), QColor(Qt::red)); } // Adjust Histogram Methods void ImageProcessor::adjustImageChannel(QVector<double> transform, QColor color) { int width = this->image.width(); int height = this->image.height(); for(int j = 0; j < height; j++) { QRgb* row = (QRgb*)this->image.scanLine(j); for(int i = 0; i < width; i++) { QRgb pixel = row[i]; int red = qRed(pixel); int green = qGreen(pixel); int blue = qBlue(pixel); if(color==Qt::red){ red = transform[red]; } else if(color==Qt::green){ green = transform[green]; } else if(color==Qt::blue){ blue = transform[blue]; } else if(color==Qt::gray){ red = transform[red]; green = transform[green]; blue = transform[blue]; } this->image.setPixel(i, j, qRgb(red, green, blue)); } } } void ImageProcessor::adjustChannel(QColor color, int Xmax, int Xmin) { QVector<double> histogram; if(color == Qt::red) histogram = this->histRed(); else if(color == Qt::green) histogram = this->histGreen(); else if(color == Qt::blue) histogram = this->histBlue(); else if(color == Qt::gray) histogram = this->histGray(); int size = histogram.size(); QVector<double> adjusted(size); QVector<double> transform(size); double xmax = 0; double xmin = 255; for(int i=0; i < size; i++) { double value = histogram.at(i); if(value == 0) continue; double x = i; if(x>xmax){ xmax = x; }if(x<xmin){ xmin = x; } } for(int i=0; i < size; i++) { double value = histogram.at(i); if(value == 0) continue; double x = i; int X = ((Xmax - Xmin)*(x - xmin)/(xmax - xmin)) + Xmin;// (xmax - xmin)/(x - xmin) = (Xmax - Xmin)/(X - Xmin) adjusted[X] = value; transform[i] = X; } this->adjustImageChannel(transform, color); } void ImageProcessor::adjustRed(int Xmax, int Xmin) { this->adjustChannel(Qt::red, Xmax, Xmin); } void ImageProcessor::adjustGreen(int Xmax, int Xmin) { this->adjustChannel(Qt::green, Xmax, Xmin); } void ImageProcessor::adjustBlue(int Xmax, int Xmin) { this->adjustChannel(Qt::blue, Xmax, Xmin); } void ImageProcessor::adjustGray(int Xmax, int Xmin) { this->adjustChannel(Qt::gray, Xmax, Xmin); } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "Trace.h" #include <array> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <iostream> #include <mutex> #include <string> #include <unordered_map> #include <utility> #include "Debug.h" #include "Macros.h" #include "Show.h" struct TraceContextAccess { static const TraceContext* get_s_context() { return TraceContext::s_context; } }; namespace { struct Tracer { bool m_show_timestamps{false}; bool m_show_tracemodule{false}; const char* m_method_filter; std::unordered_map<int /*TraceModule*/, std::string> m_module_id_name_map; Tracer() { const char* traceenv = getenv("TRACE"); const char* envfile = getenv("TRACEFILE"); const char* show_timestamps = getenv("SHOW_TIMESTAMPS"); const char* show_tracemodule = getenv("SHOW_TRACEMODULE"); m_method_filter = getenv("TRACE_METHOD_FILTER"); if (!traceenv) { return; } std::cerr << "Trace settings:" << std::endl; std::cerr << "TRACEFILE=" << (envfile == nullptr ? "" : envfile) << std::endl; std::cerr << "SHOW_TIMESTAMPS=" << (show_timestamps == nullptr ? "" : show_timestamps) << std::endl; std::cerr << "SHOW_TRACEMODULE=" << (show_tracemodule == nullptr ? "" : show_tracemodule) << std::endl; std::cerr << "TRACE_METHOD_FILTER=" << (m_method_filter == nullptr ? "" : m_method_filter) << std::endl; init_trace_modules(traceenv); init_trace_file(envfile); if (show_timestamps) { m_show_timestamps = true; } if (show_tracemodule) { m_show_tracemodule = true; } #define TM(x) m_module_id_name_map[static_cast<int>(x)] = #x; TMS #undef TM } ~Tracer() { if (m_file != nullptr && m_file != stderr) { fclose(m_file); } } bool check_trace_context() const { #if !IS_WINDOWS if (m_method_filter == nullptr) { return true; } const TraceContext* context = TraceContextAccess::get_s_context(); if (context == nullptr) { return true; } return context->get_string_value().find(m_method_filter) != std::string::npos; #else return true; #endif } bool traceEnabled(TraceModule module, int level) const { bool by_level = level <= m_level || level <= m_traces[module]; if (!by_level) { return false; } return check_trace_context(); } void trace(TraceModule module, int level, bool suppress_newline, const char* fmt, va_list ap) { // Assume that `trace` is never called without `traceEnabled`, so we // do not need to check anything (including context) here. std::lock_guard<std::mutex> guard(m_trace_mutex); if (m_show_timestamps) { auto t = std::time(nullptr); struct tm local_tm; #if IS_WINDOWS localtime_s(&local_tm, &t); #else localtime_r(&t, &local_tm); #endif std::array<char, 40> buf; std::strftime(buf.data(), sizeof(buf), "%c", &local_tm); fprintf(m_file, "[%s]", buf.data()); if (!m_show_tracemodule) { fprintf(m_file, " "); } } if (m_show_tracemodule) { fprintf(m_file, "[%s:%d] ", m_module_id_name_map[module].c_str(), level); } vfprintf(m_file, fmt, ap); if (!suppress_newline) { fprintf(m_file, "\n"); } fflush(m_file); } private: void init_trace_modules(const char* traceenv) { std::unordered_map<std::string, int> module_id_map{{ #define TM(x) {std::string(#x), x}, TMS #undef TM }}; char* tracespec = strdup(traceenv); const char* sep = ",: "; const char* module = nullptr; for (const char* tok = strtok(tracespec, sep); tok != nullptr; tok = strtok(nullptr, sep)) { auto level = strtol(tok, nullptr, 10); if (level) { if (module) { if (module_id_map.count(module) == 0) { if (strcmp(module, "REDEX") == 0) { continue; // Ignore REDEX. } fprintf(stderr, "Unknown trace level %s\n", module); abort(); } m_traces[module_id_map[module]] = level; } else { m_level = level; } module = nullptr; } else { module = tok; } } free(tracespec); } void init_trace_file(const char* envfile) { if (!envfile) { m_file = stderr; return; } try { // If redex-all is called from redex.py, the tracefile has been created // already. And TRACEFILE is replaced by the file descriptor instead. // Refer to update_trace_file in pyredex/logger.py. auto fd = std::stoi(envfile); m_file = fdopen(fd, "w"); } catch (std::invalid_argument&) { // Not an integer file descriptor; real file name. m_file = fopen(envfile, "w"); } if (!m_file) { fprintf(stderr, "Unable to open TRACEFILE, falling back to stderr\n"); m_file = stderr; } } private: FILE* m_file{nullptr}; long m_level{0}; std::array<long, N_TRACE_MODULES> m_traces; std::mutex m_trace_mutex; }; static Tracer tracer; } // namespace #ifndef NDEBUG bool traceEnabled(TraceModule module, int level) { return tracer.traceEnabled(module, level); } #endif void trace(TraceModule module, int level, bool suppress_newline, const char* fmt, ...) { va_list ap; va_start(ap, fmt); tracer.trace(module, level, suppress_newline, fmt, ap); va_end(ap); } #if !IS_WINDOWS const std::string& TraceContext::get_string_value() const { if (string_value->empty()) { if (method != nullptr) { string_value_cache = show_deobfuscated(method); } else if (type != nullptr) { string_value_cache = show_deobfuscated(type); } } return *string_value; } thread_local const TraceContext* TraceContext::s_context = nullptr; #endif <commit_msg>Fix missing `#ifdef` in `Trace.cpp`<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "Trace.h" #include <array> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <iostream> #include <mutex> #include <string> #include <unordered_map> #include <utility> #include "Debug.h" #include "Macros.h" #include "Show.h" #if !IS_WINDOWS struct TraceContextAccess { static const TraceContext* get_s_context() { return TraceContext::s_context; } }; #endif namespace { struct Tracer { bool m_show_timestamps{false}; bool m_show_tracemodule{false}; const char* m_method_filter; std::unordered_map<int /*TraceModule*/, std::string> m_module_id_name_map; Tracer() { const char* traceenv = getenv("TRACE"); const char* envfile = getenv("TRACEFILE"); const char* show_timestamps = getenv("SHOW_TIMESTAMPS"); const char* show_tracemodule = getenv("SHOW_TRACEMODULE"); m_method_filter = getenv("TRACE_METHOD_FILTER"); if (!traceenv) { return; } std::cerr << "Trace settings:" << std::endl; std::cerr << "TRACEFILE=" << (envfile == nullptr ? "" : envfile) << std::endl; std::cerr << "SHOW_TIMESTAMPS=" << (show_timestamps == nullptr ? "" : show_timestamps) << std::endl; std::cerr << "SHOW_TRACEMODULE=" << (show_tracemodule == nullptr ? "" : show_tracemodule) << std::endl; std::cerr << "TRACE_METHOD_FILTER=" << (m_method_filter == nullptr ? "" : m_method_filter) << std::endl; init_trace_modules(traceenv); init_trace_file(envfile); if (show_timestamps) { m_show_timestamps = true; } if (show_tracemodule) { m_show_tracemodule = true; } #define TM(x) m_module_id_name_map[static_cast<int>(x)] = #x; TMS #undef TM } ~Tracer() { if (m_file != nullptr && m_file != stderr) { fclose(m_file); } } bool check_trace_context() const { #if !IS_WINDOWS if (m_method_filter == nullptr) { return true; } const TraceContext* context = TraceContextAccess::get_s_context(); if (context == nullptr) { return true; } return context->get_string_value().find(m_method_filter) != std::string::npos; #else return true; #endif } bool traceEnabled(TraceModule module, int level) const { bool by_level = level <= m_level || level <= m_traces[module]; if (!by_level) { return false; } return check_trace_context(); } void trace(TraceModule module, int level, bool suppress_newline, const char* fmt, va_list ap) { // Assume that `trace` is never called without `traceEnabled`, so we // do not need to check anything (including context) here. std::lock_guard<std::mutex> guard(m_trace_mutex); if (m_show_timestamps) { auto t = std::time(nullptr); struct tm local_tm; #if IS_WINDOWS localtime_s(&local_tm, &t); #else localtime_r(&t, &local_tm); #endif std::array<char, 40> buf; std::strftime(buf.data(), sizeof(buf), "%c", &local_tm); fprintf(m_file, "[%s]", buf.data()); if (!m_show_tracemodule) { fprintf(m_file, " "); } } if (m_show_tracemodule) { fprintf(m_file, "[%s:%d] ", m_module_id_name_map[module].c_str(), level); } vfprintf(m_file, fmt, ap); if (!suppress_newline) { fprintf(m_file, "\n"); } fflush(m_file); } private: void init_trace_modules(const char* traceenv) { std::unordered_map<std::string, int> module_id_map{{ #define TM(x) {std::string(#x), x}, TMS #undef TM }}; char* tracespec = strdup(traceenv); const char* sep = ",: "; const char* module = nullptr; for (const char* tok = strtok(tracespec, sep); tok != nullptr; tok = strtok(nullptr, sep)) { auto level = strtol(tok, nullptr, 10); if (level) { if (module) { if (module_id_map.count(module) == 0) { if (strcmp(module, "REDEX") == 0) { continue; // Ignore REDEX. } fprintf(stderr, "Unknown trace level %s\n", module); abort(); } m_traces[module_id_map[module]] = level; } else { m_level = level; } module = nullptr; } else { module = tok; } } free(tracespec); } void init_trace_file(const char* envfile) { if (!envfile) { m_file = stderr; return; } try { // If redex-all is called from redex.py, the tracefile has been created // already. And TRACEFILE is replaced by the file descriptor instead. // Refer to update_trace_file in pyredex/logger.py. auto fd = std::stoi(envfile); m_file = fdopen(fd, "w"); } catch (std::invalid_argument&) { // Not an integer file descriptor; real file name. m_file = fopen(envfile, "w"); } if (!m_file) { fprintf(stderr, "Unable to open TRACEFILE, falling back to stderr\n"); m_file = stderr; } } private: FILE* m_file{nullptr}; long m_level{0}; std::array<long, N_TRACE_MODULES> m_traces; std::mutex m_trace_mutex; }; static Tracer tracer; } // namespace #ifndef NDEBUG bool traceEnabled(TraceModule module, int level) { return tracer.traceEnabled(module, level); } #endif void trace(TraceModule module, int level, bool suppress_newline, const char* fmt, ...) { va_list ap; va_start(ap, fmt); tracer.trace(module, level, suppress_newline, fmt, ap); va_end(ap); } #if !IS_WINDOWS const std::string& TraceContext::get_string_value() const { if (string_value->empty()) { if (method != nullptr) { string_value_cache = show_deobfuscated(method); } else if (type != nullptr) { string_value_cache = show_deobfuscated(type); } } return *string_value; } thread_local const TraceContext* TraceContext::s_context = nullptr; #endif <|endoftext|>
<commit_before>#pragma once //#define BOOST_VARIANT_MINIMIZE_SIZE 1 #include "boost/variant.hpp" #include "boost/optional.hpp" #include <map> #include <list> #include <string> namespace libubjpp { class value; /** * Object type. Note std::map is preferred to std::unordered_map due to its * size: 24 bytes as opposed to 32 bytes, which makes each value object 32 * bytes as opposed to 48 bytes. */ using object_type = std::map<std::string,value>; /** * Array type. */ using array_type = std::vector<value>; /** * String type. */ using string_type = std::string; /* * Floating point types. */ using float_type = float; using double_type = double; /* * Integer types. */ using int8_type = int8_t; using uint8_type = uint8_t; using int16_type = int16_t; using int32_type = int32_t; using int64_type = int64_t; /** * Boolean type. */ using bool_type = bool; /** * Nil type. */ struct nil_type { // }; /** * No-op type. */ struct noop_type { // }; /** * Variant value type. */ using value_type = boost::variant<object_type,array_type,string_type, float_type,double_type,int8_type,uint8_type,int16_type,int32_type, int64_type,bool_type,nil_type,noop_type>; /** * Value. * * @ingroup libubjpp */ class value { public: /** * Default constructor. Creates a value of object type. */ value(); /** * Constructor. * * @param T value type. * * @param value x. */ template<class T> value(const T& x) : x(x) { // } /** * Get. * * @tparam T value type. * * @param path List of strings giving names of the items. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<T&> get(const std::initializer_list<std::string>& path) { auto node = this; for (auto name : path) { if (node->x.type() == typeid(object_type)) { auto& o = boost::get<object_type>(node->x); auto iter = o.find(name); if (iter != o.end()) { node = &iter->second; } else { return boost::none; } } else { return boost::none; } } return node->get<T>(); } /** * Get. * * @tparam T value type. * * @param path List of strings giving names of the items. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<const T&> get( const std::initializer_list<std::string>& path) const { auto node = this; for (auto name : path) { if (node->x.type() == typeid(object_type)) { auto& o = boost::get<const object_type>(node->x); auto iter = o.find(name); if (iter != o.end()) { node = &iter->second; } else { return boost::none; } } else { return boost::none; } } return node->get<T>(); } /** * Get. * * @tparam T value type. * * @param name Name of the item. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<T&> get(const std::string& name) { if (x.type() == typeid(object_type)) { auto& o = boost::get<object_type&>(x); auto iter = o.find(name); if (iter != o.end()) { return iter->second.get<T>(); } } return boost::none; } /** * Get. * * @tparam T value type. * * @param name Name of the item. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<const T&> get(const std::string& name) const { if (x.type() == typeid(object_type)) { auto& o = boost::get<const object_type&>(x); auto iter = o.find(name); if (iter != o.end()) { return iter->second.get<T>(); } } return boost::none; } /** * Get. * * @tparam T value type. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<T&> get() { if (x.type() == typeid(T)) { return boost::get<T>(x); } else { return boost::none; } } /** * Get. * * @tparam T value type. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<const T&> get() const { if (x.type() == typeid(T)) { return boost::get<const T>(x); } else { return boost::none; } } /** * Get. * * @param path List of strings giving names of the items. * * @return An optional that will be empty if the value does not exist, * otherwise it will contain the value of variant type. */ boost::optional<value&> get( const std::initializer_list<std::string>& path); /** * Get. * * @param path List of strings giving names of the items. * * @return An optional that will be empty if the value does not exist, * otherwise it will contain the value of variant type. */ boost::optional<const value&> get( const std::initializer_list<std::string>& path) const; /** * Get. * * @param name Name of the item. * * @return An optional that will be empty if the value does not exist, * otherwise it will contain the value of variant type. */ boost::optional<value&> get(const std::string& name); /** * Get. * * @param name Name of the item. * * @return An optional that will be empty if the value does not exist, * otherwise it will contain the value of variant type. */ boost::optional<const value&> get(const std::string& name) const; /** * Get. * * @return The value, of variant type. */ value& get() { return *this; } /** * Get. * * @return The value, of variant type. */ const value& get() const { return *this; } /** * Set. * * @param path List of strings giving names of the items. * @param x The value. * * @return The new item. */ value& set(const std::initializer_list<std::string>& path, const value_type& x); /** * Set. * * @param name Name of the item. * @param x The value. * * @param The new item. */ value& set(const std::string& name, const value_type& x); /** * Set. * * @param x The value. * * @param The new item. */ value& set(const value_type& x); /** * Unwrap. * * @return The variant object. */ value_type& unwrap() { return x; } /** * Unwrap. * * @return The variant object. */ const value_type& unwrap() const { return x; } private: /** * The value. */ value_type x; }; } <commit_msg>Updates for boost::variant use for const values in libubjpp.<commit_after>#pragma once //#define BOOST_VARIANT_MINIMIZE_SIZE 1 #include "boost/variant.hpp" #include "boost/optional.hpp" #include <map> #include <list> #include <string> namespace libubjpp { class value; /** * Object type. Note std::map is preferred to std::unordered_map due to its * size: 24 bytes as opposed to 32 bytes, which makes each value object 32 * bytes as opposed to 48 bytes. */ using object_type = std::map<std::string,value>; /** * Array type. */ using array_type = std::vector<value>; /** * String type. */ using string_type = std::string; /* * Floating point types. */ using float_type = float; using double_type = double; /* * Integer types. */ using int8_type = int8_t; using uint8_type = uint8_t; using int16_type = int16_t; using int32_type = int32_t; using int64_type = int64_t; /** * Boolean type. */ using bool_type = bool; /** * Nil type. */ struct nil_type { // }; /** * No-op type. */ struct noop_type { // }; /** * Variant value type. */ using value_type = boost::variant<object_type,array_type,string_type, float_type,double_type,int8_type,uint8_type,int16_type,int32_type, int64_type,bool_type,nil_type,noop_type>; /** * Value. * * @ingroup libubjpp */ class value { public: /** * Default constructor. Creates a value of object type. */ value(); /** * Constructor. * * @param T value type. * * @param value x. */ template<class T> value(const T& x) : x(x) { // } /** * Get. * * @tparam T value type. * * @param path List of strings giving names of the items. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<T&> get(const std::initializer_list<std::string>& path) { auto node = this; for (auto name : path) { if (node->x.type() == typeid(object_type)) { auto& o = boost::get<object_type>(node->x); auto iter = o.find(name); if (iter != o.end()) { node = &iter->second; } else { return boost::none; } } else { return boost::none; } } return node->get<T>(); } /** * Get. * * @tparam T value type. * * @param path List of strings giving names of the items. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<const T&> get( const std::initializer_list<std::string>& path) const { auto node = this; for (auto name : path) { if (node->x.type() == typeid(object_type)) { auto& o = boost::get<object_type>(node->x); auto iter = o.find(name); if (iter != o.end()) { node = &iter->second; } else { return boost::none; } } else { return boost::none; } } return node->get<T>(); } /** * Get. * * @tparam T value type. * * @param name Name of the item. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<T&> get(const std::string& name) { if (x.type() == typeid(object_type)) { auto& o = boost::get<object_type&>(x); auto iter = o.find(name); if (iter != o.end()) { return iter->second.get<T>(); } } return boost::none; } /** * Get. * * @tparam T value type. * * @param name Name of the item. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<const T&> get(const std::string& name) const { if (x.type() == typeid(object_type)) { auto& o = boost::get<object_type&>(x); auto iter = o.find(name); if (iter != o.end()) { return iter->second.get<T>(); } } return boost::none; } /** * Get. * * @tparam T value type. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<T&> get() { if (x.type() == typeid(T)) { return boost::get<T>(x); } else { return boost::none; } } /** * Get. * * @tparam T value type. * * @return An optional that will be empty if the value does not exist or * is not of type @p T, otherwise it will contain the x. */ template<class T> boost::optional<const T&> get() const { if (x.type() == typeid(T)) { return boost::get<T>(x); } else { return boost::none; } } /** * Get. * * @param path List of strings giving names of the items. * * @return An optional that will be empty if the value does not exist, * otherwise it will contain the value of variant type. */ boost::optional<value&> get( const std::initializer_list<std::string>& path); /** * Get. * * @param path List of strings giving names of the items. * * @return An optional that will be empty if the value does not exist, * otherwise it will contain the value of variant type. */ boost::optional<const value&> get( const std::initializer_list<std::string>& path) const; /** * Get. * * @param name Name of the item. * * @return An optional that will be empty if the value does not exist, * otherwise it will contain the value of variant type. */ boost::optional<value&> get(const std::string& name); /** * Get. * * @param name Name of the item. * * @return An optional that will be empty if the value does not exist, * otherwise it will contain the value of variant type. */ boost::optional<const value&> get(const std::string& name) const; /** * Get. * * @return The value, of variant type. */ value& get() { return *this; } /** * Get. * * @return The value, of variant type. */ const value& get() const { return *this; } /** * Set. * * @param path List of strings giving names of the items. * @param x The value. * * @return The new item. */ value& set(const std::initializer_list<std::string>& path, const value_type& x); /** * Set. * * @param name Name of the item. * @param x The value. * * @param The new item. */ value& set(const std::string& name, const value_type& x); /** * Set. * * @param x The value. * * @param The new item. */ value& set(const value_type& x); /** * Unwrap. * * @return The variant object. */ value_type& unwrap() { return x; } /** * Unwrap. * * @return The variant object. */ const value_type& unwrap() const { return x; } private: /** * The value. */ value_type x; }; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: odbcconfig.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: rt $ $Date: 2007-07-24 12:08:47 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef _DBAUI_ODBC_CONFIG_HXX_ #include "odbcconfig.hxx" #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _THREAD_HXX_ #include <osl/thread.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifdef HAVE_ODBC_SUPPORT #ifdef WIN #define ODBC_LIBRARY "ODBC.DLL" #define ODBC_UI_LIBRARY "ODBCINST.DLL" #endif #if defined WNT #define ODBC_LIBRARY "ODBC32.DLL" #define ODBC_UI_LIBRARY "ODBCCP32.DLL" #endif #ifdef UNX #ifdef MACOSX #define ODBC_LIBRARY "libiodbc.dylib" #define ODBC_UI_LIBRARY "libiodbcinst.dylib" #else #define ODBC_LIBRARY_1 "libodbc.so.1" #define ODBC_UI_LIBRARY_1 "libodbcinst.so.1" #define ODBC_LIBRARY "libodbc.so" #define ODBC_UI_LIBRARY "libodbcinst.so" #endif #endif // just to go with calling convention of windows // so don't touch this #if defined(WIN) || defined(WNT) #define SQL_API __stdcall // At least under some circumstances, the below #include <odbc/sqlext.h> re- // defines SQL_API to an empty string, leading to a compiler warning on MSC; to // not break the current behavior, this is worked around by locally disabling // that warning: #if defined _MSC_VER #pragma warning(push) #pragma warning(disable: 4005) #endif #endif // defined(WIN) || defined(WNT) #ifdef SYSTEM_ODBC_HEADERS #include <sqlext.h> #else #ifndef __SQLEXT_H #include <odbc/sqlext.h> #endif #endif #if defined(WIN) || defined(WNT) #if defined _MSC_VER #pragma warning(pop) #endif #undef SQL_API #define SQL_API __stdcall #endif // defined(WIN) || defined(WNT) // from here on you can do what you want to #else #define ODBC_LIBRARY "" #define ODBC_UI_LIBRARY "" #endif // HAVE_ODBC_SUPPORT //......................................................................... namespace dbaui { //......................................................................... #ifdef HAVE_ODBC_SUPPORT typedef SQLRETURN (SQL_API* TSQLManageDataSource) (SQLHWND hwndParent); typedef SQLRETURN (SQL_API* TSQLAllocHandle) (SQLSMALLINT HandleType, SQLHANDLE InputHandle, SQLHANDLE* OutputHandlePtr); typedef SQLRETURN (SQL_API* TSQLFreeHandle) (SQLSMALLINT HandleType, SQLHANDLE Handle); typedef SQLRETURN (SQL_API* TSQLSetEnvAttr) (SQLHENV EnvironmentHandle, SQLINTEGER Attribute, SQLPOINTER ValuePtr, SQLINTEGER StringLength); typedef SQLRETURN (SQL_API* TSQLDataSources) (SQLHENV EnvironmentHandle, SQLUSMALLINT Direction, SQLCHAR* ServerName, SQLSMALLINT BufferLength1, SQLSMALLINT* NameLength1Ptr, SQLCHAR* Description, SQLSMALLINT BufferLength2, SQLSMALLINT* NameLength2Ptr); #define NSQLManageDataSource(a) (*(TSQLManageDataSource)(m_pSQLManageDataSource))(a) #define NSQLAllocHandle(a,b,c) (*(TSQLAllocHandle)(m_pAllocHandle))(a,b,c) #define NSQLFreeHandle(a,b) (*(TSQLFreeHandle)(m_pFreeHandle))(a,b) #define NSQLSetEnvAttr(a,b,c,d) (*(TSQLSetEnvAttr)(m_pSetEnvAttr))(a,b,c,d) #define NSQLDataSources(a,b,c,d,e,f,g,h) (*(TSQLDataSources)(m_pDataSources))(a,b,c,d,e,f,g,h) #endif //========================================================================= //= OOdbcLibWrapper //========================================================================= DBG_NAME(OOdbcLibWrapper) //------------------------------------------------------------------------- OOdbcLibWrapper::OOdbcLibWrapper() :m_pOdbcLib(NULL) { DBG_CTOR(OOdbcLibWrapper,NULL); } //------------------------------------------------------------------------- sal_Bool OOdbcLibWrapper::load(const sal_Char* _pLibPath) { m_sLibPath = ::rtl::OUString::createFromAscii(_pLibPath); #ifdef HAVE_ODBC_SUPPORT // load the module m_pOdbcLib = osl_loadModule(m_sLibPath.pData, SAL_LOADMODULE_NOW); return (NULL != m_pOdbcLib); #endif } //------------------------------------------------------------------------- void OOdbcLibWrapper::unload() { #ifdef HAVE_ODBC_SUPPORT if (isLoaded()) { osl_unloadModule(m_pOdbcLib); m_pOdbcLib = NULL; } #endif } //------------------------------------------------------------------------- oslGenericFunction OOdbcLibWrapper::loadSymbol(const sal_Char* _pFunctionName) { return osl_getFunctionSymbol(m_pOdbcLib, ::rtl::OUString::createFromAscii(_pFunctionName).pData); } //------------------------------------------------------------------------- OOdbcLibWrapper::~OOdbcLibWrapper() { unload(); DBG_DTOR(OOdbcLibWrapper,NULL); } //========================================================================= //= OOdbcEnumeration //========================================================================= struct OdbcTypesImpl { #ifdef HAVE_ODBC_SUPPORT SQLHANDLE hEnvironment; OdbcTypesImpl() : hEnvironment(0) { } #else void* pDummy; #endif }; DBG_NAME(OOdbcEnumeration) //------------------------------------------------------------------------- OOdbcEnumeration::OOdbcEnumeration() #ifdef HAVE_ODBC_SUPPORT :m_pAllocHandle(NULL) ,m_pSetEnvAttr(NULL) ,m_pDataSources(NULL) ,m_pImpl(new OdbcTypesImpl) #endif { DBG_CTOR(OOdbcEnumeration,NULL); sal_Bool bLoaded = load(ODBC_LIBRARY); #ifdef ODBC_LIBRARY_1 if ( !bLoaded ) bLoaded = load(ODBC_LIBRARY_1); #endif if ( bLoaded ) { #ifdef HAVE_ODBC_SUPPORT // load the generic functions m_pAllocHandle = loadSymbol("SQLAllocHandle"); m_pFreeHandle = loadSymbol("SQLFreeHandle"); m_pSetEnvAttr = loadSymbol("SQLSetEnvAttr"); m_pDataSources = loadSymbol("SQLDataSources"); // all or nothing if (!m_pAllocHandle || !m_pSetEnvAttr || !m_pDataSources || !m_pFreeHandle) { unload(); m_pAllocHandle = m_pFreeHandle = m_pSetEnvAttr = m_pDataSources = NULL; } #endif } } //------------------------------------------------------------------------- OOdbcEnumeration::~OOdbcEnumeration() { freeEnv(); delete m_pImpl; DBG_DTOR(OOdbcEnumeration,NULL); } //------------------------------------------------------------------------- sal_Bool OOdbcEnumeration::allocEnv() { OSL_ENSURE(isLoaded(), "OOdbcEnumeration::allocEnv: not loaded!"); if (!isLoaded()) return sal_False; #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) // nothing to do return sal_True; SQLRETURN nResult = NSQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_pImpl->hEnvironment); if (SQL_SUCCESS != nResult) // can't do anything without environment return sal_False; NSQLSetEnvAttr(m_pImpl->hEnvironment, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER); return sal_True; #else return sal_False; #endif } //------------------------------------------------------------------------- void OOdbcEnumeration::freeEnv() { #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) NSQLFreeHandle(SQL_HANDLE_ENV, m_pImpl->hEnvironment); m_pImpl->hEnvironment = 0; #endif } //------------------------------------------------------------------------- void OOdbcEnumeration::getDatasourceNames(StringBag& _rNames) { OSL_ENSURE(isLoaded(), "OOdbcEnumeration::getDatasourceNames: not loaded!"); if (!isLoaded()) return; if (!allocEnv()) { OSL_ENSURE(sal_False, "OOdbcEnumeration::getDatasourceNames: could not allocate an ODBC environment!"); return; } #ifdef HAVE_ODBC_SUPPORT // now that we have an environment collect the data source names UCHAR szDSN[SQL_MAX_DSN_LENGTH+1]; SWORD pcbDSN; UCHAR szDescription[1024+1]; SWORD pcbDescription; SQLRETURN nResult = SQL_SUCCESS; for ( nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_FIRST, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription), &pcbDescription); ; nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_NEXT, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription), &pcbDescription) ) { if (nResult != SQL_SUCCESS) // no further error handling break; else { ::rtl::OUStringBuffer aCurrentDsn; aCurrentDsn.appendAscii(reinterpret_cast<const char*>(szDSN)); _rNames.insert(aCurrentDsn.makeStringAndClear()); } } #endif } #ifdef HAVE_ODBC_ADMINISTRATION //========================================================================= //= ProcessTerminationWait //========================================================================= class ProcessTerminationWait : public ::osl::Thread { oslProcess m_hProcessHandle; Link m_aFinishHdl; public: ProcessTerminationWait( oslProcess _hProcessHandle, const Link& _rFinishHdl ) :m_hProcessHandle( _hProcessHandle ) ,m_aFinishHdl( _rFinishHdl ) { } protected: virtual void SAL_CALL run() { osl_joinProcess( m_hProcessHandle ); Application::PostUserEvent( m_aFinishHdl ); } }; //========================================================================= //= OOdbcManagement //========================================================================= //------------------------------------------------------------------------- OOdbcManagement::OOdbcManagement( const Link& _rAsyncFinishCallback ) :m_pProcessWait( NULL ) ,m_aAsyncFinishCallback( _rAsyncFinishCallback ) { } //------------------------------------------------------------------------- OOdbcManagement::~OOdbcManagement() { // wait for our thread to be finished if ( m_pProcessWait.get() ) m_pProcessWait->join(); } //------------------------------------------------------------------------- bool OOdbcManagement::manageDataSources_async() { OSL_PRECOND( !isRunning(), "OOdbcManagement::manageDataSources_async: still running from the previous call!" ); if ( isRunning() ) return false; // this is done in an external process, due to #i78733# // (and note this whole functionality is supported on Windows only, ATM) ::rtl::OUString sExecutableName( RTL_CONSTASCII_USTRINGPARAM( "odbcconfig.exe" ) ); oslProcess hProcessHandle(0); oslProcessError eError = osl_executeProcess( sExecutableName.pData, NULL, 0, 0, NULL, NULL, NULL, 0, &hProcessHandle ); if ( eError != osl_Process_E_None ) return false; m_pProcessWait.reset( new ProcessTerminationWait( hProcessHandle, m_aAsyncFinishCallback ) ); m_pProcessWait->create(); return true; } //------------------------------------------------------------------------- bool OOdbcManagement::isRunning() const { return ( m_pProcessWait.get() && m_pProcessWait->isRunning() ); } #endif // HAVE_ODBC_ADMINISTRATION //......................................................................... } // namespace dbaui //......................................................................... <commit_msg>INTEGRATION: CWS os2port01 (1.15.18); FILE MERGED 2007/09/05 07:15:07 obr 1.15.18.3: RESYNC: (1.18-1.19); FILE MERGED 2007/07/18 10:28:44 obr 1.15.18.2: RESYNC: (1.15-1.18); FILE MERGED 2006/12/28 14:54:08 ydario 1.15.18.1: OS/2 initial import.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: odbcconfig.cxx,v $ * * $Revision: 1.20 $ * * last change: $Author: vg $ $Date: 2007-09-20 14:58:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef _DBAUI_ODBC_CONFIG_HXX_ #include "odbcconfig.hxx" #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _THREAD_HXX_ #include <osl/thread.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifdef HAVE_ODBC_SUPPORT #ifdef WIN #define ODBC_LIBRARY "ODBC.DLL" #define ODBC_UI_LIBRARY "ODBCINST.DLL" #endif #if defined WNT #define ODBC_LIBRARY "ODBC32.DLL" #define ODBC_UI_LIBRARY "ODBCCP32.DLL" #endif #ifdef UNX #ifdef MACOSX #define ODBC_LIBRARY "libiodbc.dylib" #define ODBC_UI_LIBRARY "libiodbcinst.dylib" #else #define ODBC_LIBRARY_1 "libodbc.so.1" #define ODBC_UI_LIBRARY_1 "libodbcinst.so.1" #define ODBC_LIBRARY "libodbc.so" #define ODBC_UI_LIBRARY "libodbcinst.so" #endif #endif // just to go with calling convention of windows // so don't touch this #if defined(WIN) || defined(WNT) #define SQL_API __stdcall // At least under some circumstances, the below #include <odbc/sqlext.h> re- // defines SQL_API to an empty string, leading to a compiler warning on MSC; to // not break the current behavior, this is worked around by locally disabling // that warning: #if defined _MSC_VER #pragma warning(push) #pragma warning(disable: 4005) #endif #endif // defined(WIN) || defined(WNT) #ifdef SYSTEM_ODBC_HEADERS #include <sqlext.h> #else #ifndef __SQLEXT_H #include <odbc/sqlext.h> #endif #endif #if defined(WIN) || defined(WNT) #if defined _MSC_VER #pragma warning(pop) #endif #undef SQL_API #define SQL_API __stdcall #endif // defined(WIN) || defined(WNT) // from here on you can do what you want to #else #define ODBC_LIBRARY "" #define ODBC_UI_LIBRARY "" #endif // HAVE_ODBC_SUPPORT //......................................................................... namespace dbaui { //......................................................................... #ifdef HAVE_ODBC_SUPPORT typedef SQLRETURN (SQL_API* TSQLManageDataSource) (SQLHWND hwndParent); typedef SQLRETURN (SQL_API* TSQLAllocHandle) (SQLSMALLINT HandleType, SQLHANDLE InputHandle, SQLHANDLE* OutputHandlePtr); typedef SQLRETURN (SQL_API* TSQLFreeHandle) (SQLSMALLINT HandleType, SQLHANDLE Handle); typedef SQLRETURN (SQL_API* TSQLSetEnvAttr) (SQLHENV EnvironmentHandle, SQLINTEGER Attribute, SQLPOINTER ValuePtr, SQLINTEGER StringLength); typedef SQLRETURN (SQL_API* TSQLDataSources) (SQLHENV EnvironmentHandle, SQLUSMALLINT Direction, SQLCHAR* ServerName, SQLSMALLINT BufferLength1, SQLSMALLINT* NameLength1Ptr, SQLCHAR* Description, SQLSMALLINT BufferLength2, SQLSMALLINT* NameLength2Ptr); #define NSQLManageDataSource(a) (*(TSQLManageDataSource)(m_pSQLManageDataSource))(a) #define NSQLAllocHandle(a,b,c) (*(TSQLAllocHandle)(m_pAllocHandle))(a,b,c) #define NSQLFreeHandle(a,b) (*(TSQLFreeHandle)(m_pFreeHandle))(a,b) #define NSQLSetEnvAttr(a,b,c,d) (*(TSQLSetEnvAttr)(m_pSetEnvAttr))(a,b,c,d) #define NSQLDataSources(a,b,c,d,e,f,g,h) (*(TSQLDataSources)(m_pDataSources))(a,b,c,d,e,f,g,h) #endif //========================================================================= //= OOdbcLibWrapper //========================================================================= DBG_NAME(OOdbcLibWrapper) //------------------------------------------------------------------------- #ifdef HAVE_ODBC_SUPPORT OOdbcLibWrapper::OOdbcLibWrapper() :m_pOdbcLib(NULL) { DBG_CTOR(OOdbcLibWrapper,NULL); } #endif //------------------------------------------------------------------------- sal_Bool OOdbcLibWrapper::load(const sal_Char* _pLibPath) { m_sLibPath = ::rtl::OUString::createFromAscii(_pLibPath); #ifdef HAVE_ODBC_SUPPORT // load the module m_pOdbcLib = osl_loadModule(m_sLibPath.pData, SAL_LOADMODULE_NOW); return (NULL != m_pOdbcLib); #endif } //------------------------------------------------------------------------- void OOdbcLibWrapper::unload() { #ifdef HAVE_ODBC_SUPPORT if (isLoaded()) { osl_unloadModule(m_pOdbcLib); m_pOdbcLib = NULL; } #endif } //------------------------------------------------------------------------- oslGenericFunction OOdbcLibWrapper::loadSymbol(const sal_Char* _pFunctionName) { return osl_getFunctionSymbol(m_pOdbcLib, ::rtl::OUString::createFromAscii(_pFunctionName).pData); } //------------------------------------------------------------------------- OOdbcLibWrapper::~OOdbcLibWrapper() { unload(); DBG_DTOR(OOdbcLibWrapper,NULL); } //========================================================================= //= OOdbcEnumeration //========================================================================= struct OdbcTypesImpl { #ifdef HAVE_ODBC_SUPPORT SQLHANDLE hEnvironment; OdbcTypesImpl() : hEnvironment(0) { } #else void* pDummy; #endif }; DBG_NAME(OOdbcEnumeration) //------------------------------------------------------------------------- OOdbcEnumeration::OOdbcEnumeration() #ifdef HAVE_ODBC_SUPPORT :m_pAllocHandle(NULL) ,m_pSetEnvAttr(NULL) ,m_pDataSources(NULL) ,m_pImpl(new OdbcTypesImpl) #endif { DBG_CTOR(OOdbcEnumeration,NULL); sal_Bool bLoaded = load(ODBC_LIBRARY); #ifdef ODBC_LIBRARY_1 if ( !bLoaded ) bLoaded = load(ODBC_LIBRARY_1); #endif if ( bLoaded ) { #ifdef HAVE_ODBC_SUPPORT // load the generic functions m_pAllocHandle = loadSymbol("SQLAllocHandle"); m_pFreeHandle = loadSymbol("SQLFreeHandle"); m_pSetEnvAttr = loadSymbol("SQLSetEnvAttr"); m_pDataSources = loadSymbol("SQLDataSources"); // all or nothing if (!m_pAllocHandle || !m_pSetEnvAttr || !m_pDataSources || !m_pFreeHandle) { unload(); m_pAllocHandle = m_pFreeHandle = m_pSetEnvAttr = m_pDataSources = NULL; } #endif } } //------------------------------------------------------------------------- OOdbcEnumeration::~OOdbcEnumeration() { freeEnv(); delete m_pImpl; DBG_DTOR(OOdbcEnumeration,NULL); } //------------------------------------------------------------------------- sal_Bool OOdbcEnumeration::allocEnv() { OSL_ENSURE(isLoaded(), "OOdbcEnumeration::allocEnv: not loaded!"); if (!isLoaded()) return sal_False; #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) // nothing to do return sal_True; SQLRETURN nResult = NSQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_pImpl->hEnvironment); if (SQL_SUCCESS != nResult) // can't do anything without environment return sal_False; NSQLSetEnvAttr(m_pImpl->hEnvironment, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER); return sal_True; #else return sal_False; #endif } //------------------------------------------------------------------------- void OOdbcEnumeration::freeEnv() { #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) NSQLFreeHandle(SQL_HANDLE_ENV, m_pImpl->hEnvironment); m_pImpl->hEnvironment = 0; #endif } //------------------------------------------------------------------------- void OOdbcEnumeration::getDatasourceNames(StringBag& _rNames) { OSL_ENSURE(isLoaded(), "OOdbcEnumeration::getDatasourceNames: not loaded!"); if (!isLoaded()) return; if (!allocEnv()) { OSL_ENSURE(sal_False, "OOdbcEnumeration::getDatasourceNames: could not allocate an ODBC environment!"); return; } #ifdef HAVE_ODBC_SUPPORT // now that we have an environment collect the data source names UCHAR szDSN[SQL_MAX_DSN_LENGTH+1]; SWORD pcbDSN; UCHAR szDescription[1024+1]; SWORD pcbDescription; SQLRETURN nResult = SQL_SUCCESS; for ( nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_FIRST, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription), &pcbDescription); ; nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_NEXT, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription), &pcbDescription) ) { if (nResult != SQL_SUCCESS) // no further error handling break; else { ::rtl::OUStringBuffer aCurrentDsn; aCurrentDsn.appendAscii(reinterpret_cast<const char*>(szDSN)); _rNames.insert(aCurrentDsn.makeStringAndClear()); } } #endif } #ifdef HAVE_ODBC_ADMINISTRATION //========================================================================= //= ProcessTerminationWait //========================================================================= class ProcessTerminationWait : public ::osl::Thread { oslProcess m_hProcessHandle; Link m_aFinishHdl; public: ProcessTerminationWait( oslProcess _hProcessHandle, const Link& _rFinishHdl ) :m_hProcessHandle( _hProcessHandle ) ,m_aFinishHdl( _rFinishHdl ) { } protected: virtual void SAL_CALL run() { osl_joinProcess( m_hProcessHandle ); Application::PostUserEvent( m_aFinishHdl ); } }; //========================================================================= //= OOdbcManagement //========================================================================= //------------------------------------------------------------------------- OOdbcManagement::OOdbcManagement( const Link& _rAsyncFinishCallback ) :m_pProcessWait( NULL ) ,m_aAsyncFinishCallback( _rAsyncFinishCallback ) { } //------------------------------------------------------------------------- OOdbcManagement::~OOdbcManagement() { // wait for our thread to be finished if ( m_pProcessWait.get() ) m_pProcessWait->join(); } //------------------------------------------------------------------------- bool OOdbcManagement::manageDataSources_async() { OSL_PRECOND( !isRunning(), "OOdbcManagement::manageDataSources_async: still running from the previous call!" ); if ( isRunning() ) return false; // this is done in an external process, due to #i78733# // (and note this whole functionality is supported on Windows only, ATM) ::rtl::OUString sExecutableName( RTL_CONSTASCII_USTRINGPARAM( "odbcconfig.exe" ) ); oslProcess hProcessHandle(0); oslProcessError eError = osl_executeProcess( sExecutableName.pData, NULL, 0, 0, NULL, NULL, NULL, 0, &hProcessHandle ); if ( eError != osl_Process_E_None ) return false; m_pProcessWait.reset( new ProcessTerminationWait( hProcessHandle, m_aAsyncFinishCallback ) ); m_pProcessWait->create(); return true; } //------------------------------------------------------------------------- bool OOdbcManagement::isRunning() const { return ( m_pProcessWait.get() && m_pProcessWait->isRunning() ); } #endif // HAVE_ODBC_ADMINISTRATION //......................................................................... } // namespace dbaui //......................................................................... <|endoftext|>
<commit_before>/** Copyright (c) 2017, Philip Deegan. 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 Philip Deegan nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _MAIKEN_APP_HPP_ #define _MAIKEN_APP_HPP_ #include "maiken/defs.hpp" #include "kul/cli.hpp" #include "kul/log.hpp" #include "kul/os.hpp" #include "kul/proc.hpp" #include "kul/scm/man.hpp" #include "kul/threads.hpp" #include "maiken/compiler.hpp" #include "maiken/compiler/compilers.hpp" #include "maiken/except.hpp" #include "maiken/global.hpp" #include "maiken/project.hpp" int main(int argc, char *argv[]); namespace maiken { #if defined(_MKN_WITH_MKN_RAM_) && defined(_MKN_WITH_IO_CEREAL_) namespace dist { class CompileRequest; } // end namespace dist #endif // _MKN_WITH_MKN_RAM_ && _MKN_WITH_IO_CEREAL_ static std::string PROGRAM = ""; class Module; class ModuleLoader; class ThreadingCompiler; class Applications; class SourceFinder; class CompilerPrinter; class KUL_PUBLISH Application : public Constants { friend class Applications; friend class CompilerPrinter; friend class Executioner; friend class SourceFinder; friend class ThreadingCompiler; #if defined(_MKN_WITH_MKN_RAM_) && defined(_MKN_WITH_IO_CEREAL_) friend class dist::CompileRequest; #endif // _MKN_WITH_MKN_RAM_ && _MKN_WITH_IO_CEREAL_ protected: bool ig = 1, isMod = 0, ro = 0; const Application *par = nullptr; Application *sup = nullptr; compiler::Mode m; std::string arg, lang, lnk, main, out, scr, scv; const std::string p; kul::Dir bd, inst; YAML::Node modIArg, modCArg, modLArg, modPArg; const maiken::Project &proj; kul::hash::map::S2T<kul::hash::map::S2S> fs; kul::hash::map::S2S includeStamps, itss, ps, tests; kul::hash::map::S2S cArg, cLnk; kul::hash::map::S2T<kul::hash::set::String> args; kul::hash::map::S2T<uint64_t> stss; std::vector<Application *> deps, modDeps, rdeps; std::vector<std::shared_ptr<ModuleLoader>> mods; std::vector<kul::cli::EnvVar> evs; std::vector<std::string> libs, paths; std::vector<std::pair<std::string, bool>> incs, srcs; const kul::SCM *scm = 0; void buildExecutable(const kul::hash::set::String &objects) KTHROW(kul::Exception); CompilerProcessCapture buildLibrary(const kul::hash::set::String &objects) KTHROW(kul::Exception); void buildTest(const kul::hash::set::String &objects) KTHROW(kul::Exception); void checkErrors(const CompilerProcessCapture &cpc) KTHROW(kul::Exception); void populateMaps(const YAML::Node &n) KTHROW(kul::Exception); void preSetupValidation() KTHROW(Exception); void postSetupValidation() KTHROW(Exception); void resolveProperties() KTHROW(Exception); void resolveLang() KTHROW(Exception); static void parseDependencyString(std::string s, kul::hash::set::String &include); void compile(kul::hash::set::String &objects) KTHROW(kul::Exception); void compile(std::vector<std::pair<std::string, std::string>> &src_objs, kul::hash::set::String &objects, std::vector<kul::File> &cacheFiles) KTHROW(kul::Exception); void compile(std::queue<std::pair<std::string, std::string>> &src_objs, kul::hash::set::String &objects, std::vector<kul::File> &cacheFiles) KTHROW(kul::Exception); void build() KTHROW(kul::Exception); void pack() KTHROW(kul::Exception); void findObjects(kul::hash::set::String &objects) const; void link(const kul::hash::set::String &objects) KTHROW(kul::Exception); void run(bool dbg); void test(); void trim(); void trim(const kul::File &f); void scmStatus(const bool &deps = false) KTHROW(kul::scm::Exception); void scmUpdate(const bool &f) KTHROW(kul::scm::Exception); void scmUpdate(const bool &f, const kul::SCM *scm, const std::string &repo) KTHROW(kul::scm::Exception); void setup() KTHROW(kul::Exception); void setSuper(); void showConfig(bool force = 0); void showTree() const; void showTreeRecursive(uint8_t i) const; void cyclicCheck(const std::vector<std::pair<std::string, std::string>> &apps) const KTHROW(kul::Exception); void showProfiles(); void writeTimeStamps(kul::hash::set::String &objects, std::vector<kul::File> &cacheFiles); void loadTimeStamps() KTHROW(kul::StringException); void buildDepVec(const std::string &depVal); void buildDepVecRec(std::unordered_map<uint16_t, std::vector<Application *>> &dePs, int16_t ig, int16_t i, const kul::hash::set::String &inc); void populateMapsFromDependencies() KTHROW(kul::Exception); void loadDepOrMod(const YAML::Node &node, const kul::Dir &depOrMod, bool module) KTHROW(kul::Exception); kul::Dir resolveDepOrModDirectory(const YAML::Node &d, bool module); void popDepOrMod(const YAML::Node &n, std::vector<Application *> &vec, const std::string &s, bool module, bool with = 0) KTHROW(kul::Exception); kul::hash::set::String inactiveMains() const; bool incSrc(const kul::File &f) const; void addCLIArgs(const kul::cli::Args &args); void addSourceLine(const std::string &o) KTHROW(kul::Exception); void addIncludeLine(const std::string &o) KTHROW(kul::Exception); void modInit(const YAML::Node &modArg) { modIArg = modArg; } const YAML::Node &modInit() { return modIArg; } void modCompile(const YAML::Node &modArg) { modCArg = modArg; } const YAML::Node &modCompile() { return modCArg; } void modLink(const YAML::Node &modArg) { modLArg = modArg; } const YAML::Node &modLink() { return modLArg; } void modPack(const YAML::Node &modArg) { modPArg = modArg; } const YAML::Node &modPack() { return modPArg; } void addRDep(Application *app) { if (std::find(rdeps.begin(), rdeps.end(), app) == rdeps.end()) rdeps.push_back(app); } bool is_build_required(); bool is_build_stale(); void withArgs(const std::string with, std::vector<YAML::Node> &with_nodes, std::function<void(const YAML::Node &n, const bool mod)> getIfMissing, bool root, bool dep); void with(kul::hash::set::String &withs, std::vector<YAML::Node> &with_nodes, std::function<void(const YAML::Node &n, const bool mod)> getIfMissing, bool dep); static void showHelp(); public: Application(const maiken::Project &proj, const std::string &profile = ""); // : m(Mode::NONE), p(profile), proj(proj){} Application(const Application &a) = delete; Application(const Application &&a) = delete; Application &operator=(const Application &a) = delete; virtual ~Application(); virtual void process() KTHROW(kul::Exception); const kul::Dir &buildDir() const { return bd; } const std::string &profile() const { return p; } const maiken::Project &project() const { return proj; } const std::vector<Application *> &dependencies() const { return deps; } const std::vector<Application *> &revendencies() const { return rdeps; } const std::vector<Application *> &moduleDependencies() const { return modDeps; } const std::vector<std::shared_ptr<ModuleLoader>> &modules() const { return mods; } const std::vector<kul::cli::EnvVar> &envVars() const { return evs; } const kul::hash::map::S2T<kul::hash::map::S2S> &files() const { return fs; } const std::vector<std::string> &libraries() const { return libs; } const std::vector<std::pair<std::string, bool>> &sources() const { return srcs; } const std::vector<std::pair<std::string, bool>> &includes() const { return incs; } const std::vector<std::string> &libraryPaths() const { return paths; } const kul::hash::map::S2S &properties() const { return ps; } const kul::hash::map::S2T<kul::hash::set::String> &arguments() const { return args; } void addInclude(const std::string &s, bool p = 1) { auto it = std::find_if( incs.begin(), incs.end(), [&](const std::pair<std::string, bool>& element){ return element.first == s; } ); if(it == incs.end()) incs.push_back(std::make_pair(s, p)); } void addLibpath(const std::string &s) { paths.push_back(s); } void prependCompileString(const std::string &s) { arg = s + " " + arg; } void prependLinkString(const std::string &s) { lnk = s + " " + lnk; } std::string baseLibFilename() const { std::string n = project().root()[STR_NAME].Scalar(); return out.empty() ? inst ? p.empty() ? n : n + "_" + p : n : out; } kul::hash::map::S2T<kul::hash::map::S2T<kul::hash::set::String>> sourceMap() const; static std::vector<Application *> CREATE(const kul::cli::Args &args) KTHROW(kul::Exception); static std::vector<Application *> CREATE(int16_t argc, char *argv[]) KTHROW(kul::Exception); }; class Applications : public Constants { friend int ::main(int argc, char *argv[]); public: static Applications &INSTANCE() { static Applications a; return a; } Application *getOrCreate(const maiken::Project &proj, const std::string &_profile = "", bool setup = 1) KTHROW(kul::Exception); Application *getOrCreateRoot(const maiken::Project &proj, const std::string &_profile = "", bool setup = 1) KTHROW(kul::Exception); Application *getOrNullptr(const std::string &project); private: kul::hash::map::S2T<kul::hash::map::S2T<Application *>> m_apps; std::vector<std::unique_ptr<Application>> m_appPs; Applications() {} void clear() { m_apps.clear(); m_appPs.clear(); } }; class ThreadingCompiler : public Constants { private: maiken::Application &app; std::vector<std::string> incs; public: ThreadingCompiler(maiken::Application &app) : app(app) { for (const auto &s : app.includes()) { std::string m; kul::Dir d(s.first); kul::File f(s.first); if (d) m = (AppVars::INSTANCE().dryRun() ? d.esc() : d.escm()); else if (f) m = (AppVars::INSTANCE().dryRun() ? f.esc() : f.escm()); if (!m.empty()) incs.push_back(m); else incs.push_back("."); } } CompilationUnit compilationUnit(const std::pair<std::string, std::string> &pair) const KTHROW(kul::Exception); }; class ModuleMinimiser { friend class maiken::Application; private: static void add(const std::vector<maiken::Application *> &mods, kul::hash::map::S2T<maiken::Application *> &apps) { for (auto *const m : mods) if (!apps.count(m->buildDir().real())) apps.insert(m->buildDir().real(), m); } public: static kul::hash::map::S2T<maiken::Application *> modules(maiken::Application &app) { kul::hash::map::S2T<maiken::Application *> apps; add(app.moduleDependencies(), apps); for (auto dep = app.dependencies().rbegin(); dep != app.dependencies().rend(); ++dep) add((*dep)->moduleDependencies(), apps); return apps; } }; class CommandStateMachine { friend class maiken::Application; private: bool _main = 1; kul::hash::set::String cmds; CommandStateMachine() { reset(); } static CommandStateMachine &INSTANCE() { static CommandStateMachine a; return a; } void reset() { cmds.clear(); for (const auto &s : maiken::AppVars::INSTANCE().commands()) cmds.insert(s); } void add(const std::string &s) { cmds.insert(s); } const kul::hash::set::String &commands() const { return cmds; } void main(bool m) { _main = m; } bool main() const { return _main; } }; class BuildRecorder { friend class maiken::Application; private: kul::hash::set::String builds; static BuildRecorder &INSTANCE() { static BuildRecorder a; return a; } void add(const std::string &k) { builds.insert(k); } bool has(const std::string &k) { return builds.count(k); } }; class CompilerValidation : public Constants { public: static void check_compiler_for( const maiken::Application &app, const kul::hash::map::S2T<kul::hash::map::S2T<kul::hash::set::String>> &sources); }; } // namespace maiken #endif /* _MAIKEN_APP_HPP_ */ <commit_msg>don't overwrite module node if exists<commit_after>/** Copyright (c) 2017, Philip Deegan. 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 Philip Deegan nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _MAIKEN_APP_HPP_ #define _MAIKEN_APP_HPP_ #include "maiken/defs.hpp" #include "kul/cli.hpp" #include "kul/log.hpp" #include "kul/os.hpp" #include "kul/proc.hpp" #include "kul/scm/man.hpp" #include "kul/threads.hpp" #include "maiken/compiler.hpp" #include "maiken/compiler/compilers.hpp" #include "maiken/except.hpp" #include "maiken/global.hpp" #include "maiken/project.hpp" int main(int argc, char *argv[]); namespace maiken { #if defined(_MKN_WITH_MKN_RAM_) && defined(_MKN_WITH_IO_CEREAL_) namespace dist { class CompileRequest; } // end namespace dist #endif // _MKN_WITH_MKN_RAM_ && _MKN_WITH_IO_CEREAL_ static std::string PROGRAM = ""; class Module; class ModuleLoader; class ThreadingCompiler; class Applications; class SourceFinder; class CompilerPrinter; class KUL_PUBLISH Application : public Constants { friend class Applications; friend class CompilerPrinter; friend class Executioner; friend class SourceFinder; friend class ThreadingCompiler; #if defined(_MKN_WITH_MKN_RAM_) && defined(_MKN_WITH_IO_CEREAL_) friend class dist::CompileRequest; #endif // _MKN_WITH_MKN_RAM_ && _MKN_WITH_IO_CEREAL_ protected: bool ig = 1, isMod = 0, ro = 0; const Application *par = nullptr; Application *sup = nullptr; compiler::Mode m; std::string arg, lang, lnk, main, out, scr, scv; const std::string p; kul::Dir bd, inst; YAML::Node modIArg, modCArg, modLArg, modPArg; const maiken::Project &proj; kul::hash::map::S2T<kul::hash::map::S2S> fs; kul::hash::map::S2S includeStamps, itss, ps, tests; kul::hash::map::S2S cArg, cLnk; kul::hash::map::S2T<kul::hash::set::String> args; kul::hash::map::S2T<uint64_t> stss; std::vector<Application *> deps, modDeps, rdeps; std::vector<std::shared_ptr<ModuleLoader>> mods; std::vector<kul::cli::EnvVar> evs; std::vector<std::string> libs, paths; std::vector<std::pair<std::string, bool>> incs, srcs; const kul::SCM *scm = 0; void buildExecutable(const kul::hash::set::String &objects) KTHROW(kul::Exception); CompilerProcessCapture buildLibrary(const kul::hash::set::String &objects) KTHROW(kul::Exception); void buildTest(const kul::hash::set::String &objects) KTHROW(kul::Exception); void checkErrors(const CompilerProcessCapture &cpc) KTHROW(kul::Exception); void populateMaps(const YAML::Node &n) KTHROW(kul::Exception); void preSetupValidation() KTHROW(Exception); void postSetupValidation() KTHROW(Exception); void resolveProperties() KTHROW(Exception); void resolveLang() KTHROW(Exception); static void parseDependencyString(std::string s, kul::hash::set::String &include); void compile(kul::hash::set::String &objects) KTHROW(kul::Exception); void compile(std::vector<std::pair<std::string, std::string>> &src_objs, kul::hash::set::String &objects, std::vector<kul::File> &cacheFiles) KTHROW(kul::Exception); void compile(std::queue<std::pair<std::string, std::string>> &src_objs, kul::hash::set::String &objects, std::vector<kul::File> &cacheFiles) KTHROW(kul::Exception); void build() KTHROW(kul::Exception); void pack() KTHROW(kul::Exception); void findObjects(kul::hash::set::String &objects) const; void link(const kul::hash::set::String &objects) KTHROW(kul::Exception); void run(bool dbg); void test(); void trim(); void trim(const kul::File &f); void scmStatus(const bool &deps = false) KTHROW(kul::scm::Exception); void scmUpdate(const bool &f) KTHROW(kul::scm::Exception); void scmUpdate(const bool &f, const kul::SCM *scm, const std::string &repo) KTHROW(kul::scm::Exception); void setup() KTHROW(kul::Exception); void setSuper(); void showConfig(bool force = 0); void showTree() const; void showTreeRecursive(uint8_t i) const; void cyclicCheck(const std::vector<std::pair<std::string, std::string>> &apps) const KTHROW(kul::Exception); void showProfiles(); void writeTimeStamps(kul::hash::set::String &objects, std::vector<kul::File> &cacheFiles); void loadTimeStamps() KTHROW(kul::StringException); void buildDepVec(const std::string &depVal); void buildDepVecRec(std::unordered_map<uint16_t, std::vector<Application *>> &dePs, int16_t ig, int16_t i, const kul::hash::set::String &inc); void populateMapsFromDependencies() KTHROW(kul::Exception); void loadDepOrMod(const YAML::Node &node, const kul::Dir &depOrMod, bool module) KTHROW(kul::Exception); kul::Dir resolveDepOrModDirectory(const YAML::Node &d, bool module); void popDepOrMod(const YAML::Node &n, std::vector<Application *> &vec, const std::string &s, bool module, bool with = 0) KTHROW(kul::Exception); kul::hash::set::String inactiveMains() const; bool incSrc(const kul::File &f) const; void addCLIArgs(const kul::cli::Args &args); void addSourceLine(const std::string &o) KTHROW(kul::Exception); void addIncludeLine(const std::string &o) KTHROW(kul::Exception); void modInit(const YAML::Node &modArg) { if(modIArg.IsNull()) modIArg = modArg; } const YAML::Node &modInit() { return modIArg; } void modCompile(const YAML::Node &modArg) { if(modCArg.IsNull()) modCArg = modArg; } const YAML::Node &modCompile() { return modCArg; } void modLink(const YAML::Node &modArg) { if(modLArg.IsNull()) modLArg = modArg; } const YAML::Node &modLink() { return modLArg; } void modPack(const YAML::Node &modArg) { if(modPArg.IsNull()) modPArg = modArg; } const YAML::Node &modPack() { return modPArg; } void addRDep(Application *app) { if (std::find(rdeps.begin(), rdeps.end(), app) == rdeps.end()) rdeps.push_back(app); } bool is_build_required(); bool is_build_stale(); void withArgs(const std::string with, std::vector<YAML::Node> &with_nodes, std::function<void(const YAML::Node &n, const bool mod)> getIfMissing, bool root, bool dep); void with(kul::hash::set::String &withs, std::vector<YAML::Node> &with_nodes, std::function<void(const YAML::Node &n, const bool mod)> getIfMissing, bool dep); static void showHelp(); public: Application(const maiken::Project &proj, const std::string &profile = ""); // : m(Mode::NONE), p(profile), proj(proj){} Application(const Application &a) = delete; Application(const Application &&a) = delete; Application &operator=(const Application &a) = delete; virtual ~Application(); virtual void process() KTHROW(kul::Exception); const kul::Dir &buildDir() const { return bd; } const std::string &profile() const { return p; } const maiken::Project &project() const { return proj; } const std::vector<Application *> &dependencies() const { return deps; } const std::vector<Application *> &revendencies() const { return rdeps; } const std::vector<Application *> &moduleDependencies() const { return modDeps; } const std::vector<std::shared_ptr<ModuleLoader>> &modules() const { return mods; } const std::vector<kul::cli::EnvVar> &envVars() const { return evs; } const kul::hash::map::S2T<kul::hash::map::S2S> &files() const { return fs; } const std::vector<std::string> &libraries() const { return libs; } const std::vector<std::pair<std::string, bool>> &sources() const { return srcs; } const std::vector<std::pair<std::string, bool>> &includes() const { return incs; } const std::vector<std::string> &libraryPaths() const { return paths; } const kul::hash::map::S2S &properties() const { return ps; } const kul::hash::map::S2T<kul::hash::set::String> &arguments() const { return args; } void addInclude(const std::string &s, bool p = 1) { auto it = std::find_if( incs.begin(), incs.end(), [&](const std::pair<std::string, bool>& element){ return element.first == s; } ); if(it == incs.end()) incs.push_back(std::make_pair(s, p)); } void addLibpath(const std::string &s) { paths.push_back(s); } void prependCompileString(const std::string &s) { arg = s + " " + arg; } void prependLinkString(const std::string &s) { lnk = s + " " + lnk; } std::string baseLibFilename() const { std::string n = project().root()[STR_NAME].Scalar(); return out.empty() ? inst ? p.empty() ? n : n + "_" + p : n : out; } kul::hash::map::S2T<kul::hash::map::S2T<kul::hash::set::String>> sourceMap() const; static std::vector<Application *> CREATE(const kul::cli::Args &args) KTHROW(kul::Exception); static std::vector<Application *> CREATE(int16_t argc, char *argv[]) KTHROW(kul::Exception); }; class Applications : public Constants { friend int ::main(int argc, char *argv[]); public: static Applications &INSTANCE() { static Applications a; return a; } Application *getOrCreate(const maiken::Project &proj, const std::string &_profile = "", bool setup = 1) KTHROW(kul::Exception); Application *getOrCreateRoot(const maiken::Project &proj, const std::string &_profile = "", bool setup = 1) KTHROW(kul::Exception); Application *getOrNullptr(const std::string &project); private: kul::hash::map::S2T<kul::hash::map::S2T<Application *>> m_apps; std::vector<std::unique_ptr<Application>> m_appPs; Applications() {} void clear() { m_apps.clear(); m_appPs.clear(); } }; class ThreadingCompiler : public Constants { private: maiken::Application &app; std::vector<std::string> incs; public: ThreadingCompiler(maiken::Application &app) : app(app) { for (const auto &s : app.includes()) { std::string m; kul::Dir d(s.first); kul::File f(s.first); if (d) m = (AppVars::INSTANCE().dryRun() ? d.esc() : d.escm()); else if (f) m = (AppVars::INSTANCE().dryRun() ? f.esc() : f.escm()); if (!m.empty()) incs.push_back(m); else incs.push_back("."); } } CompilationUnit compilationUnit(const std::pair<std::string, std::string> &pair) const KTHROW(kul::Exception); }; class ModuleMinimiser { friend class maiken::Application; private: static void add(const std::vector<maiken::Application *> &mods, kul::hash::map::S2T<maiken::Application *> &apps) { for (auto *const m : mods) if (!apps.count(m->buildDir().real())) apps.insert(m->buildDir().real(), m); } public: static kul::hash::map::S2T<maiken::Application *> modules(maiken::Application &app) { kul::hash::map::S2T<maiken::Application *> apps; add(app.moduleDependencies(), apps); for (auto dep = app.dependencies().rbegin(); dep != app.dependencies().rend(); ++dep) add((*dep)->moduleDependencies(), apps); return apps; } }; class CommandStateMachine { friend class maiken::Application; private: bool _main = 1; kul::hash::set::String cmds; CommandStateMachine() { reset(); } static CommandStateMachine &INSTANCE() { static CommandStateMachine a; return a; } void reset() { cmds.clear(); for (const auto &s : maiken::AppVars::INSTANCE().commands()) cmds.insert(s); } void add(const std::string &s) { cmds.insert(s); } const kul::hash::set::String &commands() const { return cmds; } void main(bool m) { _main = m; } bool main() const { return _main; } }; class BuildRecorder { friend class maiken::Application; private: kul::hash::set::String builds; static BuildRecorder &INSTANCE() { static BuildRecorder a; return a; } void add(const std::string &k) { builds.insert(k); } bool has(const std::string &k) { return builds.count(k); } }; class CompilerValidation : public Constants { public: static void check_compiler_for( const maiken::Application &app, const kul::hash::map::S2T<kul::hash::map::S2T<kul::hash::set::String>> &sources); }; } // namespace maiken #endif /* _MAIKEN_APP_HPP_ */ <|endoftext|>
<commit_before>// Copyright 2011 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <vector> #include <Observation.hpp> #ifndef SHIFTS_HPP #define SHIFTS_HPP namespace PulsarSearch { std::vector< unsigned int > * getShifts(AstroData::Observation & observation); // Implementation std::vector< unsigned int > * getShifts(AstroData::Observation & observation) { float inverseHighFreq = 1.0f / (observation.getMaxFreq() * observation.getMaxFreq()); std::vector< unsigned int > * shifts = new std::vector< unsigned int >(observation.getNrDMs() * observation.getNrPaddedChannels()); for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { float kDM = 4148.808f * (observation.getFirstDM() + (dm * observation.getDMStep())); for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { float inverseFreq = 1.0f / ((observation.getMinFreq() + (channel * observation.getChannelBandwidth())) * (observation.getMinFreq() + (channel * observation.getChannelBandwidth()))); float delta = kDM * (inverseFreq - inverseHighFreq); shifts->at((dm * observation.getNrPaddedChannels()) + channel) = static_cast< unsigned int >(delta * observation.getNrSamplesPerSecond()); } } return shifts; } } // PulsarSearch #endif // SHIFTS_HPP <commit_msg>Changing the memory organization of the shifts.<commit_after>// Copyright 2011 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <vector> #include <Observation.hpp> #ifndef SHIFTS_HPP #define SHIFTS_HPP namespace PulsarSearch { std::vector< unsigned int > * getShifts(AstroData::Observation & observation); // Implementation std::vector< unsigned int > * getShifts(AstroData::Observation & observation) { float inverseHighFreq = 1.0f / (observation.getMaxFreq() * observation.getMaxFreq()); std::vector< unsigned int > * shifts = new std::vector< unsigned int >(observation.getNrChannels() * observation.getNrPaddedDMs()); for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { float inverseFreq = 1.0f / ((observation.getMinFreq() + (channel * observation.getChannelBandwidth())) * (observation.getMinFreq() + (channel * observation.getChannelBandwidth()))); for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { float kDM = 4148.808f * (observation.getFirstDM() + (dm * observation.getDMStep())); float delta = kDM * (inverseFreq - inverseHighFreq); shifts->at((channel * observation.getNrPaddedDMs()) + dm) = static_cast< unsigned int >(delta * observation.getNrSamplesPerSecond()); } } return shifts; } } // PulsarSearch #endif // SHIFTS_HPP <|endoftext|>
<commit_before>#ifndef CONFIG_HPP #define CONFIG_HPP // Window DLL support #ifdef _WINDOWS # define MAPNIK_DECL __declspec (dllexport) # pragma warning( disable: 4251 ) # pragma warning( disable: 4275 ) #else # define MAPNIK_DECL #endif #endif<commit_msg>added new line at the end of file<commit_after>#ifndef CONFIG_HPP #define CONFIG_HPP // Window DLL support #ifdef _WINDOWS # define MAPNIK_DECL __declspec (dllexport) # pragma warning( disable: 4251 ) # pragma warning( disable: 4275 ) #else # define MAPNIK_DECL #endif #endif <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief ルネサス RX デバイス選択 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016, 2019 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/byte_order.h" #include "common/vect.h" #include "common/delay.hpp" #include "common/device.hpp" #include "RX600/lvda.hpp" #include "RX600/bus.hpp" #if defined(SIG_RX24T) #include "RX24T/system.hpp" #include "RX24T/system_io.hpp" #include "RX600/gpt.hpp" #include "RX24T/s12ad.hpp" #include "RX24T/adc_in.hpp" #include "RX24T/da.hpp" #include "RX600/cmpc.hpp" #include "RX24T/flash.hpp" #include "RX24T/flash_io.hpp" #include "RX24T/dac_out.hpp" #elif defined(SIG_RX621) || defined(SIG_RX62N) #include "RX62x/system.hpp" #elif defined(SIG_RX64M) || defined(SIG_RX71M) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/elc.hpp" #include "RX600/exdmac.hpp" #include "RX600/mpc.hpp" #include "RX600/tpu.hpp" #include "RX600/gpt.hpp" #include "RX600/ppg.hpp" #include "RX600/cmtw.hpp" #include "RX600/can.hpp" #include "RX600/qspi.hpp" #include "RX600/s12adc.hpp" #include "RX600/adc_in.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/eptpc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/usba.hpp" #include "RX600/scif.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssi.hpp" #include "RX600/src.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/mmcif.hpp" #include "RX600/pdc.hpp" #include "RX600/standby_ram.hpp" #include "RX600/ssi_io.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX72M) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/elc.hpp" #include "RX600/exdmac.hpp" #include "RX600/mpc.hpp" #include "RX600/tpu.hpp" #include "RX600/ppg.hpp" #include "RX600/gpt.hpp" #include "RX600/ppg.hpp" #include "RX600/cmtw.hpp" #include "RX600/can.hpp" #include "RX600/qspi.hpp" #include "RX600/s12adc.hpp" #include "RX600/adc_in.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/eptpc.hpp" #include "RX600/edmac.hpp" #include "RX600/pmgi.hpp" #include "RX600/usb.hpp" #include "RX600/scif.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssie.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/mmcif.hpp" #include "RX600/pdc.hpp" #include "RX600/dsmif.hpp" #include "RX600/standby_ram.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX65N) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/elc.hpp" #include "RX600/exdmac.hpp" #include "RX600/mpc.hpp" #include "RX600/tpu.hpp" #include "RX600/ppg.hpp" #include "RX600/cmtw.hpp" #include "RX600/qspi.hpp" #include "RX600/can.hpp" #include "RX65x/s12adf.hpp" #include "RX600/adc_in.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/sdsi.hpp" #include "RX600/mmcif.hpp" #include "RX600/pdc.hpp" #include "RX600/standby_ram.hpp" #include "RX65x/glcdc.hpp" #include "RX65x/glcdc_io.hpp" #include "RX65x/drw2d.hpp" #include "RX65x/drw2d_mgr.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX66T) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/elc.hpp" #include "RX600/mpc.hpp" #include "RX66T/gptw.hpp" #include "RX66T/hrpwm.hpp" #include "RX66T/poeg.hpp" #include "RX600/can.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/usb.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/cmpc.hpp" #include "RX600/dmac_mgr.hpp" #else # error "renesas.hpp: Requires SIG_XXX to be defined" #endif // RX マイコン共通ペリフェラル #include "RX600/cac.hpp" #include "RX600/dtc.hpp" #include "RX600/port.hpp" #include "RX600/mtu3.hpp" #include "RX600/poe3.hpp" #include "RX600/tmr.hpp" #include "RX600/cmt.hpp" #include "RX600/iwdt.hpp" #include "RX600/sci.hpp" #include "RX600/riic.hpp" #include "RX600/rspi.hpp" #include "RX600/crc.hpp" #include "RX600/mpu.hpp" #include "RX600/doc.hpp" <commit_msg>Update: change path<commit_after>#pragma once //=====================================================================// /*! @file @brief ルネサス RX デバイス選択 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016, 2019 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/byte_order.h" #include "common/vect.h" #include "common/delay.hpp" #include "common/device.hpp" #include "RX600/lvda.hpp" #include "RX600/bus.hpp" #if defined(SIG_RX24T) #include "RX24T/system.hpp" #include "RX24T/system_io.hpp" #include "RX600/gpt.hpp" #include "RX24T/s12ad.hpp" #include "RX24T/adc_in.hpp" #include "RX24T/da.hpp" #include "RX600/cmpc.hpp" #include "RX24T/flash.hpp" #include "RX24T/flash_io.hpp" #include "RX24T/dac_out.hpp" #elif defined(SIG_RX621) || defined(SIG_RX62N) #include "RX62x/system.hpp" #elif defined(SIG_RX64M) || defined(SIG_RX71M) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/elc.hpp" #include "RX600/exdmac.hpp" #include "RX600/mpc.hpp" #include "RX600/tpu.hpp" #include "RX600/gpt.hpp" #include "RX600/ppg.hpp" #include "RX600/cmtw.hpp" #include "RX600/can.hpp" #include "RX600/qspi.hpp" #include "RX600/s12adc.hpp" #include "RX600/adc_in.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/eptpc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/usba.hpp" #include "RX600/scif.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssi.hpp" #include "RX600/src.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/mmcif.hpp" #include "RX600/pdc.hpp" #include "RX600/standby_ram.hpp" #include "RX600/ssi_io.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX72M) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/elc.hpp" #include "RX600/exdmac.hpp" #include "RX600/mpc.hpp" #include "RX600/tpu.hpp" #include "RX600/ppg.hpp" #include "RX600/gpt.hpp" #include "RX600/ppg.hpp" #include "RX600/cmtw.hpp" #include "RX600/can.hpp" #include "RX600/qspi.hpp" #include "RX600/s12adc.hpp" #include "RX600/adc_in.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/eptpc.hpp" #include "RX600/edmac.hpp" #include "RX600/pmgi.hpp" #include "RX600/usb.hpp" #include "RX600/scif.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssie.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/mmcif.hpp" #include "RX600/pdc.hpp" #include "RX600/dsmif.hpp" #include "RX600/standby_ram.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX65N) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/elc.hpp" #include "RX600/exdmac.hpp" #include "RX600/mpc.hpp" #include "RX600/tpu.hpp" #include "RX600/ppg.hpp" #include "RX600/cmtw.hpp" #include "RX600/qspi.hpp" #include "RX600/can.hpp" #include "RX65x/s12adf.hpp" #include "RX600/adc_in.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/sdsi.hpp" #include "RX600/mmcif.hpp" #include "RX600/pdc.hpp" #include "RX600/standby_ram.hpp" #include "RX600/glcdc.hpp" #include "RX600/glcdc_mgr.hpp" #include "RX600/drw2d.hpp" #include "RX600/drw2d_mgr.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX66T) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/elc.hpp" #include "RX600/mpc.hpp" #include "RX66T/gptw.hpp" #include "RX66T/hrpwm.hpp" #include "RX66T/poeg.hpp" #include "RX600/can.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/usb.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/cmpc.hpp" #include "RX600/dmac_mgr.hpp" #else # error "renesas.hpp: Requires SIG_XXX to be defined" #endif // RX マイコン共通ペリフェラル #include "RX600/cac.hpp" #include "RX600/dtc.hpp" #include "RX600/port.hpp" #include "RX600/mtu3.hpp" #include "RX600/poe3.hpp" #include "RX600/tmr.hpp" #include "RX600/cmt.hpp" #include "RX600/iwdt.hpp" #include "RX600/sci.hpp" #include "RX600/riic.hpp" #include "RX600/rspi.hpp" #include "RX600/crc.hpp" #include "RX600/mpu.hpp" #include "RX600/doc.hpp" <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX グループ・RSPI I/O 制御 @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "common/renesas.hpp" #include "common/vect.h" /// F_PCKB は速度パラメーター計算で必要で、設定が無いとエラーにします。 #ifndef F_PCKB # error "sci_io.hpp requires F_PCKB to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief RSPI 制御クラス @param[in] RSPI RSPI 定義クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class RSPI> class rspi_io { public: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief データ、クロック位相タイプ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class PHASE : uint8_t { TYPE1, ///< タイプ1 TYPE2, ///< タイプ2 TYPE3, ///< タイプ3 TYPE4, ///< タイプ4 (SD カードアクセス) }; private: uint8_t level_; // 便宜上のスリープ void sleep_() { asm("nop"); } bool clock_div_(uint32_t speed, uint8_t& brdv, uint8_t& spbr) { uint32_t br = F_PCKB / 2 / speed; brdv = 0; while(br > 256) { br >>= 1; ++brdv; if(brdv > 3) { brdv = 3; spbr = 255; return false; } } if(br) --br; spbr = br; return true; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// rspi_io() : level_(0) { } //-----------------------------------------------------------------// /*! @brief 設定可能な最大速度を返す(通常、F_PCKB の半分) */ //-----------------------------------------------------------------// uint32_t get_max_speed() const { return F_PCKB / 2; } //-----------------------------------------------------------------// /*! @brief 通信速度を設定して、CSI を有効にする @param[in] speed 通信速度 @param[in] dctype データ、クロック位相タイプ @param[in] level 割り込みレベル(1~2)、0の場合はポーリング @return エラー(速度設定範囲外)なら「false」 */ //-----------------------------------------------------------------// bool start(uint32_t speed, PHASE dctype, uint8_t level = 0) { level_ = level; RSPI::SPCR = 0x00; port_map::turn(RSPI::get_peripheral()); bool f = true; uint8_t brdv; uint8_t spbr; if(!clock_div_(speed, brdv, spbr)) { f = false; } power_cfg::turn(RSPI::get_peripheral()); RSPI::SPBR = spbr; RSPI::SPPCR = 0x00; // Fixed idle value, disable loop-back RSPI::SPSCR = 0x00; // disable sequence control RSPI::SPDCR = 0x20; // SPLW=1 (long word access) /// RSPI::SPCMD0 = RSPI::SPCMD0.LSBF.b() | RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0100); RSPI::SPCMD0 = RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0111); RSPI::SPCR.SPMS = 1; RSPI::SPCR.MSTR = 1; RSPI::SPCR.SPE = 1; return f; } //-----------------------------------------------------------------// /*! @brief SDカード用設定を有効にする @param[in] speed 通信速度 @return エラー(速度設定範囲外)なら「false」 */ //-----------------------------------------------------------------// bool start_sdc(uint32_t speed) { level_ = 0; RSPI::SPCR = 0x00; port_map::turn(RSPI::get_peripheral()); bool f = true; uint8_t brdv; uint8_t spbr; if(!clock_div_(speed, brdv, spbr)) { f = false; } power_cfg::turn(RSPI::get_peripheral()); RSPI::SPBR = spbr; RSPI::SPPCR = 0x00; // Fixed idle value, disable loop-back RSPI::SPSCR = 0x00; // disable sequence control RSPI::SPDCR = 0x20; // SPLW=1 (long word access) RSPI::SPCMD0 = RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0111); RSPI::SPCR.SPMS = 1; RSPI::SPCR.MSTR = 1; RSPI::SPCR.SPE = 1; return f; } //----------------------------------------------------------------// /*! @brief リード・ライト @param[in] data 書き込みデータ @return 読み出しデータ */ //----------------------------------------------------------------// uint8_t xchg(uint8_t data = 0xff) { RSPI::SPCR.SPTIE = 0; RSPI::SPCR.SPRIE = 0; RSPI::SPDR = static_cast<uint32_t>(data); while(RSPI::SPSR.SPRF() == 0) sleep_(); return static_cast<uint8_t>(RSPI::SPDR()); } //-----------------------------------------------------------------// /*! @brief シリアル送信 @param[in] src 送信ソース @param[in] cnt 送信サイズ */ //-----------------------------------------------------------------// void send(const uint8_t* src, uint16_t size) { auto end = src + size; while(src < end) { xchg(*src); ++src; } } //-----------------------------------------------------------------// /*! @brief シリアル受信 @param[out] dst 受信先 @param[in] cnt 受信サイズ */ //-----------------------------------------------------------------// void recv(uint8_t* dst, uint16_t size) { auto end = dst + size; while(dst < end) { *dst = xchg(); ++dst; } } //-----------------------------------------------------------------// /*! @brief RSPIを無効にして、パワーダウンする @param[in] power パワーダウンをしない場合「false」 */ //-----------------------------------------------------------------// void destroy(bool power = true) { RSPI::SPCR = 0x00; port_map::turn(RSPI::get_peripheral(), false); if(power) power_cfg::turn(RSPI::get_peripheral(), false); } }; } <commit_msg>update comment<commit_after>#pragma once //=====================================================================// /*! @file @brief RX グループ・RSPI I/O 制御 @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "common/renesas.hpp" #include "common/vect.h" /// F_PCKB は速度パラメーター計算で必要で、設定が無いとエラーにします。 #ifndef F_PCKB # error "sci_io.hpp requires F_PCKB to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief RSPI 制御クラス @param[in] RSPI RSPI 定義クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class RSPI> class rspi_io { public: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief データ、クロック位相タイプ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class PHASE : uint8_t { TYPE1, ///< タイプ1 TYPE2, ///< タイプ2 TYPE3, ///< タイプ3 TYPE4, ///< タイプ4 (SD カードアクセス) }; private: uint8_t level_; // 便宜上のスリープ void sleep_() { asm("nop"); } bool clock_div_(uint32_t speed, uint8_t& brdv, uint8_t& spbr) { uint32_t br = F_PCKB / 2 / speed; brdv = 0; while(br > 256) { br >>= 1; ++brdv; if(brdv > 3) { brdv = 3; spbr = 255; return false; } } if(br) --br; spbr = br; return true; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// rspi_io() : level_(0) { } //-----------------------------------------------------------------// /*! @brief 設定可能な最大速度を返す(通常、F_PCKB の半分) */ //-----------------------------------------------------------------// uint32_t get_max_speed() const { return F_PCKB / 2; } //-----------------------------------------------------------------// /*! @brief 通信速度を設定して、CSI を有効にする @param[in] speed 通信速度 @param[in] dctype データ、クロック位相タイプ @param[in] level 割り込みレベル(1~2)、0の場合はポーリング @return エラー(速度設定範囲外)なら「false」 */ //-----------------------------------------------------------------// bool start(uint32_t speed, PHASE dctype, uint8_t level = 0) { level_ = level; // ポートを有効にする port_map::turn(RSPI::get_peripheral()); bool f = true; uint8_t brdv; uint8_t spbr; if(!clock_div_(speed, brdv, spbr)) { f = false; } power_cfg::turn(RSPI::get_peripheral()); // デバイスを不許可 RSPI::SPCR = 0x00; // 設定 RSPI::SPBR = spbr; RSPI::SPPCR = 0x00; // Fixed idle value, disable loop-back RSPI::SPSCR = 0x00; // disable sequence control RSPI::SPDCR = 0x20; // SPLW=1 (long word access) /// RSPI::SPCMD0 = RSPI::SPCMD0.LSBF.b() | RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0100); RSPI::SPCMD0 = RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0111); RSPI::SPCR.SPMS = 1; RSPI::SPCR.MSTR = 1; RSPI::SPCR.SPE = 1; return f; } //-----------------------------------------------------------------// /*! @brief SDカード用設定を有効にする @param[in] speed 通信速度 @return エラー(速度設定範囲外)なら「false」 */ //-----------------------------------------------------------------// bool start_sdc(uint32_t speed) { level_ = 0; RSPI::SPCR = 0x00; port_map::turn(RSPI::get_peripheral()); bool f = true; uint8_t brdv; uint8_t spbr; if(!clock_div_(speed, brdv, spbr)) { f = false; } power_cfg::turn(RSPI::get_peripheral()); RSPI::SPBR = spbr; RSPI::SPPCR = 0x00; // Fixed idle value, disable loop-back RSPI::SPSCR = 0x00; // disable sequence control RSPI::SPDCR = 0x20; // SPLW=1 (long word access) RSPI::SPCMD0 = RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0111); RSPI::SPCR.SPMS = 1; RSPI::SPCR.MSTR = 1; RSPI::SPCR.SPE = 1; return f; } //----------------------------------------------------------------// /*! @brief リード・ライト @param[in] data 書き込みデータ @return 読み出しデータ */ //----------------------------------------------------------------// uint8_t xchg(uint8_t data = 0xff) { RSPI::SPCR.SPTIE = 0; RSPI::SPCR.SPRIE = 0; RSPI::SPDR = static_cast<uint32_t>(data); while(RSPI::SPSR.SPRF() == 0) sleep_(); return static_cast<uint8_t>(RSPI::SPDR()); } //-----------------------------------------------------------------// /*! @brief シリアル送信 @param[in] src 送信ソース @param[in] cnt 送信サイズ */ //-----------------------------------------------------------------// void send(const uint8_t* src, uint16_t size) { auto end = src + size; while(src < end) { xchg(*src); ++src; } } //-----------------------------------------------------------------// /*! @brief シリアル受信 @param[out] dst 受信先 @param[in] cnt 受信サイズ */ //-----------------------------------------------------------------// void recv(uint8_t* dst, uint16_t size) { auto end = dst + size; while(dst < end) { *dst = xchg(); ++dst; } } //-----------------------------------------------------------------// /*! @brief RSPIを無効にして、パワーダウンする @param[in] power パワーダウンをしない場合「false」 */ //-----------------------------------------------------------------// void destroy(bool power = true) { RSPI::SPCR = 0x00; port_map::turn(RSPI::get_peripheral(), false); if(power) power_cfg::turn(RSPI::get_peripheral(), false); } }; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX グループ・RSPI I/O 制御 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016, 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/vect.h" /// F_PCKx は速度パラメーター計算で必要で、設定が無いとエラーにします。 #if defined(SIG_RX24T) #ifndef F_PCLKB # error "rspi_io.hpp requires F_PCLKB to be defined" #else #undef PCLK #define PCLK F_PCLKB #define PCLK_MAX (F_PCLKB / 4) #endif #elif defined(SIG_RX64M) #ifndef F_PCLKA # error "rspi_io.hpp requires F_PCLKA to be defined" #else #undef PCLK #define PCLK F_PCLKA #define PCLK_MAX (F_PCLKA / 2) #endif #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief RSPI 制御クラス @param[in] RSPI RSPI 定義クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class RSPI> class rspi_io { public: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief データ、クロック位相タイプ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class PHASE : uint8_t { TYPE1, ///< タイプ1 TYPE2, ///< タイプ2 TYPE3, ///< タイプ3 TYPE4, ///< タイプ4 (SD カードアクセス) }; private: uint8_t level_; // 便宜上のスリープ void sleep_() { asm("nop"); } bool clock_div_(uint32_t speed, uint8_t& brdv, uint8_t& spbr) { /// utils::format("PCLK: %d\n") % static_cast<uint32_t>(PCLK); uint32_t br = static_cast<uint32_t>(PCLK) / speed; uint8_t dv = 0; while(br > 512) { br >>= 1; ++dv; if(dv > 3) { brdv = 3; spbr = 255; return false; } } brdv = dv; if(br & 1) { br >>= 1; ++br; } else { br >>= 1; } if(br) --br; spbr = br; return true; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// rspi_io() : level_(0) { } //-----------------------------------------------------------------// /*! @brief 設定可能な最大速度を返す @n ・RX24T: 20MHz @n ・RX64M: 40MHz @return 最大速度 */ //-----------------------------------------------------------------// uint32_t get_max_speed() const { return PCLK_MAX; } //-----------------------------------------------------------------// /*! @brief 通信速度を設定して、CSI を有効にする @param[in] speed 通信速度 @param[in] dctype データ、クロック位相タイプ @param[in] level 割り込みレベル(1~2)、0の場合はポーリング @param[in] port2nd 第二ポートを利用する場合「true」 @return エラー(速度設定範囲外)なら「false」 */ //-----------------------------------------------------------------// bool start(uint32_t speed, PHASE dctype, uint8_t level = 0, bool port2nd = false) { level_ = level; // デバイスを不許可 RSPI::SPCR = 0x00; // ポートを有効にする port_map::option portopt = port_map::option::FIRST; if(port2nd) { portopt = port_map::option::SECOND; } port_map::turn(RSPI::get_peripheral(), true, portopt); bool f = true; uint8_t brdv; uint8_t spbr; if(!clock_div_(speed, brdv, spbr)) { f = false; } power_cfg::turn(RSPI::get_peripheral()); // 設定 RSPI::SPBR = spbr; RSPI::SPPCR = 0x00; // Fixed idle value, disable loop-back RSPI::SPSCR = 0x00; // disable sequence control RSPI::SPDCR = 0x20; // SPLW=1 (long word access) /// RSPI::SPCMD0 = RSPI::SPCMD0.LSBF.b() | RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0100); RSPI::SPCMD0 = RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0111); RSPI::SPCR.SPMS = 1; RSPI::SPCR.MSTR = 1; RSPI::SPCR.SPE = 1; return f; } //-----------------------------------------------------------------// /*! @brief SDカード用設定を有効にする @param[in] speed 通信速度 @return エラー(速度設定範囲外)なら「false」 */ //-----------------------------------------------------------------// bool start_sdc(uint32_t speed) { level_ = 0; RSPI::SPCR = 0x00; bool f = true; uint8_t brdv; uint8_t spbr; if(!clock_div_(speed, brdv, spbr)) { f = false; } power_cfg::turn(RSPI::get_peripheral()); port_map::turn(RSPI::get_peripheral()); #if 0 utils::format("RSPI Request Speed: %u [Hz]\n") % speed; // utils::format("RSPI SPBR: %d\n") % static_cast<uint32_t>(spbr); // utils::format("RSPI BRDV: %d\n") % static_cast<uint32_t>(brdv); #endif RSPI::SPBR = spbr; // 実際のクロックを表示 #if 0 static const uint8_t n[4] = { 1, 2, 4, 8 }; uint32_t z = static_cast<uint32_t>(PCLK) / (2 * static_cast<uint32_t>(spbr + 1) * static_cast<uint32_t>(n[brdv])); utils::format("RSPI Real Speed: %u [Hz]\n") % z; #endif RSPI::SPPCR = 0x00; // Fixed idle value, disable loop-back RSPI::SPSCR = 0x00; // disable sequence control RSPI::SPDCR = 0x20; // SPLW=1 (long word access) RSPI::SPCMD0 = RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0100); /// | RSPI::SPCMD0.CPHA.b(0) | RSPI::SPCMD0.CPOL.b(1); RSPI::SPCR.SPMS = 1; RSPI::SPCR.MSTR = 1; RSPI::SPCR.SPE = 1; return f; } //----------------------------------------------------------------// /*! @brief リード・ライト @param[in] data 書き込みデータ @return 読み出しデータ */ //----------------------------------------------------------------// uint8_t xchg(uint8_t data = 0xff) { // RSPI::SPCR.SPTIE = 0; // RSPI::SPCR.SPRIE = 0; RSPI::SPDR = static_cast<uint32_t>(data); while(RSPI::SPSR.SPRF() == 0) sleep_(); uint32_t d = RSPI::SPDR(); return d & 0xff; } //-----------------------------------------------------------------// /*! @brief シリアル送信 @param[in] src 送信ソース @param[in] cnt 送信サイズ */ //-----------------------------------------------------------------// void send(const uint8_t* src, uint16_t size) { auto end = src + size; while(src < end) { xchg(*src); ++src; } } //-----------------------------------------------------------------// /*! @brief シリアル受信 @param[out] dst 受信先 @param[in] cnt 受信サイズ */ //-----------------------------------------------------------------// void recv(uint8_t* dst, uint16_t size) { auto end = dst + size; while(dst < end) { *dst = xchg(); ++dst; } } //-----------------------------------------------------------------// /*! @brief RSPIを無効にして、パワーダウンする @param[in] power パワーダウンをしない場合「false」 */ //-----------------------------------------------------------------// void destroy(bool power = true) { RSPI::SPCR = 0x00; port_map::turn(RSPI::get_peripheral(), false); if(power) power_cfg::turn(RSPI::get_peripheral(), false); } }; } <commit_msg>update 24 bits<commit_after>#pragma once //=====================================================================// /*! @file @brief RX グループ・RSPI I/O 制御 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016, 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/vect.h" /// F_PCKx は速度パラメーター計算で必要で、設定が無いとエラーにします。 #if defined(SIG_RX24T) #ifndef F_PCLKB # error "rspi_io.hpp requires F_PCLKB to be defined" #else #undef PCLK #define PCLK F_PCLKB #define PCLK_MAX (F_PCLKB / 4) #endif #elif defined(SIG_RX64M) #ifndef F_PCLKA # error "rspi_io.hpp requires F_PCLKA to be defined" #else #undef PCLK #define PCLK F_PCLKA #define PCLK_MAX (F_PCLKA / 2) #endif #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief RSPI 制御クラス @param[in] RSPI RSPI 定義クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class RSPI> class rspi_io { public: // typedef device::PORT<device::PORTJ, device::bitpos::B5> LED; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief データ、クロック位相タイプ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class PHASE : uint8_t { TYPE1, ///< タイプ1 TYPE2, ///< タイプ2 TYPE3, ///< タイプ3 TYPE4, ///< タイプ4 (SD カードアクセス) }; private: uint8_t level_; // 便宜上のスリープ void sleep_() { asm("nop"); } bool clock_div_(uint32_t speed, uint8_t& brdv, uint8_t& spbr) { /// utils::format("PCLK: %d\n") % static_cast<uint32_t>(PCLK); uint32_t br = static_cast<uint32_t>(PCLK) / speed; uint8_t dv = 0; while(br > 512) { br >>= 1; ++dv; if(dv > 3) { brdv = 3; spbr = 255; return false; } } brdv = dv; if(br & 1) { br >>= 1; ++br; } else { br >>= 1; } if(br) --br; spbr = br; return true; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// rspi_io() : level_(0) { } //-----------------------------------------------------------------// /*! @brief 設定可能な最大速度を返す @n ・RX24T: 20MHz @n ・RX64M: 40MHz @return 最大速度 */ //-----------------------------------------------------------------// uint32_t get_max_speed() const { return PCLK_MAX; } //-----------------------------------------------------------------// /*! @brief 通信速度を設定して、CSI を有効にする @param[in] speed 通信速度 @param[in] dctype データ、クロック位相タイプ @param[in] level 割り込みレベル(1~2)、0の場合はポーリング @param[in] port2nd 第二ポートを利用する場合「true」 @return エラー(速度設定範囲外)なら「false」 */ //-----------------------------------------------------------------// bool start(uint32_t speed, PHASE dctype, uint8_t level = 0, bool port2nd = false) { level_ = level; // デバイスを不許可 RSPI::SPCR = 0x00; // ポートを有効にする port_map::option portopt = port_map::option::FIRST; if(port2nd) { portopt = port_map::option::SECOND; } port_map::turn(RSPI::get_peripheral(), true, portopt); bool f = true; uint8_t brdv; uint8_t spbr; if(!clock_div_(speed, brdv, spbr)) { f = false; } power_cfg::turn(RSPI::get_peripheral()); // 設定 RSPI::SPBR = spbr; RSPI::SPPCR = 0x00; // Fixed idle value, disable loop-back RSPI::SPSCR = 0x00; // disable sequence control RSPI::SPDCR = 0x20; // SPLW=1 (long word access) /// RSPI::SPCMD0 = RSPI::SPCMD0.LSBF.b() | RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0100); // 8 bits // RSPI::SPCMD0 = RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0111); // 24 bits RSPI::SPCMD0 = RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0001); RSPI::SPCR.SPMS = 1; RSPI::SPCR.MSTR = 1; RSPI::SPCR.SPE = 1; return f; } //-----------------------------------------------------------------// /*! @brief SDカード用設定を有効にする @param[in] speed 通信速度 @return エラー(速度設定範囲外)なら「false」 */ //-----------------------------------------------------------------// bool start_sdc(uint32_t speed) { level_ = 0; RSPI::SPCR = 0x00; bool f = true; uint8_t brdv; uint8_t spbr; if(!clock_div_(speed, brdv, spbr)) { f = false; } power_cfg::turn(RSPI::get_peripheral()); port_map::turn(RSPI::get_peripheral()); #if 0 utils::format("RSPI Request Speed: %u [Hz]\n") % speed; // utils::format("RSPI SPBR: %d\n") % static_cast<uint32_t>(spbr); // utils::format("RSPI BRDV: %d\n") % static_cast<uint32_t>(brdv); #endif RSPI::SPBR = spbr; // 実際のクロックを表示 #if 0 static const uint8_t n[4] = { 1, 2, 4, 8 }; uint32_t z = static_cast<uint32_t>(PCLK) / (2 * static_cast<uint32_t>(spbr + 1) * static_cast<uint32_t>(n[brdv])); utils::format("RSPI Real Speed: %u [Hz]\n") % z; #endif RSPI::SPPCR = 0x00; // Fixed idle value, disable loop-back RSPI::SPSCR = 0x00; // disable sequence control RSPI::SPDCR = 0x20; // SPLW=1 (long word access) RSPI::SPCMD0 = RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0100); /// | RSPI::SPCMD0.CPHA.b(0) | RSPI::SPCMD0.CPOL.b(1); RSPI::SPCR.SPMS = 1; RSPI::SPCR.MSTR = 1; RSPI::SPCR.SPE = 1; return f; } //----------------------------------------------------------------// /*! @brief リード・ライト @param[in] data 書き込みデータ @return 読み出しデータ */ //----------------------------------------------------------------// uint8_t xchg(uint8_t data = 0xff) { RSPI::SPDR = static_cast<uint32_t>(data); while(RSPI::SPSR.SPRF() == 0) sleep_(); return RSPI::SPDR(); } //----------------------------------------------------------------// /*! @brief リード・ライト @param[in] data 書き込みデータ @return 読み出しデータ */ //----------------------------------------------------------------// uint32_t xchg32(uint32_t data = 0) { RSPI::SPDR = static_cast<uint32_t>(data); while(RSPI::SPSR.SPRF() == 0) sleep_(); return RSPI::SPDR(); } //-----------------------------------------------------------------// /*! @brief シリアル送信 @param[in] src 送信ソース @param[in] cnt 送信サイズ */ //-----------------------------------------------------------------// void send(const uint8_t* src, uint16_t size) { auto end = src + size; while(src < end) { xchg(*src); ++src; } } //-----------------------------------------------------------------// /*! @brief シリアル受信 @param[out] dst 受信先 @param[in] cnt 受信サイズ */ //-----------------------------------------------------------------// void recv(uint8_t* dst, uint16_t size) { auto end = dst + size; while(dst < end) { *dst = xchg(); ++dst; } } //-----------------------------------------------------------------// /*! @brief RSPIを無効にして、パワーダウンする @param[in] power パワーダウンをしない場合「false」 */ //-----------------------------------------------------------------// void destroy(bool power = true) { RSPI::SPCR = 0x00; port_map::turn(RSPI::get_peripheral(), false); if(power) power_cfg::turn(RSPI::get_peripheral(), false); } }; } <|endoftext|>
<commit_before>// Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: dingcongjun (dingcj) #include <stdlib.h> #include "Line2.h" #include "Logger.h" namespace poppy { Line2::Line2(int x1, int y1, int x2, int y2) :k_(0.0f), kb_(0.0f), a_(0.0f), b_(0.0f), c_(0.0f), vLine_(false), hLine_(false), x_(0), y_(0) { if (x1 == x2 && y1 == y2) { LOG_ERROR("point1 is equal to point2, " "x1: %d, y1: %d, x2: %d, y2: %d\n", x1, y1, x2, y2); x1 = y1 = 0; x2 = y2 = 1; } else { a_ = y1 - y2; b_ = x2 - x1; c_ = x1 * y2 - x2 * y1; if (x1 == x2) { //VLine vLine_ = true; x_ = x1; } else if (y1 == y2) { //HLine k_ = 0.0f; kb_ = y1; hLine_ = true; y_ = y1; } else { k_ = (y2 - y1) / (float)(x2 - x1); kb_ = y1 - ((y2 - y1) / (x2 - x1)) * x1; } } } int Line2::getY(int x, int *py) { if (vLine_) { LOG_ERROR("Line is vLine!\n"); return -1; } if (hLine_) { *py = y_; return 0; } *py = k_ * x + kb_ + 0.5; return 0; } int Line2::getX(int y, int *px) { if (hLine_) { LOG_ERROR("Line is hLine!\n"); return -1; } if (vLine_) { *px = x_; return 0; } *px = (y - kb_) / k_ + 0.5; return 0; } int Line2::clip(int w, int h, int *x1, int *y1, int *x2, int *y2) { Line2 line(*x1, *y1, *x2, *y2); uint32_t pointPos1 = getPosition(w, h, *x1, *y1); uint32_t pointPos2 = getPosition(w, h, *x2, *y2); if (pointPos1 & pointPos2) { return 0; } if (pointPos1 == kClipCodeC && pointPos2 == kClipCodeC) { return 1; } if (line.vLine()) { if (pointPos1 & kClipCodeN) { *y1 = 0; } else if (pointPos1 & kClipCodeS) { *y1 = h - 1; } if (pointPos2 & kClipCodeN) { *y2 = 0; } else if (pointPos2 & kClipCodeS) { *y2 = h - 1; } return 1; } if (line.hLine()) { if (pointPos1 & kClipCodeE) { *x1 = w - 1; } else if (pointPos1 & kClipCodeW) { *x1 = 0; } if (pointPos2 & kClipCodeE) { *x2 = w - 1; } else if (pointPos2 & kClipCodeW) { *x2 = 0; } return 1; } //XĽ int crossNum = 0; int cx[2] = {0}; int cy[2] = {0}; cy[crossNum] = 0; line.getX(cy[crossNum], &cx[crossNum]); if (cx[crossNum] >= 0 && cx[crossNum] < w) { crossNum++; } //YĽ cx[crossNum] = 0; line.getY(cx[crossNum], &cy[crossNum]); if (cy[crossNum] >= 0 && cy[crossNum] < h - 1) { if (crossNum == 1 && (cx[0] != cx[1] || cy[0] != cy[1])) { crossNum++; } } //XƽбߵĽ if (crossNum < 2) { cy[crossNum] = h -1; line.getX(cy[crossNum], &cx[crossNum]); if (cx[crossNum] >= 0 && cx[crossNum] < w) { if (crossNum == 1 && (cx[0] != cx[1] || cy[0] != cy[1])) { crossNum++; } } } //yƽбߵĽ if (crossNum < 2) { cx[crossNum] = w -1; line.getY(cx[crossNum], &cy[crossNum]); if (cy[crossNum] >= 0 && cy[crossNum] < h) { if (crossNum == 1 && (cx[0] != cx[1] || cy[0] != cy[1])) { crossNum++; } } } if (crossNum < 2) { return 0; } if (pointPos1 != kClipCodeC) { if (abs(*x1 - cx[0]) < abs(*x1 - cx[1])) { *x1 = cx[0]; *y1 = cy[0]; } else { *x1 = cx[1]; *y1 = cy[1]; } } if (pointPos2 != kClipCodeC) { if (abs(*x2 - cx[0]) < abs(*x2 - cx[1])) { *x2 = cx[0]; *y2 = cy[0]; } else { *x2 = cx[1]; *y2 = cy[1]; } } return 1; } int Line2::crossPoint(const Line2& line, int *px, int *py) { if (vLine_ && line.vLine_) { LOG_ERROR("Lines are both vLine\n"); return -1; } if (!vLine_ && !line.vLine_) { if (k_ == line.k_) { LOG_ERROR("Lines are parallel!\n"); return -1; } } float d = a_ * line.a_ - line.a_ * b_; // *px = (b_ * line.c_ - line.b_ * c_) / d + 0.5f; *py = (c_ * line.a_ - line.c_ * a_) / d + 0.5f; return 0; } uint32_t Line2::getPosition(int w, int h, int x, int y) { uint32_t position = 0u; int maxX = w - 1; int maxY = h - 1; if (y < 0) { position |= kClipCodeN; } else if (y > maxY) { position |= kClipCodeS; } else if (x < 0) { position |= kClipCodeW; } else if (x > maxX) { position |= kClipCodeE; } return position; } } <commit_msg>修改直线裁剪时的bug<commit_after>// Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: dingcongjun (dingcj) #include <stdlib.h> #include "Line2.h" #include "Logger.h" namespace poppy { Line2::Line2(int x1, int y1, int x2, int y2) :k_(0.0f), kb_(0.0f), a_(0.0f), b_(0.0f), c_(0.0f), vLine_(false), hLine_(false), x_(0), y_(0) { if (x1 == x2 && y1 == y2) { LOG_ERROR("point1 is equal to point2, " "x1: %d, y1: %d, x2: %d, y2: %d\n", x1, y1, x2, y2); x1 = y1 = 0; x2 = y2 = 1; } else { a_ = y1 - y2; b_ = x2 - x1; c_ = x1 * y2 - x2 * y1; if (x1 == x2) { //VLine vLine_ = true; x_ = x1; } else if (y1 == y2) { //HLine k_ = 0.0f; kb_ = y1; hLine_ = true; y_ = y1; } else { k_ = (y2 - y1) / (float)(x2 - x1); kb_ = y1 - ((y2 - y1) / (float)(x2 - x1)) * x1; } } } int Line2::getY(int x, int *py) { if (vLine_) { LOG_ERROR("Line is vLine!\n"); return -1; } if (hLine_) { *py = y_; return 0; } *py = k_ * x + kb_ + 0.5; return 0; } int Line2::getX(int y, int *px) { if (hLine_) { LOG_ERROR("Line is hLine!\n"); return -1; } if (vLine_) { *px = x_; return 0; } *px = (y - kb_) / k_ + 0.5; return 0; } int Line2::clip(int w, int h, int *x1, int *y1, int *x2, int *y2) { Line2 line(*x1, *y1, *x2, *y2); uint32_t pointPos1 = getPosition(w, h, *x1, *y1); uint32_t pointPos2 = getPosition(w, h, *x2, *y2); if (pointPos1 & pointPos2) { return 0; } if (pointPos1 == kClipCodeC && pointPos2 == kClipCodeC) { return 1; } if (line.vLine()) { if (pointPos1 & kClipCodeN) { *y1 = 0; } else if (pointPos1 & kClipCodeS) { *y1 = h - 1; } if (pointPos2 & kClipCodeN) { *y2 = 0; } else if (pointPos2 & kClipCodeS) { *y2 = h - 1; } return 1; } if (line.hLine()) { if (pointPos1 & kClipCodeE) { *x1 = w - 1; } else if (pointPos1 & kClipCodeW) { *x1 = 0; } if (pointPos2 & kClipCodeE) { *x2 = w - 1; } else if (pointPos2 & kClipCodeW) { *x2 = 0; } return 1; } //XĽ int crossNum = 0; int cx[2] = {0}; int cy[2] = {0}; cy[crossNum] = 0; line.getX(cy[crossNum], &cx[crossNum]); if (cx[crossNum] >= 0 && cx[crossNum] < w) { crossNum++; } //YĽ cx[crossNum] = 0; line.getY(cx[crossNum], &cy[crossNum]); if (cy[crossNum] >= 0 && cy[crossNum] < h - 1) { if (crossNum == 1 && (cx[0] != cx[1] || cy[0] != cy[1])) { crossNum++; } } //XƽбߵĽ if (crossNum < 2) { cy[crossNum] = h -1; line.getX(cy[crossNum], &cx[crossNum]); if (cx[crossNum] >= 0 && cx[crossNum] < w) { if (crossNum == 1 && (cx[0] != cx[1] || cy[0] != cy[1])) { crossNum++; } } } //yƽбߵĽ if (crossNum < 2) { cx[crossNum] = w -1; line.getY(cx[crossNum], &cy[crossNum]); if (cy[crossNum] >= 0 && cy[crossNum] < h) { if (crossNum == 1 && (cx[0] != cx[1] || cy[0] != cy[1])) { crossNum++; } } } if (crossNum < 2) { return 0; } if (pointPos1 != kClipCodeC) { if (abs(*x1 - cx[0]) < abs(*x1 - cx[1])) { *x1 = cx[0]; *y1 = cy[0]; } else { *x1 = cx[1]; *y1 = cy[1]; } } if (pointPos2 != kClipCodeC) { if (abs(*x2 - cx[0]) < abs(*x2 - cx[1])) { *x2 = cx[0]; *y2 = cy[0]; } else { *x2 = cx[1]; *y2 = cy[1]; } } return 1; } int Line2::crossPoint(const Line2& line, int *px, int *py) { if (vLine_ && line.vLine_) { LOG_ERROR("Lines are both vLine\n"); return -1; } if (!vLine_ && !line.vLine_) { if (k_ == line.k_) { LOG_ERROR("Lines are parallel!\n"); return -1; } } float d = a_ * line.a_ - line.a_ * b_; // *px = (b_ * line.c_ - line.b_ * c_) / d + 0.5f; *py = (c_ * line.a_ - line.c_ * a_) / d + 0.5f; return 0; } uint32_t Line2::getPosition(int w, int h, int x, int y) { uint32_t position = 0u; int maxX = w - 1; int maxY = h - 1; if (y < 0) { position |= kClipCodeN; } if (y > maxY) { position |= kClipCodeS; } if (x < 0) { position |= kClipCodeW; } if (x > maxX) { position |= kClipCodeE; } return position; } } <|endoftext|>
<commit_before>#ifndef WORKER_HPP #define WORKER_HPP #include <memory> #include <thread> #include <atomic> #include <queue> #include <stdint.h> #include <string.h> #include "basicTrie.hpp" #include "ring.hpp" #include "routingTable.hpp" #include "arpTable.hpp" #include "headers.hpp" #include "util.hpp" #include "config.hpp" using namespace std; /*! The packet processing is done here. * This class gets packets from an input ring, * applies some transformation (routing), * and outputs them through the output rings. */ class Worker { private: // Shared data structures and their updates std::shared_ptr<LPM> cur_lpm; std::shared_ptr<ARPTable::table> cur_arp_table; std::shared_ptr<LPM> new_lpm; std::shared_ptr<ARPTable::table> new_arp_table; // Rings for frame transfer Ring<frame>& ingressQ; Ring<frame>& egressQ; //Ring<frame>& hostQ; // Interfaces to be used std::shared_ptr<std::vector<interface>> interfaces; // The thread this one worker works in std::thread thread; // The state of the thread enum enum_state {RUN, STOP}; std::atomic<enum_state> state; // Big stuff happens here void process(); // Run loop void run(){ while(state.load() == RUN){ process(); cur_lpm = new_lpm; cur_arp_table = new_arp_table; } } public: /*! Start a new Worker thread. * All persistend arguments are given here, as well as the first set of updatables * \param cur_lpm Current LPM datastructre * \param cur_arp_table the Current ARP lookup table * \param ingressQ Input ring of new packets * \param egressQ Output ring of processed packets * \param interfaces Interfaces of the router */ Worker( std::shared_ptr<LPM> cur_lpm, std::shared_ptr<ARPTable::table> cur_arp_table, Ring<frame>& ingressQ, Ring<frame>& egressQ, std::shared_ptr<std::vector<interface>> interfaces) : cur_lpm(cur_lpm), cur_arp_table(cur_arp_table), ingressQ(ingressQ), egressQ(egressQ), interfaces(interfaces), thread(&Worker::run, this), state(RUN) {}; /*! Update Worker * This function updates the worker thread with new information * \param lpm New LPM datastructure * \param arp_table New ARP lookup table, corresponrint to lpm */ void update(std::shared_ptr<LPM> lpm, std::shared_ptr<ARPTable::table> arp_table){ new_lpm = lpm; new_arp_table = arp_table; }; /*! Stop this worker thread * This function blocks until the worker is actually stopped (joined) */ void stop(){ state.store(STOP); thread.join(); } }; #endif /* WORKER_HPP */ <commit_msg>minor doxygen fixes<commit_after>#ifndef WORKER_HPP #define WORKER_HPP #include <memory> #include <thread> #include <atomic> #include <queue> #include <stdint.h> #include <string.h> #include "basicTrie.hpp" #include "ring.hpp" #include "routingTable.hpp" #include "arpTable.hpp" #include "headers.hpp" #include "util.hpp" #include "config.hpp" using namespace std; /*! The packet processing is done here. * This class gets packets from an input ring, * applies some transformation (routing), * and outputs them through the output rings. */ class Worker { private: // Shared data structures and their updates std::shared_ptr<LPM> cur_lpm; std::shared_ptr<ARPTable::table> cur_arp_table; std::shared_ptr<LPM> new_lpm; std::shared_ptr<ARPTable::table> new_arp_table; // Rings for frame transfer Ring<frame>& ingressQ; Ring<frame>& egressQ; //Ring<frame>& hostQ; // Interfaces to be used std::shared_ptr<std::vector<interface>> interfaces; // The thread this one worker works in std::thread thread; // The state of the thread enum enum_state {RUN, STOP}; std::atomic<enum_state> state; // Big stuff happens here void process(); // Run loop void run(){ while(state.load() == RUN){ process(); cur_lpm = new_lpm; cur_arp_table = new_arp_table; } } public: /*! Start a new Worker thread. * All persistend arguments are given here, as well as the first set of updatables * \param cur_lpm Current LPM datastructre * \param cur_arp_table the Current ARP lookup table * \param ingressQ Input ring of new packets * \param egressQ Output ring of processed packets * \param interfaces Interfaces of the router */ Worker( std::shared_ptr<LPM> cur_lpm, std::shared_ptr<ARPTable::table> cur_arp_table, Ring<frame>& ingressQ, Ring<frame>& egressQ, std::shared_ptr<std::vector<interface>> interfaces) : cur_lpm(cur_lpm), cur_arp_table(cur_arp_table), ingressQ(ingressQ), egressQ(egressQ), interfaces(interfaces), thread(&Worker::run, this), state(RUN) {}; /*! Update Worker. * This function updates the worker thread with new information * \param lpm New LPM datastructure * \param arp_table New ARP lookup table, corresponrint to lpm */ void update(std::shared_ptr<LPM> lpm, std::shared_ptr<ARPTable::table> arp_table){ new_lpm = lpm; new_arp_table = arp_table; }; /*! Stop this worker thread. * This function blocks until the worker is actually stopped (joined) */ void stop(){ state.store(STOP); thread.join(); } }; #endif /* WORKER_HPP */ <|endoftext|>
<commit_before> #include "CMesh.h" CMesh::CMesh() {} CMesh::CMesh(SMeshBuffer * const Buffer) { Buffers.push_back(Buffer); Materials.push_back(Buffer->GetMaterial()); Root = new SMeshNode{}; Root->Buffers.push_back(Buffer); LoadDataIntoBuffers(); } CMesh::CMesh(SMeshBuffer && Buffer) : CMesh(new SMeshBuffer(Buffer)) {} void CMesh::LoadDataIntoBuffers() { std::for_each(Buffers.begin(), Buffers.end(), [](SMeshBuffer * Buffer){ Buffer->LoadDataIntoBuffers(); }); } /* uint CMesh::GetVertexCount() const { return MeshBuffer.Vertices.size() + std::accumulate(Children.begin(), Children.end(), 0, [](uint Count, CMesh * Mesh) { return Count + Mesh->MeshBuffer.Vertices.size(); }); } SBoundingBox3f CMesh::GetBoundingBox() const { SBoundingBox3f Box(SVector3f(std::numeric_limits<float>().max()), SVector3f(-std::numeric_limits<float>().max())); for (std::vector<sharedPtr<SMeshBuffer>>::const_iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::const_iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) Box.AddInternalPoint(it->Position); return Box; } SVector3f CMesh::GetExtent() const { SVector3f Min(std::numeric_limits<float>::max()), Max(-std::numeric_limits<float>::max()); { for (std::vector<sharedPtr<SMeshBuffer>>::const_iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::const_iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) { if (Min.X > it->Position.X) Min.X = it->Position.X; if (Min.Y > it->Position.Y) Min.Y = it->Position.Y; if (Min.Z > it->Position.Z) Min.Z = it->Position.Z; if (Max.X < it->Position.X) Max.X = it->Position.X; if (Max.Y < it->Position.Y) Max.Y = it->Position.Y; if (Max.Z < it->Position.Z) Max.Z = it->Position.Z; } } return (Max - Min); } void CMesh::CenterMeshByAverage(vec3f const & CenterLocation) { SVector3f VertexSum; for (std::vector<sharedPtr<SMeshBuffer>>::const_iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::const_iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) VertexSum += it->Position; VertexSum /= (f32) GetVertexCount(); SVector3f VertexOffset = CenterLocation - VertexSum; for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) it->Position += VertexOffset; } void CMesh::CenterMeshByExtents(vec3f const & CenterLocation) { SVector3f Min(std::numeric_limits<f32>::max()), Max(-std::numeric_limits<f32>::max()); { for (std::vector<sharedPtr<SMeshBuffer>>::const_iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::const_iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) { if (Min.X > it->Position.X) Min.X = it->Position.X; if (Min.Y > it->Position.Y) Min.Y = it->Position.Y; if (Min.Z > it->Position.Z) Min.Z = it->Position.Z; if (Max.X < it->Position.X) Max.X = it->Position.X; if (Max.Y < it->Position.Y) Max.Y = it->Position.Y; if (Max.Z < it->Position.Z) Max.Z = it->Position.Z; } } SVector3f Center = (Max + Min) / 2; SVector3f VertexOffset = CenterLocation - Center; for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) it->Position += VertexOffset; } void CMesh::ResizeMesh(vec3f const & Scale) { SVector3f Extent = GetExtent(); SVector3f Resize = Scale / std::max(Extent.X, std::max(Extent.Y, Extent.Z)); for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) it->Position *= Resize; } void CMesh::ReverseFaces() { for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) { for (std::vector<SMeshTriangle>::iterator it = (* bit)->Triangles.begin(); it != (* bit)->Triangles.end(); ++ it) { u32 temp = it->Indices[1]; it->Indices[1] = it->Indices[2]; it->Indices[2] = temp; } } } void CMesh::LinearizeIndices() { for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) { std::vector<SVertex> newVertices; std::vector<SMeshTriangle> newTriangles; for (std::vector<SMeshTriangle>::iterator it = (* bit)->Triangles.begin(); it != (* bit)->Triangles.end(); ++ it) { for (int i = 0; i < 3; ++ i) newVertices.push_back((* bit)->Vertices[it->Indices[i]]); } for (uint i = 0; i < newVertices.size() / 3; ++ i) { SMeshTriangle tri; tri.Indices[0] = i * 3; tri.Indices[1] = i * 3 + 1; tri.Indices[2] = i * 3 + 2; newTriangles.push_back(tri); } (* bit)->Vertices = newVertices; (* bit)->Triangles = newTriangles; } } void CMesh::CalculateNormalsPerFace() { for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) { for (std::vector<SMeshTriangle>::iterator it = (* bit)->Triangles.begin(); it != (* bit)->Triangles.end(); ++ it) { it->Normal = ((* bit)->Vertices[it->Indices[1]].Position - (* bit)->Vertices[it->Indices[0]].Position). CrossProduct((* bit)->Vertices[it->Indices[2]].Position - (* bit)->Vertices[it->Indices[0]].Position); (* bit)->Vertices[it->Indices[0]].Normal = (* bit)->Vertices[it->Indices[1]].Normal = (* bit)->Vertices[it->Indices[2]].Normal = it->Normal; } } for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) { it->Normal.Normalize(); } } void CMesh::CalculateNormalsPerVertex(bool CombineNear, f32 const NearTolerance) { CalculateNormalsPerFace(); for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) it->Normal = SVector3f(); for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SMeshTriangle>::iterator it = (* bit)->Triangles.begin(); it != (* bit)->Triangles.end(); ++ it) for (int i = 0; i < 3; ++ i) (* bit)->Vertices[it->Indices[i]].Normal += it->Normal; if (CombineNear) for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (uint i = 0; i < (* bit)->Vertices.size(); ++ i) for (uint j = i + 1; j < (* bit)->Vertices.size(); ++ j) if ((* bit)->Vertices[i].Position.Equals((* bit)->Vertices[j].Position, NearTolerance)) (* bit)->Vertices[i].Normal = (* bit)->Vertices[j].Normal = (* bit)->Vertices[i].Normal + (* bit)->Vertices[j].Normal; for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) it->Normal.Normalize(); } void CMesh::CalculateTextureCoordinates(vec3f const & uVec, vec3f const & vVec, vec2f const & Scale) { SVector3f Min(std::numeric_limits<float>::max()), Max(-std::numeric_limits<float>::max()); { for (std::vector<sharedPtr<SMeshBuffer>>::const_iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::const_iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) { if (Min.X > it->Position.X) Min.X = it->Position.X; if (Min.Y > it->Position.Y) Min.Y = it->Position.Y; if (Min.Z > it->Position.Z) Min.Z = it->Position.Z; if (Max.X < it->Position.X) Max.X = it->Position.X; if (Max.Y < it->Position.Y) Max.Y = it->Position.Y; if (Max.Z < it->Position.Z) Max.Z = it->Position.Z; } } for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) { SVector3f const RelativePosition = (it->Position - Min) / (Max - Min); it->TextureCoordinates = vec2f((RelativePosition * uVec.GetNormalized()).Length(), (RelativePosition * vVec.GetNormalized()).Length()) * Scale; } } void CMesh::UpdateBuffers() { for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) (* bit)->UpdateBuffers(); } */ <commit_msg>Spacing<commit_after> #include "CMesh.h" CMesh::CMesh() {} CMesh::CMesh(SMeshBuffer * const Buffer) { Buffers.push_back(Buffer); Materials.push_back(Buffer->GetMaterial()); Root = new SMeshNode{}; Root->Buffers.push_back(Buffer); LoadDataIntoBuffers(); } CMesh::CMesh(SMeshBuffer && Buffer) : CMesh(new SMeshBuffer(Buffer)) {} void CMesh::LoadDataIntoBuffers() { std::for_each(Buffers.begin(), Buffers.end(), [](SMeshBuffer * Buffer){ Buffer->LoadDataIntoBuffers(); }); } /* uint CMesh::GetVertexCount() const { return MeshBuffer.Vertices.size() + std::accumulate(Children.begin(), Children.end(), 0, [](uint Count, CMesh * Mesh) { return Count + Mesh->MeshBuffer.Vertices.size(); }); } SBoundingBox3f CMesh::GetBoundingBox() const { SBoundingBox3f Box(SVector3f(std::numeric_limits<float>().max()), SVector3f(-std::numeric_limits<float>().max())); for (std::vector<sharedPtr<SMeshBuffer>>::const_iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::const_iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) Box.AddInternalPoint(it->Position); return Box; } SVector3f CMesh::GetExtent() const { SVector3f Min(std::numeric_limits<float>::max()), Max(-std::numeric_limits<float>::max()); { for (std::vector<sharedPtr<SMeshBuffer>>::const_iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::const_iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) { if (Min.X > it->Position.X) Min.X = it->Position.X; if (Min.Y > it->Position.Y) Min.Y = it->Position.Y; if (Min.Z > it->Position.Z) Min.Z = it->Position.Z; if (Max.X < it->Position.X) Max.X = it->Position.X; if (Max.Y < it->Position.Y) Max.Y = it->Position.Y; if (Max.Z < it->Position.Z) Max.Z = it->Position.Z; } } return (Max - Min); } void CMesh::CenterMeshByAverage(vec3f const & CenterLocation) { SVector3f VertexSum; for (std::vector<sharedPtr<SMeshBuffer>>::const_iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::const_iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) VertexSum += it->Position; VertexSum /= (f32) GetVertexCount(); SVector3f VertexOffset = CenterLocation - VertexSum; for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) it->Position += VertexOffset; } void CMesh::CenterMeshByExtents(vec3f const & CenterLocation) { SVector3f Min(std::numeric_limits<f32>::max()), Max(-std::numeric_limits<f32>::max()); { for (std::vector<sharedPtr<SMeshBuffer>>::const_iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::const_iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) { if (Min.X > it->Position.X) Min.X = it->Position.X; if (Min.Y > it->Position.Y) Min.Y = it->Position.Y; if (Min.Z > it->Position.Z) Min.Z = it->Position.Z; if (Max.X < it->Position.X) Max.X = it->Position.X; if (Max.Y < it->Position.Y) Max.Y = it->Position.Y; if (Max.Z < it->Position.Z) Max.Z = it->Position.Z; } } SVector3f Center = (Max + Min) / 2; SVector3f VertexOffset = CenterLocation - Center; for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) it->Position += VertexOffset; } void CMesh::ResizeMesh(vec3f const & Scale) { SVector3f Extent = GetExtent(); SVector3f Resize = Scale / std::max(Extent.X, std::max(Extent.Y, Extent.Z)); for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) it->Position *= Resize; } void CMesh::ReverseFaces() { for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) { for (std::vector<SMeshTriangle>::iterator it = (* bit)->Triangles.begin(); it != (* bit)->Triangles.end(); ++ it) { u32 temp = it->Indices[1]; it->Indices[1] = it->Indices[2]; it->Indices[2] = temp; } } } void CMesh::LinearizeIndices() { for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) { std::vector<SVertex> newVertices; std::vector<SMeshTriangle> newTriangles; for (std::vector<SMeshTriangle>::iterator it = (* bit)->Triangles.begin(); it != (* bit)->Triangles.end(); ++ it) { for (int i = 0; i < 3; ++ i) newVertices.push_back((* bit)->Vertices[it->Indices[i]]); } for (uint i = 0; i < newVertices.size() / 3; ++ i) { SMeshTriangle tri; tri.Indices[0] = i * 3; tri.Indices[1] = i * 3 + 1; tri.Indices[2] = i * 3 + 2; newTriangles.push_back(tri); } (* bit)->Vertices = newVertices; (* bit)->Triangles = newTriangles; } } void CMesh::CalculateNormalsPerFace() { for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) { for (std::vector<SMeshTriangle>::iterator it = (* bit)->Triangles.begin(); it != (* bit)->Triangles.end(); ++ it) { it->Normal = ((* bit)->Vertices[it->Indices[1]].Position - (* bit)->Vertices[it->Indices[0]].Position). CrossProduct((* bit)->Vertices[it->Indices[2]].Position - (* bit)->Vertices[it->Indices[0]].Position); (* bit)->Vertices[it->Indices[0]].Normal = (* bit)->Vertices[it->Indices[1]].Normal = (* bit)->Vertices[it->Indices[2]].Normal = it->Normal; } } for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) { it->Normal.Normalize(); } } void CMesh::CalculateNormalsPerVertex(bool CombineNear, f32 const NearTolerance) { CalculateNormalsPerFace(); for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) it->Normal = SVector3f(); for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SMeshTriangle>::iterator it = (* bit)->Triangles.begin(); it != (* bit)->Triangles.end(); ++ it) for (int i = 0; i < 3; ++ i) (* bit)->Vertices[it->Indices[i]].Normal += it->Normal; if (CombineNear) for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (uint i = 0; i < (* bit)->Vertices.size(); ++ i) for (uint j = i + 1; j < (* bit)->Vertices.size(); ++ j) if ((* bit)->Vertices[i].Position.Equals((* bit)->Vertices[j].Position, NearTolerance)) (* bit)->Vertices[i].Normal = (* bit)->Vertices[j].Normal = (* bit)->Vertices[i].Normal + (* bit)->Vertices[j].Normal; for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) it->Normal.Normalize(); } void CMesh::CalculateTextureCoordinates(vec3f const & uVec, vec3f const & vVec, vec2f const & Scale) { SVector3f Min(std::numeric_limits<float>::max()), Max(-std::numeric_limits<float>::max()); { for (std::vector<sharedPtr<SMeshBuffer>>::const_iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::const_iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) { if (Min.X > it->Position.X) Min.X = it->Position.X; if (Min.Y > it->Position.Y) Min.Y = it->Position.Y; if (Min.Z > it->Position.Z) Min.Z = it->Position.Z; if (Max.X < it->Position.X) Max.X = it->Position.X; if (Max.Y < it->Position.Y) Max.Y = it->Position.Y; if (Max.Z < it->Position.Z) Max.Z = it->Position.Z; } } for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) for (std::vector<SVertex>::iterator it = (* bit)->Vertices.begin(); it != (* bit)->Vertices.end(); ++ it) { SVector3f const RelativePosition = (it->Position - Min) / (Max - Min); it->TextureCoordinates = vec2f((RelativePosition * uVec.GetNormalized()).Length(), (RelativePosition * vVec.GetNormalized()).Length()) * Scale; } } void CMesh::UpdateBuffers() { for (std::vector<sharedPtr<SMeshBuffer>>::iterator bit = MeshBuffers.begin(); bit != MeshBuffers.end(); ++ bit) (* bit)->UpdateBuffers(); } */ <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" #include "passes/pmgen/split_shiftx_pm.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN void create_split_shiftx(split_shiftx_pm &pm) { if (pm.st.shiftxB.empty()) return; log_assert(pm.st.shiftx); SigSpec A = pm.st.shiftx->getPort("\\A"); SigSpec Y = pm.st.shiftx->getPort("\\Y"); const int A_WIDTH = pm.st.shiftx->getParam("\\A_WIDTH").as_int(); const int Y_WIDTH = pm.st.shiftx->getParam("\\Y_WIDTH").as_int(); log_assert(Y_WIDTH > 1); std::vector<SigBit> bits; bits.resize(A_WIDTH / Y_WIDTH); for (int i = 0; i < Y_WIDTH; ++i) { for (int j = 0; j < A_WIDTH/Y_WIDTH; ++j) bits[j] = A[j*Y_WIDTH + i]; pm.module->addShiftx(NEW_ID, bits, pm.st.shiftxB, Y[i]); } pm.st.shiftx->unsetPort("\\Y"); pm.autoremove(pm.st.shiftx); pm.autoremove(pm.st.macc); } struct BitblastShiftxPass : public Pass { BitblastShiftxPass() : Pass("split_shiftx", "Split up multi-bit $shiftx cells") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" split_shiftx [selection]\n"); log("\n"); log("Split up $shiftx cells where Y_WIDTH > 1, with consideration for any $macc\n"); log("cells that may be driving their B inputs.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { log_header(design, "Executing SPLIT_SHIFTX pass.\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) split_shiftx_pm(module, module->selected_cells()).run(create_split_shiftx); } } BitblastShiftxPass; PRIVATE_NAMESPACE_END <commit_msg>Elaborate on help message<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" #include "passes/pmgen/split_shiftx_pm.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN void create_split_shiftx(split_shiftx_pm &pm) { if (pm.st.shiftxB.empty()) return; log_assert(pm.st.shiftx); SigSpec A = pm.st.shiftx->getPort("\\A"); SigSpec Y = pm.st.shiftx->getPort("\\Y"); const int A_WIDTH = pm.st.shiftx->getParam("\\A_WIDTH").as_int(); const int Y_WIDTH = pm.st.shiftx->getParam("\\Y_WIDTH").as_int(); log_assert(Y_WIDTH > 1); std::vector<SigBit> bits; bits.resize(A_WIDTH / Y_WIDTH); for (int i = 0; i < Y_WIDTH; ++i) { for (int j = 0; j < A_WIDTH/Y_WIDTH; ++j) bits[j] = A[j*Y_WIDTH + i]; pm.module->addShiftx(NEW_ID, bits, pm.st.shiftxB, Y[i]); } pm.st.shiftx->unsetPort("\\Y"); pm.autoremove(pm.st.shiftx); pm.autoremove(pm.st.macc); } struct BitblastShiftxPass : public Pass { BitblastShiftxPass() : Pass("split_shiftx", "Split up multi-bit $shiftx cells") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" split_shiftx [selection]\n"); log("\n"); log("Split up $shiftx cells where Y_WIDTH > 1, with consideration for any $macc\n"); log("cells -- configured as a constant multiplier equal to Y_WIDTH -- that may be\n"); log("driving their B inputs.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { log_header(design, "Executing SPLIT_SHIFTX pass.\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) split_shiftx_pm(module, module->selected_cells()).run(create_split_shiftx); } } BitblastShiftxPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/* Copyright (c) 2012 QtHttpServer Project. * 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 QtHttpServer 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 QTHTTPSERVER 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 "qhttpreply.h" #include "qhttpconnection_p.h" #include "qhttprequest.h" #include "qhttpserver_logging.h" #include <QtNetwork/QNetworkCookie> #include <zlib.h> class QHttpReply::Private : public QObject { Q_OBJECT public: Private(QHttpConnection *c, QHttpReply *parent); public slots: void writeHeaders(); void writeBody(); private: QHttpReply *q; static QHash<int, QByteArray> statusCodes; public: QHttpConnection *connection; int status; QHash<QByteArray, QByteArray> rawHeaders; QList<QNetworkCookie> cookies; QByteArray data; }; QHash<int, QByteArray> QHttpReply::Private::statusCodes; QHttpReply::Private::Private(QHttpConnection *c, QHttpReply *parent) : QObject(parent) , q(parent) , connection(c) , status(200) { if (statusCodes.isEmpty()) { statusCodes.insert(100, "Continue"); statusCodes.insert(101, "Switching Protocols"); statusCodes.insert(200, "OK"); statusCodes.insert(201, "Created"); statusCodes.insert(202, "Accepted"); statusCodes.insert(203, "Non-Authoritative Information"); statusCodes.insert(204, "No Content"); statusCodes.insert(205, "Reset Content"); statusCodes.insert(206, "Partial Content"); statusCodes.insert(300, "Multiple Choices"); statusCodes.insert(301, "Moved Permanently"); statusCodes.insert(302, "Found"); statusCodes.insert(303, "See Other"); statusCodes.insert(304, "Not Modified"); statusCodes.insert(305, "Use Proxy"); statusCodes.insert(307, "Temporary Redirect"); statusCodes.insert(400, "Bad Request"); statusCodes.insert(401, "Unauthorized"); statusCodes.insert(402, "Payment Required"); statusCodes.insert(403, "Forbidden"); statusCodes.insert(404, "Not Found"); statusCodes.insert(405, "Method Not Allowed"); statusCodes.insert(406, "Not Acceptable"); statusCodes.insert(407, "Proxy Authentication Required"); statusCodes.insert(408, "Request Time-out"); statusCodes.insert(409, "Conflict"); statusCodes.insert(410, "Gone"); statusCodes.insert(411, "Length Required"); statusCodes.insert(412, "Precondition Failed"); statusCodes.insert(413, "Request Entity Too Large"); statusCodes.insert(414, "Request-URI Too Large"); statusCodes.insert(415, "Unsupported Media Type"); statusCodes.insert(416, "Requested range not satisfiable"); statusCodes.insert(417, "Expectation Failed"); statusCodes.insert(500, "Internal Server Error"); statusCodes.insert(501, "Not Implemented"); statusCodes.insert(502, "Bad Gateway"); statusCodes.insert(503, "Service Unavailable"); statusCodes.insert(504, "Gateway Time-out"); statusCodes.insert(505, "HTTP Version not supported"); } q->setBuffer(&data); q->open(QIODevice::WriteOnly); } void QHttpReply::Private::writeHeaders() { connection->write("HTTP/1.1 "); connection->write(QByteArray::number(status)); connection->write(" "); connection->write(statusCodes.value(status)); connection->write("\r\n"); const QHttpRequest *request = connection->requestFor(q); if (request && request->hasRawHeader("Accept-Encoding") && !rawHeaders.contains("Content-Encoding")) { QList<QByteArray> acceptEncodings = request->rawHeader("Accept-Encoding").split(','); if (acceptEncodings.contains("deflate")) { z_stream z; z.zalloc = NULL; z.zfree = NULL; z.opaque = NULL; if (deflateInit(&z, Z_DEFAULT_COMPRESSION) == Z_OK) { QByteArray newData; unsigned char buf[1024]; z.avail_in = data.size(); z.next_in = reinterpret_cast<Bytef*>(data.data()); z.avail_out = 1024; z.next_out = buf; int ret = Z_OK; while (ret == Z_OK) { ret = deflate(&z, Z_FINISH); if (ret == Z_STREAM_END) { newData.append((const char*)buf, 1024 - z.avail_out); data = newData; rawHeaders["Content-Encoding"] = "deflate"; rawHeaders["Content-Length"] = QString::number(data.length()).toUtf8(); break; } else if (ret != Z_OK) { qhsWarning() << "deflate failed:" << ret << z.msg; } if (z.avail_out == 0) { newData.append((const char*)buf, 1024); z.avail_out = 1024; z.next_out = buf; } } deflateEnd(&z); } } } if (!rawHeaders.contains("Content-Length")) { rawHeaders.insert("Content-Length", QString::number(data.length()).toUtf8()); } foreach (const QByteArray &rawHeader, rawHeaders.keys()) { connection->write(rawHeader); connection->write(": "); QByteArray value = rawHeaders.value(rawHeader); connection->write(value.replace('\r', "%0D").replace('\n', "%0A")); connection->write("\r\n"); } foreach (const QNetworkCookie &cookie, cookies) { connection->write("Set-Cookie: "); QByteArray value = cookie.toRawForm(); connection->write(value.replace('\r', "%0D").replace('\n', "%0A")); connection->write(";\r\n"); } connection->write("\r\n"); } void QHttpReply::Private::writeBody() { connection->write(data); q->deleteLater(); } QHttpReply::QHttpReply(QHttpConnection *parent) : QBuffer(parent) , d(new Private(parent, this)) { } QHttpReply::~QHttpReply() { delete d; } int QHttpReply::status() const { return d->status; } void QHttpReply::setStatus(int status) { if (d->status == status) return; d->status = status; emit statusChanged(status); } bool QHttpReply::hasRawHeader(const QByteArray &headerName) const { return d->rawHeaders.contains(headerName); } //QVariant QHttpReply::header(KnownHeaders header) const //{ // return QVariant(); //} QByteArray QHttpReply::rawHeader(const QByteArray &headerName) const { return d->rawHeaders.value(headerName); } void QHttpReply::setRawHeader(const QByteArray &headerName, const QByteArray &value) { d->rawHeaders.insert(headerName, value); } QList<QByteArray> QHttpReply::rawHeaderList() const { return d->rawHeaders.keys(); } const QList<QNetworkCookie> &QHttpReply::cookies() const { return d->cookies; } void QHttpReply::setCookies(const QList<QNetworkCookie> &cookies) { if (d->cookies == cookies) return; d->cookies = cookies; } void QHttpReply::close() { QBuffer::close(); // QMetaObject::invokeMethod(d, "close", Qt::QueuedConnection); d->writeHeaders(); d->writeBody(); } #include "qhttpreply.moc" <commit_msg>fix decoding Accept-Encoding header<commit_after>/* Copyright (c) 2012 QtHttpServer Project. * 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 QtHttpServer 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 QTHTTPSERVER 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 "qhttpreply.h" #include "qhttpconnection_p.h" #include "qhttprequest.h" #include "qhttpserver_logging.h" #include <QtNetwork/QNetworkCookie> #include <zlib.h> class QHttpReply::Private : public QObject { Q_OBJECT public: Private(QHttpConnection *c, QHttpReply *parent); public slots: void writeHeaders(); void writeBody(); private: QHttpReply *q; static QHash<int, QByteArray> statusCodes; public: QHttpConnection *connection; int status; QHash<QByteArray, QByteArray> rawHeaders; QList<QNetworkCookie> cookies; QByteArray data; }; QHash<int, QByteArray> QHttpReply::Private::statusCodes; QHttpReply::Private::Private(QHttpConnection *c, QHttpReply *parent) : QObject(parent) , q(parent) , connection(c) , status(200) { if (statusCodes.isEmpty()) { statusCodes.insert(100, "Continue"); statusCodes.insert(101, "Switching Protocols"); statusCodes.insert(200, "OK"); statusCodes.insert(201, "Created"); statusCodes.insert(202, "Accepted"); statusCodes.insert(203, "Non-Authoritative Information"); statusCodes.insert(204, "No Content"); statusCodes.insert(205, "Reset Content"); statusCodes.insert(206, "Partial Content"); statusCodes.insert(300, "Multiple Choices"); statusCodes.insert(301, "Moved Permanently"); statusCodes.insert(302, "Found"); statusCodes.insert(303, "See Other"); statusCodes.insert(304, "Not Modified"); statusCodes.insert(305, "Use Proxy"); statusCodes.insert(307, "Temporary Redirect"); statusCodes.insert(400, "Bad Request"); statusCodes.insert(401, "Unauthorized"); statusCodes.insert(402, "Payment Required"); statusCodes.insert(403, "Forbidden"); statusCodes.insert(404, "Not Found"); statusCodes.insert(405, "Method Not Allowed"); statusCodes.insert(406, "Not Acceptable"); statusCodes.insert(407, "Proxy Authentication Required"); statusCodes.insert(408, "Request Time-out"); statusCodes.insert(409, "Conflict"); statusCodes.insert(410, "Gone"); statusCodes.insert(411, "Length Required"); statusCodes.insert(412, "Precondition Failed"); statusCodes.insert(413, "Request Entity Too Large"); statusCodes.insert(414, "Request-URI Too Large"); statusCodes.insert(415, "Unsupported Media Type"); statusCodes.insert(416, "Requested range not satisfiable"); statusCodes.insert(417, "Expectation Failed"); statusCodes.insert(500, "Internal Server Error"); statusCodes.insert(501, "Not Implemented"); statusCodes.insert(502, "Bad Gateway"); statusCodes.insert(503, "Service Unavailable"); statusCodes.insert(504, "Gateway Time-out"); statusCodes.insert(505, "HTTP Version not supported"); } q->setBuffer(&data); q->open(QIODevice::WriteOnly); } void QHttpReply::Private::writeHeaders() { connection->write("HTTP/1.1 "); connection->write(QByteArray::number(status)); connection->write(" "); connection->write(statusCodes.value(status)); connection->write("\r\n"); const QHttpRequest *request = connection->requestFor(q); if (request && request->hasRawHeader("Accept-Encoding") && !rawHeaders.contains("Content-Encoding")) { QList<QByteArray> acceptEncodings; foreach (const QByteArray &acceptEncoding, request->rawHeader("Accept-Encoding").split(',')) { acceptEncodings.append(acceptEncoding.trimmed()); } if (acceptEncodings.contains("deflate")) { z_stream z; z.zalloc = NULL; z.zfree = NULL; z.opaque = NULL; if (deflateInit(&z, Z_DEFAULT_COMPRESSION) == Z_OK) { QByteArray newData; unsigned char buf[1024]; z.avail_in = data.size(); z.next_in = reinterpret_cast<Bytef*>(data.data()); z.avail_out = 1024; z.next_out = buf; int ret = Z_OK; while (ret == Z_OK) { ret = deflate(&z, Z_FINISH); if (ret == Z_STREAM_END) { newData.append((const char*)buf, 1024 - z.avail_out); data = newData; rawHeaders["Content-Encoding"] = "deflate"; rawHeaders["Content-Length"] = QString::number(data.length()).toUtf8(); break; } else if (ret != Z_OK) { qhsWarning() << "deflate failed:" << ret << z.msg; } if (z.avail_out == 0) { newData.append((const char*)buf, 1024); z.avail_out = 1024; z.next_out = buf; } } deflateEnd(&z); } } } if (!rawHeaders.contains("Content-Length")) { rawHeaders.insert("Content-Length", QString::number(data.length()).toUtf8()); } foreach (const QByteArray &rawHeader, rawHeaders.keys()) { connection->write(rawHeader); connection->write(": "); QByteArray value = rawHeaders.value(rawHeader); connection->write(value.replace('\r', "%0D").replace('\n', "%0A")); connection->write("\r\n"); } foreach (const QNetworkCookie &cookie, cookies) { connection->write("Set-Cookie: "); QByteArray value = cookie.toRawForm(); connection->write(value.replace('\r', "%0D").replace('\n', "%0A")); connection->write(";\r\n"); } connection->write("\r\n"); } void QHttpReply::Private::writeBody() { connection->write(data); q->deleteLater(); } QHttpReply::QHttpReply(QHttpConnection *parent) : QBuffer(parent) , d(new Private(parent, this)) { } QHttpReply::~QHttpReply() { delete d; } int QHttpReply::status() const { return d->status; } void QHttpReply::setStatus(int status) { if (d->status == status) return; d->status = status; emit statusChanged(status); } bool QHttpReply::hasRawHeader(const QByteArray &headerName) const { return d->rawHeaders.contains(headerName); } //QVariant QHttpReply::header(KnownHeaders header) const //{ // return QVariant(); //} QByteArray QHttpReply::rawHeader(const QByteArray &headerName) const { return d->rawHeaders.value(headerName); } void QHttpReply::setRawHeader(const QByteArray &headerName, const QByteArray &value) { d->rawHeaders.insert(headerName, value); } QList<QByteArray> QHttpReply::rawHeaderList() const { return d->rawHeaders.keys(); } const QList<QNetworkCookie> &QHttpReply::cookies() const { return d->cookies; } void QHttpReply::setCookies(const QList<QNetworkCookie> &cookies) { if (d->cookies == cookies) return; d->cookies = cookies; } void QHttpReply::close() { QBuffer::close(); // QMetaObject::invokeMethod(d, "close", Qt::QueuedConnection); d->writeHeaders(); d->writeBody(); } #include "qhttpreply.moc" <|endoftext|>
<commit_before>#include "fontStyle.h" MapTile* FontStyle::processedTile = nullptr; FontStyle::FontStyle(const std::string& _fontName, std::string _name, float _fontSize, bool _sdf, GLenum _drawMode) : Style(_name, _drawMode), m_fontName(_fontName), m_fontSize(_fontSize), m_sdf(_sdf) { constructVertexLayout(); constructShaderProgram(); } FontStyle::~FontStyle() { } void FontStyle::constructVertexLayout() { m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({ {"a_position", 2, GL_FLOAT, false, 0}, {"a_texCoord", 2, GL_FLOAT, false, 0}, {"a_fsid", 1, GL_FLOAT, false, 0}, })); } void FontStyle::constructShaderProgram() { std::string frag = m_sdf ? "sdf.fs" : "text.fs"; std::string vertShaderSrcStr = stringFromResource("text.vs"); std::string fragShaderSrcStr = stringFromResource(frag.c_str()); m_shaderProgram = std::make_shared<ShaderProgram>(); m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr); } void FontStyle::buildPoint(Point& _point, std::string& _layer, Properties& _props, VboMesh& _mesh) const { std::vector<float> vertData; int nVerts = 0; auto labelContainer = LabelContainer::GetInstance(); auto ftContext = labelContainer->getFontContext(); auto textBuffer = ftContext->getCurrentBuffer(); if (!textBuffer) { return; } ftContext->setFont(m_fontName, m_fontSize * m_pixelScale); if (m_sdf) { float blurSpread = 2.5; ftContext->setSignedDistanceField(blurSpread); } if (_layer == "pois") { for (auto prop : _props.stringProps) { if (prop.first == "name") { labelContainer->addLabel(FontStyle::processedTile->getID(), m_name, { glm::vec2(_point), glm::vec2(_point) }, prop.second); } } } ftContext->clearState(); if (textBuffer->getVertices(&vertData, &nVerts)) { auto& mesh = static_cast<RawVboMesh&>(_mesh); mesh.addVertices((GLbyte*)vertData.data(), nVerts); } } void FontStyle::buildLine(Line& _line, std::string& _layer, Properties& _props, VboMesh& _mesh) const { std::vector<float> vertData; int nVerts = 0; auto labelContainer = LabelContainer::GetInstance(); auto ftContext = labelContainer->getFontContext(); auto textBuffer = ftContext->getCurrentBuffer(); if (!textBuffer) { return; } ftContext->setFont(m_fontName, m_fontSize * m_pixelScale); if (m_sdf) { float blurSpread = 2.5; ftContext->setSignedDistanceField(blurSpread); } if (_layer == "roads") { for (auto prop : _props.stringProps) { if (prop.first.compare("name") == 0) { for (int i = 0; i < _line.size() - 1; ++i) { glm::vec2 p1 = glm::vec2(_line[i]); glm::vec2 p2 = glm::vec2(_line[i + 1]); labelContainer->addLabel(FontStyle::processedTile->getID(), m_name, { p1, p2 }, prop.second); } } } } ftContext->clearState(); if (textBuffer->getVertices(&vertData, &nVerts)) { auto& mesh = static_cast<RawVboMesh&>(_mesh); mesh.addVertices((GLbyte*)vertData.data(), nVerts); } } void FontStyle::buildPolygon(Polygon& _polygon, std::string& _layer, Properties& _props, VboMesh& _mesh) const { glm::vec3 centroid; int n = 0; for (auto& l : _polygon) { for (auto& p : l) { centroid.x += p.x; centroid.y += p.y; n++; } } centroid /= n; std::vector<float> vertData; int nVerts = 0; auto labelContainer = LabelContainer::GetInstance(); auto ftContext = labelContainer->getFontContext(); auto textBuffer = ftContext->getCurrentBuffer(); if (!textBuffer) { return; } ftContext->setFont(m_fontName, m_fontSize * m_pixelScale * 1.5); if (m_sdf) { float blurSpread = 2.5; ftContext->setSignedDistanceField(blurSpread); } for (auto prop : _props.stringProps) { if (prop.first == "name") { labelContainer->addLabel(FontStyle::processedTile->getID(), m_name, { glm::vec2(centroid), glm::vec2(centroid) }, prop.second); } } ftContext->clearState(); if (textBuffer->getVertices(&vertData, &nVerts)) { auto& mesh = static_cast<RawVboMesh&>(_mesh); mesh.addVertices((GLbyte*)vertData.data(), nVerts); } } void FontStyle::prepareDataProcessing(MapTile& _tile) const { auto ftContext = LabelContainer::GetInstance()->getFontContext(); auto buffer = ftContext->genTextBuffer(); _tile.setTextBuffer(*this, buffer); ftContext->lock(); ftContext->useBuffer(buffer); buffer->init(); FontStyle::processedTile = &_tile; } void FontStyle::finishDataProcessing(MapTile& _tile) const { auto ftContext = LabelContainer::GetInstance()->getFontContext(); FontStyle::processedTile = nullptr; ftContext->useBuffer(nullptr); ftContext->unlock(); } void FontStyle::setupTile(const std::shared_ptr<MapTile>& _tile) { auto buffer = _tile->getTextBuffer(*this); if (buffer) { auto texture = buffer->getTextureTransform(); if (texture) { texture->update(); texture->bind(); // transform texture m_shaderProgram->setUniformi("u_transforms", texture->getTextureSlot()); // resolution of the transform texture m_shaderProgram->setUniformf("u_tresolution", texture->getWidth(), texture->getHeight()); } } } void FontStyle::setupFrame(const std::shared_ptr<View>& _view, const std::shared_ptr<Scene>& _scene) { auto ftContext = LabelContainer::GetInstance()->getFontContext(); const auto& atlas = ftContext->getAtlas(); float projectionMatrix[16] = {0}; ftContext->setScreenSize(_view->getWidth(), _view->getHeight()); ftContext->getProjection(projectionMatrix); atlas->update(); atlas->bind(); m_shaderProgram->setUniformi("u_tex", atlas->getTextureSlot()); m_shaderProgram->setUniformf("u_resolution", _view->getWidth(), _view->getHeight()); m_shaderProgram->setUniformf("u_color", 1.0, 1.0, 1.0); m_shaderProgram->setUniformMatrix4f("u_proj", projectionMatrix); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); } void FontStyle::teardown() { glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); } <commit_msg>reduce number of labels<commit_after>#include "fontStyle.h" MapTile* FontStyle::processedTile = nullptr; FontStyle::FontStyle(const std::string& _fontName, std::string _name, float _fontSize, bool _sdf, GLenum _drawMode) : Style(_name, _drawMode), m_fontName(_fontName), m_fontSize(_fontSize), m_sdf(_sdf) { constructVertexLayout(); constructShaderProgram(); } FontStyle::~FontStyle() { } void FontStyle::constructVertexLayout() { m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({ {"a_position", 2, GL_FLOAT, false, 0}, {"a_texCoord", 2, GL_FLOAT, false, 0}, {"a_fsid", 1, GL_FLOAT, false, 0}, })); } void FontStyle::constructShaderProgram() { std::string frag = m_sdf ? "sdf.fs" : "text.fs"; std::string vertShaderSrcStr = stringFromResource("text.vs"); std::string fragShaderSrcStr = stringFromResource(frag.c_str()); m_shaderProgram = std::make_shared<ShaderProgram>(); m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr); } void FontStyle::buildPoint(Point& _point, std::string& _layer, Properties& _props, VboMesh& _mesh) const { std::vector<float> vertData; int nVerts = 0; auto labelContainer = LabelContainer::GetInstance(); auto ftContext = labelContainer->getFontContext(); auto textBuffer = ftContext->getCurrentBuffer(); if (!textBuffer) { return; } ftContext->setFont(m_fontName, m_fontSize * m_pixelScale); if (m_sdf) { float blurSpread = 2.5; ftContext->setSignedDistanceField(blurSpread); } if (_layer == "pois") { for (auto prop : _props.stringProps) { if (prop.first == "name") { labelContainer->addLabel(FontStyle::processedTile->getID(), m_name, { glm::vec2(_point), glm::vec2(_point) }, prop.second); } } } ftContext->clearState(); if (textBuffer->getVertices(&vertData, &nVerts)) { auto& mesh = static_cast<RawVboMesh&>(_mesh); mesh.addVertices((GLbyte*)vertData.data(), nVerts); } } void FontStyle::buildLine(Line& _line, std::string& _layer, Properties& _props, VboMesh& _mesh) const { std::vector<float> vertData; int nVerts = 0; auto labelContainer = LabelContainer::GetInstance(); auto ftContext = labelContainer->getFontContext(); auto textBuffer = ftContext->getCurrentBuffer(); if (!textBuffer) { return; } ftContext->setFont(m_fontName, m_fontSize * m_pixelScale); if (m_sdf) { float blurSpread = 2.5; ftContext->setSignedDistanceField(blurSpread); } int lineLength = _line.size(); int skipOffset = floor(lineLength / 2); float minLength = 0.15; // default, probably need some more thoughts if (_layer == "roads") { for (auto prop : _props.stringProps) { if (prop.first.compare("name") == 0) { for (int i = 0; i < _line.size() - 1; i += skipOffset) { glm::vec2 p1 = glm::vec2(_line[i]); glm::vec2 p2 = glm::vec2(_line[i + 1]); glm::vec2 p1p2 = p2 - p1; float length = glm::length(p1p2); if (length < minLength) { continue; } labelContainer->addLabel(FontStyle::processedTile->getID(), m_name, { p1, p2 }, prop.second); } } } } ftContext->clearState(); if (textBuffer->getVertices(&vertData, &nVerts)) { auto& mesh = static_cast<RawVboMesh&>(_mesh); mesh.addVertices((GLbyte*)vertData.data(), nVerts); } } void FontStyle::buildPolygon(Polygon& _polygon, std::string& _layer, Properties& _props, VboMesh& _mesh) const { glm::vec3 centroid; int n = 0; for (auto& l : _polygon) { for (auto& p : l) { centroid.x += p.x; centroid.y += p.y; n++; } } centroid /= n; std::vector<float> vertData; int nVerts = 0; auto labelContainer = LabelContainer::GetInstance(); auto ftContext = labelContainer->getFontContext(); auto textBuffer = ftContext->getCurrentBuffer(); if (!textBuffer) { return; } ftContext->setFont(m_fontName, m_fontSize * m_pixelScale * 1.5); if (m_sdf) { float blurSpread = 2.5; ftContext->setSignedDistanceField(blurSpread); } for (auto prop : _props.stringProps) { if (prop.first == "name") { labelContainer->addLabel(FontStyle::processedTile->getID(), m_name, { glm::vec2(centroid), glm::vec2(centroid) }, prop.second); } } ftContext->clearState(); if (textBuffer->getVertices(&vertData, &nVerts)) { auto& mesh = static_cast<RawVboMesh&>(_mesh); mesh.addVertices((GLbyte*)vertData.data(), nVerts); } } void FontStyle::prepareDataProcessing(MapTile& _tile) const { auto ftContext = LabelContainer::GetInstance()->getFontContext(); auto buffer = ftContext->genTextBuffer(); _tile.setTextBuffer(*this, buffer); ftContext->lock(); ftContext->useBuffer(buffer); buffer->init(); FontStyle::processedTile = &_tile; } void FontStyle::finishDataProcessing(MapTile& _tile) const { auto ftContext = LabelContainer::GetInstance()->getFontContext(); FontStyle::processedTile = nullptr; ftContext->useBuffer(nullptr); ftContext->unlock(); } void FontStyle::setupTile(const std::shared_ptr<MapTile>& _tile) { auto buffer = _tile->getTextBuffer(*this); if (buffer) { auto texture = buffer->getTextureTransform(); if (texture) { texture->update(); texture->bind(); // transform texture m_shaderProgram->setUniformi("u_transforms", texture->getTextureSlot()); // resolution of the transform texture m_shaderProgram->setUniformf("u_tresolution", texture->getWidth(), texture->getHeight()); } } } void FontStyle::setupFrame(const std::shared_ptr<View>& _view, const std::shared_ptr<Scene>& _scene) { auto ftContext = LabelContainer::GetInstance()->getFontContext(); const auto& atlas = ftContext->getAtlas(); float projectionMatrix[16] = {0}; ftContext->setScreenSize(_view->getWidth(), _view->getHeight()); ftContext->getProjection(projectionMatrix); atlas->update(); atlas->bind(); m_shaderProgram->setUniformi("u_tex", atlas->getTextureSlot()); m_shaderProgram->setUniformf("u_resolution", _view->getWidth(), _view->getHeight()); m_shaderProgram->setUniformf("u_color", 1.0, 1.0, 1.0); m_shaderProgram->setUniformMatrix4f("u_proj", projectionMatrix); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); } void FontStyle::teardown() { glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); } <|endoftext|>
<commit_before>/*****************************************************************************/ /** * @file main.cpp * @author Naohisa Sakamoto * @brief Example program for kvs::KMeansClustering class. */ /*****************************************************************************/ #include <kvs/glut/Application> #include <kvs/glut/Screen> #include <kvs/ValueTable> #include <kvs/ValueArray> #include <kvs/MersenneTwister> #include <kvs/KMeansClustering> #include <kvs/TableObject> #include <kvs/ScatterPlotRenderer> #include <kvs/Axis2D> /*===========================================================================*/ /** * @brief Creates value table. * @param nrows [in] number of rows */ /*===========================================================================*/ kvs::ValueTable<kvs::Real32> CreateValueTable( const size_t nrows ) { kvs::Real32 xmin = 2.0f; kvs::Real32 xmax = 6.0f; kvs::Real32 ymin = 2.0f; kvs::Real32 ymax = 6.0f; kvs::ValueArray<kvs::Real32> x( nrows ); kvs::ValueArray<kvs::Real32> y( nrows ); kvs::MersenneTwister R; for ( size_t i = 0; i < nrows / 4; i++ ) { x[i] = -( R() * ( xmax - xmin ) + xmin ); y[i] = +( R() * ( ymax - ymin ) + ymin ); } for ( size_t i = nrows / 4; i < nrows / 4 * 2; i++ ) { x[i] = -( R() * ( xmax - xmin ) + xmin ); y[i] = -( R() * ( ymax - ymin ) + ymin ); } for ( size_t i = nrows / 4 * 2; i < nrows / 4 * 3; i++ ) { x[i] = +( R() * ( xmax - xmin ) + xmin ); y[i] = -( R() * ( ymax - ymin ) + ymin ); } for ( size_t i = nrows / 4 * 3; i < nrows; i++ ) { x[i] = +( R() * ( xmax - xmin ) + xmin ); y[i] = +( R() * ( ymax - ymin ) + ymin ); } kvs::ValueTable<kvs::Real32> table; table.pushBackColumn( x ); table.pushBackColumn( y ); return table; } /*===========================================================================*/ /** * @brief Main function. * @param argc [i] argument count * @param argv [i] argument values */ /*===========================================================================*/ int main( int argc, char** argv ) { kvs::glut::Application app( argc, argv ); kvs::glut::Screen screen( &app ); screen.setTitle( "k-means clsutering" ); screen.setSize( 600, 600 ); screen.show(); const size_t nrows = 1000; auto data = CreateValueTable( nrows ); auto* table = new kvs::TableObject(); table->setTable( data ); table->setMinValue( 0, -7 ); table->setMaxValue( 0, 7 ); table->setMinValue( 1, -7 ); table->setMaxValue( 1, 7 ); // Original { auto* renderer = new kvs::ScatterPlotRenderer(); renderer->setPointSize( 4.0 ); renderer->setEdgeColor( kvs::RGBColor::White() ); auto* axis = new kvs::Axis2D(); axis->setTitle( "Original" ); axis->xAxis().setNumberOfTicks( 3 ); axis->yAxis().setNumberOfTicks( 3 ); const int right_margin = screen.width() / 2 + axis->rightMargin(); const int bottom_margin = screen.height() / 2 + axis->bottomMargin(); renderer->setRightMargin( right_margin ); renderer->setBottomMargin( bottom_margin ); axis->setRightMargin( right_margin ); axis->setBottomMargin( bottom_margin ); screen.registerObject( table, axis ); screen.registerObject( table, renderer ); } // Random Seeding. { const int nclusters = 4; auto* kmeans = new kvs::KMeansClustering(); kmeans->setClusteringMethod( kvs::KMeansClustering::FastKMeans ); kmeans->setSeedingMethod( kvs::KMeansClustering::RandomSeeding ); kmeans->setNumberOfClusters( nclusters ); auto* object = kmeans->exec( table ); object->setMinValue( 0, -7 ); object->setMaxValue( 0, 7 ); object->setMinValue( 1, -7 ); object->setMaxValue( 1, 7 ); auto* renderer = new kvs::ScatterPlotRenderer(); renderer->setPointSize( 4.0 ); auto* axis = new kvs::Axis2D(); axis->setTitle( "Random Seeding" ); axis->xAxis().setNumberOfTicks( 3 ); axis->yAxis().setNumberOfTicks( 3 ); const int left_margin = screen.width() / 2 + axis->leftMargin(); const int bottom_margin = screen.height() / 2 + axis->bottomMargin(); renderer->setLeftMargin( left_margin ); renderer->setBottomMargin( bottom_margin ); axis->setLeftMargin( left_margin ); axis->setBottomMargin( bottom_margin ); screen.registerObject( object, axis ); screen.registerObject( object, renderer ); } // Smart Seeding. { const int nclusters = 4; auto* kmeans = new kvs::KMeansClustering(); kmeans->setClusteringMethod( kvs::KMeansClustering::FastKMeans ); kmeans->setSeedingMethod( kvs::KMeansClustering::SmartSeeding ); kmeans->setNumberOfClusters( nclusters ); auto* object = kmeans->exec( table ); object->setMinValue( 0, -7 ); object->setMaxValue( 0, 7 ); object->setMinValue( 1, -7 ); object->setMaxValue( 1, 7 ); auto* renderer = new kvs::ScatterPlotRenderer(); renderer->setPointSize( 4.0 ); auto* axis = new kvs::Axis2D(); axis->setTitle( "Smart Seeding" ); axis->xAxis().setNumberOfTicks( 3 ); axis->yAxis().setNumberOfTicks( 3 ); const int right_margin = screen.width() / 2 + axis->rightMargin(); const int top_margin = screen.height() / 2 + axis->topMargin(); renderer->setRightMargin( right_margin ); renderer->setTopMargin( top_margin ); axis->setRightMargin( right_margin ); axis->setTopMargin( top_margin ); screen.registerObject( object, axis ); screen.registerObject( object, renderer ); } // Auto-estimation { const int max_nclusters = 10; auto* kmeans = new kvs::KMeansClustering(); kmeans->setClusteringMethod( kvs::KMeansClustering::AdaptiveKMeans ); kmeans->setNumberOfClusters( max_nclusters ); auto* object = kmeans->exec( table ); object->setMinValue( 0, -7 ); object->setMaxValue( 0, 7 ); object->setMinValue( 1, -7 ); object->setMaxValue( 1, 7 ); auto* renderer = new kvs::ScatterPlotRenderer(); renderer->setPointSize( 4.0 ); auto* axis = new kvs::Axis2D(); axis->setTitle( "Auto-estimation" ); axis->xAxis().setNumberOfTicks( 3 ); axis->yAxis().setNumberOfTicks( 3 ); const int left_margin = screen.width() / 2 + axis->leftMargin(); const int top_margin = screen.height() / 2 + axis->topMargin(); renderer->setLeftMargin( left_margin ); renderer->setTopMargin( top_margin ); axis->setLeftMargin( left_margin ); axis->setTopMargin( top_margin ); screen.registerObject( object, axis ); screen.registerObject( object, renderer ); } return app.run(); } <commit_msg>Update main.cpp<commit_after>/*****************************************************************************/ /** * @file main.cpp * @author Naohisa Sakamoto * @brief Example program for kvs::KMeansClustering class. */ /*****************************************************************************/ #include <kvs/glut/Application> #include <kvs/glut/Screen> #include <kvs/ValueTable> #include <kvs/ValueArray> #include <kvs/MersenneTwister> #include <kvs/KMeansClustering> #include <kvs/TableObject> #include <kvs/ScatterPlotRenderer> #include <kvs/Axis2D> /*===========================================================================*/ /** * @brief Creates value table. * @param nrows [in] number of rows */ /*===========================================================================*/ kvs::ValueTable<kvs::Real32> CreateValueTable( const size_t nrows ) { kvs::Real32 xmin = 2.0f; kvs::Real32 xmax = 6.0f; kvs::Real32 ymin = 2.0f; kvs::Real32 ymax = 6.0f; kvs::ValueArray<kvs::Real32> x( nrows ); kvs::ValueArray<kvs::Real32> y( nrows ); kvs::MersenneTwister R; for ( size_t i = 0; i < nrows / 4; i++ ) { x[i] = -( R() * ( xmax - xmin ) + xmin ); y[i] = +( R() * ( ymax - ymin ) + ymin ); } for ( size_t i = nrows / 4; i < nrows / 4 * 2; i++ ) { x[i] = -( R() * ( xmax - xmin ) + xmin ); y[i] = -( R() * ( ymax - ymin ) + ymin ); } for ( size_t i = nrows / 4 * 2; i < nrows / 4 * 3; i++ ) { x[i] = +( R() * ( xmax - xmin ) + xmin ); y[i] = -( R() * ( ymax - ymin ) + ymin ); } for ( size_t i = nrows / 4 * 3; i < nrows; i++ ) { x[i] = +( R() * ( xmax - xmin ) + xmin ); y[i] = +( R() * ( ymax - ymin ) + ymin ); } kvs::ValueTable<kvs::Real32> table; table.pushBackColumn( x ); table.pushBackColumn( y ); return table; } /*===========================================================================*/ /** * @brief Main function. * @param argc [i] argument count * @param argv [i] argument values */ /*===========================================================================*/ int main( int argc, char** argv ) { kvs::glut::Application app( argc, argv ); kvs::glut::Screen screen( &app ); screen.setTitle( "k-means clsutering" ); screen.setSize( 600, 600 ); screen.show(); const size_t nrows = 1000; auto data = CreateValueTable( nrows ); auto* table = new kvs::TableObject(); table->setTable( data ); table->setMinValue( 0, -7 ); table->setMaxValue( 0, 7 ); table->setMinValue( 1, -7 ); table->setMaxValue( 1, 7 ); kvs::ColorMap cmap( 4 ); cmap.addPoint( 0, kvs::UIColor::Red() ); cmap.addPoint( 1, kvs::UIColor::Green() ); cmap.addPoint( 2, kvs::UIColor::Yellow() ); cmap.addPoint( 3, kvs::UIColor::Indigo() ); cmap.create(); // Original { auto* renderer = new kvs::ScatterPlotRenderer(); renderer->setPointSize( 4.0 ); renderer->setPointColor( kvs::UIColor::Gray() ); auto* axis = new kvs::Axis2D(); axis->setTitle( "Original" ); axis->xAxis().setNumberOfTicks( 3 ); axis->yAxis().setNumberOfTicks( 3 ); const int right_margin = screen.width() / 2 + axis->rightMargin(); const int bottom_margin = screen.height() / 2 + axis->bottomMargin(); renderer->setRightMargin( right_margin ); renderer->setBottomMargin( bottom_margin ); axis->setRightMargin( right_margin ); axis->setBottomMargin( bottom_margin ); screen.registerObject( table, axis ); screen.registerObject( table, renderer ); } // Random Seeding. { const int nclusters = 4; auto* kmeans = new kvs::KMeansClustering(); kmeans->setClusteringMethod( kvs::KMeansClustering::FastKMeans ); kmeans->setSeedingMethod( kvs::KMeansClustering::RandomSeeding ); kmeans->setNumberOfClusters( nclusters ); auto* object = kmeans->exec( table ); object->setMinValue( 0, -7 ); object->setMaxValue( 0, 7 ); object->setMinValue( 1, -7 ); object->setMaxValue( 1, 7 ); auto* renderer = new kvs::ScatterPlotRenderer(); renderer->setPointSize( 4.0 ); renderer->setColorMap( cmap ); auto* axis = new kvs::Axis2D(); axis->setTitle( "Random Seeding" ); axis->xAxis().setNumberOfTicks( 3 ); axis->yAxis().setNumberOfTicks( 3 ); const int left_margin = screen.width() / 2 + axis->leftMargin(); const int bottom_margin = screen.height() / 2 + axis->bottomMargin(); renderer->setLeftMargin( left_margin ); renderer->setBottomMargin( bottom_margin ); axis->setLeftMargin( left_margin ); axis->setBottomMargin( bottom_margin ); screen.registerObject( object, axis ); screen.registerObject( object, renderer ); } // Smart Seeding. { const int nclusters = 4; auto* kmeans = new kvs::KMeansClustering(); kmeans->setClusteringMethod( kvs::KMeansClustering::FastKMeans ); kmeans->setSeedingMethod( kvs::KMeansClustering::SmartSeeding ); kmeans->setNumberOfClusters( nclusters ); auto* object = kmeans->exec( table ); object->setMinValue( 0, -7 ); object->setMaxValue( 0, 7 ); object->setMinValue( 1, -7 ); object->setMaxValue( 1, 7 ); auto* renderer = new kvs::ScatterPlotRenderer(); renderer->setPointSize( 4.0 ); renderer->setColorMap( cmap ); auto* axis = new kvs::Axis2D(); axis->setTitle( "Smart Seeding" ); axis->xAxis().setNumberOfTicks( 3 ); axis->yAxis().setNumberOfTicks( 3 ); const int right_margin = screen.width() / 2 + axis->rightMargin(); const int top_margin = screen.height() / 2 + axis->topMargin(); renderer->setRightMargin( right_margin ); renderer->setTopMargin( top_margin ); axis->setRightMargin( right_margin ); axis->setTopMargin( top_margin ); screen.registerObject( object, axis ); screen.registerObject( object, renderer ); } // Auto-estimation { const int max_nclusters = 10; auto* kmeans = new kvs::KMeansClustering(); kmeans->setClusteringMethod( kvs::KMeansClustering::AdaptiveKMeans ); kmeans->setNumberOfClusters( max_nclusters ); auto* object = kmeans->exec( table ); object->setMinValue( 0, -7 ); object->setMaxValue( 0, 7 ); object->setMinValue( 1, -7 ); object->setMaxValue( 1, 7 ); auto* renderer = new kvs::ScatterPlotRenderer(); renderer->setPointSize( 4.0 ); renderer->setColorMap( cmap ); auto* axis = new kvs::Axis2D(); axis->setTitle( "Auto-estimation" ); axis->xAxis().setNumberOfTicks( 3 ); axis->yAxis().setNumberOfTicks( 3 ); const int left_margin = screen.width() / 2 + axis->leftMargin(); const int top_margin = screen.height() / 2 + axis->topMargin(); renderer->setLeftMargin( left_margin ); renderer->setTopMargin( top_margin ); axis->setLeftMargin( left_margin ); axis->setTopMargin( top_margin ); screen.registerObject( object, axis ); screen.registerObject( object, renderer ); } return app.run(); } <|endoftext|>
<commit_before>//============================================================================== // Single cell simulation view information solvers widget //============================================================================== #include "cellmlfileruntime.h" #include "singlecellsimulationviewinformationsolverswidget.h" //============================================================================== namespace OpenCOR { namespace SingleCellSimulationView { //============================================================================== SingleCellSimulationViewInformationSolversWidget::SingleCellSimulationViewInformationSolversWidget(QWidget *pParent) : PropertyEditorWidget(true, pParent), mNeedOdeSolver(true), mNeedDaeSolver(false), mNeedNlaSolver(false), mOdeSolversProperty(Core::Property()), mDaeSolversProperty(Core::Property()), mNlaSolversProperty(Core::Property()) { } //============================================================================== void SingleCellSimulationViewInformationSolversWidget::retranslateUi() { // Update our property names if (!mOdeSolversProperty.isEmpty()) { setNonEditablePropertyItem(mOdeSolversProperty.name, tr("ODE solver")); setNonEditablePropertyItem(mOdeSolversListProperty.name, tr("Name")); mOdeSolversListProperty.value->setEmptyListValue(tr("None available")); } if (!mDaeSolversProperty.isEmpty()) { setNonEditablePropertyItem(mDaeSolversProperty.name, tr("DAE solver")); setNonEditablePropertyItem(mDaeSolversListProperty.name, tr("Name")); mDaeSolversListProperty.value->setEmptyListValue(tr("None available")); } if (!mNlaSolversProperty.isEmpty()) { setNonEditablePropertyItem(mNlaSolversProperty.name, tr("NLA solver")); setNonEditablePropertyItem(mNlaSolversListProperty.name, tr("Name")); mNlaSolversListProperty.value->setEmptyListValue(tr("None available")); } // Default retranslation // Note: we must do it last since we set the empty list value of some // properties above... PropertyEditorWidget::retranslateUi(); } //============================================================================== void SingleCellSimulationViewInformationSolversWidget::addSolverProperties(const SolverInterfaces &pSolverInterfaces, const Solver::Type &pSolverType, Core::Property &pSolversProperty, Core::Property &pSolversListProperty) { // Make sure that we have at least one solver interface if (pSolverInterfaces.isEmpty()) { pSolversProperty = Core::Property(); pSolversListProperty = Core::Property(); return; } // Add our category property pSolversProperty = addCategoryProperty(); // Add our list property for the solvers pSolversListProperty = addListProperty(pSolversProperty); // Retrieve the name of the solvers which type is the one we are interested // in QStringList solvers = QStringList(); foreach (SolverInterface *solverInterface, pSolverInterfaces) if (solverInterface->type() == pSolverType) { // Keep track of the solver's name solvers << solverInterface->name(); // Add the solver's properties Core::Property property; Core::Properties properties = Core::Properties(); foreach (const Solver::Property &solverInterfaceProperty, solverInterface->properties()) { // Add the solver's property switch (solverInterfaceProperty.type) { case Solver::Double: property = addDoubleProperty(pSolversProperty); break; default: // Solver::Integer property = addIntegerProperty(pSolversProperty); } // Set the solver's property name setNonEditablePropertyItem(property.name, solverInterfaceProperty.name); // Keep track of the solver's property properties << property; } // Keep track of the solver's properties mSolversProperties.insert(solverInterface->name(), properties); } // Add the list of solvers to our list property value item pSolversListProperty.value->setList(solvers); } //============================================================================== void SingleCellSimulationViewInformationSolversWidget::setSolverInterfaces(const SolverInterfaces &pSolverInterfaces) { // Remove all our properties removeAllProperties(); // Add properties for our different solvers addSolverProperties(pSolverInterfaces, Solver::Ode, mOdeSolversProperty, mOdeSolversListProperty); addSolverProperties(pSolverInterfaces, Solver::Dae, mDaeSolversProperty, mDaeSolversListProperty); addSolverProperties(pSolverInterfaces, Solver::Nla, mNlaSolversProperty, mNlaSolversListProperty); } //============================================================================== void SingleCellSimulationViewInformationSolversWidget::initialize(CellMLSupport::CellmlFileRuntime *pCellmlFileRuntime, const SolverInterfaces &pSolverInterfaces) { // Make sure that we have a CellML file runtime if (!pCellmlFileRuntime) return; // Make sure that the CellML file runtime is valid if (pCellmlFileRuntime->isValid()) { // Check whether we need an ODE or DAE solver, and add a list property // for the ODE or DEA solvers mNeedOdeSolver = pCellmlFileRuntime->modelType() == CellMLSupport::CellmlFileRuntime::Ode; mNeedDaeSolver = !mNeedOdeSolver; setPropertyVisible(mOdeSolversProperty, mNeedOdeSolver); setPropertyVisible(mDaeSolversProperty, mNeedDaeSolver); // Check whether we need an NLA solver, and add a list property if, if // needed mNeedNlaSolver = pCellmlFileRuntime->needNlaSolver(); setPropertyVisible(mNlaSolversProperty, mNeedNlaSolver); // Retranslate ourselves so that the property names get properly set retranslateUi(); } } //============================================================================== bool SingleCellSimulationViewInformationSolversWidget::needOdeSolver() const { // Return whether we need an ODE solver return mNeedOdeSolver; } //============================================================================== bool SingleCellSimulationViewInformationSolversWidget::needDaeSolver() const { // Return whether we need a DAE solver return mNeedDaeSolver; } //============================================================================== bool SingleCellSimulationViewInformationSolversWidget::needNlaSolver() const { // Return whether we need an NLA solver return mNeedNlaSolver; } //============================================================================== QStringList SingleCellSimulationViewInformationSolversWidget::odeSolvers() const { // Return the available ODE solvers, if any return mOdeSolversListProperty.isEmpty()?QStringList():mOdeSolversListProperty.value->list(); } //============================================================================== QStringList SingleCellSimulationViewInformationSolversWidget::daeSolvers() const { // Return the available DAE solvers, if any return mDaeSolversListProperty.isEmpty()?QStringList():mDaeSolversListProperty.value->list(); } //============================================================================== QStringList SingleCellSimulationViewInformationSolversWidget::nlaSolvers() const { // Return the available NLA solvers, if any return mNlaSolversListProperty.isEmpty()?QStringList():mNlaSolversListProperty.value->list(); } //============================================================================== } // namespace SingleCellSimulationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Minor editing.<commit_after>//============================================================================== // Single cell simulation view information solvers widget //============================================================================== #include "cellmlfileruntime.h" #include "singlecellsimulationviewinformationsolverswidget.h" //============================================================================== namespace OpenCOR { namespace SingleCellSimulationView { //============================================================================== SingleCellSimulationViewInformationSolversWidget::SingleCellSimulationViewInformationSolversWidget(QWidget *pParent) : PropertyEditorWidget(true, pParent), mNeedOdeSolver(true), mNeedDaeSolver(false), mNeedNlaSolver(false), mOdeSolversProperty(Core::Property()), mDaeSolversProperty(Core::Property()), mNlaSolversProperty(Core::Property()) { } //============================================================================== void SingleCellSimulationViewInformationSolversWidget::retranslateUi() { // Update our property names if (!mOdeSolversProperty.isEmpty()) { setNonEditablePropertyItem(mOdeSolversProperty.name, tr("ODE solver")); setNonEditablePropertyItem(mOdeSolversListProperty.name, tr("Name")); mOdeSolversListProperty.value->setEmptyListValue(tr("None available")); } if (!mDaeSolversProperty.isEmpty()) { setNonEditablePropertyItem(mDaeSolversProperty.name, tr("DAE solver")); setNonEditablePropertyItem(mDaeSolversListProperty.name, tr("Name")); mDaeSolversListProperty.value->setEmptyListValue(tr("None available")); } if (!mNlaSolversProperty.isEmpty()) { setNonEditablePropertyItem(mNlaSolversProperty.name, tr("NLA solver")); setNonEditablePropertyItem(mNlaSolversListProperty.name, tr("Name")); mNlaSolversListProperty.value->setEmptyListValue(tr("None available")); } // Default retranslation // Note: we must do it last since we set the empty list value of some // properties above... PropertyEditorWidget::retranslateUi(); } //============================================================================== void SingleCellSimulationViewInformationSolversWidget::addSolverProperties(const SolverInterfaces &pSolverInterfaces, const Solver::Type &pSolverType, Core::Property &pSolversProperty, Core::Property &pSolversListProperty) { // Make sure that we have at least one solver interface if (pSolverInterfaces.isEmpty()) { pSolversProperty = Core::Property(); pSolversListProperty = Core::Property(); return; } // Add our category property pSolversProperty = addCategoryProperty(); // Add our list property for the solvers pSolversListProperty = addListProperty(pSolversProperty); // Retrieve the name of the solvers which type is the one we are interested // in QStringList solvers = QStringList(); foreach (SolverInterface *solverInterface, pSolverInterfaces) if (solverInterface->type() == pSolverType) { // Keep track of the solver's name solvers << solverInterface->name(); // Add the solver's properties Core::Property property; Core::Properties properties = Core::Properties(); foreach (const Solver::Property &solverInterfaceProperty, solverInterface->properties()) { // Add the solver's property switch (solverInterfaceProperty.type) { case Solver::Double: property = addDoubleProperty(pSolversProperty); break; default: // Solver::Integer property = addIntegerProperty(pSolversProperty); } // Set the solver's property's name setNonEditablePropertyItem(property.name, solverInterfaceProperty.name); // Keep track of the solver's property properties << property; } // Keep track of the solver's properties mSolversProperties.insert(solverInterface->name(), properties); } // Add the list of solvers to our list property value item pSolversListProperty.value->setList(solvers); } //============================================================================== void SingleCellSimulationViewInformationSolversWidget::setSolverInterfaces(const SolverInterfaces &pSolverInterfaces) { // Remove all our properties removeAllProperties(); // Add properties for our different solvers addSolverProperties(pSolverInterfaces, Solver::Ode, mOdeSolversProperty, mOdeSolversListProperty); addSolverProperties(pSolverInterfaces, Solver::Dae, mDaeSolversProperty, mDaeSolversListProperty); addSolverProperties(pSolverInterfaces, Solver::Nla, mNlaSolversProperty, mNlaSolversListProperty); } //============================================================================== void SingleCellSimulationViewInformationSolversWidget::initialize(CellMLSupport::CellmlFileRuntime *pCellmlFileRuntime, const SolverInterfaces &pSolverInterfaces) { // Make sure that we have a CellML file runtime if (!pCellmlFileRuntime) return; // Make sure that the CellML file runtime is valid if (pCellmlFileRuntime->isValid()) { // Check whether we need an ODE or DAE solver, and add a list property // for the ODE or DEA solvers mNeedOdeSolver = pCellmlFileRuntime->modelType() == CellMLSupport::CellmlFileRuntime::Ode; mNeedDaeSolver = !mNeedOdeSolver; setPropertyVisible(mOdeSolversProperty, mNeedOdeSolver); setPropertyVisible(mDaeSolversProperty, mNeedDaeSolver); // Check whether we need an NLA solver, and add a list property if, if // needed mNeedNlaSolver = pCellmlFileRuntime->needNlaSolver(); setPropertyVisible(mNlaSolversProperty, mNeedNlaSolver); // Retranslate ourselves so that the property names get properly set retranslateUi(); } } //============================================================================== bool SingleCellSimulationViewInformationSolversWidget::needOdeSolver() const { // Return whether we need an ODE solver return mNeedOdeSolver; } //============================================================================== bool SingleCellSimulationViewInformationSolversWidget::needDaeSolver() const { // Return whether we need a DAE solver return mNeedDaeSolver; } //============================================================================== bool SingleCellSimulationViewInformationSolversWidget::needNlaSolver() const { // Return whether we need an NLA solver return mNeedNlaSolver; } //============================================================================== QStringList SingleCellSimulationViewInformationSolversWidget::odeSolvers() const { // Return the available ODE solvers, if any return mOdeSolversListProperty.isEmpty()?QStringList():mOdeSolversListProperty.value->list(); } //============================================================================== QStringList SingleCellSimulationViewInformationSolversWidget::daeSolvers() const { // Return the available DAE solvers, if any return mDaeSolversListProperty.isEmpty()?QStringList():mDaeSolversListProperty.value->list(); } //============================================================================== QStringList SingleCellSimulationViewInformationSolversWidget::nlaSolvers() const { // Return the available NLA solvers, if any return mNlaSolversListProperty.isEmpty()?QStringList():mNlaSolversListProperty.value->list(); } //============================================================================== } // namespace SingleCellSimulationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: rscdep.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: vg $ $Date: 2002-01-29 14:58:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /*************************************************************** * * rscdep.cxx * * (c) Martin Hollmichel 1998 * added intern simple_getopt Vladimir Glazounov 2002 * ***************************************************************/ #ifdef WNT #define __STDC__ 1 #include <string.h> char *optarg = NULL; int optind = 1; int optopt = 0; int opterr = 0; #endif #ifdef UNX #include <unistd.h> #endif #include <sys/stat.h> #include <stdio.h> #include <string.h> #include "prj.hxx" #if SUPD < 356 #include <tools.hxx> #else #include <string.hxx> #include <list.hxx> #include <fsys.hxx> #include <stream.hxx> #endif #include "cppdep.hxx" /* Heiner Rechtien: poor man's getopt() */ int simple_getopt(int argc, char *argv[], const char *optstring); class RscHrcDep : public CppDep { public: RscHrcDep(); virtual ~RscHrcDep(); virtual void Execute(); }; RscHrcDep::RscHrcDep() : CppDep() { } RscHrcDep::~RscHrcDep() { } void RscHrcDep::Execute() { CppDep::Execute(); } static String aDelim = DirEntry::GetAccessDelimiter(); int #ifdef WNT _cdecl #endif main( int argc, char **argv ) { int c; int digit_optind = 0; char aBuf[255]; char pOutputFileName[255]; String aSrsBaseName; BOOL bSource = FALSE; ByteString aRespArg; RscHrcDep *pDep = new RscHrcDep; for ( int i=1; i<argc; i++) { strcpy( aBuf, (const char *)argv[i] ); if ( aBuf[0] == '-' && aBuf[1] == 'f' && aBuf[2] == 'o' ) { strcpy(pOutputFileName, &aBuf[3]); //break; } if ( aBuf[0] == '-' && aBuf[1] == 'f' && aBuf[2] == 'p' ) { strcpy(pOutputFileName, &aBuf[3]); String aName( pOutputFileName, gsl_getSystemTextEncoding()); USHORT nPos = 0; DirEntry aDest( aName ); aSrsBaseName = aDest.GetBase(); //break; } if (aBuf[0] == '-' && aBuf[1] == 'i' ) { //printf("Include : %s\n", &aBuf[2] ); pDep->AddSearchPath( &aBuf[2] ); } if (aBuf[0] == '-' && aBuf[1] == 'I' ) { //printf("Include : %s\n", &aBuf[2] ); pDep->AddSearchPath( &aBuf[2] ); } if (aBuf[0] == '@' ) { ByteString aToken; String aRespName( &aBuf[1], gsl_getSystemTextEncoding()); SimpleConfig aConfig( aRespName ); while ( (aToken = aConfig.GetNext()) != "") { char aBuf2[255]; (void) strcpy( aBuf2, aToken.GetBuffer()); if ( aBuf2[0] == '-' && aBuf2[1] == 'f' && aBuf2[2] == 'o' ) { strcpy(pOutputFileName, &aBuf2[3]); //break; } if ( aBuf2[0] == '-' && aBuf2[1] == 'f' && aBuf2[2] == 'p' ) { strcpy(pOutputFileName, &aBuf2[3]); String aName( pOutputFileName, gsl_getSystemTextEncoding()); USHORT nPos = 0; DirEntry aDest( aName ); aSrsBaseName = aDest.GetBase(); //break; } if (aBuf2[0] == '-' && aBuf2[1] == 'i' ) { //printf("Include : %s\n", &aBuf[2] ); pDep->AddSearchPath( &aBuf2[2] ); } if (aBuf2[0] == '-' && aBuf2[1] == 'I' ) { //printf("Include : %s\n", &aBuf[2] ); pDep->AddSearchPath( &aBuf2[2] ); } if (( aBuf2[0] != '-' ) && ( aBuf2[0] != '@' )) { pDep->AddSource( &aBuf2[0] ); aRespArg += " "; aRespArg += &aBuf2[0]; bSource = TRUE; } } } } while( 1 ) { int this_option_optind = optind ? optind : 1; c = simple_getopt( argc, argv, "_abcdefghi:jklmnopqrstuvwxyzABCDEFGHI:JKLMNOPQRSTUVWXYZ1234567890/-+=.\\()\""); if ( c == -1 ) break; switch( c ) { case 0: break; case 'a' : #ifdef DEBUG_VERBOSE printf("option a\n"); #endif break; case 'l' : #ifdef DEBUG_VERBOSE printf("option l with Value %s\n", optarg ); #endif pDep->AddSource( optarg ); break; case 'h' : case 'H' : case '?' : printf("RscDep 1.0 (c)2000 StarOffice\n"); break; default: #ifdef DEBUG_VERBOSE printf("Unknown getopt error\n"); #endif ; } } DirEntry aEntry("."); aEntry.ToAbs(); String aCwd = aEntry.GetName(); /* USHORT nPos; #ifndef UNX while ( (nPos = aCwd.Search('\\') != STRING_NOTFOUND )) #else while ( (nPos = aCwd.Search('/') != STRING_NOTFOUND )) #endif { String attt = aCwd.Copy( 0, nPos ); aCwd.Erase( 0, nPos ); } */ SvFileStream aOutStream; String aOutputFileName( pOutputFileName, gsl_getSystemTextEncoding()); DirEntry aOutEntry( aOutputFileName ); String aOutPath = aOutEntry.GetPath().GetFull(); String aFileName( aOutPath ); aFileName += aDelim; aFileName += aCwd; aFileName += String(".", gsl_getSystemTextEncoding()); aFileName += aSrsBaseName; aFileName += String(".dpr", gsl_getSystemTextEncoding()); //fprintf( stderr, "OutFileName : %s \n",aFileName.GetStr()); aOutStream.Open( aFileName, STREAM_WRITE ); ByteString aString; if ( optind < argc ) { #ifdef DEBUG_VERBOSE printf("further arguments : "); #endif aString = ByteString( pOutputFileName ); aString += ByteString(" : " ); while ( optind < argc ) { if (!bSource ) { aString += ByteString(" " ); aString += ByteString( argv[optind]); pDep->AddSource( argv[optind++]); } else { optind++; } } } aString += aRespArg; pDep->Execute(); ByteStringList *pLst = pDep->GetDepList(); ULONG nCount = pLst->Count(); if ( nCount == 0 ) { aOutStream.WriteLine( aString ); } else { aString += ByteString( "\\" ); aOutStream.WriteLine( aString ); } for ( ULONG j=0; j<nCount; j++ ) { ByteString *pStr = pLst->GetObject(j); #ifdef UNX pStr->SearchAndReplaceAll('\\', ByteString( aDelim, RTL_TEXTENCODING_ASCII_US )); #endif #ifdef WNT pStr->SearchAndReplaceAll('/', ByteString( aDelim, RTL_TEXTENCODING_ASCII_US )); #endif if ( j != (nCount-1) ) *pStr += ByteString( "\\" ); aOutStream.WriteLine( *pStr ); } delete pDep; aOutStream.Close(); return 0; } /* Heiner Rechtien: my very simple minded implementation of getopt() * it's too sad that getopt() is not available everywhere * note: this is not a full POSIX conforming getopt() */ simple_getopt(int argc, char *argv[], const char *optstring) { char *arg = argv[optind]; /* skip all response file arguments */ if ( arg ) { while ( *arg == '@' ) arg = argv[++optind]; if ( arg[0] == '-' && arg[1] != '\0' ) { char *popt; int c = arg[1]; if ( (popt = strchr(optstring, c)) == NULL ) { optopt = c; if ( opterr ) fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); return '?'; } if ( *(++popt) == ':') { if ( arg[2] != '\0' ) { optarg = ++arg; } else { optarg = argv[++optind]; } } else { optarg = NULL; } ++optind; return c; } } return -1; } <commit_msg>#65293#: fix static init.<commit_after>/************************************************************************* * * $RCSfile: rscdep.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2002-02-07 16:34:45 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /*************************************************************** * * rscdep.cxx * * (c) Martin Hollmichel 1998 * added intern simple_getopt Vladimir Glazounov 2002 * ***************************************************************/ #ifdef UNX #include <unistd.h> #endif #include <sys/stat.h> #include <stdio.h> #include <string.h> #include "prj.hxx" #if SUPD < 356 #include <tools.hxx> #else #include <string.hxx> #include <list.hxx> #include <fsys.hxx> #include <stream.hxx> #endif #include "cppdep.hxx" class RscHrcDep : public CppDep { public: RscHrcDep(); virtual ~RscHrcDep(); virtual void Execute(); }; RscHrcDep::RscHrcDep() : CppDep() { } RscHrcDep::~RscHrcDep() { } void RscHrcDep::Execute() { CppDep::Execute(); } //static String aDelim; /* poor man's getopt() */ int simple_getopt(int argc, char *argv[], const char *optstring); #ifdef WNT static char *optarg = NULL; static int optind = 1; static int optopt = 0; static int opterr = 0; #endif int #ifdef WNT _cdecl #endif main( int argc, char **argv ) { int c; int digit_optind = 0; char aBuf[255]; char pOutputFileName[255]; String aSrsBaseName; BOOL bSource = FALSE; ByteString aRespArg; String aDelim = String(DirEntry::GetAccessDelimiter()); RscHrcDep *pDep = new RscHrcDep; for ( int i=1; i<argc; i++) { strcpy( aBuf, (const char *)argv[i] ); if ( aBuf[0] == '-' && aBuf[1] == 'f' && aBuf[2] == 'o' ) { strcpy(pOutputFileName, &aBuf[3]); //break; } if ( aBuf[0] == '-' && aBuf[1] == 'f' && aBuf[2] == 'p' ) { strcpy(pOutputFileName, &aBuf[3]); String aName( pOutputFileName, gsl_getSystemTextEncoding()); USHORT nPos = 0; DirEntry aDest( aName ); aSrsBaseName = aDest.GetBase(); //break; } if (aBuf[0] == '-' && aBuf[1] == 'i' ) { //printf("Include : %s\n", &aBuf[2] ); pDep->AddSearchPath( &aBuf[2] ); } if (aBuf[0] == '-' && aBuf[1] == 'I' ) { //printf("Include : %s\n", &aBuf[2] ); pDep->AddSearchPath( &aBuf[2] ); } if (aBuf[0] == '@' ) { ByteString aToken; String aRespName( &aBuf[1], gsl_getSystemTextEncoding()); SimpleConfig aConfig( aRespName ); while ( (aToken = aConfig.GetNext()) != "") { char aBuf2[255]; (void) strcpy( aBuf2, aToken.GetBuffer()); if ( aBuf2[0] == '-' && aBuf2[1] == 'f' && aBuf2[2] == 'o' ) { strcpy(pOutputFileName, &aBuf2[3]); //break; } if ( aBuf2[0] == '-' && aBuf2[1] == 'f' && aBuf2[2] == 'p' ) { strcpy(pOutputFileName, &aBuf2[3]); String aName( pOutputFileName, gsl_getSystemTextEncoding()); USHORT nPos = 0; DirEntry aDest( aName ); aSrsBaseName = aDest.GetBase(); //break; } if (aBuf2[0] == '-' && aBuf2[1] == 'i' ) { //printf("Include : %s\n", &aBuf[2] ); pDep->AddSearchPath( &aBuf2[2] ); } if (aBuf2[0] == '-' && aBuf2[1] == 'I' ) { //printf("Include : %s\n", &aBuf[2] ); pDep->AddSearchPath( &aBuf2[2] ); } if (( aBuf2[0] != '-' ) && ( aBuf2[0] != '@' )) { pDep->AddSource( &aBuf2[0] ); aRespArg += " "; aRespArg += &aBuf2[0]; bSource = TRUE; } } } } while( 1 ) { int this_option_optind = optind ? optind : 1; c = simple_getopt( argc, argv, "_abcdefghi:jklmnopqrstuvwxyzABCDEFGHI:JKLMNOPQRSTUVWXYZ1234567890/-+=.\\()\""); if ( c == -1 ) break; switch( c ) { case 0: break; case 'a' : #ifdef DEBUG_VERBOSE printf("option a\n"); #endif break; case 'l' : #ifdef DEBUG_VERBOSE printf("option l with Value %s\n", optarg ); #endif pDep->AddSource( optarg ); break; case 'h' : case 'H' : case '?' : printf("RscDep 1.0 (c)2000 StarOffice\n"); break; default: #ifdef DEBUG_VERBOSE printf("Unknown getopt error\n"); #endif ; } } DirEntry aEntry("."); aEntry.ToAbs(); String aCwd = aEntry.GetName(); /* USHORT nPos; #ifndef UNX while ( (nPos = aCwd.Search('\\') != STRING_NOTFOUND )) #else while ( (nPos = aCwd.Search('/') != STRING_NOTFOUND )) #endif { String attt = aCwd.Copy( 0, nPos ); aCwd.Erase( 0, nPos ); } */ SvFileStream aOutStream; String aOutputFileName( pOutputFileName, gsl_getSystemTextEncoding()); DirEntry aOutEntry( aOutputFileName ); String aOutPath = aOutEntry.GetPath().GetFull(); String aFileName( aOutPath ); aFileName += aDelim; aFileName += aCwd; aFileName += String(".", gsl_getSystemTextEncoding()); aFileName += aSrsBaseName; aFileName += String(".dpr", gsl_getSystemTextEncoding()); //fprintf( stderr, "OutFileName : %s \n",aFileName.GetStr()); aOutStream.Open( aFileName, STREAM_WRITE ); ByteString aString; if ( optind < argc ) { #ifdef DEBUG_VERBOSE printf("further arguments : "); #endif aString = ByteString( pOutputFileName ); aString += ByteString(" : " ); while ( optind < argc ) { if (!bSource ) { aString += ByteString(" " ); aString += ByteString( argv[optind]); pDep->AddSource( argv[optind++]); } else { optind++; } } } aString += aRespArg; pDep->Execute(); ByteStringList *pLst = pDep->GetDepList(); ULONG nCount = pLst->Count(); if ( nCount == 0 ) { aOutStream.WriteLine( aString ); } else { aString += ByteString( "\\" ); aOutStream.WriteLine( aString ); } for ( ULONG j=0; j<nCount; j++ ) { ByteString *pStr = pLst->GetObject(j); #ifdef UNX pStr->SearchAndReplaceAll('\\', ByteString( aDelim, RTL_TEXTENCODING_ASCII_US )); #endif #ifdef WNT pStr->SearchAndReplaceAll('/', ByteString( aDelim, RTL_TEXTENCODING_ASCII_US )); #endif if ( j != (nCount-1) ) *pStr += ByteString( "\\" ); aOutStream.WriteLine( *pStr ); } delete pDep; aOutStream.Close(); return 0; } /* Heiner Rechtien: my very simple minded implementation of getopt() * it's too sad that getopt() is not available everywhere * note: this is not a full POSIX conforming getopt() */ simple_getopt(int argc, char *argv[], const char *optstring) { char *arg = argv[optind]; /* skip all response file arguments */ if ( arg ) { while ( *arg == '@' ) arg = argv[++optind]; if ( arg[0] == '-' && arg[1] != '\0' ) { char *popt; int c = arg[1]; if ( (popt = strchr(optstring, c)) == NULL ) { optopt = c; if ( opterr ) fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); return '?'; } if ( *(++popt) == ':') { if ( arg[2] != '\0' ) { optarg = ++arg; } else { optarg = argv[++optind]; } } else { optarg = NULL; } ++optind; return c; } } return -1; } <|endoftext|>
<commit_before>/* * @file ex9.cpp * @details This file is the solution to exercise 9. * @author Alexander Rettkowski * @date 12.07.2017 */ #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/fusion/include/io.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp> #include <boost/property_map/property_map.hpp> #include <boost/timer/timer.hpp> #include <boost/chrono.hpp> #include <iostream> #include <string> #include <complex> #include <fstream> #include <queue> #include <omp.h> using namespace boost; namespace exercise9 { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; struct edge { int startNode; int endNode; int length; }; } BOOST_FUSION_ADAPT_STRUCT( exercise9::edge, (int, startNode) (int, endNode) (int, length) ) namespace exercise9 { template <typename Iterator> struct line_parser : qi::grammar<Iterator, edge()> { line_parser() : line_parser::base_type(start) { using qi::int_; start %= int_ >> ' ' >> int_ >> ' ' >> int_; } qi::rule<Iterator, edge()> start; }; } /** * This method checks (in a naive way), if a given number is prime or not. * @param number The number to check. * @returns True, if number is prime; false otherwise. */ bool isPrime(int number) { if (number == 2) return true; if (number % 2 == 0) return false; for (int i = 3; (i*i) <= number; i += 2) { if (number % i == 0) return false; } return true; } /** * The function that calculates the shortest paths using Dijkstra's method. * @param numberOfNodes Number of nodes in the graph. * @param graph The graph represented as a vector auf edge-vectors. * @param startNode The id of the node where the search starts. * @returns The weight of the Steiner Tree and the edge list of the tree coupled as a std::pair */ std::pair<int, std::list<std::pair<int, int>>> steinerTree(int numberOfNodes, std::vector< std::vector< std::pair<int, int> > > graph, int startNode) { std::vector<int> connectedVertices; connectedVertices.push_back(startNode); std::list<std::pair<int, int>> edgeList; std::vector<int> predecessors(numberOfNodes, -1); std::vector<int> distanceTo(numberOfNodes, INT_MAX); std::priority_queue< std::pair<int, int>, std::vector< std::pair<int, int> >, std::greater< std::pair<int, int> > > queue; queue.push(std::pair<int, int>(startNode, 0)); distanceTo[startNode] = 0; //predecessors[startNode] = -1; int steinerWeight = 0; int currentNode, compareNode, compareNodeDistance, currentNodeDistance; while (!queue.empty()) { currentNode = queue.top().first; currentNodeDistance = queue.top().second; queue.pop(); if (distanceTo[currentNode] < currentNodeDistance) continue; for (int i = 0; i < graph[currentNode].size(); i++) { compareNode = graph[currentNode][i].first; compareNodeDistance = graph[currentNode][i].second; if (distanceTo[compareNode] > distanceTo[currentNode] + compareNodeDistance) { if (isPrime(compareNode)) { predecessors[compareNode] = currentNode; int backtracknode = compareNode; while (std::find(connectedVertices.begin(), connectedVertices.end(), backtracknode) == connectedVertices.end()) { for (std::pair<int, int> edge : graph[predecessors[backtracknode]]) { if (edge.first == backtracknode) { edgeList.push_back(std::pair<int, int>(predecessors[backtracknode], backtracknode)); steinerWeight += edge.second; } } distanceTo[backtracknode] = 0; connectedVertices.push_back(backtracknode); backtracknode = predecessors[backtracknode]; queue.push(std::pair<int, int>(backtracknode, 0)); } } else { distanceTo[compareNode] = distanceTo[currentNode] + compareNodeDistance; queue.push(std::pair<int, int>(compareNode, distanceTo[compareNode])); predecessors[compareNode] = currentNode; } } } } return std::pair<int, std::list<std::pair<int, int>>>(steinerWeight, edgeList); } /** * The main function that reads in a file and processes it. * @param argc Number of command line arguments. * @param *argv a pointer to the array of command line arguments. */ int main(int argc, char *argv[]) { timer::cpu_timer boostTimer; using boost::spirit::ascii::space; typedef std::string::const_iterator iterator_type; typedef exercise9::line_parser<iterator_type> line_parser; line_parser parser; std::string currentLine; std::ifstream file(argv[1]); // get number of nodes char delimiter = ' '; getline(file, currentLine, delimiter); const int numberOfNodes = stoi(currentLine); getline(file, currentLine); int constSub = 1; std::vector<std::vector<std::pair<int, int>>> edges(numberOfNodes); while (getline(file, currentLine)) { exercise9::edge parsedLine; std::string::const_iterator currentPosition = currentLine.begin(); std::string::const_iterator lineEnd = currentLine.end(); bool parsingSucceeded = phrase_parse(currentPosition, lineEnd, parser, space, parsedLine); if (parsingSucceeded && currentPosition == lineEnd) { std::pair<int, int> *tempEdge = new std::pair<int, int>(); tempEdge->first = parsedLine.endNode - constSub; tempEdge->second = parsedLine.length; edges[parsedLine.startNode - constSub].push_back(*tempEdge); std::pair<int, int> *reverseEdge = new std::pair<int, int>(); reverseEdge->first = parsedLine.startNode - constSub; reverseEdge->second = parsedLine.length; edges[parsedLine.endNode - constSub].push_back(*reverseEdge); } } file.close(); omp_set_dynamic(0); omp_set_num_threads(std::stoi(argv[2])); std::vector<int> terminalIds; for (int i = 0; i < numberOfNodes; i++) { if (isPrime(i)) terminalIds.push_back(i); } std::vector<int> lengths(terminalIds.size()); #pragma omp parallel for for (int i = 0; i < terminalIds.size(); i++) { std::pair<int, std::list<std::pair<int, int>>> currentRun = steinerTree(numberOfNodes, edges, terminalIds[i]); lengths[i] = currentRun.first; std::cout << "Length starting from " << i << ": " << lengths[i] << std::endl; } int minlength = INT32_MAX; int minId = -1; for (int i = 0; i < terminalIds.size(); i++) { if (lengths[i] < minlength) { minlength = lengths[i]; minId = i; } } std::list<std::pair<int, int>> edgelist = steinerTree(numberOfNodes, edges, minId).second; for (std::pair<int, int> edge : edgelist) { std::cout << "(" << edge.first << ", " << edge.second << ")" << std::endl; } std::cout << "TOTAL WEIGHT: " << minlength; return 0; } <commit_msg>Update ex9.cpp<commit_after>/* * @file ex9.cpp * @details This file is the solution to exercise 9. * @author Alexander Rettkowski * @date 12.07.2017 */ #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/fusion/include/io.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp> #include <boost/property_map/property_map.hpp> #include <boost/timer/timer.hpp> #include <boost/chrono.hpp> #include <iostream> #include <string> #include <complex> #include <fstream> #include <queue> #include <omp.h> using namespace boost; namespace exercise9 { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; struct edge { int startNode; int endNode; int length; }; } BOOST_FUSION_ADAPT_STRUCT( exercise9::edge, (int, startNode) (int, endNode) (int, length) ) namespace exercise9 { template <typename Iterator> struct line_parser : qi::grammar<Iterator, edge()> { line_parser() : line_parser::base_type(start) { using qi::int_; start %= int_ >> ' ' >> int_ >> ' ' >> int_; } qi::rule<Iterator, edge()> start; }; } /** * This method checks (in a naive way), if a given number is prime or not. * @param number The number to check. * @returns True, if number is prime; false otherwise. */ bool isPrime(int number) { if (number == 2) return true; if (number % 2 == 0) return false; for (int i = 3; (i*i) <= number; i += 2) { if (number % i == 0) return false; } return true; } /** * The function that calculates the shortest paths using Dijkstra's method. * @param numberOfNodes Number of nodes in the graph. * @param graph The graph represented as a vector auf edge-vectors. * @param startNode The id of the node where the search starts. * @returns The weight of the Steiner Tree and the edge list of the tree coupled as a std::pair */ std::pair<int, std::list<std::pair<int, int>>> steinerTree(int numberOfNodes, std::vector< std::vector< std::pair<int, int> > > graph, int startNode) { std::vector<int> connectedVertices; connectedVertices.push_back(startNode); std::list<std::pair<int, int>> edgeList; std::vector<int> predecessors(numberOfNodes, -1); std::vector<int> distanceTo(numberOfNodes, INT_MAX); std::priority_queue< std::pair<int, int>, std::vector< std::pair<int, int> >, std::greater< std::pair<int, int> > > queue; queue.push(std::pair<int, int>(startNode, 0)); distanceTo[startNode] = 0; //predecessors[startNode] = -1; int steinerWeight = 0; int currentNode, compareNode, compareNodeDistance, currentNodeDistance; while (!queue.empty()) { currentNode = queue.top().first; currentNodeDistance = queue.top().second; queue.pop(); if (distanceTo[currentNode] < currentNodeDistance) continue; for (int i = 0; i < graph[currentNode].size(); i++) { compareNode = graph[currentNode][i].first; compareNodeDistance = graph[currentNode][i].second; if (distanceTo[compareNode] > distanceTo[currentNode] + compareNodeDistance) { if (isPrime(compareNode)) { predecessors[compareNode] = currentNode; int backtracknode = compareNode; while (std::find(connectedVertices.begin(), connectedVertices.end(), backtracknode) == connectedVertices.end()) { for (std::pair<int, int> edge : graph[predecessors[backtracknode]]) { if (edge.first == backtracknode) { edgeList.push_back(std::pair<int, int>(predecessors[backtracknode], backtracknode)); steinerWeight += edge.second; } } distanceTo[backtracknode] = 0; connectedVertices.push_back(backtracknode); backtracknode = predecessors[backtracknode]; queue.push(std::pair<int, int>(backtracknode, 0)); } } else { distanceTo[compareNode] = distanceTo[currentNode] + compareNodeDistance; queue.push(std::pair<int, int>(compareNode, distanceTo[compareNode])); predecessors[compareNode] = currentNode; } } } } return std::pair<int, std::list<std::pair<int, int>>>(steinerWeight, edgeList); } /** * The main function that reads in a file and processes it. * @param argc Number of command line arguments. * @param *argv a pointer to the array of command line arguments. */ int main(int argc, char *argv[]) { timer::cpu_timer boostTimer; using boost::spirit::ascii::space; typedef std::string::const_iterator iterator_type; typedef exercise9::line_parser<iterator_type> line_parser; line_parser parser; std::string currentLine; std::ifstream file(argv[1]); // get number of nodes char delimiter = ' '; getline(file, currentLine, delimiter); const int numberOfNodes = stoi(currentLine); getline(file, currentLine); int constSub = 1; std::vector<std::vector<std::pair<int, int>>> edges(numberOfNodes); while (getline(file, currentLine)) { exercise9::edge parsedLine; std::string::const_iterator currentPosition = currentLine.begin(); std::string::const_iterator lineEnd = currentLine.end(); bool parsingSucceeded = phrase_parse(currentPosition, lineEnd, parser, space, parsedLine); if (parsingSucceeded && currentPosition == lineEnd) { std::pair<int, int> *tempEdge = new std::pair<int, int>(); tempEdge->first = parsedLine.endNode - constSub; tempEdge->second = parsedLine.length; edges[parsedLine.startNode - constSub].push_back(*tempEdge); std::pair<int, int> *reverseEdge = new std::pair<int, int>(); reverseEdge->first = parsedLine.startNode - constSub; reverseEdge->second = parsedLine.length; edges[parsedLine.endNode - constSub].push_back(*reverseEdge); } } file.close(); timer::cpu_timer runTimer; omp_set_dynamic(0); omp_set_num_threads(std::stoi(argv[2])); std::vector<int> terminalIds; for (int i = 0; i < numberOfNodes; i++) { if (isPrime(i)) terminalIds.push_back(i); } std::vector<int> lengths(terminalIds.size()); #pragma omp parallel for for (int i = 0; i < terminalIds.size(); i++) { std::pair<int, std::list<std::pair<int, int>>> currentRun = steinerTree(numberOfNodes, edges, terminalIds[i]); lengths[i] = currentRun.first; std::cout << "Length starting from " << i << ": " << lengths[i] << std::endl; } int minlength = INT32_MAX; int minId = -1; for (int i = 0; i < terminalIds.size(); i++) { if (lengths[i] < minlength) { minlength = lengths[i]; minId = i; } } timer::cpu_times runtime = boostTimer.elapsed(); std::list<std::pair<int, int>> edgelist = steinerTree(numberOfNodes, edges, minId).second; std::cout << "TLEN: " << minlength << std::endl; std::cout << "TREE: "; for (std::pair<int, int> edge : edgelist) { std::cout << "(" << edge.first << ", " << edge.second << ") "; } std::cout << std::endl; timer::cpu_times time = boostTimer.elapsed(); std::cout << "TIME: " << (time.user + time.system) / 1e9 << "s\n"; std::cout << "WALL: " << runtime.wall / 1e9 << "s\n"; return 0; } <|endoftext|>
<commit_before><commit_msg>Fix to use the correct vulkan device<commit_after><|endoftext|>
<commit_before>#include "replication/delete_queue.hpp" #include "btree/node.hpp" #include "buffer_cache/buf_lock.hpp" #include "buffer_cache/co_functions.hpp" #include "containers/scoped_malloc.hpp" #include "logger.hpp" #include "store.hpp" namespace replication { namespace delete_queue { // The offset of the primal offset. const int PRIMAL_OFFSET_OFFSET = sizeof(block_magic_t); const int TIMESTAMPS_AND_OFFSETS_OFFSET = PRIMAL_OFFSET_OFFSET + sizeof(off64_t); const int TIMESTAMPS_AND_OFFSETS_SIZE = sizeof(large_buf_ref) + 3 * sizeof(block_id_t); off64_t *primal_offset(void *root_buffer) { return reinterpret_cast<off64_t *>(reinterpret_cast<char *>(root_buffer) + PRIMAL_OFFSET_OFFSET); } large_buf_ref *timestamps_and_offsets_largebuf(void *root_buffer) { char *p = reinterpret_cast<char *>(root_buffer); return reinterpret_cast<large_buf_ref *>(p + TIMESTAMPS_AND_OFFSETS_OFFSET); } large_buf_ref *keys_largebuf(void *root_buffer) { char *p = reinterpret_cast<char *>(root_buffer); return reinterpret_cast<large_buf_ref *>(p + (TIMESTAMPS_AND_OFFSETS_OFFSET + TIMESTAMPS_AND_OFFSETS_SIZE)); } int keys_largebuf_ref_size(block_size_t block_size) { return block_size.value() - (TIMESTAMPS_AND_OFFSETS_OFFSET + TIMESTAMPS_AND_OFFSETS_SIZE); } } // namespace delete_queue void add_key_to_delete_queue(int64_t delete_queue_limit, boost::shared_ptr<transactor_t>& txor, block_id_t queue_root_id, repli_timestamp timestamp, const store_key_t *key) { thread_saver_t saver; // Beware: Right now, some aspects of correctness depend on the // fact that we hold the queue_root lock for the entire operation. buf_lock_t queue_root(saver, *txor, queue_root_id, rwi_write); // TODO this could be a non-major write? void *queue_root_buf = queue_root->get_data_major_write(); off64_t *primal_offset = delete_queue::primal_offset(queue_root_buf); large_buf_ref *t_o_ref = delete_queue::timestamps_and_offsets_largebuf(queue_root_buf); large_buf_ref *keys_ref = delete_queue::keys_largebuf(queue_root_buf); rassert(t_o_ref->size % sizeof(delete_queue::t_and_o) == 0); // Figure out what we need to do. bool will_want_to_dequeue = (keys_ref->size + 1 + int64_t(key->size) > delete_queue_limit); bool will_actually_dequeue = false; delete_queue::t_and_o second_tao = { repli_timestamp::invalid, -1 }; // Possibly update the (timestamp, offset) queue. (This happens at most once per second.) { if (t_o_ref->size == 0) { // HEY: Why must we allocate large_buf_t's with new? boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write)); // The size is only zero in the unallocated state. (Large // bufs can't actually handle size zero, so we can't let // the large buf shrink to that size.) delete_queue::t_and_o tao; tao.timestamp = timestamp; tao.offset = *primal_offset + keys_ref->size; t_o_largebuf->allocate(sizeof(tao)); t_o_largebuf->fill_at(0, &tao, sizeof(tao)); rassert(keys_ref->size == 0); rassert(!will_want_to_dequeue); } else { delete_queue::t_and_o last_tao; { boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write)); co_acquire_large_buf_slice(saver, t_o_largebuf.get(), t_o_ref->size - sizeof(last_tao), sizeof(last_tao)); t_o_largebuf->read_at(t_o_ref->size - sizeof(last_tao), &last_tao, sizeof(last_tao)); if (last_tao.timestamp.time > timestamp.time) { logWRN("The delete queue is receiving updates out of order (t1 = %d, t2 = %d), or the system clock has been set back! Bringing up a replica may be excessively inefficient.\n", last_tao.timestamp.time, timestamp.time); // Timestamps must be monotonically increasing, so sorry. timestamp = last_tao.timestamp; } if (last_tao.timestamp.time != timestamp.time) { delete_queue::t_and_o tao; tao.timestamp = timestamp; tao.offset = *primal_offset + keys_ref->size; int refsize_adjustment_dontcare; // It's okay to append because we acquired the rhs // of the large buf. t_o_largebuf->append(sizeof(tao), &refsize_adjustment_dontcare); t_o_largebuf->fill_at(t_o_ref->size - sizeof(tao), &tao, sizeof(tao)); } } if (will_want_to_dequeue && t_o_ref->size >= int64_t(2 * sizeof(second_tao))) { boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write)); co_acquire_large_buf_slice(saver, t_o_largebuf.get(), 0, 2 * sizeof(second_tao)); t_o_largebuf->read_at(sizeof(second_tao), &second_tao, sizeof(second_tao)); will_actually_dequeue = true; // It's okay to unprepend because we acquired the lhs of the large buf. int refsize_adjustment_dontcare; t_o_largebuf->unprepend(sizeof(second_tao), &refsize_adjustment_dontcare); } } } // Update the keys list. { lbref_limit_t reflimit = lbref_limit_t(delete_queue::keys_largebuf_ref_size((*txor)->cache->get_block_size())); int64_t amount_to_unprepend = will_actually_dequeue ? second_tao.offset - *primal_offset : 0; large_buf_t::co_enqueue(txor, keys_ref, reflimit, amount_to_unprepend, key, 1 + key->size); *primal_offset += amount_to_unprepend; } } bool dump_keys_from_delete_queue(boost::shared_ptr<transactor_t>& txor, block_id_t queue_root_id, repli_timestamp begin_timestamp, deletion_key_stream_receiver_t *recipient) { thread_saver_t saver; // Beware: Right now, some aspects of correctness depend on the // fact that we hold the queue_root lock for the entire operation. buf_lock_t queue_root(saver, *txor, queue_root_id, rwi_read); void *queue_root_buf = const_cast<void *>(queue_root->get_data_read()); off64_t *primal_offset = delete_queue::primal_offset(queue_root_buf); large_buf_ref *t_o_ref = delete_queue::timestamps_and_offsets_largebuf(queue_root_buf); large_buf_ref *keys_ref = delete_queue::keys_largebuf(queue_root_buf); if (t_o_ref->size != 0 && keys_ref->size != 0) { rassert(t_o_ref->size % sizeof(delete_queue::t_and_o) == 0); // TODO: DON'T hold the queue_root lock for the entire operation. Sheesh. int64_t begin_offset = 0; int64_t end_offset = keys_ref->size; { boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_read)); co_acquire_large_buf(saver, t_o_largebuf.get()); delete_queue::t_and_o tao; int64_t i = 0, ie = t_o_ref->size; bool begin_found = false; while (i < ie) { t_o_largebuf->read_at(i, &tao, sizeof(tao)); if (!begin_found && begin_timestamp.time <= tao.timestamp.time) { begin_offset = tao.offset - *primal_offset; begin_found = true; break; } i += sizeof(tao); } if (!recipient->should_send_deletion_keys(begin_found)) { return false; } // So we have a begin_offset and an end_offset. } rassert(begin_offset <= end_offset); if (begin_offset < end_offset) { boost::scoped_ptr<large_buf_t> keys_largebuf(new large_buf_t(txor, keys_ref, lbref_limit_t(delete_queue::keys_largebuf_ref_size((*txor)->cache->get_block_size())), rwi_read_outdated_ok)); // TODO: acquire subinterval. co_acquire_large_buf_slice(saver, keys_largebuf.get(), begin_offset, end_offset - begin_offset); int64_t n = end_offset - begin_offset; // TODO: don't copy needlessly... sheesh. This is a fake // implementation, make something that actually streams later. scoped_malloc<char> buf(n); keys_largebuf->read_at(begin_offset, buf.get(), n); char *p = buf.get(); char *e = p + n; while (p < e) { btree_key_t *k = reinterpret_cast<btree_key_t *>(p); rassert(k->size + 1 <= e - p); recipient->deletion_key(k); p += k->size + 1; } } } recipient->done_deletion_keys(); return true; } // TODO: maybe this function should be somewhere else. Well, // certainly. Right now we don't have a notion of an "empty" // largebuf, so we'll know that we have to ->allocate the largebuf // when we see a size of 0 in the large_buf_ref. void initialize_large_buf_ref(large_buf_ref *ref, int size_in_bytes) { int ids_bytes = size_in_bytes - offsetof(large_buf_ref, block_ids); rassert(ids_bytes > 0); ref->offset = 0; ref->size = 0; for (int i = 0, e = ids_bytes / sizeof(block_id_t); i < e; ++i) { ref->block_ids[i] = NULL_BLOCK_ID; } } void initialize_empty_delete_queue(delete_queue_block_t *dqb, block_size_t block_size) { dqb->magic = delete_queue_block_t::expected_magic; *delete_queue::primal_offset(dqb) = 0; large_buf_ref *t_and_o = delete_queue::timestamps_and_offsets_largebuf(dqb); initialize_large_buf_ref(t_and_o, delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE); large_buf_ref *k = delete_queue::keys_largebuf(dqb); initialize_large_buf_ref(k, delete_queue::keys_largebuf_ref_size(block_size)); } const block_magic_t delete_queue_block_t::expected_magic = { { 'D', 'e', 'l', 'Q' } }; } // namespace replication <commit_msg>The delete queue was deciding that we needed to delete everything when people tried to use it with a deletion key that comes _later_ than previous deletion keys. This was causing the --failover test to fail somehow, by exposing an actual bug. Now the problem with the delete queue is fixed, and the --failover test is passing, but the other bug (which has to do with delete_everything, presumably) which caused the test to actually fail, still exists.<commit_after>#include "replication/delete_queue.hpp" #include "btree/node.hpp" #include "buffer_cache/buf_lock.hpp" #include "buffer_cache/co_functions.hpp" #include "containers/scoped_malloc.hpp" #include "logger.hpp" #include "store.hpp" namespace replication { namespace delete_queue { // The offset of the primal offset. const int PRIMAL_OFFSET_OFFSET = sizeof(block_magic_t); const int TIMESTAMPS_AND_OFFSETS_OFFSET = PRIMAL_OFFSET_OFFSET + sizeof(off64_t); const int TIMESTAMPS_AND_OFFSETS_SIZE = sizeof(large_buf_ref) + 3 * sizeof(block_id_t); off64_t *primal_offset(void *root_buffer) { return reinterpret_cast<off64_t *>(reinterpret_cast<char *>(root_buffer) + PRIMAL_OFFSET_OFFSET); } large_buf_ref *timestamps_and_offsets_largebuf(void *root_buffer) { char *p = reinterpret_cast<char *>(root_buffer); return reinterpret_cast<large_buf_ref *>(p + TIMESTAMPS_AND_OFFSETS_OFFSET); } large_buf_ref *keys_largebuf(void *root_buffer) { char *p = reinterpret_cast<char *>(root_buffer); return reinterpret_cast<large_buf_ref *>(p + (TIMESTAMPS_AND_OFFSETS_OFFSET + TIMESTAMPS_AND_OFFSETS_SIZE)); } int keys_largebuf_ref_size(block_size_t block_size) { return block_size.value() - (TIMESTAMPS_AND_OFFSETS_OFFSET + TIMESTAMPS_AND_OFFSETS_SIZE); } } // namespace delete_queue void add_key_to_delete_queue(int64_t delete_queue_limit, boost::shared_ptr<transactor_t>& txor, block_id_t queue_root_id, repli_timestamp timestamp, const store_key_t *key) { thread_saver_t saver; // Beware: Right now, some aspects of correctness depend on the // fact that we hold the queue_root lock for the entire operation. buf_lock_t queue_root(saver, *txor, queue_root_id, rwi_write); // TODO this could be a non-major write? void *queue_root_buf = queue_root->get_data_major_write(); off64_t *primal_offset = delete_queue::primal_offset(queue_root_buf); large_buf_ref *t_o_ref = delete_queue::timestamps_and_offsets_largebuf(queue_root_buf); large_buf_ref *keys_ref = delete_queue::keys_largebuf(queue_root_buf); rassert(t_o_ref->size % sizeof(delete_queue::t_and_o) == 0); // Figure out what we need to do. bool will_want_to_dequeue = (keys_ref->size + 1 + int64_t(key->size) > delete_queue_limit); bool will_actually_dequeue = false; delete_queue::t_and_o second_tao = { repli_timestamp::invalid, -1 }; // Possibly update the (timestamp, offset) queue. (This happens at most once per second.) { if (t_o_ref->size == 0) { // HEY: Why must we allocate large_buf_t's with new? boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write)); // The size is only zero in the unallocated state. (Large // bufs can't actually handle size zero, so we can't let // the large buf shrink to that size.) delete_queue::t_and_o tao; tao.timestamp = timestamp; tao.offset = *primal_offset + keys_ref->size; t_o_largebuf->allocate(sizeof(tao)); t_o_largebuf->fill_at(0, &tao, sizeof(tao)); rassert(keys_ref->size == 0); rassert(!will_want_to_dequeue); } else { delete_queue::t_and_o last_tao; { boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write)); co_acquire_large_buf_slice(saver, t_o_largebuf.get(), t_o_ref->size - sizeof(last_tao), sizeof(last_tao)); t_o_largebuf->read_at(t_o_ref->size - sizeof(last_tao), &last_tao, sizeof(last_tao)); if (last_tao.timestamp.time > timestamp.time) { logWRN("The delete queue is receiving updates out of order (t1 = %d, t2 = %d), or the system clock has been set back! Bringing up a replica may be excessively inefficient.\n", last_tao.timestamp.time, timestamp.time); // Timestamps must be monotonically increasing, so sorry. timestamp = last_tao.timestamp; } if (last_tao.timestamp.time != timestamp.time) { delete_queue::t_and_o tao; tao.timestamp = timestamp; tao.offset = *primal_offset + keys_ref->size; int refsize_adjustment_dontcare; // It's okay to append because we acquired the rhs // of the large buf. t_o_largebuf->append(sizeof(tao), &refsize_adjustment_dontcare); t_o_largebuf->fill_at(t_o_ref->size - sizeof(tao), &tao, sizeof(tao)); } } if (will_want_to_dequeue && t_o_ref->size >= int64_t(2 * sizeof(second_tao))) { boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write)); co_acquire_large_buf_slice(saver, t_o_largebuf.get(), 0, 2 * sizeof(second_tao)); t_o_largebuf->read_at(sizeof(second_tao), &second_tao, sizeof(second_tao)); will_actually_dequeue = true; // It's okay to unprepend because we acquired the lhs of the large buf. int refsize_adjustment_dontcare; t_o_largebuf->unprepend(sizeof(second_tao), &refsize_adjustment_dontcare); } } } // Update the keys list. { lbref_limit_t reflimit = lbref_limit_t(delete_queue::keys_largebuf_ref_size((*txor)->cache->get_block_size())); int64_t amount_to_unprepend = will_actually_dequeue ? second_tao.offset - *primal_offset : 0; large_buf_t::co_enqueue(txor, keys_ref, reflimit, amount_to_unprepend, key, 1 + key->size); *primal_offset += amount_to_unprepend; } } bool dump_keys_from_delete_queue(boost::shared_ptr<transactor_t>& txor, block_id_t queue_root_id, repli_timestamp begin_timestamp, deletion_key_stream_receiver_t *recipient) { thread_saver_t saver; // Beware: Right now, some aspects of correctness depend on the // fact that we hold the queue_root lock for the entire operation. buf_lock_t queue_root(saver, *txor, queue_root_id, rwi_read); void *queue_root_buf = const_cast<void *>(queue_root->get_data_read()); off64_t *primal_offset = delete_queue::primal_offset(queue_root_buf); large_buf_ref *t_o_ref = delete_queue::timestamps_and_offsets_largebuf(queue_root_buf); large_buf_ref *keys_ref = delete_queue::keys_largebuf(queue_root_buf); if (t_o_ref->size != 0 && keys_ref->size != 0) { rassert(t_o_ref->size % sizeof(delete_queue::t_and_o) == 0); // TODO: DON'T hold the queue_root lock for the entire operation. Sheesh. int64_t begin_offset = 0; int64_t end_offset = keys_ref->size; { boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_read)); co_acquire_large_buf(saver, t_o_largebuf.get()); delete_queue::t_and_o tao; int64_t i = 0, ie = t_o_ref->size; bool begin_found = false; while (i < ie) { t_o_largebuf->read_at(i, &tao, sizeof(tao)); if (!begin_found && begin_timestamp.time <= tao.timestamp.time) { begin_offset = tao.offset - *primal_offset; begin_found = true; break; } i += sizeof(tao); } if (!begin_found && ie > 0 && begin_timestamp.time > tao.timestamp.time) { begin_offset = end_offset; begin_found = true; } if (!recipient->should_send_deletion_keys(begin_found)) { return false; } // So we have a begin_offset and an end_offset. } rassert(begin_offset <= end_offset); if (begin_offset < end_offset) { boost::scoped_ptr<large_buf_t> keys_largebuf(new large_buf_t(txor, keys_ref, lbref_limit_t(delete_queue::keys_largebuf_ref_size((*txor)->cache->get_block_size())), rwi_read_outdated_ok)); // TODO: acquire subinterval. co_acquire_large_buf_slice(saver, keys_largebuf.get(), begin_offset, end_offset - begin_offset); int64_t n = end_offset - begin_offset; // TODO: don't copy needlessly... sheesh. This is a fake // implementation, make something that actually streams later. scoped_malloc<char> buf(n); keys_largebuf->read_at(begin_offset, buf.get(), n); char *p = buf.get(); char *e = p + n; while (p < e) { btree_key_t *k = reinterpret_cast<btree_key_t *>(p); rassert(k->size + 1 <= e - p); recipient->deletion_key(k); p += k->size + 1; } } } recipient->done_deletion_keys(); return true; } // TODO: maybe this function should be somewhere else. Well, // certainly. Right now we don't have a notion of an "empty" // largebuf, so we'll know that we have to ->allocate the largebuf // when we see a size of 0 in the large_buf_ref. void initialize_large_buf_ref(large_buf_ref *ref, int size_in_bytes) { int ids_bytes = size_in_bytes - offsetof(large_buf_ref, block_ids); rassert(ids_bytes > 0); ref->offset = 0; ref->size = 0; for (int i = 0, e = ids_bytes / sizeof(block_id_t); i < e; ++i) { ref->block_ids[i] = NULL_BLOCK_ID; } } void initialize_empty_delete_queue(delete_queue_block_t *dqb, block_size_t block_size) { dqb->magic = delete_queue_block_t::expected_magic; *delete_queue::primal_offset(dqb) = 0; large_buf_ref *t_and_o = delete_queue::timestamps_and_offsets_largebuf(dqb); initialize_large_buf_ref(t_and_o, delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE); large_buf_ref *k = delete_queue::keys_largebuf(dqb); initialize_large_buf_ref(k, delete_queue::keys_largebuf_ref_size(block_size)); } const block_magic_t delete_queue_block_t::expected_magic = { { 'D', 'e', 'l', 'Q' } }; } // namespace replication <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formsimp.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-04-11 13:27:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_FORMSIMP_HXX #define _XMLOFF_FORMSIMP_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif ////////////////////////////////////////////////////////////////////////////// // presentations:animations class XMLFormsContext : public SvXMLImportContext { public: TYPEINFO(); XMLFormsContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName); virtual ~XMLFormsContext(); virtual SvXMLImportContext * CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList ); }; #endif // _XMLOFF_ANIMIMP_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.2.212); FILE MERGED 2008/04/01 13:04:26 thb 1.2.212.2: #i85898# Stripping all external header guards 2008/03/31 16:27:57 rt 1.2.212.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formsimp.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _XMLOFF_FORMSIMP_HXX #define _XMLOFF_FORMSIMP_HXX #include <xmloff/xmlictxt.hxx> ////////////////////////////////////////////////////////////////////////////// // presentations:animations class XMLFormsContext : public SvXMLImportContext { public: TYPEINFO(); XMLFormsContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName); virtual ~XMLFormsContext(); virtual SvXMLImportContext * CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList ); }; #endif // _XMLOFF_ANIMIMP_HXX <|endoftext|>
<commit_before>/* * Copyright (C) 2018 The Android Open Source Project * * 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 "PlatformWGL.h" #include <Wingdi.h> #include "OpenGLDriverFactory.h" #ifdef _MSC_VER // this variable is checked in BlueGL.h (included from "gl_headers.h" right after this), // and prevents duplicate definition of OpenGL apis when building this file. // However, GL_GLEXT_PROTOTYPES need to be defined in BlueGL.h when included from other files. #define FILAMENT_PLATFORM_WGL #endif #include "gl_headers.h" #include "Windows.h" #include <GL/gl.h> #include "GL/glext.h" #include "GL/wglext.h" #include <utils/Log.h> #include <utils/Panic.h> namespace { void reportLastWindowsError() { LPSTR lpMessageBuffer = nullptr; DWORD dwError = GetLastError(); if (dwError == 0) { return; } FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), lpMessageBuffer, 0, nullptr ); utils::slog.e << "Windows error code: " << dwError << ". " << lpMessageBuffer << utils::io::endl; LocalFree(lpMessageBuffer); } } // namespace namespace filament { using namespace backend; Driver* PlatformWGL::createDriver(void* const sharedGLContext) noexcept { mPfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, // Flags PFD_TYPE_RGBA, // The kind of framebuffer. RGBA or palette. 32, // Colordepth of the framebuffer. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, // Number of bits for the depthbuffer 0, // Number of bits for the stencilbuffer 0, // Number of Aux buffers in the framebuffer. PFD_MAIN_PLANE, 0, 0, 0, 0 }; int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_PROFILE_MASK_ARB, 0 }; HGLRC tempContext = NULL; mHWnd = CreateWindowA("STATIC", "dummy", 0, 0, 0, 1, 1, NULL, NULL, NULL, NULL); HDC whdc = mWhdc = GetDC(mHWnd); if (whdc == NULL) { utils::slog.e << "CreateWindowA() failed" << utils::io::endl; goto error; } int pixelFormat = ChoosePixelFormat(whdc, &mPfd); SetPixelFormat(whdc, pixelFormat, &mPfd); // We need a tmp context to retrieve and call wglCreateContextAttribsARB. tempContext = wglCreateContext(whdc); if (!wglMakeCurrent(whdc, tempContext)) { utils::slog.e << "wglMakeCurrent() failed, whdc=" << whdc << ", tempContext=" << tempContext << utils::io::endl; goto error; } PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribs = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB"); mContext = wglCreateContextAttribs(whdc, (HGLRC) sharedGLContext, attribs); if (!mContext) { utils::slog.e << "wglCreateContextAttribs() failed, whdc=" << whdc << utils::io::endl; goto error; } wglMakeCurrent(NULL, NULL); wglDeleteContext(tempContext); tempContext = NULL; if (!wglMakeCurrent(whdc, mContext)) { utils::slog.e << "wglMakeCurrent() failed, whdc=" << whdc << ", mContext=" << mContext << utils::io::endl; goto error; } int result = bluegl::bind(); ASSERT_POSTCONDITION(!result, "Unable to load OpenGL entry points."); return OpenGLDriverFactory::create(this, sharedGLContext); error: if (tempContext) { wglDeleteContext(tempContext); } reportLastWindowsError(); terminate(); return NULL; } void PlatformWGL::terminate() noexcept { wglMakeCurrent(NULL, NULL); if (mContext) { wglDeleteContext(mContext); mContext = NULL; } if (mHWnd && mWhdc) { ReleaseDC(mHWnd, mWhdc); DestroyWindow(mHWnd); mHWnd = NULL; mWhdc = NULL; } else if (mHWnd) { DestroyWindow(mHWnd); mHWnd = NULL; } bluegl::unbind(); } Platform::SwapChain* PlatformWGL::createSwapChain(void* nativeWindow, uint64_t& flags) noexcept { // on Windows, the nativeWindow maps to a HWND HDC hdc = GetDC((HWND) nativeWindow); if (!ASSERT_POSTCONDITION_NON_FATAL(hdc, "Unable to create the SwapChain (nativeWindow = %p)", nativeWindow)) { reportLastWindowsError(); } // We have to match pixel formats across the HDC and HGLRC (mContext) int pixelFormat = ChoosePixelFormat(hdc, &mPfd); SetPixelFormat(hdc, pixelFormat, &mPfd); SwapChain* swapChain = (SwapChain*) hdc; return swapChain; } Platform::SwapChain* PlatformWGL::createSwapChain(uint32_t width, uint32_t height, uint64_t& flags) noexcept { // TODO: implement headless SwapChain return nullptr; } void PlatformWGL::destroySwapChain(Platform::SwapChain* swapChain) noexcept { HDC dc = (HDC) swapChain; HWND window = WindowFromDC(dc); ReleaseDC(window, dc); // make this swapChain not current (by making a dummy one current) wglMakeCurrent(mWhdc, mContext); } void PlatformWGL::makeCurrent(Platform::SwapChain* drawSwapChain, Platform::SwapChain* readSwapChain) noexcept { ASSERT_PRECONDITION_NON_FATAL(drawSwapChain == readSwapChain, "PlatformWGL does not support distinct draw/read swap chains."); HDC hdc = (HDC)(drawSwapChain); if (hdc != NULL) { BOOL success = wglMakeCurrent(hdc, mContext); if (!ASSERT_POSTCONDITION_NON_FATAL(success, "wglMakeCurrent() failed. hdc = %p", hdc)) { reportLastWindowsError(); wglMakeCurrent(0, NULL); } } } void PlatformWGL::commit(Platform::SwapChain* swapChain) noexcept { HDC hdc = (HDC)(swapChain); if (hdc != NULL) { SwapBuffers(hdc); } } //TODO Implement WGL fences Platform::Fence* PlatformWGL::createFence() noexcept { return nullptr; } void PlatformWGL::destroyFence(Fence* fence) noexcept { } backend::FenceStatus PlatformWGL::waitFence(Fence* fence, uint64_t timeout) noexcept { return backend::FenceStatus::ERROR; } } // namespace filament <commit_msg>Implement headless swapchains on Windows (#2374)<commit_after>/* * Copyright (C) 2018 The Android Open Source Project * * 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 "PlatformWGL.h" #include <Wingdi.h> #include "OpenGLDriverFactory.h" #ifdef _MSC_VER // this variable is checked in BlueGL.h (included from "gl_headers.h" right after this), // and prevents duplicate definition of OpenGL apis when building this file. // However, GL_GLEXT_PROTOTYPES need to be defined in BlueGL.h when included from other files. #define FILAMENT_PLATFORM_WGL #endif #include "gl_headers.h" #include "Windows.h" #include <GL/gl.h> #include "GL/glext.h" #include "GL/wglext.h" #include <utils/Log.h> #include <utils/Panic.h> namespace { void reportLastWindowsError() { LPSTR lpMessageBuffer = nullptr; DWORD dwError = GetLastError(); if (dwError == 0) { return; } FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), lpMessageBuffer, 0, nullptr ); utils::slog.e << "Windows error code: " << dwError << ". " << lpMessageBuffer << utils::io::endl; LocalFree(lpMessageBuffer); } } // namespace namespace filament { using namespace backend; struct WGLSwapChain { HDC hDc = NULL; HWND hWnd = NULL; bool isHeadless = false; }; Driver* PlatformWGL::createDriver(void* const sharedGLContext) noexcept { mPfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, // Flags PFD_TYPE_RGBA, // The kind of framebuffer. RGBA or palette. 32, // Colordepth of the framebuffer. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, // Number of bits for the depthbuffer 0, // Number of bits for the stencilbuffer 0, // Number of Aux buffers in the framebuffer. PFD_MAIN_PLANE, 0, 0, 0, 0 }; int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_PROFILE_MASK_ARB, 0 }; HGLRC tempContext = NULL; mHWnd = CreateWindowA("STATIC", "dummy", 0, 0, 0, 1, 1, NULL, NULL, NULL, NULL); HDC whdc = mWhdc = GetDC(mHWnd); if (whdc == NULL) { utils::slog.e << "CreateWindowA() failed" << utils::io::endl; goto error; } int pixelFormat = ChoosePixelFormat(whdc, &mPfd); SetPixelFormat(whdc, pixelFormat, &mPfd); // We need a tmp context to retrieve and call wglCreateContextAttribsARB. tempContext = wglCreateContext(whdc); if (!wglMakeCurrent(whdc, tempContext)) { utils::slog.e << "wglMakeCurrent() failed, whdc=" << whdc << ", tempContext=" << tempContext << utils::io::endl; goto error; } PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribs = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB"); mContext = wglCreateContextAttribs(whdc, (HGLRC) sharedGLContext, attribs); if (!mContext) { utils::slog.e << "wglCreateContextAttribs() failed, whdc=" << whdc << utils::io::endl; goto error; } wglMakeCurrent(NULL, NULL); wglDeleteContext(tempContext); tempContext = NULL; if (!wglMakeCurrent(whdc, mContext)) { utils::slog.e << "wglMakeCurrent() failed, whdc=" << whdc << ", mContext=" << mContext << utils::io::endl; goto error; } int result = bluegl::bind(); ASSERT_POSTCONDITION(!result, "Unable to load OpenGL entry points."); return OpenGLDriverFactory::create(this, sharedGLContext); error: if (tempContext) { wglDeleteContext(tempContext); } reportLastWindowsError(); terminate(); return NULL; } void PlatformWGL::terminate() noexcept { wglMakeCurrent(NULL, NULL); if (mContext) { wglDeleteContext(mContext); mContext = NULL; } if (mHWnd && mWhdc) { ReleaseDC(mHWnd, mWhdc); DestroyWindow(mHWnd); mHWnd = NULL; mWhdc = NULL; } else if (mHWnd) { DestroyWindow(mHWnd); mHWnd = NULL; } bluegl::unbind(); } Platform::SwapChain* PlatformWGL::createSwapChain(void* nativeWindow, uint64_t& flags) noexcept { auto* swapChain = new WGLSwapChain(); swapChain->isHeadless = false; // on Windows, the nativeWindow maps to a HWND swapChain->hWnd = (HWND) nativeWindow; swapChain->hDc = GetDC(swapChain->hWnd); if (!ASSERT_POSTCONDITION_NON_FATAL(swapChain->hDc, "Unable to create the SwapChain (nativeWindow = %p)", nativeWindow)) { reportLastWindowsError(); } // We have to match pixel formats across the HDC and HGLRC (mContext) int pixelFormat = ChoosePixelFormat(swapChain->hDc, &mPfd); SetPixelFormat(swapChain->hDc, pixelFormat, &mPfd); return (Platform::SwapChain*) swapChain; } Platform::SwapChain* PlatformWGL::createSwapChain(uint32_t width, uint32_t height, uint64_t& flags) noexcept { auto* swapChain = new WGLSwapChain(); swapChain->isHeadless = true; // WS_POPUP was chosen for the window style here after some experimentation. // For some reason, using other window styles resulted in corrupted pixel buffers when using // readPixels. RECT rect = {0, 0, width, height}; AdjustWindowRect(&rect, WS_POPUP, FALSE); width = rect.right - rect.left; height = rect.bottom - rect.top; swapChain->hWnd = CreateWindowA("STATIC", "headless", WS_POPUP, 0, 0, width, height, NULL, NULL, NULL, NULL); swapChain->hDc = GetDC(swapChain->hWnd); int pixelFormat = ChoosePixelFormat(swapChain->hDc, &mPfd); SetPixelFormat(swapChain->hDc, pixelFormat, &mPfd); return (Platform::SwapChain*) swapChain; } void PlatformWGL::destroySwapChain(Platform::SwapChain* swapChain) noexcept { auto* wglSwapChain = (WGLSwapChain*) swapChain; HDC dc = wglSwapChain->hDc; HWND window = wglSwapChain->hWnd; ReleaseDC(window, dc); if (wglSwapChain->isHeadless) { DestroyWindow(window); } delete wglSwapChain; // make this swapChain not current (by making a dummy one current) wglMakeCurrent(mWhdc, mContext); } void PlatformWGL::makeCurrent(Platform::SwapChain* drawSwapChain, Platform::SwapChain* readSwapChain) noexcept { ASSERT_PRECONDITION_NON_FATAL(drawSwapChain == readSwapChain, "PlatformWGL does not support distinct draw/read swap chains."); auto* wglSwapChain = (WGLSwapChain*) drawSwapChain; HDC hdc = wglSwapChain->hDc; if (hdc != NULL) { BOOL success = wglMakeCurrent(hdc, mContext); if (!ASSERT_POSTCONDITION_NON_FATAL(success, "wglMakeCurrent() failed. hdc = %p", hdc)) { reportLastWindowsError(); wglMakeCurrent(0, NULL); } } } void PlatformWGL::commit(Platform::SwapChain* swapChain) noexcept { auto* wglSwapChain = (WGLSwapChain*) swapChain; HDC hdc = wglSwapChain->hDc; if (hdc != NULL) { SwapBuffers(hdc); } } //TODO Implement WGL fences Platform::Fence* PlatformWGL::createFence() noexcept { return nullptr; } void PlatformWGL::destroyFence(Fence* fence) noexcept { } backend::FenceStatus PlatformWGL::waitFence(Fence* fence, uint64_t timeout) noexcept { return backend::FenceStatus::ERROR; } } // namespace filament <|endoftext|>
<commit_before>/** * This is an open source non-commercial project. Dear PVS-Studio, please check it. * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com * * @file FileProviderList.cpp * @brief * @details * @date Created on 06.12.2016 * @copyright 2016 DDwarf LLC, <dev@ddwarf.org> * @author Gilmanov Ildar <dev@ddwarf.org> */ #include <QDebug> #include <QtQml> #include "FileProviderList.h" #include "FileProvider.h" namespace DDwarf { namespace Files { FileProviderList *FileProviderList::m_instance = nullptr; FileProviderList *FileProviderList::initStatic() { if(m_instance) { qWarning().noquote() << QString("FileProviderList is already initialized"); return m_instance; } m_instance = new FileProviderList(); qmlRegisterSingletonType<FileProviderList>("org.ddwarf.files", 1, 0, "FileProviderList", &FileProviderList::fileProviderListProvider); qmlRegisterType<FileProvider>("org.ddwarf.files", 1, 0, "FileProvider"); return m_instance; } FileProviderList *FileProviderList::instance() { return m_instance; } FileProviderList::FileProviderList(QObject *parent) : QAbstractListModel(parent) { m_roles.insert(Qt::UserRole, "modelData"); int index = Qt::UserRole + 1; for(int i = 0; i < FileProvider::staticMetaObject.propertyCount(); ++i) { QMetaProperty prop = FileProvider::staticMetaObject.property(i); if(prop.isReadable()) { m_roles.insert(index, prop.name()); ++index; } } } QObject *FileProviderList::fileProviderListProvider(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) return m_instance; } int FileProviderList::rowCount(const QModelIndex &parent) const { if(parent.isValid()) { return 0; } return m_list.count(); } QVariant FileProviderList::data(const QModelIndex &index, int role) const { if(!index.isValid()) { return QVariant(); } FileProvider *item = at(index.row()); if(item) { if(role != Qt::UserRole && m_roles.contains(role)) { int propIndex = item->metaObject()->indexOfProperty(m_roles.value(role)); if(propIndex >= 0 && propIndex < item->metaObject()->propertyCount()) { item->metaObject()->property(propIndex).read(item); } } return QVariant::fromValue(item); } else { return QVariant(); } } QHash<int, QByteArray> FileProviderList::roleNames() const { return m_roles; } int FileProviderList::length() const { return m_list.count(); } void FileProviderList::append(FileProvider *item) { if(!m_list.contains(item)) { beginInsertRows(QModelIndex(), m_list.count(), m_list.count()); item->setParent(this); m_list.push_back(item); emit listChanged(); endInsertRows(); } } void FileProviderList::insert(int index, FileProvider *item) { if(!m_list.contains(item)) { beginInsertRows(QModelIndex(), index, index); item->setParent(this); m_list.insert(index, item); emit listChanged(); endInsertRows(); } } void FileProviderList::remove(FileProvider *item) { int index = m_list.indexOf(item); if(index >= 0) { removeAt(index); } else { qWarning().noquote() << "Can not find IFileProvider to remove"; } } void FileProviderList::removeAt(int index) { if(index >= 0 && index < m_list.count()) { beginRemoveRows(QModelIndex(), index, index); m_list.takeAt(index)->deleteLater(); emit listChanged(); endRemoveRows(); } else { qWarning().noquote() << QString("index %1 is out of range [0, %2]") .arg(index) .arg(m_list.count()); } } void FileProviderList::clear() { if(!m_list.isEmpty()) { beginResetModel(); while(!m_list.isEmpty()) { m_list.takeFirst()->deleteLater(); } emit listChanged(); endResetModel(); } } FileProvider *FileProviderList::at(int index) const { if(index >= 0 && index < m_list.count()) { return m_list.at(index); } else { qWarning().noquote() << QString("index %1 is out of range [0, %2]") .arg(index) .arg(m_list.count()); return nullptr; } } } // namespace Files } // namespace DDwarf <commit_msg>add additional checks to FileProviderList::data() method<commit_after>/** * This is an open source non-commercial project. Dear PVS-Studio, please check it. * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com * * @file FileProviderList.cpp * @brief * @details * @date Created on 06.12.2016 * @copyright 2016 DDwarf LLC, <dev@ddwarf.org> * @author Gilmanov Ildar <dev@ddwarf.org> */ #include <QDebug> #include <QtQml> #include "FileProviderList.h" #include "FileProvider.h" namespace DDwarf { namespace Files { FileProviderList *FileProviderList::m_instance = nullptr; FileProviderList *FileProviderList::initStatic() { if(m_instance) { qWarning().noquote() << QString("FileProviderList is already initialized"); return m_instance; } m_instance = new FileProviderList(); qmlRegisterSingletonType<FileProviderList>("org.ddwarf.files", 1, 0, "FileProviderList", &FileProviderList::fileProviderListProvider); qmlRegisterType<FileProvider>("org.ddwarf.files", 1, 0, "FileProvider"); return m_instance; } FileProviderList *FileProviderList::instance() { return m_instance; } FileProviderList::FileProviderList(QObject *parent) : QAbstractListModel(parent) { m_roles.insert(Qt::UserRole, "modelData"); int index = Qt::UserRole + 1; for(int i = 0; i < FileProvider::staticMetaObject.propertyCount(); ++i) { QMetaProperty prop = FileProvider::staticMetaObject.property(i); if(prop.isReadable()) { m_roles.insert(index, prop.name()); ++index; } } } QObject *FileProviderList::fileProviderListProvider(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) return m_instance; } int FileProviderList::rowCount(const QModelIndex &parent) const { if(parent.isValid()) { return 0; } return m_list.count(); } QVariant FileProviderList::data(const QModelIndex &index, int role) const { if(!index.isValid()) { return QVariant(); } FileProvider *item = at(index.row()); if(item) { if(role == Qt::UserRole) { return QVariant::fromValue(item); } else if(m_roles.contains(role)) { int propIndex = item->metaObject()->indexOfProperty(m_roles.value(role)); if(propIndex >= 0 && propIndex < item->metaObject()->propertyCount()) { return item->metaObject()->property(propIndex).read(item); } else { qWarning().noquote() << QString("Can not find role '%1'") .arg(QString(m_roles.value(role))); return QVariant(); } } else { qWarning().noquote() << QString("Can not recognize role '%1'").arg(role); return QVariant(); } } else { return QVariant(); } } QHash<int, QByteArray> FileProviderList::roleNames() const { return m_roles; } int FileProviderList::length() const { return m_list.count(); } void FileProviderList::append(FileProvider *item) { if(!m_list.contains(item)) { beginInsertRows(QModelIndex(), m_list.count(), m_list.count()); item->setParent(this); m_list.push_back(item); emit listChanged(); endInsertRows(); } } void FileProviderList::insert(int index, FileProvider *item) { if(!m_list.contains(item)) { beginInsertRows(QModelIndex(), index, index); item->setParent(this); m_list.insert(index, item); emit listChanged(); endInsertRows(); } } void FileProviderList::remove(FileProvider *item) { int index = m_list.indexOf(item); if(index >= 0) { removeAt(index); } else { qWarning().noquote() << "Can not find IFileProvider to remove"; } } void FileProviderList::removeAt(int index) { if(index >= 0 && index < m_list.count()) { beginRemoveRows(QModelIndex(), index, index); m_list.takeAt(index)->deleteLater(); emit listChanged(); endRemoveRows(); } else { qWarning().noquote() << QString("index %1 is out of range [0, %2]") .arg(index) .arg(m_list.count()); } } void FileProviderList::clear() { if(!m_list.isEmpty()) { beginResetModel(); while(!m_list.isEmpty()) { m_list.takeFirst()->deleteLater(); } emit listChanged(); endResetModel(); } } FileProvider *FileProviderList::at(int index) const { if(index >= 0 && index < m_list.count()) { return m_list.at(index); } else { qWarning().noquote() << QString("index %1 is out of range [0, %2]") .arg(index) .arg(m_list.count()); return nullptr; } } } // namespace Files } // namespace DDwarf <|endoftext|>
<commit_before>/* Drawing Area * * Gtk::DrawingArea is a blank area where you can draw custom displays * of various kinds. * * This demo has two drawing areas. The checkerboard area shows * how you can just draw something; all you have to do is write * a draw function, as shown here. * * The "scribble" area is a bit more advanced, and shows how to handle * events such as button presses and mouse motion. Click the mouse * and drag in the scribble area to draw squiggles. Resize the window * to clear the area. */ //TODO: Remove this undef when we know what to use instead of // signal_motion_notify_event() and signal_button_release_event(). #undef GTKMM_DISABLE_DEPRECATED #include <gtkmm.h> class Example_DrawingArea : public Gtk::Window { public: Example_DrawingArea(); ~Example_DrawingArea() override; protected: //draw functions: void on_drawingarea_checkerboard_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height); void on_drawingarea_scribble_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height); //signal handlers: void on_drawingarea_scribble_size_allocate(const Gtk::Allocation& allocation, int baseline, Gtk::Allocation& out_clip); bool on_drawingarea_scribble_motion_notify_event(Gdk::EventMotion& event); bool on_drawingarea_scribble_button_press_event(Gdk::EventButton& event); void scribble_create_surface(); void scribble_draw_brush(double x, double y); //Member widgets: Gtk::Frame m_Frame_Checkerboard, m_Frame_Scribble; Gtk::Box m_VBox; Gtk::Label m_Label_Checkerboard, m_Label_Scribble; Gtk::DrawingArea m_DrawingArea_Checkerboard, m_DrawingArea_Scribble; Cairo::RefPtr<Cairo::ImageSurface> m_surface; }; //Called by DemoWindow; Gtk::Window* do_drawingarea() { return new Example_DrawingArea(); } Example_DrawingArea::Example_DrawingArea() : m_VBox(Gtk::Orientation::VERTICAL, 8) { set_title("Drawing Area"); m_VBox.property_margin() = 16; add(m_VBox); /* * Create the checkerboard area */ m_Label_Checkerboard.set_markup("<u>Checkerboard pattern</u>"); m_VBox.pack_start(m_Label_Checkerboard, Gtk::PackOptions::SHRINK); m_Frame_Checkerboard.set_shadow_type(Gtk::ShadowType::IN); m_VBox.pack_start(m_Frame_Checkerboard, Gtk::PackOptions::EXPAND_WIDGET); /* set a minimum size */ m_DrawingArea_Checkerboard.set_content_width(100); m_DrawingArea_Checkerboard.set_content_height(100); m_Frame_Checkerboard.add(m_DrawingArea_Checkerboard); m_DrawingArea_Checkerboard.set_draw_func( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_checkerboard_draw)); /* * Create the scribble area */ m_Label_Scribble.set_markup("<u>Scribble area</u>"); m_VBox.pack_start(m_Label_Scribble, Gtk::PackOptions::SHRINK); m_Frame_Scribble.set_shadow_type(Gtk::ShadowType::IN); m_VBox.pack_start(m_Frame_Scribble, Gtk::PackOptions::EXPAND_WIDGET); /* set a minimum size */ m_DrawingArea_Scribble.set_content_width(100); m_DrawingArea_Scribble.set_content_height(100); m_Frame_Scribble.add(m_DrawingArea_Scribble); m_DrawingArea_Scribble.set_draw_func( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_scribble_draw)); m_DrawingArea_Scribble.signal_size_allocate().connect( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_scribble_size_allocate)); /* Event signals */ m_DrawingArea_Scribble.signal_motion_notify_event().connect( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_scribble_motion_notify_event), false); m_DrawingArea_Scribble.signal_button_press_event().connect( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_scribble_button_press_event), false); } Example_DrawingArea::~Example_DrawingArea() { } void Example_DrawingArea::on_drawingarea_checkerboard_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height) { enum { CHECK_SIZE = 10, SPACING = 2 }; /* At the start of a draw handler, a clip region has been set on * the Cairo context, and the contents have been cleared to the * widget's background color. The docs for * Gdk::Window::begin_paint_region() give more details on how this * works. */ int xcount = 0; int i = SPACING; while (i < width) { int j = SPACING; int ycount = xcount % 2; /* start with even/odd depending on row */ while (j < height) { if (ycount % 2) cr->set_source_rgb(0.45777, 0, 0.45777); else cr->set_source_rgb(1, 1, 1); /* If we're outside event->area, this will do nothing. * It might be mildly more efficient if we handled * the clipping ourselves, but again we're feeling lazy. */ cr->rectangle(i, j, CHECK_SIZE, CHECK_SIZE); cr->fill(); j += CHECK_SIZE + SPACING; ++ycount; } i += CHECK_SIZE + SPACING; ++xcount; } } void Example_DrawingArea::on_drawingarea_scribble_draw(const Cairo::RefPtr<Cairo::Context>& cr, int, int) { cr->set_source(m_surface, 0, 0); cr->paint(); } // Create a new surface of the appropriate size to store our scribbles. void Example_DrawingArea::scribble_create_surface() { const auto allocation = m_DrawingArea_Scribble.get_allocation(); m_surface = Cairo::ImageSurface::create(Cairo::Surface::Format::ARGB32, allocation.get_width(), allocation.get_height()); // Initialize the surface to white. auto cr = Cairo::Context::create(m_surface); cr->set_source_rgb(1, 1, 1); cr->paint(); } void Example_DrawingArea::on_drawingarea_scribble_size_allocate( const Gtk::Allocation& /* allocation */, int /* baseline */, Gtk::Allocation& /* out_clip */) { scribble_create_surface(); } bool Example_DrawingArea::on_drawingarea_scribble_motion_notify_event(Gdk::EventMotion& motion_event) { if ((motion_event.get_state() & Gdk::ModifierType::BUTTON1_MASK) == Gdk::ModifierType::BUTTON1_MASK) { double x = 0.0; double y = 0.0; motion_event.get_coords(x, y); scribble_draw_brush(x, y); } // We've handled it, stop processing. return true; } bool Example_DrawingArea::on_drawingarea_scribble_button_press_event(Gdk::EventButton& button_event) { if (button_event.get_button() == GDK_BUTTON_PRIMARY) { double x = 0.0; double y = 0.0; button_event.get_coords(x, y); scribble_draw_brush(x, y); } // We've handled the event, stop processing. return true; } // Draw a rectangle on the screen. void Example_DrawingArea::scribble_draw_brush(double x, double y) { if (!m_surface || m_surface->get_width() != m_DrawingArea_Scribble.get_allocated_width() || m_surface->get_height() != m_DrawingArea_Scribble.get_allocated_height()) scribble_create_surface(); const Gdk::Rectangle update_rect((int)x - 3, (int)y - 3, 6, 6); // Paint to the surface, where we store our state. auto cr = Cairo::Context::create(m_surface); Gdk::Cairo::add_rectangle_to_path(cr, update_rect); cr->fill(); m_DrawingArea_Scribble.queue_draw_area(update_rect.get_x(), update_rect.get_y(), update_rect.get_width(), update_rect.get_height()); } <commit_msg>Update the DrawingArea demo<commit_after>/* Drawing Area * * Gtk::DrawingArea is a blank area where you can draw custom displays * of various kinds. * * This demo has two drawing areas. The checkerboard area shows * how you can just draw something; all you have to do is write * a draw function, as shown here. * * The "scribble" area is a bit more advanced, and shows how to handle * events such as button presses and mouse motion. Click the mouse * and drag in the scribble area to draw squiggles. Resize the window * to clear the area. */ #include <gtkmm.h> class Example_DrawingArea : public Gtk::Window { public: Example_DrawingArea(); ~Example_DrawingArea() override; protected: //draw functions: void on_drawingarea_checkerboard_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height); void on_drawingarea_scribble_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height); //signal handlers: void on_drawingarea_scribble_size_allocate(const Gtk::Allocation& allocation, int baseline, Gtk::Allocation& out_clip); void on_drawingarea_scribble_drag_begin(double start_x, double start_y); void on_drawingarea_scribble_drag_update(double offset_x, double offset_y); void on_drawingarea_scribble_drag_end(double offset_x, double offset_y); void scribble_create_surface(); void scribble_draw_brush(double x, double y); //Member widgets: Gtk::Frame m_Frame_Checkerboard, m_Frame_Scribble; Gtk::Box m_VBox; Gtk::Label m_Label_Checkerboard, m_Label_Scribble; Gtk::DrawingArea m_DrawingArea_Checkerboard, m_DrawingArea_Scribble; Cairo::RefPtr<Cairo::ImageSurface> m_surface; Glib::RefPtr<Gtk::GestureDrag> m_drag; double m_start_x = 0.0; double m_start_y = 0.0; }; //Called by DemoWindow; Gtk::Window* do_drawingarea() { return new Example_DrawingArea(); } Example_DrawingArea::Example_DrawingArea() : m_VBox(Gtk::Orientation::VERTICAL, 8) { set_title("Drawing Area"); m_VBox.property_margin() = 16; add(m_VBox); /* * Create the checkerboard area */ m_Label_Checkerboard.set_markup("<u>Checkerboard pattern</u>"); m_VBox.pack_start(m_Label_Checkerboard, Gtk::PackOptions::SHRINK); m_Frame_Checkerboard.set_shadow_type(Gtk::ShadowType::IN); m_VBox.pack_start(m_Frame_Checkerboard, Gtk::PackOptions::EXPAND_WIDGET); /* set a minimum size */ m_DrawingArea_Checkerboard.set_content_width(100); m_DrawingArea_Checkerboard.set_content_height(100); m_Frame_Checkerboard.add(m_DrawingArea_Checkerboard); m_DrawingArea_Checkerboard.set_draw_func( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_checkerboard_draw)); /* * Create the scribble area */ m_Label_Scribble.set_markup("<u>Scribble area</u>"); m_VBox.pack_start(m_Label_Scribble, Gtk::PackOptions::SHRINK); m_Frame_Scribble.set_shadow_type(Gtk::ShadowType::IN); m_VBox.pack_start(m_Frame_Scribble, Gtk::PackOptions::EXPAND_WIDGET); m_drag = Gtk::GestureDrag::create(m_DrawingArea_Scribble); m_drag->set_button(GDK_BUTTON_PRIMARY); /* set a minimum size */ m_DrawingArea_Scribble.set_content_width(100); m_DrawingArea_Scribble.set_content_height(100); m_Frame_Scribble.add(m_DrawingArea_Scribble); m_DrawingArea_Scribble.set_draw_func( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_scribble_draw)); /* Connect signal handlers */ m_DrawingArea_Scribble.signal_size_allocate().connect( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_scribble_size_allocate)); m_drag->signal_drag_begin().connect( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_scribble_drag_begin)); m_drag->signal_drag_update().connect( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_scribble_drag_update)); m_drag->signal_drag_end().connect( sigc::mem_fun(*this, &Example_DrawingArea::on_drawingarea_scribble_drag_end)); } Example_DrawingArea::~Example_DrawingArea() { } void Example_DrawingArea::on_drawingarea_checkerboard_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height) { enum { CHECK_SIZE = 10, SPACING = 2 }; /* At the start of a draw handler, a clip region has been set on * the Cairo context, and the contents have been cleared to the * widget's background color. The docs for * Gdk::Window::begin_paint_region() give more details on how this * works. */ int xcount = 0; int i = SPACING; while (i < width) { int j = SPACING; int ycount = xcount % 2; /* start with even/odd depending on row */ while (j < height) { if (ycount % 2) cr->set_source_rgb(0.45777, 0, 0.45777); else cr->set_source_rgb(1, 1, 1); /* If we're outside event->area, this will do nothing. * It might be mildly more efficient if we handled * the clipping ourselves, but again we're feeling lazy. */ cr->rectangle(i, j, CHECK_SIZE, CHECK_SIZE); cr->fill(); j += CHECK_SIZE + SPACING; ++ycount; } i += CHECK_SIZE + SPACING; ++xcount; } } void Example_DrawingArea::on_drawingarea_scribble_draw(const Cairo::RefPtr<Cairo::Context>& cr, int, int) { cr->set_source(m_surface, 0, 0); cr->paint(); } // Create a new surface of the appropriate size to store our scribbles. void Example_DrawingArea::scribble_create_surface() { m_surface = Cairo::ImageSurface::create(Cairo::Surface::Format::ARGB32, m_DrawingArea_Scribble.get_width(), m_DrawingArea_Scribble.get_height()); // Initialize the surface to white. auto cr = Cairo::Context::create(m_surface); cr->set_source_rgb(1, 1, 1); cr->paint(); } void Example_DrawingArea::on_drawingarea_scribble_size_allocate( const Gtk::Allocation& /* allocation */, int /* baseline */, Gtk::Allocation& /* out_clip */) { scribble_create_surface(); } void Example_DrawingArea::on_drawingarea_scribble_drag_begin(double start_x, double start_y) { m_start_x = start_x; m_start_y = start_y; scribble_draw_brush(m_start_x, m_start_y); } void Example_DrawingArea::on_drawingarea_scribble_drag_update(double offset_x, double offset_y) { scribble_draw_brush(m_start_x + offset_x, m_start_y + offset_y); } void Example_DrawingArea::on_drawingarea_scribble_drag_end(double offset_x, double offset_y) { scribble_draw_brush(m_start_x + offset_x, m_start_y + offset_y); } // Draw a rectangle on the screen. void Example_DrawingArea::scribble_draw_brush(double x, double y) { if (!m_surface || m_surface->get_width() != m_DrawingArea_Scribble.get_width() || m_surface->get_height() != m_DrawingArea_Scribble.get_height()) scribble_create_surface(); const Gdk::Rectangle update_rect((int)x - 3, (int)y - 3, 6, 6); // Paint to the surface, where we store our state. auto cr = Cairo::Context::create(m_surface); Gdk::Cairo::add_rectangle_to_path(cr, update_rect); cr->fill(); m_DrawingArea_Scribble.queue_draw_area(update_rect.get_x(), update_rect.get_y(), update_rect.get_width(), update_rect.get_height()); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: filtertracer.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-01-19 17:47:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _FILTERTRACER_HXX #define _FILTERTRACER_HXX #ifndef __RTL_USTRING_ #include <rtl/ustring> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _STACK_HXX #include <tools/stack.hxx> #endif #include <com/sun/star/uno/Reference.h> #include <com/sun/star/uno/RuntimeException.hpp> #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/registry/XRegistryKey.hpp> #include <com/sun/star/lang/XComponent.hpp> #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE4_HXX_ #include <cppuhelper/implbase4.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_LOGGING_XLOGGER_HPP_ #include <com/sun/star/util/logging/XLogger.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_LOGGING_LOGLEVEL_HPP_ #include <com/sun/star/util/logging/LogLevel.hpp> #endif #ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_ #include <com/sun/star/io/XOutputStream.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XTEXTSEARCH_HPP_ #include <com/sun/star/util/XTextSearch.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHRESULT_HPP_ #include <com/sun/star/util/SearchResult.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif // ----------------------------------------------------------------------------- #define NMSP_IO com::sun::star::io #define NMSP_UNO com::sun::star::uno #define NMSP_BEANS com::sun::star::beans #define NMSP_LANG com::sun::star::lang #define NMSP_UTIL com::sun::star::util #define NMSP_SAX com::sun::star::xml::sax #define NMSP_LOGGING NMSP_UTIL::logging #define REF( _def_Obj ) NMSP_UNO::Reference< _def_Obj > #define SEQ( _def_Obj ) NMSP_UNO::Sequence< _def_Obj > #define B2UCONST( _def_pChar ) (rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar ))) // ---------------- // - FILTERTRACER - // ---------------- // /** Some options of the FilterTracer can be initialized via XInitialization interface. Therefore the first sequence of PropertyValues that is given in the argument list is used. Following Properties are supported: OutputStream com.sun.star.io.XOutputStream Defines the output stream. Optional it is possible to provide the URL property, then the corresponding output stream will be generated automatically. URL string Defines the URL, which is used to create an output stream. This property is used only, if there is no valid OutputStream property available. DocumentHandler com.sun.star.xml.sax.XDocumentHandler The output can also be written to a DocumentHandler, then the "characters" method of the handler is used. LogLevel long Defines the LogLevel for the FilterTracer. Using logp with a LogLevel that is higher as the LogLevel for the FilterTracer component will generate no output. LogLevel constants are defined in sun::star::util::logging::LogLevel The default LogLevel com::sun::star::logging::LogLevel::ALL ClassFilter string This property defines a filter for the SourceClass string of logp. The ClassFilter string can be separated into multiple tokens using a semicolon. If one of the ClassFilter token is part of the SourceClass string of the logp method then there will be no output. MethodFilter string This property defines a filter for the SourceMethod string of logp. The MethodFilter string can be separated into multiple tokens using a semicolon. If one of the MethodFilter token is part of the SourceMethod string of the logp method then there will be no output. MessageFilter string This property defines a filter for the Message string of logp. The MessageFilter string can be separated into multiple tokens using a semicolon. If one of the MessageFilter token is part of the Message string of the logp method then there will be no output. */ class FilterTracer : public cppu::WeakImplHelper4 < NMSP_LOGGING::XLogger, NMSP_LANG::XInitialization, NMSP_LANG::XServiceInfo, NMSP_UTIL::XTextSearch > { REF( NMSP_LANG::XMultiServiceFactory ) xFact; sal_Int32 mnLogLevel; rtl::OUString msClassFilter; rtl::OUString msMethodFilter; rtl::OUString msMessageFilter; rtl::OUString msURL; SvStream* mpStream; REF( NMSP_IO::XOutputStream ) mxOutputStream; REF( NMSP_SAX::XDocumentHandler) mxDocumentHandler; REF( NMSP_UTIL::XTextSearch ) mxTextSearch; NMSP_UTIL::SearchOptions maSearchOptions; sal_Bool ImplFilter( const rtl::OUString& rFilter, const rtl::OUString& rString ); public: FilterTracer( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr ); virtual ~FilterTracer(); // XInterface virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // XInitialization virtual void SAL_CALL initialize( const SEQ( NMSP_UNO::Any )& aArguments ) throw ( NMSP_UNO::Exception, NMSP_UNO::RuntimeException ); // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName() throw ( NMSP_UNO::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& rServiceName ) throw ( NMSP_UNO::RuntimeException ); virtual SEQ( rtl::OUString ) SAL_CALL getSupportedServiceNames() throw ( NMSP_UNO::RuntimeException ); // XLogger virtual REF( NMSP_LOGGING::XLogger ) SAL_CALL getLogger( const rtl::OUString& rName ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getLevel() throw (::com::sun::star::uno::RuntimeException); virtual rtl::OUString SAL_CALL getName() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isLoggable( sal_Int32 nLevel ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL logp( sal_Int32 nLevel, const rtl::OUString& rSourceClass, const rtl::OUString& rSourceMethod, const rtl::OUString& rMessage ) throw (::com::sun::star::uno::RuntimeException); // XTextSearch virtual void SAL_CALL setOptions( const NMSP_UTIL::SearchOptions& ) throw (::com::sun::star::uno::RuntimeException); virtual NMSP_UTIL::SearchResult SAL_CALL searchForward( const rtl::OUString& rSearchStr, sal_Int32 nStartPos, sal_Int32 nEndPos ) throw (::com::sun::star::uno::RuntimeException); virtual NMSP_UTIL::SearchResult SAL_CALL searchBackward( const rtl::OUString& rSearchStr, sal_Int32 nStartPos, sal_Int32 nEndPos ) throw (::com::sun::star::uno::RuntimeException); }; rtl::OUString FilterTracer_getImplementationName() throw ( NMSP_UNO::RuntimeException ); sal_Bool SAL_CALL FilterTracer_supportsService( const rtl::OUString& rServiceName ) throw( NMSP_UNO::RuntimeException ); SEQ( rtl::OUString ) SAL_CALL FilterTracer_getSupportedServiceNames() throw( NMSP_UNO::RuntimeException ); #endif <commit_msg>INTEGRATION: CWS warnings01 (1.5.78); FILE MERGED 2006/05/12 16:34:22 sb 1.5.78.1: #i53898# Made code warning-free and/or compile at all after resync to SRC680m162.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: filtertracer.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-19 17:10:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _FILTERTRACER_HXX #define _FILTERTRACER_HXX #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _STACK_HXX #include <tools/stack.hxx> #endif #include <com/sun/star/uno/Reference.h> #include <com/sun/star/uno/RuntimeException.hpp> #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/registry/XRegistryKey.hpp> #include <com/sun/star/lang/XComponent.hpp> #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE4_HXX_ #include <cppuhelper/implbase4.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_LOGGING_XLOGGER_HPP_ #include <com/sun/star/util/logging/XLogger.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_LOGGING_LOGLEVEL_HPP_ #include <com/sun/star/util/logging/LogLevel.hpp> #endif #ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_ #include <com/sun/star/io/XOutputStream.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XTEXTSEARCH_HPP_ #include <com/sun/star/util/XTextSearch.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHRESULT_HPP_ #include <com/sun/star/util/SearchResult.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif // ----------------------------------------------------------------------------- #define NMSP_IO com::sun::star::io #define NMSP_UNO com::sun::star::uno #define NMSP_BEANS com::sun::star::beans #define NMSP_LANG com::sun::star::lang #define NMSP_UTIL com::sun::star::util #define NMSP_SAX com::sun::star::xml::sax #define NMSP_LOGGING NMSP_UTIL::logging #define REF( _def_Obj ) NMSP_UNO::Reference< _def_Obj > #define SEQ( _def_Obj ) NMSP_UNO::Sequence< _def_Obj > #define B2UCONST( _def_pChar ) (rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar ))) // ---------------- // - FILTERTRACER - // ---------------- // /** Some options of the FilterTracer can be initialized via XInitialization interface. Therefore the first sequence of PropertyValues that is given in the argument list is used. Following Properties are supported: OutputStream com.sun.star.io.XOutputStream Defines the output stream. Optional it is possible to provide the URL property, then the corresponding output stream will be generated automatically. URL string Defines the URL, which is used to create an output stream. This property is used only, if there is no valid OutputStream property available. DocumentHandler com.sun.star.xml.sax.XDocumentHandler The output can also be written to a DocumentHandler, then the "characters" method of the handler is used. LogLevel long Defines the LogLevel for the FilterTracer. Using logp with a LogLevel that is higher as the LogLevel for the FilterTracer component will generate no output. LogLevel constants are defined in sun::star::util::logging::LogLevel The default LogLevel com::sun::star::logging::LogLevel::ALL ClassFilter string This property defines a filter for the SourceClass string of logp. The ClassFilter string can be separated into multiple tokens using a semicolon. If one of the ClassFilter token is part of the SourceClass string of the logp method then there will be no output. MethodFilter string This property defines a filter for the SourceMethod string of logp. The MethodFilter string can be separated into multiple tokens using a semicolon. If one of the MethodFilter token is part of the SourceMethod string of the logp method then there will be no output. MessageFilter string This property defines a filter for the Message string of logp. The MessageFilter string can be separated into multiple tokens using a semicolon. If one of the MessageFilter token is part of the Message string of the logp method then there will be no output. */ class FilterTracer : public cppu::WeakImplHelper4 < NMSP_LOGGING::XLogger, NMSP_LANG::XInitialization, NMSP_LANG::XServiceInfo, NMSP_UTIL::XTextSearch > { REF( NMSP_LANG::XMultiServiceFactory ) xFact; sal_Int32 mnLogLevel; rtl::OUString msClassFilter; rtl::OUString msMethodFilter; rtl::OUString msMessageFilter; rtl::OUString msURL; SvStream* mpStream; REF( NMSP_IO::XOutputStream ) mxOutputStream; REF( NMSP_SAX::XDocumentHandler) mxDocumentHandler; REF( NMSP_UTIL::XTextSearch ) mxTextSearch; NMSP_UTIL::SearchOptions maSearchOptions; sal_Bool ImplFilter( const rtl::OUString& rFilter, const rtl::OUString& rString ); public: FilterTracer( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr ); virtual ~FilterTracer(); // XInterface virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // XInitialization virtual void SAL_CALL initialize( const SEQ( NMSP_UNO::Any )& aArguments ) throw ( NMSP_UNO::Exception, NMSP_UNO::RuntimeException ); // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName() throw ( NMSP_UNO::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& rServiceName ) throw ( NMSP_UNO::RuntimeException ); virtual SEQ( rtl::OUString ) SAL_CALL getSupportedServiceNames() throw ( NMSP_UNO::RuntimeException ); // XLogger virtual REF( NMSP_LOGGING::XLogger ) SAL_CALL getLogger( const rtl::OUString& rName ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getLevel() throw (::com::sun::star::uno::RuntimeException); virtual rtl::OUString SAL_CALL getName() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isLoggable( sal_Int32 nLevel ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL logp( sal_Int32 nLevel, const rtl::OUString& rSourceClass, const rtl::OUString& rSourceMethod, const rtl::OUString& rMessage ) throw (::com::sun::star::uno::RuntimeException); // XTextSearch virtual void SAL_CALL setOptions( const NMSP_UTIL::SearchOptions& ) throw (::com::sun::star::uno::RuntimeException); virtual NMSP_UTIL::SearchResult SAL_CALL searchForward( const rtl::OUString& rSearchStr, sal_Int32 nStartPos, sal_Int32 nEndPos ) throw (::com::sun::star::uno::RuntimeException); virtual NMSP_UTIL::SearchResult SAL_CALL searchBackward( const rtl::OUString& rSearchStr, sal_Int32 nStartPos, sal_Int32 nEndPos ) throw (::com::sun::star::uno::RuntimeException); }; rtl::OUString FilterTracer_getImplementationName() throw ( NMSP_UNO::RuntimeException ); sal_Bool SAL_CALL FilterTracer_supportsService( const rtl::OUString& rServiceName ) throw( NMSP_UNO::RuntimeException ); SEQ( rtl::OUString ) SAL_CALL FilterTracer_getSupportedServiceNames() throw( NMSP_UNO::RuntimeException ); #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2013 Frank Mertens. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <flux/IoMonitor.h> #include <flux/Thread.h> #include <flux/Process.h> #include <flux/User.h> #include "exceptions.h" #include "ErrorLog.h" #include "AccessLog.h" #include "SystemLog.h" #include "NodeConfig.h" #include "WorkerPool.h" #include "ServiceRegistry.h" #include "DispatchInstance.h" #include "ConnectionManager.h" #include "NodeMaster.h" namespace fluxnode { NodeMaster::NodeMaster() {} int NodeMaster::run(int argc, char **argv) { SystemLog::open(String(argv[0])->fileName(), 0, LOG_DAEMON); Process::enableInterrupt(SIGINT); Process::enableInterrupt(SIGTERM); Process::enableInterrupt(SIGHUP); Thread::blockSignals(SignalSet::createFull()); { Ref<SignalSet> signalSet = SignalSet::createEmpty(); signalSet->insert(SIGINT); signalSet->insert(SIGTERM); signalSet->insert(SIGHUP); Thread::unblockSignals(signalSet); } while (true) { try { runNode(argc, argv); } catch (Interrupt &ex) { if (ex.signal() == SIGINT || ex.signal() == SIGTERM || ex.signal() == SIGHUP) break; return ex.signal() + 128; } #ifdef NDEBUG catch (SystemError &ex) { return 1; } #endif } return 0; } void NodeMaster::runNode(int argc, char **argv) { nodeConfig()->load(argc, argv); if (nodeConfig()->daemon() && !Process::isDaemonized()) Process::daemonize(); errorLog()->open(nodeConfig()->errorLogConfig()); #ifdef NDEBUG try { runNode(); } catch (SystemError &ex) { FLUXNODE_ERROR() << ex.what() << nl; throw; } #else runNode(); #endif } void NodeMaster::runNode() { FLUXNODE_NOTICE() << "Starting (pid = " << Process::currentId() << ")" << nl; Ref<DispatchInstance> dispatchInstance; for (int i = 0; i < nodeConfig()->serviceInstances()->size(); ++i) { if (nodeConfig()->serviceInstances()->at(i)->serviceName() == "Dispatch") { dispatchInstance = nodeConfig()->serviceInstances()->at(i); nodeConfig()->serviceInstances()->pop(i); --i; } } if (!dispatchInstance) { ServiceDefinition *dispatchService = serviceRegistry()->serviceByName("Dispatch"); YasonObject *config = dispatchService->configPrototype(); dispatchInstance = dispatchService->createInstance(config); } if (nodeConfig()->serviceInstances()->size() == 0) { FLUXNODE_WARNING() << "No service configured, falling back to Echo service" << nl; ServiceDefinition *echoService = serviceRegistry()->serviceByName("Echo"); YasonObject *config = echoService->configPrototype(); config->establish("host", "*"); Ref<ServiceInstance> echoInstance = echoService->createInstance(config); nodeConfig()->serviceInstances()->append(echoInstance); } typedef List< Ref<StreamSocket> > ListeningSockets; Ref<ListeningSockets> listeningSockets = ListeningSockets::create(nodeConfig()->address()->size()); for (int i = 0; i < nodeConfig()->address()->size(); ++i) { SocketAddress *address = nodeConfig()->address()->at(i); FLUXNODE_NOTICE() << "Start listening at " << address << nl; Ref<StreamSocket> socket = StreamSocket::listen(address); listeningSockets->at(i) = socket; } if (nodeConfig()->user() != "") { Ref<User> user = User::lookup(nodeConfig()->user()); if (!user->exists()) throw UsageError("No such user: \"" + nodeConfig()->user() + "\""); FLUXNODE_NOTICE() << "Switching to user " << user->name() << " (uid = " << user->id() << ")" << nl; Process::setUserId(user->id()); } Ref<ConnectionManager> connectionManager = ConnectionManager::create(nodeConfig()->serviceWindow()); dispatchInstance->workerPools_ = WorkerPools::create(nodeConfig()->serviceInstances()->size()); for (int i = 0; i < nodeConfig()->serviceInstances()->size(); ++i) dispatchInstance->workerPools_->at(i) = WorkerPool::create(nodeConfig()->serviceInstances()->at(i), connectionManager->closedConnections()); Ref<WorkerPool> dispatchPool = WorkerPool::create(dispatchInstance, connectionManager->closedConnections()); FLUXNODE_NOTICE() << "Up and running (pid = " << Process::currentId() << ")" << nl; try { FLUXNODE_DEBUG() << "Accepting connections" << nl; Ref<IoMonitor> ioMonitor = IoMonitor::create(); while (true) { ioMonitor->readyAccept()->clear(); for (int i = 0; i < listeningSockets->size(); ++i) ioMonitor->readyAccept()->insert(listeningSockets->at(i)); int n = ioMonitor->wait(1); if (n > 0) { for (int i = 0; i < listeningSockets->size(); ++i) { StreamSocket *socket = listeningSockets->at(i); if (ioMonitor->readyAccept()->contains(socket)) { Ref<StreamSocket> clientSocket = socket->accept(); Ref<SocketAddress> clientAddress = SocketAddress::create(); if (!clientSocket->getPeerAddress(clientAddress)) { FLUXNODE_DEBUG() << "Failed to get peer address" << nl; continue; } Ref<ClientConnection> client = ClientConnection::create(clientSocket, clientAddress); connectionManager->prioritize(client); FLUXNODE_DEBUG() << "Accepted connection from " << client->address() << " with priority " << client->priority() << nl; dispatchPool->dispatch(client); } } } connectionManager->cycle(); } } catch (Interrupt &ex) { FLUXNODE_NOTICE() << "Received " << ex.signalName() << ", shutting down" << nl; dispatchInstance->workerPools_ = 0; dispatchPool = 0; FLUXNODE_NOTICE() << "Shutdown complete" << nl; throw ex; } } } // namespace fluxnode <commit_msg>node: fix fallback exception<commit_after>/* * Copyright (C) 2013 Frank Mertens. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <flux/IoMonitor.h> #include <flux/Thread.h> #include <flux/Process.h> #include <flux/User.h> #include "exceptions.h" #include "ErrorLog.h" #include "AccessLog.h" #include "SystemLog.h" #include "NodeConfig.h" #include "WorkerPool.h" #include "ServiceRegistry.h" #include "DispatchInstance.h" #include "ConnectionManager.h" #include "NodeMaster.h" namespace fluxnode { NodeMaster::NodeMaster() {} int NodeMaster::run(int argc, char **argv) { SystemLog::open(String(argv[0])->fileName(), 0, LOG_DAEMON); Process::enableInterrupt(SIGINT); Process::enableInterrupt(SIGTERM); Process::enableInterrupt(SIGHUP); Thread::blockSignals(SignalSet::createFull()); { Ref<SignalSet> signalSet = SignalSet::createEmpty(); signalSet->insert(SIGINT); signalSet->insert(SIGTERM); signalSet->insert(SIGHUP); Thread::unblockSignals(signalSet); } while (true) { try { runNode(argc, argv); } catch (Interrupt &ex) { if (ex.signal() == SIGINT || ex.signal() == SIGTERM || ex.signal() == SIGHUP) break; return ex.signal() + 128; } #ifdef NDEBUG catch (SystemError &ex) { return 1; } #endif } return 0; } void NodeMaster::runNode(int argc, char **argv) { nodeConfig()->load(argc, argv); if (nodeConfig()->daemon() && !Process::isDaemonized()) Process::daemonize(); errorLog()->open(nodeConfig()->errorLogConfig()); #ifdef NDEBUG try { runNode(); } catch (Exception &ex) { FLUXNODE_ERROR() << ex.what() << nl; throw; } #else runNode(); #endif } void NodeMaster::runNode() { FLUXNODE_NOTICE() << "Starting (pid = " << Process::currentId() << ")" << nl; Ref<DispatchInstance> dispatchInstance; for (int i = 0; i < nodeConfig()->serviceInstances()->size(); ++i) { if (nodeConfig()->serviceInstances()->at(i)->serviceName() == "Dispatch") { dispatchInstance = nodeConfig()->serviceInstances()->at(i); nodeConfig()->serviceInstances()->pop(i); --i; } } if (!dispatchInstance) { ServiceDefinition *dispatchService = serviceRegistry()->serviceByName("Dispatch"); YasonObject *config = dispatchService->configPrototype(); dispatchInstance = dispatchService->createInstance(config); } if (nodeConfig()->serviceInstances()->size() == 0) { FLUXNODE_WARNING() << "No service configured, falling back to Echo service" << nl; ServiceDefinition *echoService = serviceRegistry()->serviceByName("Echo"); YasonObject *config = echoService->configPrototype(); config->establish("host", "*"); Ref<ServiceInstance> echoInstance = echoService->createInstance(config); nodeConfig()->serviceInstances()->append(echoInstance); } typedef List< Ref<StreamSocket> > ListeningSockets; Ref<ListeningSockets> listeningSockets = ListeningSockets::create(nodeConfig()->address()->size()); for (int i = 0; i < nodeConfig()->address()->size(); ++i) { SocketAddress *address = nodeConfig()->address()->at(i); FLUXNODE_NOTICE() << "Start listening at " << address << nl; Ref<StreamSocket> socket = StreamSocket::listen(address); listeningSockets->at(i) = socket; } if (nodeConfig()->user() != "") { Ref<User> user = User::lookup(nodeConfig()->user()); if (!user->exists()) throw UsageError("No such user: \"" + nodeConfig()->user() + "\""); FLUXNODE_NOTICE() << "Switching to user " << user->name() << " (uid = " << user->id() << ")" << nl; Process::setUserId(user->id()); } Ref<ConnectionManager> connectionManager = ConnectionManager::create(nodeConfig()->serviceWindow()); dispatchInstance->workerPools_ = WorkerPools::create(nodeConfig()->serviceInstances()->size()); for (int i = 0; i < nodeConfig()->serviceInstances()->size(); ++i) dispatchInstance->workerPools_->at(i) = WorkerPool::create(nodeConfig()->serviceInstances()->at(i), connectionManager->closedConnections()); Ref<WorkerPool> dispatchPool = WorkerPool::create(dispatchInstance, connectionManager->closedConnections()); FLUXNODE_NOTICE() << "Up and running (pid = " << Process::currentId() << ")" << nl; try { FLUXNODE_DEBUG() << "Accepting connections" << nl; Ref<IoMonitor> ioMonitor = IoMonitor::create(); while (true) { ioMonitor->readyAccept()->clear(); for (int i = 0; i < listeningSockets->size(); ++i) ioMonitor->readyAccept()->insert(listeningSockets->at(i)); int n = ioMonitor->wait(1); if (n > 0) { for (int i = 0; i < listeningSockets->size(); ++i) { StreamSocket *socket = listeningSockets->at(i); if (ioMonitor->readyAccept()->contains(socket)) { Ref<StreamSocket> clientSocket = socket->accept(); Ref<SocketAddress> clientAddress = SocketAddress::create(); if (!clientSocket->getPeerAddress(clientAddress)) { FLUXNODE_DEBUG() << "Failed to get peer address" << nl; continue; } Ref<ClientConnection> client = ClientConnection::create(clientSocket, clientAddress); connectionManager->prioritize(client); FLUXNODE_DEBUG() << "Accepted connection from " << client->address() << " with priority " << client->priority() << nl; dispatchPool->dispatch(client); } } } connectionManager->cycle(); } } catch (Interrupt &ex) { FLUXNODE_NOTICE() << "Received " << ex.signalName() << ", shutting down" << nl; dispatchInstance->workerPools_ = 0; dispatchPool = 0; FLUXNODE_NOTICE() << "Shutdown complete" << nl; throw ex; } } } // namespace fluxnode <|endoftext|>
<commit_before>#include <Arduino.h> #include "HaskinoComm.h" #include "HaskinoCommands.h" #include "HaskinoDigital.h" #include "HaskinoExpr.h" static bool handleReadPin(int size, const byte *msg, CONTEXT *context); static bool handleWritePin(int size, const byte *msg, CONTEXT *context); static bool handleReadPort(int size, const byte *msg, CONTEXT *context); static bool handleWritePort(int size, const byte *msg, CONTEXT *context); bool parseDigitalMessage(int size, const byte *msg, CONTEXT *context) { switch (msg[0]) { case DIG_CMD_READ_PIN: handleReadPin(size, msg, context); break; case DIG_CMD_WRITE_PIN: handleWritePin(size, msg, context); break; case DIG_CMD_READ_PORT: handleReadPort(size, msg, context); break; case DIG_CMD_WRITE_PORT: handleWritePort(size, msg, context); break; } return false; } static bool handleReadPin(int size, const byte *msg, CONTEXT *context) { byte bind = msg[1]; byte *expr = (byte *) &msg[2]; byte pinNo = evalWord8Expr(&expr, context); byte digitalReply[2]; digitalReply[0] = EXPR(EXPR_WORD8, EXPR_LIT); digitalReply[1] = digitalRead(pinNo); sendReply(sizeof(digitalReply), DIG_RESP_READ_PIN, digitalReply, context, bind); return false; } static bool handleWritePin(int size, const byte *msg, CONTEXT *context) { byte *expr = (byte *) &msg[1]; byte pinNo = evalWord8Expr(&expr, context); byte value = evalBoolExpr(&expr, context); digitalWrite(pinNo, value); return false; } static uint8_t bits[8] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; static bool handleReadPort(int size, const byte *msg, CONTEXT *context) { byte bind = msg[1]; byte *expr = (byte *) &msg[2]; byte pinNo = evalWord8Expr(&expr, context); byte mask = evalWord8Expr(&expr, context); byte digitalReply[2]; digitalReply[0] = EXPR(EXPR_WORD8, EXPR_LIT); digitalReply[1] = 0; for (int i=0;i<8;i++) { if ((bits[i] & mask) && digitalRead(pinNo+i)) digitalReply[1] |= bits[i]; } sendReply(sizeof(digitalReply), DIG_RESP_READ_PORT, digitalReply, context, bind); return false; } static bool handleWritePort(int size, const byte *msg, CONTEXT *context) { byte *expr = (byte *) &msg[1]; byte pinNo = evalWord8Expr(&expr, context); byte value = evalWord8Expr(&expr, context); byte mask = evalWord8Expr(&expr, context); for (int i=0;i<8;i++) { if (bits[i] & mask) digitalWrite(pinNo+i, bits[i] & value); } return false; } <commit_msg>Fix long standing bug made visible by Expr mods for Float/Signed.<commit_after>#include <Arduino.h> #include "HaskinoComm.h" #include "HaskinoCommands.h" #include "HaskinoDigital.h" #include "HaskinoExpr.h" static bool handleReadPin(int size, const byte *msg, CONTEXT *context); static bool handleWritePin(int size, const byte *msg, CONTEXT *context); static bool handleReadPort(int size, const byte *msg, CONTEXT *context); static bool handleWritePort(int size, const byte *msg, CONTEXT *context); bool parseDigitalMessage(int size, const byte *msg, CONTEXT *context) { switch (msg[0]) { case DIG_CMD_READ_PIN: handleReadPin(size, msg, context); break; case DIG_CMD_WRITE_PIN: handleWritePin(size, msg, context); break; case DIG_CMD_READ_PORT: handleReadPort(size, msg, context); break; case DIG_CMD_WRITE_PORT: handleWritePort(size, msg, context); break; } return false; } static bool handleReadPin(int size, const byte *msg, CONTEXT *context) { byte bind = msg[1]; byte *expr = (byte *) &msg[2]; byte pinNo = evalWord8Expr(&expr, context); byte digitalReply[2]; digitalReply[0] = EXPR(EXPR_BOOL, EXPR_LIT); digitalReply[1] = digitalRead(pinNo); sendReply(sizeof(digitalReply), DIG_RESP_READ_PIN, digitalReply, context, bind); return false; } static bool handleWritePin(int size, const byte *msg, CONTEXT *context) { byte *expr = (byte *) &msg[1]; byte pinNo = evalWord8Expr(&expr, context); byte value = evalBoolExpr(&expr, context); digitalWrite(pinNo, value); return false; } static uint8_t bits[8] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; static bool handleReadPort(int size, const byte *msg, CONTEXT *context) { byte bind = msg[1]; byte *expr = (byte *) &msg[2]; byte pinNo = evalWord8Expr(&expr, context); byte mask = evalWord8Expr(&expr, context); byte digitalReply[2]; digitalReply[0] = EXPR(EXPR_WORD8, EXPR_LIT); digitalReply[1] = 0; for (int i=0;i<8;i++) { if ((bits[i] & mask) && digitalRead(pinNo+i)) digitalReply[1] |= bits[i]; } sendReply(sizeof(digitalReply), DIG_RESP_READ_PORT, digitalReply, context, bind); return false; } static bool handleWritePort(int size, const byte *msg, CONTEXT *context) { byte *expr = (byte *) &msg[1]; byte pinNo = evalWord8Expr(&expr, context); byte value = evalWord8Expr(&expr, context); byte mask = evalWord8Expr(&expr, context); for (int i=0;i<8;i++) { if (bits[i] & mask) digitalWrite(pinNo+i, bits[i] & value); } return false; } <|endoftext|>
<commit_before>#pragma once <commit_msg>feat: Added support of the demonstrator robot model<commit_after>#pragma once // C++ STL #include <vector> // HOP #include <hop_bits/optimisationProblem/robotic/robotModel.hpp> #include <hop_bits/optimisationProblem/robotic/robotModel/parallelKinematicMachine_6pups.hpp> namespace hop { class MultiLevelStewartPlatform : public RobotModel { public: MultiLevelStewartPlatform( const std::vector<ParallelKinematicMachine_6PUPS>& platformLevels); // Copy constructors are not used in this library and deleted to avoid unintended/any usage. MultiLevelStewartPlatform(const MultiLevelStewartPlatform&) = delete; MultiLevelStewartPlatform& operator=(const MultiLevelStewartPlatform&) = delete; std::vector<arma::Mat<double>> getModelCharacterisation( const arma::Col<double>& endEffectorPose, const arma::Mat<double>& redundantJointActuations) const override; arma::Mat<double> getActuation( const arma::Col<double>& endEffectorPose, const arma::Mat<double>& redundantJointActuations) const override; double getPositionError( const arma::Col<double>& endEffectorPose, const arma::Mat<double>& redundantJointActuations) const override; protected: const std::vector<ParallelKinematicMachine_6PUPS> platformLevels_; }; } <|endoftext|>
<commit_before>#include <QtCore/QCoreApplication> #include <QtCore/QFile> #include <QtCore/QXmlStreamReader> #include <QtCore/QStack> #include <QtCore/QStringList> #include <QtCore/QDebug> class Reader { QString outString; QTextStream out; QXmlStreamReader xml; int depth; bool supressIndent; QStringList knownListProperties; inline QString depthString() {if (supressIndent) { supressIndent = false; return QString(); } return QString(depth*4, QLatin1Char(' '));} public: Reader(QIODevice *in) :xml(in) { knownListProperties << "states" << "transitions" << "children" << "resources" << "transform" << "notes"; depth = 0; supressIndent = false; out.setString(&outString); loop(); out.flush(); QTextStream print(stdout); print << outString; } void comment() { if (xml.isComment()) { out << depthString() << "// " << xml.text().toString().trimmed().replace(QRegExp("\n\\s*"),"\n"+depthString()+"// ") << endl; } } void emptyLoop() { while (!xml.atEnd()) { xml.readNext(); comment(); if (xml.tokenType() == QXmlStreamReader::EndElement) return; } } void loop() { while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::EndElement) return; else if (xml.tokenType() == QXmlStreamReader::StartElement) startElement(); else if (xml.tokenType() == QXmlStreamReader::ProcessingInstruction) { if (xml.processingInstructionTarget() == QLatin1String("qtfx")) { QString data = xml.processingInstructionData().toString().trimmed(); if (data.startsWith(QLatin1String("namespacepath:="))) { outString.prepend( QLatin1String("import \"") + data.mid(data.indexOf(QLatin1Char('='))+1) + QLatin1String("\"\n")); } } } comment(); } } void startElement() { if (!propertyChangeSet.isEmpty() && xml.name() != "SetProperties" && xml.name() != "SetProperty") { clearPropertyChangeSet(); } if (xml.name() == "properties") startDeclareProperties(); else if (xml.name() == "signals") startDeclareSignals(); else if (xml.name() == "states") loop(); // ignore else if (xml.name() == "transitions") loop(); // ignore else if (knownListProperties.contains(xml.name().toString())) startList(); else if (xml.name() == "SetProperties") startSetProperties(); else if (xml.name() == "SetProperty") startSetProperty(); else if (xml.name() == "ParentChange") startParentChange(); else if (xml.name() == "Connection") startConnection(); else if (xml.name() == "Script") startScript(); else if (xml.name().at(0).isLower() && xml.attributes().isEmpty()) startObjectProperty(); else startItem(); } static void possiblyRemoveBraces(QString *s) { if (s->startsWith('{') && s->endsWith('}')) *s = s->mid(1, s->length() - 2); } static bool isNumber(const QString &s) { bool ok = true; s.toFloat(&ok); return ok; } static bool isSignalHandler(const QString &s) { return s.size() > 3 && s.startsWith("on") && s.at(2).isUpper(); } static bool isEnum(const QString &property, const QString &value) { return !value.contains(' ') && (property == "vAlign" || property == "hAlign" || property == "style"); } static bool isIdentifier(const QString &s) { if (s.isEmpty()) return false; if (!s.at(1).isLetter()) return false; for (int i = 1; i < s.size(); ++i) { QChar c = s.at(i); if (c.isLetterOrNumber() || c == QLatin1Char('_') || c == QLatin1Char('-')) continue; return false; } return true; } void setProperty(const QString &property, const QString &value, bool newline = true) { QString v = value.trimmed(); if (v.startsWith('{')) { possiblyRemoveBraces(&v); } else if (v == "true" || v == "false" || isNumber(v) || property == "id" || isEnum(property, value) ) { ; } else if (isSignalHandler(property)) { // if not a function name, create an anonymous function if (!isIdentifier(v)) { v.prepend("{ "); v.append(" }"); } } else // if (property == "text" || property == "name" || value.contains(' ') // || value.contains("/") || value.startsWith('#') // || property == "filename" || property == "source" || property == "src" // || property == "title" || property == "movieTitle" || property == "movieDescription" // || property == "properties" || property == "fromState" || property == "toState" // ) { v.prepend('\"'); v.append('\"'); } // QByteArray semiColon = ";"; // if (v.endsWith(QLatin1Char('}')) || v.endsWith(QLatin1Char(';'))) // semiColon.clear(); if (!newline) out << property << ": " << v /* << semiColon.constData() */; else out << depthString() << property << ": " << v /* << semiColon.constData() */ << endl; } typedef QPair<QString,QString> StringPair; QList<StringPair> propertyChangeSet; void startItem(bool inList = false) { QString name = xml.name().toString(); out << depthString() << name << " {" << endl; ++depth; foreach (QXmlStreamAttribute attribute, xml.attributes()) { setProperty(attribute.name().toString(), attribute.value().toString()); } loop(); if (name == "State") clearPropertyChangeSet(); --depth; out << depthString() << "}"; if (!inList) out << endl; } void clearPropertyChangeSet() { if (propertyChangeSet.isEmpty()) return; out << depthString() << "PropertyChangeSet" << " {" << endl; ++depth; foreach(StringPair pair, propertyChangeSet) setProperty(pair.first, pair.second); --depth; out << depthString() << "}" << endl; propertyChangeSet.clear(); } void startObjectProperty() { QString name = xml.name().toString(); bool hasElements = false; while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::EndElement) break; if (xml.tokenType() == QXmlStreamReader::StartElement) { hasElements = true; out << depthString() << name << ": "; supressIndent = true; startElement(); } else if (!hasElements && xml.tokenType() == QXmlStreamReader::Characters) { if (!xml.text().toString().trimmed().isEmpty()) { setProperty(name, xml.text().toString()); } } comment(); } } void startDeclareProperty() { out << depthString() << "public property "; QString name = xml.attributes().value("name").toString(); if (xml.attributes().hasAttribute("value")) setProperty(name, xml.attributes().value("value").toString(), false); else out << name; QMap<QString, QString> attributes; foreach (QXmlStreamAttribute attribute, xml.attributes()) { if (attribute.name() == "name" || attribute.name() == "value") continue; attributes.insert(attribute.name().toString(), attribute.value().toString()); } if (attributes.isEmpty()) { out << endl; } else { out << " {" << endl; ++depth; foreach (QString key, attributes.keys()) setProperty(key, attributes.value(key)); --depth; out << depthString() << "}" << endl; } emptyLoop(); } void startDeclareProperties() { while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::EndElement) return; if (xml.tokenType() == QXmlStreamReader::StartElement) { if (xml.name() == "Property") startDeclareProperty(); } comment(); } } void startDeclareSignal() { out << depthString() << "public signal " << xml.attributes().value("name").toString() << endl; emptyLoop(); } void startDeclareSignals() { while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::EndElement) return; if (xml.tokenType() == QXmlStreamReader::StartElement) { if (xml.name() == "Signal") startDeclareSignal(); } comment(); } } void startSetProperties() { QString target = xml.attributes().value("target").toString(); possiblyRemoveBraces(&target); foreach (QXmlStreamAttribute attribute, xml.attributes()) { if (attribute.name() == "target") continue; propertyChangeSet += StringPair(target + "." + attribute.name().toString(), attribute.value().toString()); } emptyLoop(); } void startSetProperty() { QString target = xml.attributes().value("target").toString(); possiblyRemoveBraces(&target); propertyChangeSet += StringPair(target + "." + xml.attributes().value("property").toString(), xml.attributes().value("value").toString()); emptyLoop(); } void startParentChange() { QString target = xml.attributes().value("target").toString(); possiblyRemoveBraces(&target); out << depthString() << "ParentChangeSet" << " {" << endl; ++depth; setProperty(target + ".parent", xml.attributes().value("parent").toString()); --depth; out << depthString() << "}" << endl; // propertyChangeSet += StringPair(target + ".moveToParent", xml.attributes().value("parent").toString()); emptyLoop(); } void startConnection() { QString sender = xml.attributes().value("sender").toString(); possiblyRemoveBraces(&sender); out << depthString() << "Connection {" << endl; ++depth; out << depthString() << "signal: " << sender + "." + xml.attributes().value("signal").toString() << endl; out << depthString() << "onSignal: { " << xml.attributes().value("script").toString() << " }" << endl; --depth; out << depthString() << "}" << endl; emptyLoop(); } void startScript() { if (xml.attributes().hasAttribute(QLatin1String("src"))) { /* QString import; QTextStream ts(&import); ts << "import \""; ts << xml.attributes().value(QLatin1String("src")).toString(); ts << "\"" << endl; ts.flush(); outString.prepend(import); */ } QString text = xml.readElementText(); if (!text.trimmed().isEmpty()) { out << text << endl; } if (xml.tokenType() != QXmlStreamReader::EndElement) emptyLoop(); } void startList() { out << depthString() << xml.name().toString() << ": [" << endl; ++depth; bool needComma = false; while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::EndElement) break; if (xml.tokenType() == QXmlStreamReader::StartElement) { if (needComma) out << "," << endl; startItem(true); needComma = true; } comment(); } out << endl; --depth; out << depthString() << "]" << endl; } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); if (argc != 2) { qWarning() << "Usage: qmlconf filename"; exit(1); } QFile file(argv[1]); if (file.open(QIODevice::ReadOnly)) { Reader r(&file); } file.close(); return 0; } <commit_msg>Updated the QML converter.<commit_after>#include <QtCore/QCoreApplication> #include <QtCore/QFile> #include <QtCore/QXmlStreamReader> #include <QtCore/QStack> #include <QtCore/QStringList> #include <QtCore/QDebug> class Reader { QString outString; QTextStream out; QXmlStreamReader xml; int depth; bool supressIndent; QStringList knownListProperties; inline QString depthString() {if (supressIndent) { supressIndent = false; return QString(); } return QString(depth*4, QLatin1Char(' '));} public: Reader(QIODevice *in) :xml(in) { knownListProperties << "states" << "transitions" << "children" << "resources" << "transform" << "notes"; depth = 0; supressIndent = false; out.setString(&outString); loop(); out.flush(); QTextStream print(stdout); print << outString; } void comment() { if (xml.isComment()) { out << depthString() << "// " << xml.text().toString().trimmed().replace(QRegExp("\n\\s*"),"\n"+depthString()+"// ") << endl; } } void emptyLoop() { while (!xml.atEnd()) { xml.readNext(); comment(); if (xml.tokenType() == QXmlStreamReader::EndElement) return; } } void loop() { while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::EndElement) return; else if (xml.tokenType() == QXmlStreamReader::StartElement) startElement(); else if (xml.tokenType() == QXmlStreamReader::ProcessingInstruction) { if (xml.processingInstructionTarget() == QLatin1String("qtfx")) { QString data = xml.processingInstructionData().toString().trimmed(); if (data.startsWith(QLatin1String("namespacepath:="))) { outString.prepend( QLatin1String("import \"") + data.mid(data.indexOf(QLatin1Char('='))+1) + QLatin1String("\"\n")); } } } comment(); } } void startElement() { if (!propertyChangeSet.isEmpty() && xml.name() != "SetProperties" && xml.name() != "SetProperty") { clearPropertyChangeSet(); } if (xml.name() == "properties") startDeclareProperties(); else if (xml.name() == "signals") startDeclareSignals(); else if (xml.name() == "states") loop(); // ignore else if (xml.name() == "transitions") loop(); // ignore else if (knownListProperties.contains(xml.name().toString())) startList(); else if (xml.name() == "SetProperties") startSetProperties(); else if (xml.name() == "SetProperty") startSetProperty(); else if (xml.name() == "ParentChange") startParentChange(); else if (xml.name() == "Connection") startConnection(); else if (xml.name() == "Script") startScript(); else if (xml.name().at(0).isLower() && xml.attributes().isEmpty()) startObjectProperty(); else startItem(); } static void possiblyRemoveBraces(QString *s) { if (s->startsWith('{') && s->endsWith('}')) *s = s->mid(1, s->length() - 2); } static bool isNumber(const QString &s) { bool ok = true; s.toFloat(&ok); return ok; } static bool isSignalHandler(const QString &s) { return s.size() > 3 && s.startsWith("on") && s.at(2).isUpper(); } static bool isEnum(const QString &property, const QString &value) { return !value.contains(' ') && (property == "vAlign" || property == "hAlign" || property == "style"); } static bool isIdentifier(const QString &s) { if (s.isEmpty()) return false; if (!s.at(1).isLetter()) return false; for (int i = 1; i < s.size(); ++i) { QChar c = s.at(i); if (c.isLetterOrNumber() || c == QLatin1Char('_') || c == QLatin1Char('-')) continue; return false; } return true; } void setProperty(const QString &property, const QString &value, bool newline = true) { QString v = value.trimmed(); if (v.startsWith('{')) { possiblyRemoveBraces(&v); } else if (v == "true" || v == "false" || isNumber(v) || property == "id" || isEnum(property, value) ) { ; } else if (isSignalHandler(property)) { // if not a function name, create an anonymous function if (!isIdentifier(v)) { v.prepend("{ "); v.append(" }"); } } else // if (property == "text" || property == "name" || value.contains(' ') // || value.contains("/") || value.startsWith('#') // || property == "filename" || property == "source" || property == "src" // || property == "title" || property == "movieTitle" || property == "movieDescription" // || property == "properties" || property == "fromState" || property == "toState" // ) { v.prepend('\"'); v.append('\"'); } // QByteArray semiColon = ";"; // if (v.endsWith(QLatin1Char('}')) || v.endsWith(QLatin1Char(';'))) // semiColon.clear(); if (!newline) out << property << ": " << v /* << semiColon.constData() */; else out << depthString() << property << ": " << v /* << semiColon.constData() */ << endl; } typedef QPair<QString,QString> StringPair; QList<StringPair> propertyChangeSet; void startItem(bool inList = false) { QString name = xml.name().toString(); out << depthString() << name << " {" << endl; ++depth; foreach (QXmlStreamAttribute attribute, xml.attributes()) { setProperty(attribute.name().toString(), attribute.value().toString()); } loop(); if (name == "State") clearPropertyChangeSet(); --depth; out << depthString() << "}"; if (!inList) out << endl; } void clearPropertyChangeSet() { if (propertyChangeSet.isEmpty()) return; out << depthString() << "PropertyChangeSet" << " {" << endl; ++depth; foreach(StringPair pair, propertyChangeSet) setProperty(pair.first, pair.second); --depth; out << depthString() << "}" << endl; propertyChangeSet.clear(); } void startObjectProperty() { QString name = xml.name().toString(); bool hasElements = false; while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::EndElement) break; if (xml.tokenType() == QXmlStreamReader::StartElement) { hasElements = true; out << depthString() << name << ": "; supressIndent = true; startElement(); } else if (!hasElements && xml.tokenType() == QXmlStreamReader::Characters) { if (!xml.text().toString().trimmed().isEmpty()) { setProperty(name, xml.text().toString()); } } comment(); } } void startDeclareProperty() { out << depthString() << "public property "; if (xml.attributes().hasAttribute("type")) out << "/* " << xml.attributes().value("type").toString() << " */ "; QString name = xml.attributes().value("name").toString(); if (xml.attributes().hasAttribute("value")) setProperty(name, xml.attributes().value("value").toString(), false); else out << name; QMap<QString, QString> attributes; foreach (QXmlStreamAttribute attribute, xml.attributes()) { if (attribute.name() == "name" || attribute.name() == "value") continue; attributes.insert(attribute.name().toString(), attribute.value().toString()); } out << endl; emptyLoop(); } void startDeclareProperties() { while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::EndElement) return; if (xml.tokenType() == QXmlStreamReader::StartElement) { if (xml.name() == "Property") startDeclareProperty(); } comment(); } } void startDeclareSignal() { out << depthString() << "public signal " << xml.attributes().value("name").toString() << endl; emptyLoop(); } void startDeclareSignals() { while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::EndElement) return; if (xml.tokenType() == QXmlStreamReader::StartElement) { if (xml.name() == "Signal") startDeclareSignal(); } comment(); } } void startSetProperties() { QString target = xml.attributes().value("target").toString(); possiblyRemoveBraces(&target); foreach (QXmlStreamAttribute attribute, xml.attributes()) { if (attribute.name() == "target") continue; propertyChangeSet += StringPair(target + "." + attribute.name().toString(), attribute.value().toString()); } emptyLoop(); } void startSetProperty() { QString target = xml.attributes().value("target").toString(); possiblyRemoveBraces(&target); propertyChangeSet += StringPair(target + "." + xml.attributes().value("property").toString(), xml.attributes().value("value").toString()); emptyLoop(); } void startParentChange() { QString target = xml.attributes().value("target").toString(); possiblyRemoveBraces(&target); out << depthString() << "ParentChangeSet" << " {" << endl; ++depth; setProperty(target + ".parent", xml.attributes().value("parent").toString()); --depth; out << depthString() << "}" << endl; // propertyChangeSet += StringPair(target + ".moveToParent", xml.attributes().value("parent").toString()); emptyLoop(); } void startConnection() { QString sender = xml.attributes().value("sender").toString(); possiblyRemoveBraces(&sender); out << depthString() << "Connection {" << endl; ++depth; out << depthString() << "signal: " << sender + "." + xml.attributes().value("signal").toString() << endl; out << depthString() << "onSignal: { " << xml.attributes().value("script").toString() << " }" << endl; --depth; out << depthString() << "}" << endl; emptyLoop(); } void startScript() { if (xml.attributes().hasAttribute(QLatin1String("src"))) { /* QString import; QTextStream ts(&import); ts << "import \""; ts << xml.attributes().value(QLatin1String("src")).toString(); ts << "\"" << endl; ts.flush(); outString.prepend(import); */ } QString text = xml.readElementText(); if (!text.trimmed().isEmpty()) { out << text << endl; } if (xml.tokenType() != QXmlStreamReader::EndElement) emptyLoop(); } void startList() { out << depthString() << xml.name().toString() << ": [" << endl; ++depth; bool needComma = false; while (!xml.atEnd()) { xml.readNext(); if (xml.tokenType() == QXmlStreamReader::EndElement) break; if (xml.tokenType() == QXmlStreamReader::StartElement) { if (needComma) out << "," << endl; startItem(true); needComma = true; } comment(); } out << endl; --depth; out << depthString() << "]" << endl; } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); if (argc != 2) { qWarning() << "Usage: qmlconf filename"; exit(1); } QFile file(argv[1]); if (file.open(QIODevice::ReadOnly)) { Reader r(&file); } file.close(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rpc/rawtransaction_util.h> #include <coins.h> #include <core_io.h> #include <key_io.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <rpc/request.h> #include <rpc/util.h> #include <script/sign.h> #include <script/signingprovider.h> #include <tinyformat.h> #include <univalue.h> #include <util/strencodings.h> #include <util/system.h> CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniValue& outputs_in, const UniValue& locktime, const UniValue& timestamp) { if (inputs_in.isNull() || outputs_in.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null"); UniValue inputs = inputs_in.get_array(); const bool outputs_is_obj = outputs_in.isObject(); UniValue outputs = outputs_is_obj ? outputs_in.get_obj() : outputs_in.get_array(); CMutableTransaction rawTx; rawTx.nVersion = gArgs.GetArg("-txversion", CTransaction::CURRENT_VERSION); if (!locktime.isNull()) { int64_t nLockTime = locktime.get_int64(); if (nLockTime < 0 || nLockTime > LOCKTIME_MAX) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range"); rawTx.nLockTime = nLockTime; } if (!timestamp.isNull()) { int64_t nTime = timestamp.get_int64(); if (nTime < 0 || nTime > LOCKTIME_MAX) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, timestamp out of range"); rawTx.nTime = nTime; } for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; const UniValue& o = input.get_obj(); CScript scriptSig; uint256 txid = ParseHashO(o, "txid"); const UniValue& vout_v = find_value(o, "vout"); if (!vout_v.isNum()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); uint32_t nSequence; if (rawTx.nLockTime) { nSequence = CTxIn::SEQUENCE_FINAL - 1; } else { nSequence = CTxIn::SEQUENCE_FINAL; } // set the sequence number if passed in the parameters object const UniValue& sequenceObj = find_value(o, "sequence"); if (sequenceObj.isNum()) { int64_t seqNr64 = sequenceObj.get_int64(); if (seqNr64 < 0 || seqNr64 > CTxIn::SEQUENCE_FINAL) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range"); } else { nSequence = (uint32_t)seqNr64; } } // set redeem script const UniValue& rs = find_value(o, "redeemScript"); if (!rs.isNull()) { std::vector<unsigned char> redeemScriptData(ParseHex(rs.getValStr())); CScript redeemScript(redeemScriptData.begin(), redeemScriptData.end()); scriptSig = redeemScript; } CTxIn in(COutPoint(txid, nOutput), scriptSig, nSequence); rawTx.vin.push_back(in); } if (!outputs_is_obj) { // Translate array of key-value pairs into dict UniValue outputs_dict = UniValue(UniValue::VOBJ); for (size_t i = 0; i < outputs.size(); ++i) { const UniValue& output = outputs[i]; if (!output.isObject()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair not an object as expected"); } if (output.size() != 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair must contain exactly one key"); } outputs_dict.pushKVs(output); } outputs = std::move(outputs_dict); } // Duplicate checking std::set<CTxDestination> destinations; bool has_data{false}; for (const std::string& name_ : outputs.getKeys()) { if (name_ == "data") { if (has_data) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, duplicate key: data"); } has_data = true; std::vector<unsigned char> data = ParseHexV(outputs[name_].getValStr(), "Data"); CTxOut out(0, CScript() << OP_RETURN << data); rawTx.vout.push_back(out); } else if (name_ == "coinstake") { rawTx.nVersion = 1; rawTx.vout.push_back(CTxOut(0, CScript())); } else { CTxDestination destination = DecodeDestination(name_); if (!IsValidDestination(destination)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Peercoin address: ") + name_); } if (!destinations.insert(destination).second) { throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_); } CScript scriptPubKey = GetScriptForDestination(destination); CAmount nAmount = AmountFromValue(outputs[name_]); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } } return rawTx; } /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */ static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage) { UniValue entry(UniValue::VOBJ); entry.pushKV("txid", txin.prevout.hash.ToString()); entry.pushKV("vout", (uint64_t)txin.prevout.n); UniValue witness(UniValue::VARR); for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) { witness.push_back(HexStr(txin.scriptWitness.stack[i].begin(), txin.scriptWitness.stack[i].end())); } entry.pushKV("witness", witness); entry.pushKV("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); entry.pushKV("sequence", (uint64_t)txin.nSequence); entry.pushKV("error", strMessage); vErrorsRet.push_back(entry); } void ParsePrevouts(const UniValue& prevTxsUnival, FillableSigningProvider* keystore, std::map<COutPoint, Coin>& coins) { if (!prevTxsUnival.isNull()) { UniValue prevTxs = prevTxsUnival.get_array(); for (unsigned int idx = 0; idx < prevTxs.size(); ++idx) { const UniValue& p = prevTxs[idx]; if (!p.isObject()) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); } UniValue prevOut = p.get_obj(); RPCTypeCheckObj(prevOut, { {"txid", UniValueType(UniValue::VSTR)}, {"vout", UniValueType(UniValue::VNUM)}, {"scriptPubKey", UniValueType(UniValue::VSTR)}, }); uint256 txid = ParseHashO(prevOut, "txid"); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); } COutPoint out(txid, nOut); std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { auto coin = coins.find(out); if (coin != coins.end() && !coin->second.IsSpent() && coin->second.out.scriptPubKey != scriptPubKey) { std::string err("Previous output scriptPubKey mismatch:\n"); err = err + ScriptToAsmStr(coin->second.out.scriptPubKey) + "\nvs:\n"+ ScriptToAsmStr(scriptPubKey); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } Coin newcoin; newcoin.out.scriptPubKey = scriptPubKey; newcoin.out.nValue = MAX_MONEY; if (prevOut.exists("amount")) { newcoin.out.nValue = AmountFromValue(find_value(prevOut, "amount")); } newcoin.nHeight = 1; coins[out] = std::move(newcoin); } // if redeemScript and private keys were given, add redeemScript to the keystore so it can be signed const bool is_p2sh = scriptPubKey.IsPayToScriptHash(); const bool is_p2wsh = scriptPubKey.IsPayToWitnessScriptHash(); if (keystore && (is_p2sh || is_p2wsh)) { RPCTypeCheckObj(prevOut, { {"redeemScript", UniValueType(UniValue::VSTR)}, {"witnessScript", UniValueType(UniValue::VSTR)}, }, true); UniValue rs = find_value(prevOut, "redeemScript"); UniValue ws = find_value(prevOut, "witnessScript"); if (rs.isNull() && ws.isNull()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing redeemScript/witnessScript"); } // work from witnessScript when possible std::vector<unsigned char> scriptData(!ws.isNull() ? ParseHexV(ws, "witnessScript") : ParseHexV(rs, "redeemScript")); CScript script(scriptData.begin(), scriptData.end()); keystore->AddCScript(script); // Automatically also add the P2WSH wrapped version of the script (to deal with P2SH-P2WSH). // This is done for redeemScript only for compatibility, it is encouraged to use the explicit witnessScript field instead. CScript witness_output_script{GetScriptForDestination(WitnessV0ScriptHash(script))}; keystore->AddCScript(witness_output_script); if (!ws.isNull() && !rs.isNull()) { // if both witnessScript and redeemScript are provided, // they should either be the same (for backwards compat), // or the redeemScript should be the encoded form of // the witnessScript (ie, for p2sh-p2wsh) if (ws.get_str() != rs.get_str()) { std::vector<unsigned char> redeemScriptData(ParseHexV(rs, "redeemScript")); CScript redeemScript(redeemScriptData.begin(), redeemScriptData.end()); if (redeemScript != witness_output_script) { throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript does not correspond to witnessScript"); } } } if (is_p2sh) { const CTxDestination p2sh{ScriptHash(script)}; const CTxDestination p2sh_p2wsh{ScriptHash(witness_output_script)}; if (scriptPubKey == GetScriptForDestination(p2sh)) { // traditional p2sh; arguably an error if // we got here with rs.IsNull(), because // that means the p2sh script was specified // via witnessScript param, but for now // we'll just quietly accept it } else if (scriptPubKey == GetScriptForDestination(p2sh_p2wsh)) { // p2wsh encoded as p2sh; ideally the witness // script was specified in the witnessScript // param, but also support specifying it via // redeemScript param for backwards compat // (in which case ws.IsNull() == true) } else { // otherwise, can't generate scriptPubKey from // either script, so we got unusable parameters throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey"); } } else if (is_p2wsh) { // plain p2wsh; could throw an error if script // was specified by redeemScript rather than // witnessScript (ie, ws.IsNull() == true), but // accept it for backwards compat const CTxDestination p2wsh{WitnessV0ScriptHash(script)}; if (scriptPubKey != GetScriptForDestination(p2wsh)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey"); } } } } } } void SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, const UniValue& hashType, UniValue& result) { int nHashType = ParseSighashString(hashType); // Script verification errors std::map<int, std::string> input_errors; bool complete = SignTransaction(mtx, keystore, coins, nHashType, input_errors); SignTransactionResultToJSON(mtx, complete, coins, input_errors, result); } void SignTransactionResultToJSON(CMutableTransaction& mtx, bool complete, const std::map<COutPoint, Coin>& coins, std::map<int, std::string>& input_errors, UniValue& result) { // Make errors UniValue UniValue vErrors(UniValue::VARR); for (const auto& err_pair : input_errors) { if (err_pair.second == "Missing amount") { // This particular error needs to be an exception for some reason throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing amount for %s", coins.at(mtx.vin.at(err_pair.first).prevout).out.ToString())); } TxInErrorToJSON(mtx.vin.at(err_pair.first), vErrors, err_pair.second); } result.pushKV("hex", EncodeHexTx(CTransaction(mtx))); result.pushKV("complete", complete); if (!vErrors.empty()) { if (result.exists("errors")) { vErrors.push_backV(result["errors"].getValues()); } result.pushKV("errors", vErrors); } } <commit_msg>allow pubkey vouts in create raw transaction<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rpc/rawtransaction_util.h> #include <coins.h> #include <core_io.h> #include <key_io.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <rpc/request.h> #include <rpc/util.h> #include <script/sign.h> #include <script/signingprovider.h> #include <tinyformat.h> #include <univalue.h> #include <util/strencodings.h> #include <util/system.h> CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniValue& outputs_in, const UniValue& locktime, const UniValue& timestamp) { if (inputs_in.isNull() || outputs_in.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null"); UniValue inputs = inputs_in.get_array(); const bool outputs_is_obj = outputs_in.isObject(); UniValue outputs = outputs_is_obj ? outputs_in.get_obj() : outputs_in.get_array(); CMutableTransaction rawTx; rawTx.nVersion = gArgs.GetArg("-txversion", CTransaction::CURRENT_VERSION); if (!locktime.isNull()) { int64_t nLockTime = locktime.get_int64(); if (nLockTime < 0 || nLockTime > LOCKTIME_MAX) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range"); rawTx.nLockTime = nLockTime; } if (!timestamp.isNull()) { int64_t nTime = timestamp.get_int64(); if (nTime < 0 || nTime > LOCKTIME_MAX) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, timestamp out of range"); rawTx.nTime = nTime; } for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; const UniValue& o = input.get_obj(); CScript scriptSig; uint256 txid = ParseHashO(o, "txid"); const UniValue& vout_v = find_value(o, "vout"); if (!vout_v.isNum()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); uint32_t nSequence; if (rawTx.nLockTime) { nSequence = CTxIn::SEQUENCE_FINAL - 1; } else { nSequence = CTxIn::SEQUENCE_FINAL; } // set the sequence number if passed in the parameters object const UniValue& sequenceObj = find_value(o, "sequence"); if (sequenceObj.isNum()) { int64_t seqNr64 = sequenceObj.get_int64(); if (seqNr64 < 0 || seqNr64 > CTxIn::SEQUENCE_FINAL) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range"); } else { nSequence = (uint32_t)seqNr64; } } // set redeem script const UniValue& rs = find_value(o, "redeemScript"); if (!rs.isNull()) { std::vector<unsigned char> redeemScriptData(ParseHex(rs.getValStr())); CScript redeemScript(redeemScriptData.begin(), redeemScriptData.end()); scriptSig = redeemScript; } CTxIn in(COutPoint(txid, nOutput), scriptSig, nSequence); rawTx.vin.push_back(in); } if (!outputs_is_obj) { // Translate array of key-value pairs into dict UniValue outputs_dict = UniValue(UniValue::VOBJ); for (size_t i = 0; i < outputs.size(); ++i) { const UniValue& output = outputs[i]; if (!output.isObject()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair not an object as expected"); } if (output.size() != 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair must contain exactly one key"); } outputs_dict.pushKVs(output); } outputs = std::move(outputs_dict); } // Duplicate checking std::set<CTxDestination> destinations; bool has_data{false}; for (const std::string& name_ : outputs.getKeys()) { if (name_ == "data") { if (has_data) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, duplicate key: data"); } has_data = true; std::vector<unsigned char> data = ParseHexV(outputs[name_].getValStr(), "Data"); CTxOut out(0, CScript() << OP_RETURN << data); rawTx.vout.push_back(out); } else if (name_ == "coinstake") { rawTx.nVersion = 1; rawTx.vout.push_back(CTxOut(0, CScript())); } else { CTxDestination destination = DecodeDestination(name_); if (!IsValidDestination(destination)) { if(name_.rfind("pubkey:",0) == 0) { CScript scriptPubKey = CScript() << ToByteVector(ParseHex(name_.substr(7))) << OP_CHECKSIG; CTxOut out(AmountFromValue(outputs[name_]), scriptPubKey); rawTx.vout.push_back(out); continue; } throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Peercoin address: ") + name_); } if (!destinations.insert(destination).second) { throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_); } CScript scriptPubKey = GetScriptForDestination(destination); CAmount nAmount = AmountFromValue(outputs[name_]); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } } return rawTx; } /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */ static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage) { UniValue entry(UniValue::VOBJ); entry.pushKV("txid", txin.prevout.hash.ToString()); entry.pushKV("vout", (uint64_t)txin.prevout.n); UniValue witness(UniValue::VARR); for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) { witness.push_back(HexStr(txin.scriptWitness.stack[i].begin(), txin.scriptWitness.stack[i].end())); } entry.pushKV("witness", witness); entry.pushKV("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); entry.pushKV("sequence", (uint64_t)txin.nSequence); entry.pushKV("error", strMessage); vErrorsRet.push_back(entry); } void ParsePrevouts(const UniValue& prevTxsUnival, FillableSigningProvider* keystore, std::map<COutPoint, Coin>& coins) { if (!prevTxsUnival.isNull()) { UniValue prevTxs = prevTxsUnival.get_array(); for (unsigned int idx = 0; idx < prevTxs.size(); ++idx) { const UniValue& p = prevTxs[idx]; if (!p.isObject()) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); } UniValue prevOut = p.get_obj(); RPCTypeCheckObj(prevOut, { {"txid", UniValueType(UniValue::VSTR)}, {"vout", UniValueType(UniValue::VNUM)}, {"scriptPubKey", UniValueType(UniValue::VSTR)}, }); uint256 txid = ParseHashO(prevOut, "txid"); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); } COutPoint out(txid, nOut); std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { auto coin = coins.find(out); if (coin != coins.end() && !coin->second.IsSpent() && coin->second.out.scriptPubKey != scriptPubKey) { std::string err("Previous output scriptPubKey mismatch:\n"); err = err + ScriptToAsmStr(coin->second.out.scriptPubKey) + "\nvs:\n"+ ScriptToAsmStr(scriptPubKey); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } Coin newcoin; newcoin.out.scriptPubKey = scriptPubKey; newcoin.out.nValue = MAX_MONEY; if (prevOut.exists("amount")) { newcoin.out.nValue = AmountFromValue(find_value(prevOut, "amount")); } newcoin.nHeight = 1; coins[out] = std::move(newcoin); } // if redeemScript and private keys were given, add redeemScript to the keystore so it can be signed const bool is_p2sh = scriptPubKey.IsPayToScriptHash(); const bool is_p2wsh = scriptPubKey.IsPayToWitnessScriptHash(); if (keystore && (is_p2sh || is_p2wsh)) { RPCTypeCheckObj(prevOut, { {"redeemScript", UniValueType(UniValue::VSTR)}, {"witnessScript", UniValueType(UniValue::VSTR)}, }, true); UniValue rs = find_value(prevOut, "redeemScript"); UniValue ws = find_value(prevOut, "witnessScript"); if (rs.isNull() && ws.isNull()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing redeemScript/witnessScript"); } // work from witnessScript when possible std::vector<unsigned char> scriptData(!ws.isNull() ? ParseHexV(ws, "witnessScript") : ParseHexV(rs, "redeemScript")); CScript script(scriptData.begin(), scriptData.end()); keystore->AddCScript(script); // Automatically also add the P2WSH wrapped version of the script (to deal with P2SH-P2WSH). // This is done for redeemScript only for compatibility, it is encouraged to use the explicit witnessScript field instead. CScript witness_output_script{GetScriptForDestination(WitnessV0ScriptHash(script))}; keystore->AddCScript(witness_output_script); if (!ws.isNull() && !rs.isNull()) { // if both witnessScript and redeemScript are provided, // they should either be the same (for backwards compat), // or the redeemScript should be the encoded form of // the witnessScript (ie, for p2sh-p2wsh) if (ws.get_str() != rs.get_str()) { std::vector<unsigned char> redeemScriptData(ParseHexV(rs, "redeemScript")); CScript redeemScript(redeemScriptData.begin(), redeemScriptData.end()); if (redeemScript != witness_output_script) { throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript does not correspond to witnessScript"); } } } if (is_p2sh) { const CTxDestination p2sh{ScriptHash(script)}; const CTxDestination p2sh_p2wsh{ScriptHash(witness_output_script)}; if (scriptPubKey == GetScriptForDestination(p2sh)) { // traditional p2sh; arguably an error if // we got here with rs.IsNull(), because // that means the p2sh script was specified // via witnessScript param, but for now // we'll just quietly accept it } else if (scriptPubKey == GetScriptForDestination(p2sh_p2wsh)) { // p2wsh encoded as p2sh; ideally the witness // script was specified in the witnessScript // param, but also support specifying it via // redeemScript param for backwards compat // (in which case ws.IsNull() == true) } else { // otherwise, can't generate scriptPubKey from // either script, so we got unusable parameters throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey"); } } else if (is_p2wsh) { // plain p2wsh; could throw an error if script // was specified by redeemScript rather than // witnessScript (ie, ws.IsNull() == true), but // accept it for backwards compat const CTxDestination p2wsh{WitnessV0ScriptHash(script)}; if (scriptPubKey != GetScriptForDestination(p2wsh)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey"); } } } } } } void SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, const UniValue& hashType, UniValue& result) { int nHashType = ParseSighashString(hashType); // Script verification errors std::map<int, std::string> input_errors; bool complete = SignTransaction(mtx, keystore, coins, nHashType, input_errors); SignTransactionResultToJSON(mtx, complete, coins, input_errors, result); } void SignTransactionResultToJSON(CMutableTransaction& mtx, bool complete, const std::map<COutPoint, Coin>& coins, std::map<int, std::string>& input_errors, UniValue& result) { // Make errors UniValue UniValue vErrors(UniValue::VARR); for (const auto& err_pair : input_errors) { if (err_pair.second == "Missing amount") { // This particular error needs to be an exception for some reason throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing amount for %s", coins.at(mtx.vin.at(err_pair.first).prevout).out.ToString())); } TxInErrorToJSON(mtx.vin.at(err_pair.first), vErrors, err_pair.second); } result.pushKV("hex", EncodeHexTx(CTransaction(mtx))); result.pushKV("complete", complete); if (!vErrors.empty()) { if (result.exists("errors")) { vErrors.push_backV(result["errors"].getValues()); } result.pushKV("errors", vErrors); } } <|endoftext|>
<commit_before>// $Id$ /* * Example macro to run locally an analysis task for comparing the offline * with the HLT esd tree. * * The output is a root file containing the histograms defined in the * analysis task. There is one output file per detector. * * Run without arguments to get a few examples how to use the macro. * * The arguments are: * - the input file or txt file containing a list of ESDs to be processed (CreateESDChain takes 20 files as a default argument) * - the task you want to use * - the path of the task location * - the beam type, "p-p" or "Pb-Pb", this is relevant ONLY for the central barrel task at the moment and is * used to select proper binning and axes ranges for the THnSparse objects that it fills * - options to make the central barrel task more flexible and lightweight; you can select if you want to * fill the THnSparse object with only event or track properties or only HLT data or only OFF * possible options are: event-off event-hlt track-off track-hlt, all are turned on by default * - boolean variable for selecting events which contain an HLT trigger * - number of events to be analyzed * * If alien:// is placed before the input filename, then the macro connects to the grid to access the file. * * In case you want to run over many ESD files, then prepare a list of them in a .txt file and they will be chained for the analysis. * The .txt file takes the place of the first argument in that case. * * @ingroup alihlt_qa * @author Kalliopi.Kanaki@ift.uib.no, Hege.Erdal@student.uib.no */ void compare_HLT_offline_local( TString file ,const char* detectorTask="global" ,TString taskFolder="$ALICE_ROOT/HLT/QA/tasks/" ,TString beamType="p-p" ,TString options="event-off event-hlt track-off track-hlt" ,bool fUseHLTTrigger=kFALSE ,Long64_t nEvents=1234567890 ) { TStopwatch timer; timer.Start(); gSystem->Load("libTree.so"); gSystem->Load("libGeom.so"); gSystem->Load("libVMC.so"); gSystem->Load("libPhysics.so"); //----------- Loading the required libraries ---------// gSystem->Load("libSTEERBase.so"); gSystem->Load("libESD.so"); gSystem->Load("libAOD.so"); gSystem->Load("libANALYSIS.so"); gSystem->Load("libANALYSISalice.so"); gSystem->Load("libHLTbase.so"); gSystem->AddIncludePath("-I$ALICE_ROOT/HLT/BASE -I$ALICE_ROOT/PWG1/TPC -I. -I$ALICE_ROOT/STEER -I$ALICE_ROOT/ANALYSIS"); gSystem->Load("libTPCcalib.so"); gSystem->Load("libTRDbase.so"); gSystem->Load("libTRDrec.so"); gSystem->Load("libITSbase.so"); gSystem->Load("libITSrec.so"); gSystem->Load("libTENDER.so"); gSystem->Load("libPWG1.so"); gROOT->ProcessLine(".include $ALICE_ROOT/include"); //gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C"); Bool_t bPHOS = kFALSE, bGLOBAL = kFALSE, bEMCAL = kFALSE, bPWG1 = kFALSE, bD0 = kFALSE, bCB = kFALSE; TString allArgs = detectorTask; TString argument; TObjArray *pTokens = allArgs.Tokenize(" "); if(pTokens){ for(int i=0; i<pTokens->GetEntries(); i++){ argument=((TObjString*)pTokens->At(i))->GetString(); if(argument.IsNull()) continue; if(argument.CompareTo("phos", TString::kIgnoreCase)==0){ bPHOS = kTRUE; continue; } else if(argument.CompareTo("emcal", TString::kIgnoreCase)==0){ bEMCAL = kTRUE; continue; } if(argument.CompareTo("global", TString::kIgnoreCase)==0){ bGLOBAL = kTRUE; continue; } if(argument.CompareTo("pwg1", TString::kIgnoreCase)==0){ bPWG1 = kTRUE; continue; } if(argument.CompareTo("D0", TString::kIgnoreCase)==0){ bD0 = kTRUE; continue; } if(argument.CompareTo("cb", TString::kIgnoreCase)==0){ bCB = kTRUE; continue; } else break; } } //-------------- Compile the analysis tasks ---------- // if(bPHOS){ //gSystem->Load("libHLTbase"); gSystem->Load("libAliHLTUtil"); gSystem->Load("libAliHLTGlobal"); TString strTask1("AliAnalysisTaskHLTCalo.cxx+"); TString strTask2("AliAnalysisTaskHLTPHOS.cxx+"); gROOT->LoadMacro(taskFolder+strTask1); gROOT->LoadMacro(taskFolder+strTask2); cout << "\n========= You are loading the following tasks --> "<< (taskFolder+strTask1).Chop() << " and " << (taskFolder+strTask2).Chop() << endl; } if(bEMCAL){ //gSystem->Load("libHLTbase"); gSystem->Load("libAliHLTUtil"); gSystem->Load("libAliHLTGlobal"); TString strTask1("AliAnalysisTaskHLTCalo.cxx+"); TString strTask2("AliAnalysisTaskHLTEMCAL.cxx+"); gROOT->LoadMacro(taskFolder+strTask1); gROOT->LoadMacro(taskFolder+strTask2); cout << "\n========= You are loading the following tasks --> "<< (taskFolder+strTask1).Chop() << " and " << (taskFolder+strTask2).Chop() << endl; } if(bGLOBAL){ TString strTask("AliAnalysisTaskHLT.cxx+"); gROOT->LoadMacro(taskFolder+strTask); cout << "\n========= You are loading the following task --> "<< (taskFolder+strTask).Chop() << endl; } if(bD0){ TString strTask("AliAnalysisTaskD0Trigger.cxx+"); gROOT->LoadMacro(taskFolder+strTask); cout << "\n========= You are loading the following task --> "<< (taskFolder+strTask).Chop() << endl; } if(bCB){ TString strTask("AliAnalysisTaskHLTCentralBarrel.cxx+"); gROOT->LoadMacro(taskFolder+strTask); cout << "\n========= You are loading the following task --> "<< (taskFolder+strTask).Chop() << endl; } if(bPWG1) gROOT->LoadMacro("$ALICE_ROOT/HLT/QA/tasks/macros/AddTaskPerformance.C"); if(file.Contains("alien")) TGrid::Connect("alien://"); if(file.Contains("AliESDs.root")){ TChain *chain = new TChain("esdTree"); chain->Add(file); } //Constructs chain from filenames in *.txt //on the form $DIR/AliESDs.root else if(file.Contains(".txt")){ gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C"); chain=CreateESDChain(file.Data(),200); } else if(!file){ printf("File %s does not exist or is corrupted.\n",file.Data()); return; } if(!chain){ Printf("Chain is empty.\n"); return; } //-------- Make the analysis manager ---------------// AliAnalysisManager *mgr = new AliAnalysisManager("TestManager"); AliESDInputHandler *esdH = new AliESDInputHandler; //For the PWG1 task, setting HLT is handled inside AliPerformanceTask.C if(!bPWG1) esdH->SetReadHLT(); esdH->SetReadFriends(kFALSE); mgr->SetInputEventHandler(esdH); mgr->SetNSysInfo(1000); //AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(kFALSE,kTRUE); //-------------- define the tasks ------------// if(bPHOS){ AliAnalysisTaskHLTPHOS *taskPHOS = new AliAnalysisTaskHLTPHOS("offhlt_comparison_PHOS"); taskPHOS->SetUseHLTTriggerDecision(fUseHLTTrigger); if(fUseHLTTrigger==kTRUE) printf("\n\nOnly HLT triggered events will be used to fill the distributions for task %s.\n\n", taskPHOS->GetName()); mgr->AddTask(taskPHOS); if(fUseHLTTrigger==kFALSE) AliAnalysisDataContainer *coutputPHOS = mgr->CreateContainer("phos_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-PHOS-comparison.root"); else AliAnalysisDataContainer *coutputPHOS = mgr->CreateContainer("phos_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-PHOS-comparison_triggered.root"); mgr->ConnectInput(taskPHOS,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskPHOS,1,coutputPHOS); } if(bEMCAL){ AliAnalysisTaskHLTEMCAL *taskEMCAL = new AliAnalysisTaskHLTEMCAL("offhlt_comparison_EMCAL"); taskEMCAL->SetUseHLTTriggerDecision(fUseHLTTrigger); if(fUseHLTTrigger==kTRUE) printf("\n\nOnly HLT triggered events will be used to fill the distributions for task %s.\n\n", taskEMCAL->GetName()); mgr->AddTask(taskEMCAL); if(fUseHLTTrigger==kFALSE) AliAnalysisDataContainer *coutputEMCAL = mgr->CreateContainer("emcal_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-EMCAL-comparison.root"); else AliAnalysisDataContainer *coutputEMCAL = mgr->CreateContainer("emcal_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-EMCAL-comparison_triggered.root"); mgr->ConnectInput(taskEMCAL,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskEMCAL,1,coutputEMCAL); } if(bGLOBAL){ AliAnalysisTaskHLT *taskGLOBAL = new AliAnalysisTaskHLT("offhlt_comparison_GLOBAL"); taskGLOBAL->SetUseHLTTriggerDecision(fUseHLTTrigger); if(fUseHLTTrigger==kTRUE) printf("\n\nOnly HLT triggered events will be used to fill the distributions for task %s.\n\n", taskGLOBAL->GetName()); //taskGLOBAL->SelectCollisionCandidates(); mgr->AddTask(taskGLOBAL); if(fUseHLTTrigger==kFALSE) AliAnalysisDataContainer *coutputGLOBAL = mgr->CreateContainer("global_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-GLOBAL-comparison.root"); else AliAnalysisDataContainer *coutputGLOBAL = mgr->CreateContainer("global_histograms",TList::Class(), AliAnalysisManager::kOutputContainer,"HLT-OFFLINE-GLOBAL-comparison_triggered.root"); mgr->ConnectInput(taskGLOBAL,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskGLOBAL,1,coutputGLOBAL); } if(bPWG1){ Bool_t hasMC=kFALSE; // -- Add Task for HLT and Offline AliPerformanceTask *HLTtpcQA = AddTaskPerformance(hasMC,kFALSE,kTRUE); AliPerformanceTask *tpcQA = AddTaskPerformance(hasMC,kFALSE); if(!HLTtpcQA || !tpcQA) { Error("RunPerformanceTrain","AliPerformanceTask not created!"); return; } } if(bD0){ float cuts[7]={0.5,0.04,0.7,0.8,0.05,-0.00025,0.7}; AliAnalysisTaskD0Trigger *taskD0 = new AliAnalysisTaskD0Trigger("offhlt_comparison_D0",cuts); mgr->AddTask(taskD0); AliAnalysisDataContainer *coutputD0 = mgr->CreateContainer("D0_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-D0-comparison.root"); mgr->ConnectInput(taskD0,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskD0,1,coutputD0); } if(bCB){ AliAnalysisTaskHLTCentralBarrel *taskCB = new AliAnalysisTaskHLTCentralBarrel("offhlt_comparison_CB"); mgr->AddTask(taskCB); taskCB->SetBeamType(beamType); if(beamType.Contains("Pb-Pb")){ gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C"); AliCentralitySelectionTask *taskCentrality = AddTaskCentrality(); } taskCB->SetOptions(options); AliAnalysisDataContainer *coutputCB = mgr->CreateContainer("esd_thnsparse", TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-CentralBarrel-comparison.root"); mgr->ConnectInput(taskCB,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskCB,1,coutputCB); } if (!mgr->InitAnalysis()) return; mgr->PrintStatus(); mgr->StartAnalysis("local",chain, nEvents); timer.Stop(); timer.Print(); } void compare_HLT_offline_local(){ cout << " " << endl; cout << " Usage examples:" << endl; cout << " compare-HLT-offline-local.C'(file, taskOption, taskFolder, beamType, options, fUseHLTTrigger, nEvents)' 2>&1 | tee log" << endl; cout << " compare-HLT-offline-local.C'(\"AliESDs.root\",\"global\")' 2>&1 | tee log" << endl; cout << " compare-HLT-offline-local.C'(\"AliESDs.root\",\"global\",\"./\", \"p-p\", \"event-off event-hlt track-off track-hlt\", kFALSE, nEvents)' 2>&1 | tee log" << endl; cout << " compare-HLT-offline-local.C'(\"AliESDs.root\",\"global phos cb D0\", \"./\", \"Pb-Pb\", \"event-hlt\", kTRUE, nEvents)' 2>&1 | tee log" << endl; cout << " compare-HLT-offline-local.C'(\"alien:///alice/data/2010/LHC10b/000115322/ESDs/pass1/10000115322040.20/AliESDs.root\",\"global\")' 2>&1 | tee log" << endl; cout << " " << endl; } <commit_msg>- added the new function call that sets the pass for the centrality task<commit_after>// $Id$ /* * Example macro to run locally an analysis task for comparing the offline * with the HLT esd tree. * * The output is a root file containing the histograms defined in the * analysis task. There is one output file per detector. * * Run without arguments to get a few examples how to use the macro. * * The arguments are: * - the input file or txt file containing a list of ESDs to be processed (CreateESDChain takes 20 files as a default argument) * - the task you want to use * - the path of the task location * - the beam type, "p-p" or "Pb-Pb", this is relevant ONLY for the central barrel task at the moment and is * used to select proper binning and axes ranges for the THnSparse objects that it fills * - options to make the central barrel task more flexible and lightweight; you can select if you want to * fill the THnSparse object with only event or track properties or only HLT data or only OFF * possible options are: event-off event-hlt track-off track-hlt, all are turned on by default * - boolean variable for selecting events which contain an HLT trigger * - number of events to be analyzed * * If alien:// is placed before the input filename, then the macro connects to the grid to access the file. * * In case you want to run over many ESD files, then prepare a list of them in a .txt file and they will be chained for the analysis. * The .txt file takes the place of the first argument in that case. * * @ingroup alihlt_qa * @author Kalliopi.Kanaki@ift.uib.no, Hege.Erdal@student.uib.no */ void compare_HLT_offline_local( TString file ,const char* detectorTask="global" ,TString taskFolder="$ALICE_ROOT/HLT/QA/tasks/" ,TString beamType="p-p" ,TString options="event-off event-hlt track-off track-hlt" ,bool fUseHLTTrigger=kFALSE ,Long64_t nEvents=1234567890 ) { TStopwatch timer; timer.Start(); gSystem->Load("libTree.so"); gSystem->Load("libGeom.so"); gSystem->Load("libVMC.so"); gSystem->Load("libPhysics.so"); //----------- Loading the required libraries ---------// gSystem->Load("libSTEERBase.so"); gSystem->Load("libESD.so"); gSystem->Load("libAOD.so"); gSystem->Load("libANALYSIS.so"); gSystem->Load("libANALYSISalice.so"); gSystem->Load("libHLTbase.so"); gSystem->AddIncludePath("-I$ALICE_ROOT/HLT/BASE -I$ALICE_ROOT/PWG1/TPC -I. -I$ALICE_ROOT/STEER -I$ALICE_ROOT/ANALYSIS"); gSystem->Load("libTPCcalib.so"); gSystem->Load("libTRDbase.so"); gSystem->Load("libTRDrec.so"); gSystem->Load("libITSbase.so"); gSystem->Load("libITSrec.so"); gSystem->Load("libTENDER.so"); gSystem->Load("libPWG1.so"); gROOT->ProcessLine(".include $ALICE_ROOT/include"); //gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C"); Bool_t bPHOS = kFALSE, bGLOBAL = kFALSE, bEMCAL = kFALSE, bPWG1 = kFALSE, bD0 = kFALSE, bCB = kFALSE; TString allArgs = detectorTask; TString argument; TObjArray *pTokens = allArgs.Tokenize(" "); if(pTokens){ for(int i=0; i<pTokens->GetEntries(); i++){ argument=((TObjString*)pTokens->At(i))->GetString(); if(argument.IsNull()) continue; if(argument.CompareTo("phos", TString::kIgnoreCase)==0){ bPHOS = kTRUE; continue; } else if(argument.CompareTo("emcal", TString::kIgnoreCase)==0){ bEMCAL = kTRUE; continue; } if(argument.CompareTo("global", TString::kIgnoreCase)==0){ bGLOBAL = kTRUE; continue; } if(argument.CompareTo("pwg1", TString::kIgnoreCase)==0){ bPWG1 = kTRUE; continue; } if(argument.CompareTo("D0", TString::kIgnoreCase)==0){ bD0 = kTRUE; continue; } if(argument.CompareTo("cb", TString::kIgnoreCase)==0){ bCB = kTRUE; continue; } else break; } } //-------------- Compile the analysis tasks ---------- // if(bPHOS){ //gSystem->Load("libHLTbase"); gSystem->Load("libAliHLTUtil"); gSystem->Load("libAliHLTGlobal"); TString strTask1("AliAnalysisTaskHLTCalo.cxx+"); TString strTask2("AliAnalysisTaskHLTPHOS.cxx+"); gROOT->LoadMacro(taskFolder+strTask1); gROOT->LoadMacro(taskFolder+strTask2); cout << "\n========= You are loading the following tasks --> "<< (taskFolder+strTask1).Chop() << " and " << (taskFolder+strTask2).Chop() << endl; } if(bEMCAL){ //gSystem->Load("libHLTbase"); gSystem->Load("libAliHLTUtil"); gSystem->Load("libAliHLTGlobal"); TString strTask1("AliAnalysisTaskHLTCalo.cxx+"); TString strTask2("AliAnalysisTaskHLTEMCAL.cxx+"); gROOT->LoadMacro(taskFolder+strTask1); gROOT->LoadMacro(taskFolder+strTask2); cout << "\n========= You are loading the following tasks --> "<< (taskFolder+strTask1).Chop() << " and " << (taskFolder+strTask2).Chop() << endl; } if(bGLOBAL){ TString strTask("AliAnalysisTaskHLT.cxx+"); gROOT->LoadMacro(taskFolder+strTask); cout << "\n========= You are loading the following task --> "<< (taskFolder+strTask).Chop() << endl; } if(bD0){ TString strTask("AliAnalysisTaskD0Trigger.cxx+"); gROOT->LoadMacro(taskFolder+strTask); cout << "\n========= You are loading the following task --> "<< (taskFolder+strTask).Chop() << endl; } if(bCB){ TString strTask("AliAnalysisTaskHLTCentralBarrel.cxx+"); gROOT->LoadMacro(taskFolder+strTask); cout << "\n========= You are loading the following task --> "<< (taskFolder+strTask).Chop() << endl; } if(bPWG1) gROOT->LoadMacro("$ALICE_ROOT/HLT/QA/tasks/macros/AddTaskPerformance.C"); if(file.Contains("alien")) TGrid::Connect("alien://"); if(file.Contains("AliESDs.root")){ TChain *chain = new TChain("esdTree"); chain->Add(file); } //Constructs chain from filenames in *.txt //on the form $DIR/AliESDs.root else if(file.Contains(".txt")){ gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C"); chain=CreateESDChain(file.Data(),200); } else if(!file){ printf("File %s does not exist or is corrupted.\n",file.Data()); return; } if(!chain){ Printf("Chain is empty.\n"); return; } //-------- Make the analysis manager ---------------// AliAnalysisManager *mgr = new AliAnalysisManager("TestManager"); AliESDInputHandler *esdH = new AliESDInputHandler; //For the PWG1 task, setting HLT is handled inside AliPerformanceTask.C if(!bPWG1) esdH->SetReadHLT(); esdH->SetReadFriends(kFALSE); mgr->SetInputEventHandler(esdH); mgr->SetNSysInfo(1000); //AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(kFALSE,kTRUE); //-------------- define the tasks ------------// if(bPHOS){ AliAnalysisTaskHLTPHOS *taskPHOS = new AliAnalysisTaskHLTPHOS("offhlt_comparison_PHOS"); taskPHOS->SetUseHLTTriggerDecision(fUseHLTTrigger); if(fUseHLTTrigger==kTRUE) printf("\n\nOnly HLT triggered events will be used to fill the distributions for task %s.\n\n", taskPHOS->GetName()); mgr->AddTask(taskPHOS); if(fUseHLTTrigger==kFALSE) AliAnalysisDataContainer *coutputPHOS = mgr->CreateContainer("phos_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-PHOS-comparison.root"); else AliAnalysisDataContainer *coutputPHOS = mgr->CreateContainer("phos_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-PHOS-comparison_triggered.root"); mgr->ConnectInput(taskPHOS,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskPHOS,1,coutputPHOS); } if(bEMCAL){ AliAnalysisTaskHLTEMCAL *taskEMCAL = new AliAnalysisTaskHLTEMCAL("offhlt_comparison_EMCAL"); taskEMCAL->SetUseHLTTriggerDecision(fUseHLTTrigger); if(fUseHLTTrigger==kTRUE) printf("\n\nOnly HLT triggered events will be used to fill the distributions for task %s.\n\n", taskEMCAL->GetName()); mgr->AddTask(taskEMCAL); if(fUseHLTTrigger==kFALSE) AliAnalysisDataContainer *coutputEMCAL = mgr->CreateContainer("emcal_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-EMCAL-comparison.root"); else AliAnalysisDataContainer *coutputEMCAL = mgr->CreateContainer("emcal_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-EMCAL-comparison_triggered.root"); mgr->ConnectInput(taskEMCAL,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskEMCAL,1,coutputEMCAL); } if(bGLOBAL){ AliAnalysisTaskHLT *taskGLOBAL = new AliAnalysisTaskHLT("offhlt_comparison_GLOBAL"); taskGLOBAL->SetUseHLTTriggerDecision(fUseHLTTrigger); if(fUseHLTTrigger==kTRUE) printf("\n\nOnly HLT triggered events will be used to fill the distributions for task %s.\n\n", taskGLOBAL->GetName()); //taskGLOBAL->SelectCollisionCandidates(); mgr->AddTask(taskGLOBAL); if(fUseHLTTrigger==kFALSE) AliAnalysisDataContainer *coutputGLOBAL = mgr->CreateContainer("global_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-GLOBAL-comparison.root"); else AliAnalysisDataContainer *coutputGLOBAL = mgr->CreateContainer("global_histograms",TList::Class(), AliAnalysisManager::kOutputContainer,"HLT-OFFLINE-GLOBAL-comparison_triggered.root"); mgr->ConnectInput(taskGLOBAL,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskGLOBAL,1,coutputGLOBAL); } if(bPWG1){ Bool_t hasMC=kFALSE; // -- Add Task for HLT and Offline AliPerformanceTask *HLTtpcQA = AddTaskPerformance(hasMC,kFALSE,kTRUE); AliPerformanceTask *tpcQA = AddTaskPerformance(hasMC,kFALSE); if(!HLTtpcQA || !tpcQA) { Error("RunPerformanceTrain","AliPerformanceTask not created!"); return; } } if(bD0){ float cuts[7]={0.5,0.04,0.7,0.8,0.05,-0.00025,0.7}; AliAnalysisTaskD0Trigger *taskD0 = new AliAnalysisTaskD0Trigger("offhlt_comparison_D0",cuts); mgr->AddTask(taskD0); AliAnalysisDataContainer *coutputD0 = mgr->CreateContainer("D0_histograms",TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-D0-comparison.root"); mgr->ConnectInput(taskD0,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskD0,1,coutputD0); } if(bCB){ AliAnalysisTaskHLTCentralBarrel *taskCB = new AliAnalysisTaskHLTCentralBarrel("offhlt_comparison_CB"); mgr->AddTask(taskCB); taskCB->SetBeamType(beamType); if(beamType.Contains("Pb-Pb")){ gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C"); AliCentralitySelectionTask *taskCentrality = AddTaskCentrality(); taskCentrality->SetPass(1); } taskCB->SetOptions(options); AliAnalysisDataContainer *coutputCB = mgr->CreateContainer("esd_thnsparse", TList::Class(), AliAnalysisManager::kOutputContainer, "HLT-OFFLINE-CentralBarrel-comparison.root"); mgr->ConnectInput(taskCB,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskCB,1,coutputCB); } if (!mgr->InitAnalysis()) return; mgr->PrintStatus(); mgr->StartAnalysis("local",chain, nEvents); timer.Stop(); timer.Print(); } void compare_HLT_offline_local(){ cout << " " << endl; cout << " Usage examples:" << endl; cout << " compare-HLT-offline-local.C'(file, taskOption, taskFolder, beamType, options, fUseHLTTrigger, nEvents)' 2>&1 | tee log" << endl; cout << " compare-HLT-offline-local.C'(\"AliESDs.root\",\"global\")' 2>&1 | tee log" << endl; cout << " compare-HLT-offline-local.C'(\"AliESDs.root\",\"global\",\"./\", \"p-p\", \"event-off event-hlt track-off track-hlt\", kFALSE, nEvents)' 2>&1 | tee log" << endl; cout << " compare-HLT-offline-local.C'(\"AliESDs.root\",\"global phos cb D0\", \"./\", \"Pb-Pb\", \"event-hlt\", kTRUE, nEvents)' 2>&1 | tee log" << endl; cout << " compare-HLT-offline-local.C'(\"alien:///alice/data/2010/LHC10b/000115322/ESDs/pass1/10000115322040.20/AliESDs.root\",\"global\")' 2>&1 | tee log" << endl; cout << " " << endl; } <|endoftext|>
<commit_before>#ifndef _WIN32 #include "WindowsContainer.h" int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WindowsContainer win; win.main(hInstance, hPrevInstance, lpCmdLine, nCmdShow); return 0; } #else //#include "vld.h" //insert debug-flag here #include "LinuxContainer.h" int main(int argc, char** argv) { LinuxContainer* linuxContainer = new LinuxContainer(); linuxContainer->mainContainer(argc, argv); DELETE_NULL(linuxContainer); return 0; } #endif //_WIN32 <commit_msg>redundant<commit_after>#ifndef _WIN32 #include "WindowsContainer.h" int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WindowsContainer win; win.main(hInstance, hPrevInstance, lpCmdLine, nCmdShow); return 0; } #else #include "vld.h" //insert debug-flag here #include "LinuxContainer.h" int main(int argc, char** argv) { LinuxContainer* linuxContainer = new LinuxContainer(); linuxContainer->mainContainer(argc, argv); DELETE_NULL(linuxContainer); return 0; } #endif //_WIN32 <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "customListView.h" #include "rosterItem.h" #include <QApplication> #include <QMenu> #include <QKeyEvent> customListView::customListView(QWidget* parent):QListView(parent), m_chat("Chat", this), m_profile("View Profile", this) { bool check = connect(this, SIGNAL(pressed(const QModelIndex&)), this, SLOT(mousePressed(const QModelIndex&))); Q_ASSERT(check); check = connect(this, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(doubleClicked(const QModelIndex&))); Q_ASSERT(check); check = connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clicked(const QModelIndex&))); Q_ASSERT(check); check = connect(&m_chat, SIGNAL(triggered()), this, SLOT(showChatDialog_helper())); Q_ASSERT(check); } bool customListView::event(QEvent* e) { return QListView::event(e); } void customListView::mousePressed(const QModelIndex& index) { if(QApplication::mouseButtons() == Qt::RightButton) { QString bareJid = index.data().toString(); QMenu menu(this); menu.addAction(&m_chat); menu.setDefaultAction(&m_chat); menu.addAction(&m_profile); menu.exec(QCursor::pos()); } } void customListView::doubleClicked(const QModelIndex& index) { m_chat.trigger(); } void customListView::clicked(const QModelIndex& index) { } QString customListView::selectedBareJid() { if(selectedIndexes().size() > 0) return selectedIndexes().at(0).data(rosterItem::BareJid).toString(); else return ""; } void customListView::showChatDialog_helper() { QString bareJid = selectedBareJid(); if(!bareJid.isEmpty()) emit showChatDialog(bareJid); } void customListView::showProfile_helper() { QString bareJid = selectedBareJid(); if(!bareJid.isEmpty()) emit showProfile(bareJid); } void customListView::keyPressEvent(QKeyEvent* event1) { if(event1->key() == Qt::Key_Return) { showChatDialog_helper(); } QListView::keyPressEvent(event1); } <commit_msg>prepare for profileDialog<commit_after>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "customListView.h" #include "rosterItem.h" #include <QApplication> #include <QMenu> #include <QKeyEvent> customListView::customListView(QWidget* parent):QListView(parent), m_chat("Chat", this), m_profile("View Profile", this) { bool check = connect(this, SIGNAL(pressed(const QModelIndex&)), this, SLOT(mousePressed(const QModelIndex&))); Q_ASSERT(check); check = connect(this, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(doubleClicked(const QModelIndex&))); Q_ASSERT(check); check = connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clicked(const QModelIndex&))); Q_ASSERT(check); check = connect(&m_chat, SIGNAL(triggered()), this, SLOT(showChatDialog_helper())); Q_ASSERT(check); check = connect(&m_profile, SIGNAL(triggered()), this, SLOT(showProfile_helper())); Q_ASSERT(check); } bool customListView::event(QEvent* e) { return QListView::event(e); } void customListView::mousePressed(const QModelIndex& index) { if(QApplication::mouseButtons() == Qt::RightButton) { QString bareJid = index.data().toString(); QMenu menu(this); menu.addAction(&m_chat); menu.setDefaultAction(&m_chat); menu.addAction(&m_profile); menu.exec(QCursor::pos()); } } void customListView::doubleClicked(const QModelIndex& index) { m_chat.trigger(); } void customListView::clicked(const QModelIndex& index) { } QString customListView::selectedBareJid() { if(selectedIndexes().size() > 0) return selectedIndexes().at(0).data(rosterItem::BareJid).toString(); else return ""; } void customListView::showChatDialog_helper() { QString bareJid = selectedBareJid(); if(!bareJid.isEmpty()) emit showChatDialog(bareJid); } void customListView::showProfile_helper() { QString bareJid = selectedBareJid(); if(!bareJid.isEmpty()) emit showProfile(bareJid); } void customListView::keyPressEvent(QKeyEvent* event1) { if(event1->key() == Qt::Key_Return) { showChatDialog_helper(); } QListView::keyPressEvent(event1); } <|endoftext|>
<commit_before>/* This file is part of the kblog library. Copyright (c) 2007 Mike Arthur <mike@mikearthur.co.uk> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "movabletype.h" #include "movabletype_p.h" #include "blogposting.h" #include <kxmlrpcclient/client.h> #include <KDebug> #include <KLocale> #include <KDateTime> #include <QtCore/QStringList> using namespace KBlog; MovableType::MovableType( const KUrl &server, QObject *parent ) : MetaWeblog( server, *new MovableTypePrivate, parent ) { setUrl( server ); } MovableType::~MovableType() { } void MovableType::createPosting( KBlog::BlogPosting *posting ) { Q_D(MovableType); if ( !posting ) { kDebug(5323) << "MovableType::createPosting: posting is a null pointer"; emit error ( Other, i18n( "Posting is a null pointer." ) ); return; } unsigned int i = d->callCounter++; d->callMap[ i ] = posting; kDebug(5323) << "Creating new Posting with blogId" << blogId(); QList<QVariant> args( d->defaultArgs( blogId() ) ); QMap<QString, QVariant> map; map["categories"] = posting->categories(); map["description"] = posting->content(); map["title"] = posting->title(); map["dateCreated"] = posting->creationDateTime().toUtc().dateTime(); map["mt_allow_comments"] = (int)posting->isCommentAllowed(); map["mt_allow_pings"] = (int)posting->isTrackBackAllowed(); map["mt_text_more"] = posting->summary(); //map["mt_tb_ping_urls"] check for that, i think this should only be done on the server. args << map; args << QVariant( posting->isPublished() ); d->mXmlRpcClient->call ( "metaWeblog.newPost", args, this, SLOT( slotCreatePosting( const QList<QVariant>&, const QVariant& ) ), this, SLOT ( slotError( int, const QString&, const QVariant& ) ), QVariant( i ) ); } void MovableType::modifyPosting( KBlog::BlogPosting *posting ) { Q_D(MovableType); if ( !posting ) { kDebug(5323) << "MovableType::modifyPosting: posting is a null pointer"; emit error ( Other, i18n( "Posting is a null pointer." ) ); return; } unsigned int i = d->callCounter++; d->callMap[ i ] = posting; kDebug(5323) << "Uploading Posting with postId" << posting->postingId(); QList<QVariant> args( d->defaultArgs( posting->postingId() ) ); QMap<QString, QVariant> map; map["categories"] = posting->categories(); map["description"] = posting->content(); map["title"] = posting->title(); map["lastModified"] = posting->modificationDateTime().toUtc().dateTime(); map["mt_allow_comments"] = (int)posting->isCommentAllowed(); map["mt_allow_pings"] = (int)posting->isTrackBackAllowed(); map["mt_text_more"] = posting->summary(); args << map; args << QVariant( posting->isPublished() ); d->mXmlRpcClient->call( "metaWeblog.editPost", args, this, SLOT( slotModifyPosting( const QList<QVariant>&, const QVariant& ) ), this, SLOT ( slotError( int, const QString&, const QVariant& ) ), QVariant( i ) ); } void MovableType::fetchPosting( KBlog::BlogPosting *posting ) { Q_D(MovableType); if ( !posting ) { kDebug(5323) << "MovableType::fetchPosting: posting is a null pointer"; emit error ( Other, i18n( "Posting is a null pointer." ) ); return; } unsigned int i = d->callCounter++; d->callMap[ i ] = posting; kDebug(5323) << "Fetching Posting with url" << posting->postingId(); QList<QVariant> args( d->defaultArgs( posting->postingId() ) ); d->mXmlRpcClient->call( "metaWeblog.getPost", args, this, SLOT( slotFetchPosting( const QList<QVariant>&, const QVariant& ) ), this, SLOT( slotError( int, const QString&, const QVariant& ) ), QVariant( i ) ); } QString MovableType::interfaceName() const { return QLatin1String( "Movable Type" ); } void MovableType::listRecentPostings( const int number ) { //TODO } void MovableType::listTrackbackPings( KBlog::BlogPosting *posting ) { //TODO /* Q_D(MovableType); d->mXmlRpcClient->call( "mt.getTracebackPings", args, d, SLOT( slotListTrackbackPings( const QList<QVariant>&, const QVariant& ) ), d, SLOT( slotError( int, const QString&, const QVariant& ) ) ); */ } MovableTypePrivate::MovableTypePrivate() { mXmlRpcClient = 0; } MovableTypePrivate::~MovableTypePrivate() { delete mXmlRpcClient; } QList<QVariant> MovableTypePrivate::defaultArgs( const QString &id ) { Q_Q(MovableType); QList<QVariant> args; if ( id.toInt() ) { args << QVariant( id.toInt() ); } if ( !id.toInt() && !id.isNull() ){ args << QVariant( id ); } args << QVariant( q->username() ) << QVariant( q->password() ); return args; } bool MovableTypePrivate::readPostingFromMap( BlogPosting *post, const QMap<QString, QVariant> &postInfo ) { //TODO return false; } void MovableTypePrivate::slotCreatePosting( const QList<QVariant> &result, const QVariant &id ) { //TODO 7 new keys are: // int mt_allow_comments: the value for the allow_comments field // int mt_allow_pings, the value for the allow_pings field // String mt_convert_breaks, the value for the convert_breaks field // String mt_text_more, the value for the additional entry text // String mt_excerpt, the value for the excerpt field // String mt_keywords, the value for the keywords field // array mt_tb_ping_urls, the list of TrackBack ping URLs for this entry } void MovableTypePrivate::slotError( int number, const QString &errorString, const QVariant &id ) { //TODO } void MovableTypePrivate::slotFetchPosting( const QList<QVariant> &result, const QVariant &id ) { //TODO 6 new keys are: // int mt_allow_comments: the value for the allow_comments field // int mt_allow_pings, the value for the allow_pings field // String mt_convert_breaks, the value for the convert_breaks field // String mt_text_more, the value for the additional entry text // String mt_excerpt, the value for the excerpt field // String mt_keywords, the value for the keywords field } void MovableTypePrivate::slotListRecentPostings( const QList<QVariant> &result, const QVariant &id ) { //TODO 6 new keys are: // int mt_allow_comments: the value for the allow_comments field // int mt_allow_pings, the value for the allow_pings field // String mt_convert_breaks, the value for the convert_breaks field // String mt_text_more, the value for the additional entry text // String mt_excerpt, the value for the excerpt field // String mt_keywords, the value for the keywords field } void MovableTypePrivate::slotListTrackbackPings( const QList<QVariant> &result, const QVariant &id ) { //TODO Contains: // String pingTitle: the title of the entry sent in the ping // String pingURL: the URL of the entry // String pingIP: the IP address of the host that sent the ping } void MovableTypePrivate::slotModifyPosting( const QList<QVariant> &result, const QVariant &id ) { //TODO 5 new keys are: // int mt_allow_comments: the value for the allow_comments field // int mt_allow_pings, the value for the allow_pings field // String mt_convert_breaks, the value for the convert_breaks field // String mt_text_more, the value for the additional entry text // String mt_excerpt, the value for the excerpt field // String mt_keywords, the value for the keywords field // array mt_tb_ping_urls, the list of TrackBack ping URLs for this entry } #include "movabletype.moc" <commit_msg>MovableType mostly done. Unit test and TrackBackPings missing.<commit_after>/* This file is part of the kblog library. Copyright (c) 2004 Reinhold Kainhofer <reinhold@kainhofer.com> Copyright (c) 2006-2007 Christian Weilbach <christian_weilbach@web.de> Copyright (c) 2007 Mike Arthur <mike@mikearthur.co.uk> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "movabletype.h" #include "movabletype_p.h" #include "blogposting.h" #include <kxmlrpcclient/client.h> #include <KDebug> #include <KLocale> #include <KDateTime> #include <QtCore/QStringList> using namespace KBlog; MovableType::MovableType( const KUrl &server, QObject *parent ) : MetaWeblog( server, *new MovableTypePrivate, parent ) { setUrl( server ); } MovableType::~MovableType() { } void MovableType::createPosting( KBlog::BlogPosting *posting ) { //TODO 3 new keys are: // String mt_convert_breaks, the value for the convert_breaks field // String mt_text_more, the value for the additional entry text // array mt_tb_ping_urls, the list of TrackBack ping URLs for this entry Q_D(MovableType); if ( !posting ) { kDebug(5323) << "MovableType::createPosting: posting is a null pointer"; emit error ( Other, i18n( "Posting is a null pointer." ) ); return; } unsigned int i = d->callCounter++; d->callMap[ i ] = posting; kDebug(5323) << "Creating new Posting with blogId" << blogId(); QList<QVariant> args( d->defaultArgs( blogId() ) ); QMap<QString, QVariant> map; map["categories"] = posting->categories(); map["description"] = posting->content(); map["title"] = posting->title(); map["dateCreated"] = posting->creationDateTime().toUtc().dateTime(); map["mt_allow_comments"] = (int)posting->isCommentAllowed(); map["mt_allow_pings"] = (int)posting->isTrackBackAllowed(); map["mt_excerpt"] = posting->summary(); map["mt_keywords"] = posting->tags(); // TODO some convertion needed? //map["mt_tb_ping_urls"] check for that, i think this should only be done on the server. args << map; args << QVariant( posting->isPublished() ); d->mXmlRpcClient->call ( "metaWeblog.newPost", args, this, SLOT( slotCreatePosting( const QList<QVariant>&, const QVariant& ) ), this, SLOT ( slotError( int, const QString&, const QVariant& ) ), QVariant( i ) ); } void MovableType::modifyPosting( KBlog::BlogPosting *posting ) { //TODO 3 new keys are: // String mt_convert_breaks, the value for the convert_breaks field // String mt_text_more, the value for the additional entry text // array mt_tb_ping_urls, the list of TrackBack ping URLs for this entry Q_D(MovableType); if ( !posting ) { kDebug(5323) << "MovableType::modifyPosting: posting is a null pointer"; emit error ( Other, i18n( "Posting is a null pointer." ) ); return; } unsigned int i = d->callCounter++; d->callMap[ i ] = posting; kDebug(5323) << "Uploading Posting with postId" << posting->postingId(); QList<QVariant> args( d->defaultArgs( posting->postingId() ) ); QMap<QString, QVariant> map; map["categories"] = posting->categories(); map["description"] = posting->content(); map["title"] = posting->title(); map["lastModified"] = posting->modificationDateTime().toUtc().dateTime(); map["mt_allow_comments"] = (int)posting->isCommentAllowed(); map["mt_allow_pings"] = (int)posting->isTrackBackAllowed(); map["mt_excerpt"] = posting->summary(); map["mt_keywords"] = posting->tags(); // TODO some convertion needed? args << map; args << QVariant( posting->isPublished() ); d->mXmlRpcClient->call( "metaWeblog.editPost", args, this, SLOT( slotModifyPosting( const QList<QVariant>&, const QVariant& ) ), this, SLOT ( slotError( int, const QString&, const QVariant& ) ), QVariant( i ) ); } void MovableType::fetchPosting( KBlog::BlogPosting *posting ) { Q_D(MovableType); if ( !posting ) { kDebug(5323) << "MovableType::fetchPosting: posting is a null pointer"; emit error ( Other, i18n( "Posting is a null pointer." ) ); return; } unsigned int i = d->callCounter++; d->callMap[ i ] = posting; kDebug(5323) << "Fetching Posting with url" << posting->postingId(); QList<QVariant> args( d->defaultArgs( posting->postingId() ) ); d->mXmlRpcClient->call( "metaWeblog.getPost", args, this, SLOT( slotFetchPosting( const QList<QVariant>&, const QVariant& ) ), this, SLOT( slotError( int, const QString&, const QVariant& ) ), QVariant( i ) ); } QString MovableType::interfaceName() const { return QLatin1String( "Movable Type" ); } void MovableType::listRecentPostings( const int number ) { Q_D(MovableType); kDebug(5323) << "Fetching List of Posts..."; QList<QVariant> args( d->defaultArgs( blogId() ) ); args << QVariant( number ); d->mXmlRpcClient->call( "metaWeblog.getRecentPosts", args, this, SLOT( slotListRecentPostings( const QList<QVariant>&, const QVariant& ) ), this, SLOT( slotError( int, const QString&, const QVariant& ) ), QVariant( number ) ); } void MovableType::listTrackbackPings( KBlog::BlogPosting *posting ) { //TODO /* Q_D(MovableType); d->mXmlRpcClient->call( "mt.getTracebackPings", args, d, SLOT( slotListTrackbackPings( const QList<QVariant>&, const QVariant& ) ), d, SLOT( slotError( int, const QString&, const QVariant& ) ) ); */ } MovableTypePrivate::MovableTypePrivate() { mXmlRpcClient = 0; } MovableTypePrivate::~MovableTypePrivate() { delete mXmlRpcClient; } QList<QVariant> MovableTypePrivate::defaultArgs( const QString &id ) { Q_Q(MovableType); QList<QVariant> args; if ( id.toInt() ) { args << QVariant( id.toInt() ); } if ( !id.toInt() && !id.isNull() ){ args << QVariant( id ); } args << QVariant( q->username() ) << QVariant( q->password() ); return args; } bool MovableTypePrivate::readPostingFromMap( BlogPosting *post, const QMap<QString, QVariant> &postInfo ) { // FIXME: integrate error handling if ( !post ) { return false; } QStringList mapkeys = postInfo.keys(); kDebug(5323) << endl << "Keys:" << mapkeys.join( ", " ); kDebug(5323) << endl; KDateTime dt = KDateTime( postInfo["dateCreated"].toDateTime(), KDateTime::UTC ); if ( dt.isValid() && !dt.isNull() ) { post->setCreationDateTime( dt ); } dt = KDateTime( postInfo["lastModified"].toDateTime(), KDateTime::UTC ); if ( dt.isValid() && !dt.isNull() ) { post->setModificationDateTime( dt ); } post->setPostingId( postInfo["postid"].toString() ); QString title( postInfo["title"].toString() ); QString description( postInfo["description"].toString() ); QStringList categories( postInfo["categories"].toStringList() ); //TODO 2 new keys are: // String mt_convert_breaks, the value for the convert_breaks field // String mt_text_more, the value for the additional entry text post->setTitle( title ); post->setContent( description ); post->setCommentAllowed( (bool)postInfo["mt_allow_comments"].toInt() ); post->setTrackBackAllowed( (bool)postInfo["mt_allow_pings"].toInt() ); post->setSummary( postInfo["mt_excerpt"].toString() ); post->setTags( postInfo["mt_keywords"].toString() ); if ( !categories.isEmpty() ){ kDebug(5323) << "Categories:" << categories; post->setCategories( categories ); } return true; } void MovableTypePrivate::slotCreatePosting( const QList<QVariant> &result, const QVariant &id ) { Q_Q(MovableType); KBlog::BlogPosting* posting = callMap[ id.toInt() ]; callMap.remove( id.toInt() ); kDebug(5323) << "MovableType::slotCreatePosting"; //array of structs containing ISO.8601 // dateCreated, String userid, String postid, String content; // TODO: Time zone for the dateCreated! kDebug(5323) << "TOP:" << result[0].typeName(); if ( result[0].type() != QVariant::String ) { kDebug(5323) << "Could not read the postingId, not a string."; emit q->error( MovableType::ParsingError, i18n( "Could not read the postingId, not a string." ), posting ); } else { posting->setPostingId( result[0].toString() ); posting->setStatus( BlogPosting::Created ); emit q->createdPosting( posting ); kDebug(5323) << "emitting createdPosting(" << result[0].toString() << ")"; } } void MovableTypePrivate::slotError( int number, const QString &errorString, const QVariant &id ) { Q_Q(MovableType); Q_UNUSED( number ); Q_UNUSED( id ); emit q->error( MovableType::XmlRpc, errorString ); } void MovableTypePrivate::slotFetchPosting( const QList<QVariant> &result, const QVariant &id ) { Q_Q(MovableType); KBlog::BlogPosting* posting = callMap[ id.toInt() ]; callMap.remove( id.toInt() ); kDebug(5323) << "MovableType::slotFetchPosting"; //array of structs containing ISO.8601 // dateCreated, String userid, String postid, String content; // TODO: Time zone for the dateCreated! kDebug(5323) << "TOP:" << result[0].typeName(); if ( result[0].type() != QVariant::Map ) { kDebug(5323) << "Could not fetch posting out of the result from the server."; emit q->error( MovableType::ParsingError, i18n( "Could not fetch posting out of the " "result from the server." ), posting ); } else { const QMap<QString, QVariant> postInfo = result[0].toMap(); if ( readPostingFromMap( posting, postInfo ) ) { kDebug(5323) << "Emitting fetchedPosting( posting.postingId()=" << posting->postingId() << ");"; posting->setStatus( BlogPosting::Fetched ); emit q->fetchedPosting( posting ); } else { kDebug(5323) << "readPostingFromMap failed!"; emit q->error( MovableType::ParsingError, i18n( "Could not read posting." ), posting ); } } } void MovableTypePrivate::slotListRecentPostings( const QList<QVariant> &result, const QVariant &id ) { Q_Q(MovableType); int count = id.toInt(); QList <BlogPosting> fetchedPostingList; kDebug(5323) << "MovableType::slotListRecentPostings"; kDebug(5323) << "TOP:" << result[0].typeName(); if ( result[0].type() != QVariant::List ) { kDebug(5323) << "Could not fetch list of postings out of the" << "result from the server."; emit q->error( MovableType::ParsingError, i18n( "Could not fetch list of postings out of the " "result from the server." ) ); } else { const QList<QVariant> postReceived = result[0].toList(); QList<QVariant>::ConstIterator it = postReceived.begin(); QList<QVariant>::ConstIterator end = postReceived.end(); for ( ; it != end; ++it ) { BlogPosting posting; kDebug(5323) << "MIDDLE:" << ( *it ).typeName(); const QMap<QString, QVariant> postInfo = ( *it ).toMap(); if ( readPostingFromMap( &posting, postInfo ) ) { kDebug(5323) << "Emitting listedPosting( posting.postingId()=" << posting.postingId() << ");"; fetchedPostingList << posting; } else { kDebug(5323) << "readPostingFromMap failed!"; emit q->error( MovableType::ParsingError, i18n( "Could not read posting." ) ); } if( --count == 0 ) break; } } //FIXME should we emit here? (see below, too) kDebug(5323) << "Emitting listRecentPostingsFinished()"; emit q->listedRecentPostings( fetchedPostingList ); } void MovableTypePrivate::slotListTrackbackPings( const QList<QVariant> &result, const QVariant &id ) { //TODO Contains: // String pingTitle: the title of the entry sent in the ping // String pingURL: the URL of the entry // String pingIP: the IP address of the host that sent the ping } void MovableTypePrivate::slotModifyPosting( const QList<QVariant> &result, const QVariant &id ) { Q_Q(MovableType); KBlog::BlogPosting* posting = callMap[ id.toInt() ]; callMap.remove( id.toInt() ); kDebug(5323) << "MovableType::slotModifyPosting"; //array of structs containing ISO.8601 // dateCreated, String userid, String postid, String content; // TODO: Time zone for the dateCreated! kDebug(5323) << "TOP:" << result[0].typeName(); if ( result[0].type() != QVariant::Bool ) { kDebug(5323) << "Could not read the result, not a boolean."; emit q->error( MovableType::ParsingError, i18n( "Could not read the result, not a boolean." ), posting ); } else { posting->setStatus( BlogPosting::Modified ); emit q->modifiedPosting( posting ); kDebug(5323) << "emitting modifiedPosting()"; } } #include "movabletype.moc" <|endoftext|>
<commit_before>/** \file FullTextCache.cc * \brief Implementation of functions relating to our full-text cache. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2017 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "FullTextCache.h" #include <algorithm> #include <ctime> #include "Compiler.h" #include "DbConnection.h" #include "DbRow.h" #include "Random.h" #include "SqlUtil.h" #include "StringUtil.h" #include "UrlUtil.h" #include "util.h" #include "VuFind.h" const unsigned MIN_CACHE_EXPIRE_TIME(84600 * 60); // About 2 months in seconds. const unsigned MAX_CACHE_EXPIRE_TIME(84600 * 120); // About 4 months in seconds. FullTextCache::FullTextCache() { std::string mysql_url; VuFind::GetMysqlURL(&mysql_url); db_connection_ = new DbConnection(mysql_url); } bool FullTextCache::getDomainFromUrl(const std::string &url, std::string * const domain) { std::string scheme, username_password, authority, port, path, params, query, fragment, relative_url; bool result = UrlUtil::ParseUrl(url, &scheme, &username_password, &authority, &port, &path, &params, &query, &fragment, &relative_url); if (result) *domain = authority; return result; } std::vector<std::string> FullTextCache::getDomains() { db_connection_->queryOrDie("SELECT url FROM full_text_cache_urls"); DbResultSet result_set(db_connection_->getLastResultSet()); std::vector<std::string> domains; while (const DbRow row = result_set.getNextRow()) { std::string domain; FullTextCache::getDomainFromUrl(row["url"], &domain); domains.emplace_back(domain); } return domains; } bool FullTextCache::entryExpired(const std::string &id, std::vector<std::string> urls) { Entry entry; if (not getEntry(id, &entry)) return true; const time_t now(std::time(nullptr)); if (now < entry.expiration_) { std::vector<std::string> existing_urls(FullTextCache::getEntryUrlsAsStrings(id)); std::sort(existing_urls.begin(), existing_urls.end()); std::sort(urls.begin(), urls.end()); if (urls == existing_urls) return false; } db_connection_->queryOrDie("DELETE FROM full_text_cache WHERE id=\"" + db_connection_->escapeString(id) + "\""); return true; } void FullTextCache::expireEntries() { const std::string now(SqlUtil::TimeTToDatetime(std::time(nullptr))); db_connection_->queryOrDie("DELETE FROM full_text_cache WHERE expiration < \"" + now + "\""); } bool FullTextCache::getEntry(const std::string &id, Entry * const entry) { db_connection_->queryOrDie("SELECT expiration FROM full_text_cache WHERE id=\"" + db_connection_->escapeString(id) + "\""); DbResultSet result_set(db_connection_->getLastResultSet()); if (result_set.empty()) return false; const DbRow row(result_set.getNextRow()); entry->id_ = id; entry->expiration_ = SqlUtil::DatetimeToTimeT(row["expiration"]); return true; } std::vector<FullTextCache::EntryUrl> FullTextCache::getEntryUrls(const std::string &id) { db_connection_->queryOrDie("SELECT url, domain, error_message FROM full_text_cache_urls " "WHERE id=\"" + db_connection_->escapeString(id) + "\""); DbResultSet result_set(db_connection_->getLastResultSet()); std::vector<EntryUrl> entry_urls; while (const DbRow row = result_set.getNextRow()) { EntryUrl entry_url; entry_url.id_ = id; entry_url.url_ = row["url"]; entry_url.domain_ = row["domain"]; entry_url.error_message_ = row["error_message"]; entry_urls.emplace_back(entry_url); } return entry_urls; } std::vector<std::string> FullTextCache::getEntryUrlsAsStrings(const std::string &id) { db_connection_->queryOrDie("SELECT url FROM full_text_cache_urls " "WHERE id=\"" + db_connection_->escapeString(id) + "\""); DbResultSet result_set(db_connection_->getLastResultSet()); std::vector<std::string> urls; while (const DbRow row = result_set.getNextRow()) { urls.emplace_back(row["url"]); } return urls; } unsigned FullTextCache::getErrorCount() { db_connection_->queryOrDie("SELECT count(*) AS count FROM (" "SELECT cache.id FROM full_text_cache_urls AS urls " "LEFT JOIN full_text_cache AS cache " "ON cache.id = urls.id " "WHERE error_message IS NOT NULL " "GROUP BY cache.id " ") AS subselect"); DbResultSet result_set(db_connection_->getLastResultSet()); const DbRow row(result_set.getNextRow()); return StringUtil::ToUnsigned(row["count"]); } bool FullTextCache::getFullText(const std::string &id, std::string * const full_text) { db_connection_->queryOrDie("SELECT full_text FROM full_text_cache " "WHERE id=\"" + db_connection_->escapeString(id) + "\""); DbResultSet result_set(db_connection_->getLastResultSet()); if (result_set.empty()) return false; const DbRow row(result_set.getNextRow()); *full_text = row["full_text"]; return true; } std::vector<FullTextCache::EntryGroup> FullTextCache::getEntryGroupsByDomainAndErrorMessage() { std::vector<EntryGroup> groups; // In a group statement you can only select fields that are part of the group. // Get first part. Indented block because DbResultSet needs to get out of scope // for connection to be free again. { db_connection_->queryOrDie("SELECT domain, error_message, count(*) AS count " "FROM full_text_cache_urls AS urls " "LEFT JOIN full_text_cache AS cache " "ON cache.id = urls.id " "WHERE urls.error_message IS NOT NULL " "GROUP BY urls.error_message, urls.domain " "ORDER BY count DESC "); DbResultSet result_set(db_connection_->getLastResultSet()); while (const DbRow row = result_set.getNextRow()) { EntryGroup group; group.count_ = StringUtil::ToUnsigned(row["count"]); group.domain_ = row["domain"]; group.error_message_ = row["error_message"]; groups.emplace_back(group); } } // get example entry for (auto &group : groups) group.example_entry_ = getJoinedEntryByDomainAndErrorMessage(group.domain_, group.error_message_); return groups; } std::vector<FullTextCache::JoinedEntry> FullTextCache::getJoinedEntriesByDomainAndErrorMessage(const std::string &domain, const std::string &error_message) { std::vector<JoinedEntry> entries; db_connection_->queryOrDie("SELECT cache.id, url " "FROM full_text_cache_urls AS urls " "LEFT JOIN full_text_cache AS cache " "ON cache.id = urls.id " "WHERE urls.error_message='" + db_connection_->escapeString(error_message) + "' " "AND urls.domain='" + db_connection_->escapeString(domain) + "' "); DbResultSet result_set(db_connection_->getLastResultSet()); while (const DbRow row = result_set.getNextRow()) { JoinedEntry entry; entry.id_ = row["id"]; entry.url_ = row["url"]; entry.domain_ = domain; entry.error_message_ = error_message; entries.emplace_back(entry); } return entries; } FullTextCache::JoinedEntry FullTextCache::getJoinedEntryByDomainAndErrorMessage(const std::string &domain, const std::string &error_message) { JoinedEntry entry; db_connection_->queryOrDie("SELECT cache.id, url " "FROM full_text_cache_urls AS urls " "LEFT JOIN full_text_cache AS cache " "ON cache.id = urls.id " "WHERE urls.error_message='" + db_connection_->escapeString(error_message) + "' " "AND urls.domain='" + db_connection_->escapeString(domain) + "' " "LIMIT 1 "); DbResultSet result_set(db_connection_->getLastResultSet()); const DbRow row(result_set.getNextRow()); entry.id_ = row["id"]; entry.url_ = row["url"]; entry.domain_ = domain; entry.error_message_ = error_message; return entry; } unsigned FullTextCache::getSize() { return SqlUtil::GetTableSize(db_connection_, "full_text_cache"); } void FullTextCache::insertEntry(const std::string &id, const std::string &full_text, const std::vector<EntryUrl> &entry_urls) { const time_t now(std::time(nullptr)); Random::Rand rand(now); const time_t expiration(now + MIN_CACHE_EXPIRE_TIME + rand(MAX_CACHE_EXPIRE_TIME - MIN_CACHE_EXPIRE_TIME)); const std::string escaped_id(db_connection_->escapeString(id)); db_connection_->queryOrDie("INSERT INTO full_text_cache " "SET id=\"" + escaped_id + "\"," "expiration=\"" + SqlUtil::TimeTToDatetime(expiration) + "\"," "full_text=\"" + db_connection_->escapeString(full_text) + "\""); for (const auto &entry_url : entry_urls) { if (not full_text.empty()) { if (unlikely(not entry_url.error_message_.empty())) logger->error("in FullTextCache::InsertIntoCache (id " + id + "): " "when you provide the data for the full-text cache " "you must not also provide an error message!"); } else if (unlikely(entry_url.error_message_.empty())) logger->error("in FullTextCache::InsertIntoCache (id " + id + "): " "you must provide either data to be cached or a non-empty " "error message!"); db_connection_->queryOrDie("INSERT INTO full_text_cache_urls " "SET id=\"" + escaped_id + "\"," "url=\"" + db_connection_->escapeString(entry_url.url_) + "\"," "domain=\"" + db_connection_->escapeString(entry_url.domain_) + "\"" + (entry_url.error_message_.empty() ? "" : ", error_message=\"" + db_connection_->escapeString(entry_url.error_message_) + "\"")); } } <commit_msg>FullTextCache: Allow full_text if at least 1 URL was correctly processed<commit_after>/** \file FullTextCache.cc * \brief Implementation of functions relating to our full-text cache. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2017 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "FullTextCache.h" #include <algorithm> #include <ctime> #include "Compiler.h" #include "DbConnection.h" #include "DbRow.h" #include "Random.h" #include "SqlUtil.h" #include "StringUtil.h" #include "UrlUtil.h" #include "util.h" #include "VuFind.h" const unsigned MIN_CACHE_EXPIRE_TIME(84600 * 60); // About 2 months in seconds. const unsigned MAX_CACHE_EXPIRE_TIME(84600 * 120); // About 4 months in seconds. FullTextCache::FullTextCache() { std::string mysql_url; VuFind::GetMysqlURL(&mysql_url); db_connection_ = new DbConnection(mysql_url); } bool FullTextCache::getDomainFromUrl(const std::string &url, std::string * const domain) { std::string scheme, username_password, authority, port, path, params, query, fragment, relative_url; bool result = UrlUtil::ParseUrl(url, &scheme, &username_password, &authority, &port, &path, &params, &query, &fragment, &relative_url); if (result) *domain = authority; return result; } std::vector<std::string> FullTextCache::getDomains() { db_connection_->queryOrDie("SELECT url FROM full_text_cache_urls"); DbResultSet result_set(db_connection_->getLastResultSet()); std::vector<std::string> domains; while (const DbRow row = result_set.getNextRow()) { std::string domain; FullTextCache::getDomainFromUrl(row["url"], &domain); domains.emplace_back(domain); } return domains; } bool FullTextCache::entryExpired(const std::string &id, std::vector<std::string> urls) { Entry entry; if (not getEntry(id, &entry)) return true; const time_t now(std::time(nullptr)); if (now < entry.expiration_) { std::vector<std::string> existing_urls(FullTextCache::getEntryUrlsAsStrings(id)); std::sort(existing_urls.begin(), existing_urls.end()); std::sort(urls.begin(), urls.end()); if (urls == existing_urls) return false; } db_connection_->queryOrDie("DELETE FROM full_text_cache WHERE id=\"" + db_connection_->escapeString(id) + "\""); return true; } void FullTextCache::expireEntries() { const std::string now(SqlUtil::TimeTToDatetime(std::time(nullptr))); db_connection_->queryOrDie("DELETE FROM full_text_cache WHERE expiration < \"" + now + "\""); } bool FullTextCache::getEntry(const std::string &id, Entry * const entry) { db_connection_->queryOrDie("SELECT expiration FROM full_text_cache WHERE id=\"" + db_connection_->escapeString(id) + "\""); DbResultSet result_set(db_connection_->getLastResultSet()); if (result_set.empty()) return false; const DbRow row(result_set.getNextRow()); entry->id_ = id; entry->expiration_ = SqlUtil::DatetimeToTimeT(row["expiration"]); return true; } std::vector<FullTextCache::EntryUrl> FullTextCache::getEntryUrls(const std::string &id) { db_connection_->queryOrDie("SELECT url, domain, error_message FROM full_text_cache_urls " "WHERE id=\"" + db_connection_->escapeString(id) + "\""); DbResultSet result_set(db_connection_->getLastResultSet()); std::vector<EntryUrl> entry_urls; while (const DbRow row = result_set.getNextRow()) { EntryUrl entry_url; entry_url.id_ = id; entry_url.url_ = row["url"]; entry_url.domain_ = row["domain"]; entry_url.error_message_ = row["error_message"]; entry_urls.emplace_back(entry_url); } return entry_urls; } std::vector<std::string> FullTextCache::getEntryUrlsAsStrings(const std::string &id) { db_connection_->queryOrDie("SELECT url FROM full_text_cache_urls " "WHERE id=\"" + db_connection_->escapeString(id) + "\""); DbResultSet result_set(db_connection_->getLastResultSet()); std::vector<std::string> urls; while (const DbRow row = result_set.getNextRow()) { urls.emplace_back(row["url"]); } return urls; } unsigned FullTextCache::getErrorCount() { db_connection_->queryOrDie("SELECT count(*) AS count FROM (" "SELECT cache.id FROM full_text_cache_urls AS urls " "LEFT JOIN full_text_cache AS cache " "ON cache.id = urls.id " "WHERE error_message IS NOT NULL " "GROUP BY cache.id " ") AS subselect"); DbResultSet result_set(db_connection_->getLastResultSet()); const DbRow row(result_set.getNextRow()); return StringUtil::ToUnsigned(row["count"]); } bool FullTextCache::getFullText(const std::string &id, std::string * const full_text) { db_connection_->queryOrDie("SELECT full_text FROM full_text_cache " "WHERE id=\"" + db_connection_->escapeString(id) + "\""); DbResultSet result_set(db_connection_->getLastResultSet()); if (result_set.empty()) return false; const DbRow row(result_set.getNextRow()); *full_text = row["full_text"]; return true; } std::vector<FullTextCache::EntryGroup> FullTextCache::getEntryGroupsByDomainAndErrorMessage() { std::vector<EntryGroup> groups; // In a group statement you can only select fields that are part of the group. // Get first part. Indented block because DbResultSet needs to get out of scope // for connection to be free again. { db_connection_->queryOrDie("SELECT domain, error_message, count(*) AS count " "FROM full_text_cache_urls AS urls " "LEFT JOIN full_text_cache AS cache " "ON cache.id = urls.id " "WHERE urls.error_message IS NOT NULL " "GROUP BY urls.error_message, urls.domain " "ORDER BY count DESC "); DbResultSet result_set(db_connection_->getLastResultSet()); while (const DbRow row = result_set.getNextRow()) { EntryGroup group; group.count_ = StringUtil::ToUnsigned(row["count"]); group.domain_ = row["domain"]; group.error_message_ = row["error_message"]; groups.emplace_back(group); } } // get example entry for (auto &group : groups) group.example_entry_ = getJoinedEntryByDomainAndErrorMessage(group.domain_, group.error_message_); return groups; } std::vector<FullTextCache::JoinedEntry> FullTextCache::getJoinedEntriesByDomainAndErrorMessage(const std::string &domain, const std::string &error_message) { std::vector<JoinedEntry> entries; db_connection_->queryOrDie("SELECT cache.id, url " "FROM full_text_cache_urls AS urls " "LEFT JOIN full_text_cache AS cache " "ON cache.id = urls.id " "WHERE urls.error_message='" + db_connection_->escapeString(error_message) + "' " "AND urls.domain='" + db_connection_->escapeString(domain) + "' "); DbResultSet result_set(db_connection_->getLastResultSet()); while (const DbRow row = result_set.getNextRow()) { JoinedEntry entry; entry.id_ = row["id"]; entry.url_ = row["url"]; entry.domain_ = domain; entry.error_message_ = error_message; entries.emplace_back(entry); } return entries; } FullTextCache::JoinedEntry FullTextCache::getJoinedEntryByDomainAndErrorMessage(const std::string &domain, const std::string &error_message) { JoinedEntry entry; db_connection_->queryOrDie("SELECT cache.id, url " "FROM full_text_cache_urls AS urls " "LEFT JOIN full_text_cache AS cache " "ON cache.id = urls.id " "WHERE urls.error_message='" + db_connection_->escapeString(error_message) + "' " "AND urls.domain='" + db_connection_->escapeString(domain) + "' " "LIMIT 1 "); DbResultSet result_set(db_connection_->getLastResultSet()); const DbRow row(result_set.getNextRow()); entry.id_ = row["id"]; entry.url_ = row["url"]; entry.domain_ = domain; entry.error_message_ = error_message; return entry; } unsigned FullTextCache::getSize() { return SqlUtil::GetTableSize(db_connection_, "full_text_cache"); } void FullTextCache::insertEntry(const std::string &id, const std::string &full_text, const std::vector<EntryUrl> &entry_urls) { const time_t now(std::time(nullptr)); Random::Rand rand(now); const time_t expiration(now + MIN_CACHE_EXPIRE_TIME + rand(MAX_CACHE_EXPIRE_TIME - MIN_CACHE_EXPIRE_TIME)); const std::string escaped_id(db_connection_->escapeString(id)); db_connection_->queryOrDie("INSERT INTO full_text_cache " "SET id=\"" + escaped_id + "\"," "expiration=\"" + SqlUtil::TimeTToDatetime(expiration) + "\"," "full_text=\"" + db_connection_->escapeString(full_text) + "\""); for (const auto &entry_url : entry_urls) { if (full_text.empty() and entry_url.error_message_.empty()) logger->error("in FullTextCache::InsertIntoCache (id " + id + "): " "you must provide either data to be cached or a non-empty " "error message!"); db_connection_->queryOrDie("INSERT INTO full_text_cache_urls " "SET id=\"" + escaped_id + "\"," "url=\"" + db_connection_->escapeString(entry_url.url_) + "\"," "domain=\"" + db_connection_->escapeString(entry_url.domain_) + "\"" + (entry_url.error_message_.empty() ? "" : ", error_message=\"" + db_connection_->escapeString(entry_url.error_message_) + "\"")); } } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "testable.hpp" TEST(GetTwoTest, Two) { EXPECT_EQ(2, getTwo()); } <commit_msg>`TEST(ShaderStruct_must_be_initialized_appropriately, ShaderStruct)`.<commit_after>#include "gtest/gtest.h" #include "testable.hpp" #include "cpp/ylikuutio/common/globals.hpp" TEST(GetTwoTest, Two) { EXPECT_EQ(2, getTwo()); } TEST(ShaderStruct_must_be_initialized_appropriately, ShaderStruct) { ShaderStruct test_shader_struct; ASSERT_EQ(test_shader_struct.parent_pointer, nullptr); ASSERT_TRUE(test_shader_struct.vertex_shader.empty()); ASSERT_TRUE(test_shader_struct.fragment_shader.empty()); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include <sal/config.h> #include <cstdlib> #include <com/sun/star/loader/CannotActivateFactoryException.hpp> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/uno/Sequence.hxx> #include <osl/module.h> #include <sal/types.h> namespace com { namespace sun { namespace star { namespace lang { class XMultiComponentFactory; class XMultiServiceFactory; class XTypeProvider; } namespace reflection { class XIdlClass; } namespace registry { class XRegistryKey; class XSimpleRegistry; } namespace uno { class XComponentContext; class XInterface; } } } } namespace rtl { class OUString; } // Stubs for removed functionality, to be killed when we bump cppuhelper SONAME namespace cppu { SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::lang::XMultiComponentFactory > bootstrapInitialSF( rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::uno::XComponentContext > SAL_CALL bootstrap_InitialComponentContext( css::uno::Reference< css::registry::XSimpleRegistry > const &, rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::registry::XSimpleRegistry > SAL_CALL createNestedRegistry(rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::lang::XMultiServiceFactory > SAL_CALL createRegistryServiceFactory( rtl::OUString const &, rtl::OUString const &, sal_Bool, rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::registry::XSimpleRegistry > SAL_CALL createSimpleRegistry(rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::reflection::XIdlClass * SAL_CALL createStandardClassWithSequence( css::uno::Reference< css::lang::XMultiServiceFactory > const &, rtl::OUString const &, css::uno::Reference< css::reflection::XIdlClass > const &, css::uno::Sequence< rtl::OUString > const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference<css::uno::XInterface> SAL_CALL invokeStaticComponentFactory( oslGenericFunction, rtl::OUString const &, css::uno::Reference<css::lang::XMultiServiceFactory> const &, css::uno::Reference<css::registry::XRegistryKey> const &, rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference<css::uno::XInterface> SAL_CALL loadSharedLibComponentFactory( rtl::OUString const &, rtl::OUString const &, rtl::OUString const &, css::uno::Reference<css::lang::XMultiServiceFactory> const &, css::uno::Reference<css::registry::XRegistryKey> const &, rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } struct SAL_DLLPUBLIC_EXPORT ClassData { css::uno::Sequence<sal_Int8> SAL_CALL getImplementationId(); css::uno::Sequence<css::uno::Type> SAL_CALL getTypes(); void SAL_CALL initTypeProvider(); css::uno::Any SAL_CALL query( css::uno::Type const &, css::lang::XTypeProvider *); void SAL_CALL writeTypeOffset(css::uno::Type const &, sal_Int32); }; css::uno::Sequence<sal_Int8> ClassData::getImplementationId() { for (;;) { std::abort(); } // avoid "must return a value" warnings } css::uno::Sequence<css::uno::Type> ClassData::getTypes() { for (;;) { std::abort(); } // avoid "must return a value" warnings } void ClassData::initTypeProvider() { std::abort(); } css::uno::Any ClassData::query( css::uno::Type const &, css::lang::XTypeProvider *) { for (;;) { std::abort(); } // avoid "must return a value" warnings } void ClassData::writeTypeOffset(css::uno::Type const &, sal_Int32) { std::abort(); } SAL_WNOUNREACHABLE_CODE_PUSH struct SAL_DLLPUBLIC_EXPORT ClassDataBase { ClassDataBase(); ClassDataBase(sal_Int32); ~ClassDataBase(); }; ClassDataBase::ClassDataBase() { std::abort(); } ClassDataBase::ClassDataBase(sal_Int32) { std::abort(); } ClassDataBase::~ClassDataBase() { std::abort(); } SAL_WNOUNREACHABLE_CODE_POP } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Remove unnecessary #include<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include <sal/config.h> #include <cstdlib> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/uno/Sequence.hxx> #include <osl/module.h> #include <sal/types.h> namespace com { namespace sun { namespace star { namespace lang { class XMultiComponentFactory; class XMultiServiceFactory; class XTypeProvider; } namespace reflection { class XIdlClass; } namespace registry { class XRegistryKey; class XSimpleRegistry; } namespace uno { class XComponentContext; class XInterface; } } } } namespace rtl { class OUString; } // Stubs for removed functionality, to be killed when we bump cppuhelper SONAME namespace cppu { SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::lang::XMultiComponentFactory > bootstrapInitialSF( rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::uno::XComponentContext > SAL_CALL bootstrap_InitialComponentContext( css::uno::Reference< css::registry::XSimpleRegistry > const &, rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::registry::XSimpleRegistry > SAL_CALL createNestedRegistry(rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::lang::XMultiServiceFactory > SAL_CALL createRegistryServiceFactory( rtl::OUString const &, rtl::OUString const &, sal_Bool, rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::registry::XSimpleRegistry > SAL_CALL createSimpleRegistry(rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::reflection::XIdlClass * SAL_CALL createStandardClassWithSequence( css::uno::Reference< css::lang::XMultiServiceFactory > const &, rtl::OUString const &, css::uno::Reference< css::reflection::XIdlClass > const &, css::uno::Sequence< rtl::OUString > const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference<css::uno::XInterface> SAL_CALL invokeStaticComponentFactory( oslGenericFunction, rtl::OUString const &, css::uno::Reference<css::lang::XMultiServiceFactory> const &, css::uno::Reference<css::registry::XRegistryKey> const &, rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } SAL_DLLPUBLIC_EXPORT css::uno::Reference<css::uno::XInterface> SAL_CALL loadSharedLibComponentFactory( rtl::OUString const &, rtl::OUString const &, rtl::OUString const &, css::uno::Reference<css::lang::XMultiServiceFactory> const &, css::uno::Reference<css::registry::XRegistryKey> const &, rtl::OUString const &) { for (;;) { std::abort(); } // avoid "must return a value" warnings } struct SAL_DLLPUBLIC_EXPORT ClassData { css::uno::Sequence<sal_Int8> SAL_CALL getImplementationId(); css::uno::Sequence<css::uno::Type> SAL_CALL getTypes(); void SAL_CALL initTypeProvider(); css::uno::Any SAL_CALL query( css::uno::Type const &, css::lang::XTypeProvider *); void SAL_CALL writeTypeOffset(css::uno::Type const &, sal_Int32); }; css::uno::Sequence<sal_Int8> ClassData::getImplementationId() { for (;;) { std::abort(); } // avoid "must return a value" warnings } css::uno::Sequence<css::uno::Type> ClassData::getTypes() { for (;;) { std::abort(); } // avoid "must return a value" warnings } void ClassData::initTypeProvider() { std::abort(); } css::uno::Any ClassData::query( css::uno::Type const &, css::lang::XTypeProvider *) { for (;;) { std::abort(); } // avoid "must return a value" warnings } void ClassData::writeTypeOffset(css::uno::Type const &, sal_Int32) { std::abort(); } SAL_WNOUNREACHABLE_CODE_PUSH struct SAL_DLLPUBLIC_EXPORT ClassDataBase { ClassDataBase(); ClassDataBase(sal_Int32); ~ClassDataBase(); }; ClassDataBase::ClassDataBase() { std::abort(); } ClassDataBase::ClassDataBase(sal_Int32) { std::abort(); } ClassDataBase::~ClassDataBase() { std::abort(); } SAL_WNOUNREACHABLE_CODE_POP } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY vincent.acary@inrialpes.fr */ /*! \file PivotJoint.cpp */ #include "PivotJoint.hpp" #include <boost/math/quaternion.hpp> int PivotJointR::_sNbEqualities = 5; PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::NewtonEulerDS d2, SP::SimpleVector P, SP::SimpleVector A): KneeJointR(d1, d2, P) { // SP::SiconosVector q1 = d1->q0(); // ::boost::math::quaternion<float> quat1(q1->getValue(3),-q1->getValue(4),-q1->getValue(5),-q1->getValue(6)); // ::boost::math::quaternion<float> quatA(0,A->getValue(0),A->getValue(1),A->getValue(2)); // ::boost::math::quaternion<float> quatBuff(0,0,0,0); // /*calcul of axis _A*/ // quatBuff=quat1*quatA/quat1; // _Ax=quatBuff.R_component_2(); // _Ay=quatBuff.R_component_3(); // _Az=quatBuff.R_component_4(); _Ax = A->getValue(0); _Ay = A->getValue(1); _Az = A->getValue(2); buildA1A2(); } /* constructor, \param a SP::NewtonEulerDS d1, a dynamical system containing the intial position \param a SP::SimpleVector P0, see KneeJointR documentation. \param a SP::SimpleVector A, axis in the frame of the object. \param a bool, used only by the KneeJointR constructor see KneeJointR documentation. */ PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::SimpleVector P0, SP::SimpleVector A, bool absolutRef): KneeJointR(d1, P0, absolutRef) { _Ax = A->getValue(0); _Ay = A->getValue(1); _Az = A->getValue(2); buildA1A2(); } void PivotJointR::initComponents() { KneeJointR::initComponents(); _jachqProj.reset(new SimpleMatrix(6, 7)); _yProj.reset(new SimpleVector(6)); } void PivotJointR::buildA1A2() { orthoBaseFromVector(&_Ax, &_Ay, &_Az, &_A1x, &_A1y, &_A1z, &_A2x, &_A2y, &_A2z); assert(fabs(_A1x * _Ax + _A1y * _Ay + _A1z * _Az) < 1e-9 && "PivotJoint, _A1 wrong\n"); assert(fabs(_A2x * _Ax + _A2y * _Ay + _A2z * _Az) < 1e-9 && "PivotJoint, _A2 wrong\n"); assert(fabs(_A1x * _A2x + _A1y * _A2y + _A1z * _A2z) < 1e-9 && "PivotJoint, _A12 wrong\n"); std::cout << "JointPivot: _A1x _A1y _A1z :" << _A1x << " " << _A1y << " " << _A1z << std::endl; std::cout << "JointPivot: _A2x _A2y _A2z :" << _A2x << " " << _A2y << " " << _A2z << std::endl; } void PivotJointR::Jd1d2(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13, double X2, double Y2, double Z2, double q20, double q21, double q22, double q23) { KneeJointR::Jd1d2(X1, Y1, Z1, q10, q11, q12, q13, X2, Y2, Z2, q20, q21, q22, q23); _jachq->setValue(3, 0, 0); _jachq->setValue(3, 1, 0); _jachq->setValue(3, 2, 0); _jachq->setValue(3, 3, _A1x * (-q21) + _A1y * (-q22) + _A1z * (-q23)); _jachq->setValue(3, 4, _A1x * (q20) + _A1y * (q23) + _A1z * (-q22)); _jachq->setValue(3, 5, _A1x * (-q23) + _A1y * (q20) + _A1z * (q21)); _jachq->setValue(3, 6, _A1x * (q22) + _A1y * (-q21) + _A1z * (q20)); _jachq->setValue(3, 7, 0); _jachq->setValue(3, 8, 0); _jachq->setValue(3, 9, 0); _jachq->setValue(3, 10, _A1x * (q11) + _A1y * (q12) + _A1z * (q13)); _jachq->setValue(3, 11, _A1x * (-q10) + _A1y * (-q13) + _A1z * (q12)); _jachq->setValue(3, 12, _A1x * (q13) + _A1y * (-q10) + _A1z * (-q11)); _jachq->setValue(3, 13, _A1x * (-q12) + _A1y * (q11) + _A1z * (-q10)); _jachq->setValue(4, 0, 0); _jachq->setValue(4, 1, 0); _jachq->setValue(4, 2, 0); _jachq->setValue(4, 3, _A2x * (-q21) + _A2y * (-q22) + _A2z * (-q23)); _jachq->setValue(4, 4, _A2x * (q20) + _A2y * (q23) + _A2z * (-q22)); _jachq->setValue(4, 5, _A2x * (-q23) + _A2y * (q20) + _A2z * (q21)); _jachq->setValue(4, 6, _A2x * (q22) + _A2y * (-q21) + _A2z * (q20)); _jachq->setValue(4, 7, 0); _jachq->setValue(4, 8, 0); _jachq->setValue(4, 9, 0); _jachq->setValue(4, 10, _A2x * (q11) + _A2y * (q12) + _A2z * (q13)); _jachq->setValue(4, 11, _A2x * (-q10) + _A2y * (-q13) + _A2z * (q12)); _jachq->setValue(4, 12, _A2x * (q13) + _A2y * (-q10) + _A2z * (-q11)); _jachq->setValue(4, 13, _A2x * (-q12) + _A2y * (q11) + _A2z * (-q10)); //_jachq->display(); } void PivotJointR::Jd1(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13) { KneeJointR::Jd1(X1, Y1, Z1, q10, q11, q12, q13); _jachq->setValue(3, 0, 0); _jachq->setValue(3, 1, 0); _jachq->setValue(3, 2, 0); _jachq->setValue(3, 3, 0); _jachq->setValue(3, 4, _A1x); _jachq->setValue(3, 5, _A1y); _jachq->setValue(3, 6, _A1z); _jachq->setValue(4, 0, 0); _jachq->setValue(4, 1, 0); _jachq->setValue(4, 2, 0); _jachq->setValue(4, 3, 0); _jachq->setValue(4, 4, _A2x); _jachq->setValue(4, 5, _A2y); _jachq->setValue(4, 6, _A2z); for (int ii = 0; ii < _jachq->size(0); ii++) for (int jj = 0; jj < _jachq->size(1); jj++) _jachqProj->setValue(ii, jj, _jachq->getValue(ii, jj)); _jachqProj->setValue(5, 0, 0); _jachqProj->setValue(5, 1, 0); _jachqProj->setValue(5, 2, 0); _jachqProj->setValue(5, 3, 2.0 * q10); _jachqProj->setValue(5, 4, 2.0 * q11); _jachqProj->setValue(5, 5, 2.0 * q12); _jachqProj->setValue(5, 6, 2.0 * q13); } double PivotJointR::AscalA1(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23) { ::boost::math::quaternion<float> quat1(q10, q11, q12, q13); ::boost::math::quaternion<float> quat2_inv(q20, -q21, -q22, -q23); ::boost::math::quaternion<float> quatBuff = quat1 * quat2_inv; double aX = quatBuff.R_component_2(); double aY = quatBuff.R_component_3(); double aZ = quatBuff.R_component_4(); return _A1x * aX + _A1y * aY + _A1z * aZ; } double PivotJointR::AscalA2(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23) { ::boost::math::quaternion<float> quat1(q10, q11, q12, q13); ::boost::math::quaternion<float> quat2_inv(q20, -q21, -q22, -q23); ::boost::math::quaternion<float> quatBuff = quat1 * quat2_inv; double aX = quatBuff.R_component_2(); double aY = quatBuff.R_component_3(); double aZ = quatBuff.R_component_4(); return _A2x * aX + _A2y * aY + _A2z * aZ; } void PivotJointR::computeh(double t) { KneeJointR::computeh(t); SP::SiconosVector x1 = _d1->q(); //std::cout<<"PivotJoint computeH d1->q:\n"; //x1->display(); double q10 = x1->getValue(3); double q11 = x1->getValue(4); double q12 = x1->getValue(5); double q13 = x1->getValue(6); double q20 = 1; double q21 = 0; double q22 = 0; double q23 = 0; if (_d2) { SP::SiconosVector x2 = _d2->q(); q20 = x2->getValue(3); q21 = x2->getValue(4); q22 = x2->getValue(5); q23 = x2->getValue(6); } SP::SiconosVector y = interaction()->y(0); y->setValue(3, AscalA1(q10, q11, q12, q13, q20, q21, q22, q23)); y->setValue(4, AscalA2(q10, q11, q12, q13, q20, q21, q22, q23)); std::cout << "PivotJoint computeH:\n"; y->display(); for (int ii = 0; ii < y->size(); ii++) _yProj->setValue(ii, y->getValue(ii)); _yProj->setValue(5, q10 * q10 + q11 * q11 + q12 * q12 + q13 * q13 - 1.0); } <commit_msg>h and jachq for the projection on constraints in the case of a pivot between two bodies<commit_after>/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY vincent.acary@inrialpes.fr */ /*! \file PivotJoint.cpp */ #include "PivotJoint.hpp" #include <boost/math/quaternion.hpp> int PivotJointR::_sNbEqualities = 5; PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::NewtonEulerDS d2, SP::SimpleVector P, SP::SimpleVector A): KneeJointR(d1, d2, P) { // SP::SiconosVector q1 = d1->q0(); // ::boost::math::quaternion<float> quat1(q1->getValue(3),-q1->getValue(4),-q1->getValue(5),-q1->getValue(6)); // ::boost::math::quaternion<float> quatA(0,A->getValue(0),A->getValue(1),A->getValue(2)); // ::boost::math::quaternion<float> quatBuff(0,0,0,0); // /*calcul of axis _A*/ // quatBuff=quat1*quatA/quat1; // _Ax=quatBuff.R_component_2(); // _Ay=quatBuff.R_component_3(); // _Az=quatBuff.R_component_4(); _Ax = A->getValue(0); _Ay = A->getValue(1); _Az = A->getValue(2); buildA1A2(); } /* constructor, \param a SP::NewtonEulerDS d1, a dynamical system containing the intial position \param a SP::SimpleVector P0, see KneeJointR documentation. \param a SP::SimpleVector A, axis in the frame of the object. \param a bool, used only by the KneeJointR constructor see KneeJointR documentation. */ PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::SimpleVector P0, SP::SimpleVector A, bool absolutRef): KneeJointR(d1, P0, absolutRef) { _Ax = A->getValue(0); _Ay = A->getValue(1); _Az = A->getValue(2); buildA1A2(); } void PivotJointR::initComponents() { KneeJointR::initComponents(); if (_d2) { _jachqProj.reset(new SimpleMatrix(7, 14)); _yProj.reset(new SimpleVector(7)); } else { _jachqProj.reset(new SimpleMatrix(6, 7)); _yProj.reset(new SimpleVector(6)); } } void PivotJointR::buildA1A2() { orthoBaseFromVector(&_Ax, &_Ay, &_Az, &_A1x, &_A1y, &_A1z, &_A2x, &_A2y, &_A2z); assert(fabs(_A1x * _Ax + _A1y * _Ay + _A1z * _Az) < 1e-9 && "PivotJoint, _A1 wrong\n"); assert(fabs(_A2x * _Ax + _A2y * _Ay + _A2z * _Az) < 1e-9 && "PivotJoint, _A2 wrong\n"); assert(fabs(_A1x * _A2x + _A1y * _A2y + _A1z * _A2z) < 1e-9 && "PivotJoint, _A12 wrong\n"); std::cout << "JointPivot: _A1x _A1y _A1z :" << _A1x << " " << _A1y << " " << _A1z << std::endl; std::cout << "JointPivot: _A2x _A2y _A2z :" << _A2x << " " << _A2y << " " << _A2z << std::endl; } void PivotJointR::Jd1d2(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13, double X2, double Y2, double Z2, double q20, double q21, double q22, double q23) { KneeJointR::Jd1d2(X1, Y1, Z1, q10, q11, q12, q13, X2, Y2, Z2, q20, q21, q22, q23); _jachq->setValue(3, 0, 0); _jachq->setValue(3, 1, 0); _jachq->setValue(3, 2, 0); _jachq->setValue(3, 3, _A1x * (-q21) + _A1y * (-q22) + _A1z * (-q23)); _jachq->setValue(3, 4, _A1x * (q20) + _A1y * (q23) + _A1z * (-q22)); _jachq->setValue(3, 5, _A1x * (-q23) + _A1y * (q20) + _A1z * (q21)); _jachq->setValue(3, 6, _A1x * (q22) + _A1y * (-q21) + _A1z * (q20)); _jachq->setValue(3, 7, 0); _jachq->setValue(3, 8, 0); _jachq->setValue(3, 9, 0); _jachq->setValue(3, 10, _A1x * (q11) + _A1y * (q12) + _A1z * (q13)); _jachq->setValue(3, 11, _A1x * (-q10) + _A1y * (-q13) + _A1z * (q12)); _jachq->setValue(3, 12, _A1x * (q13) + _A1y * (-q10) + _A1z * (-q11)); _jachq->setValue(3, 13, _A1x * (-q12) + _A1y * (q11) + _A1z * (-q10)); _jachq->setValue(4, 0, 0); _jachq->setValue(4, 1, 0); _jachq->setValue(4, 2, 0); _jachq->setValue(4, 3, _A2x * (-q21) + _A2y * (-q22) + _A2z * (-q23)); _jachq->setValue(4, 4, _A2x * (q20) + _A2y * (q23) + _A2z * (-q22)); _jachq->setValue(4, 5, _A2x * (-q23) + _A2y * (q20) + _A2z * (q21)); _jachq->setValue(4, 6, _A2x * (q22) + _A2y * (-q21) + _A2z * (q20)); _jachq->setValue(4, 7, 0); _jachq->setValue(4, 8, 0); _jachq->setValue(4, 9, 0); _jachq->setValue(4, 10, _A2x * (q11) + _A2y * (q12) + _A2z * (q13)); _jachq->setValue(4, 11, _A2x * (-q10) + _A2y * (-q13) + _A2z * (q12)); _jachq->setValue(4, 12, _A2x * (q13) + _A2y * (-q10) + _A2z * (-q11)); _jachq->setValue(4, 13, _A2x * (-q12) + _A2y * (q11) + _A2z * (-q10)); for (int ii = 0; ii < _jachq->size(0); ii++) for (int jj = 0; jj < _jachq->size(1); jj++) _jachqProj->setValue(ii, jj, _jachq->getValue(ii, jj)); _jachqProj->setValue(5, 0, 0); _jachqProj->setValue(5, 1, 0); _jachqProj->setValue(5, 2, 0); _jachqProj->setValue(5, 3, 2.0 * q10); _jachqProj->setValue(5, 4, 2.0 * q11); _jachqProj->setValue(5, 5, 2.0 * q12); _jachqProj->setValue(5, 6, 2.0 * q13); _jachqProj->setValue(6, 0, 0); _jachqProj->setValue(6, 1, 0); _jachqProj->setValue(6, 2, 0); _jachqProj->setValue(6, 3, 2.0 * q20); _jachqProj->setValue(6, 4, 2.0 * q21); _jachqProj->setValue(6, 5, 2.0 * q22); _jachqProj->setValue(6, 6, 2.0 * q23); //_jachq->display(); } void PivotJointR::Jd1(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13) { KneeJointR::Jd1(X1, Y1, Z1, q10, q11, q12, q13); _jachq->setValue(3, 0, 0); _jachq->setValue(3, 1, 0); _jachq->setValue(3, 2, 0); _jachq->setValue(3, 3, 0); _jachq->setValue(3, 4, _A1x); _jachq->setValue(3, 5, _A1y); _jachq->setValue(3, 6, _A1z); _jachq->setValue(4, 0, 0); _jachq->setValue(4, 1, 0); _jachq->setValue(4, 2, 0); _jachq->setValue(4, 3, 0); _jachq->setValue(4, 4, _A2x); _jachq->setValue(4, 5, _A2y); _jachq->setValue(4, 6, _A2z); for (int ii = 0; ii < _jachq->size(0); ii++) for (int jj = 0; jj < _jachq->size(1); jj++) _jachqProj->setValue(ii, jj, _jachq->getValue(ii, jj)); _jachqProj->setValue(5, 0, 0); _jachqProj->setValue(5, 1, 0); _jachqProj->setValue(5, 2, 0); _jachqProj->setValue(5, 3, 2.0 * q10); _jachqProj->setValue(5, 4, 2.0 * q11); _jachqProj->setValue(5, 5, 2.0 * q12); _jachqProj->setValue(5, 6, 2.0 * q13); } double PivotJointR::AscalA1(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23) { ::boost::math::quaternion<float> quat1(q10, q11, q12, q13); ::boost::math::quaternion<float> quat2_inv(q20, -q21, -q22, -q23); ::boost::math::quaternion<float> quatBuff = quat1 * quat2_inv; double aX = quatBuff.R_component_2(); double aY = quatBuff.R_component_3(); double aZ = quatBuff.R_component_4(); return _A1x * aX + _A1y * aY + _A1z * aZ; } double PivotJointR::AscalA2(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23) { ::boost::math::quaternion<float> quat1(q10, q11, q12, q13); ::boost::math::quaternion<float> quat2_inv(q20, -q21, -q22, -q23); ::boost::math::quaternion<float> quatBuff = quat1 * quat2_inv; double aX = quatBuff.R_component_2(); double aY = quatBuff.R_component_3(); double aZ = quatBuff.R_component_4(); return _A2x * aX + _A2y * aY + _A2z * aZ; } void PivotJointR::computeh(double t) { KneeJointR::computeh(t); SP::SiconosVector x1 = _d1->q(); //std::cout<<"PivotJoint computeH d1->q:\n"; //x1->display(); double q10 = x1->getValue(3); double q11 = x1->getValue(4); double q12 = x1->getValue(5); double q13 = x1->getValue(6); double q20 = 1; double q21 = 0; double q22 = 0; double q23 = 0; if (_d2) { SP::SiconosVector x2 = _d2->q(); q20 = x2->getValue(3); q21 = x2->getValue(4); q22 = x2->getValue(5); q23 = x2->getValue(6); } SP::SiconosVector y = interaction()->y(0); y->setValue(3, AscalA1(q10, q11, q12, q13, q20, q21, q22, q23)); y->setValue(4, AscalA2(q10, q11, q12, q13, q20, q21, q22, q23)); std::cout << "PivotJoint computeH:\n"; y->display(); for (int ii = 0; ii < y->size(); ii++) _yProj->setValue(ii, y->getValue(ii)); _yProj->setValue(5, q10 * q10 + q11 * q11 + q12 * q12 + q13 * q13 - 1.0); if (_d2) { _yProj->setValue(6, q20 * q20 + q21 * q21 + q22 * q22 + q23 * q23 - 1.0); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTracker/ontologies/nco.h> #include <QDebug> #include "trackerchangelistener.h" #include "qcontact.h" using namespace SopranoLive; TrackerChangeListener::TrackerChangeListener(QObject* parent) :QObject(parent) { SopranoLive::BackEnds::Tracker::ClassUpdateSignaler *signaler = SopranoLive::BackEnds::Tracker::ClassUpdateSignaler::get( nco::Contact::iri()); // Note here that we are not using // QAbstractItemModel signals from LiveNodes::model() because // node list for which notification comes is fixed. Those are used for // async implementation if (signaler) { connect(signaler, SIGNAL(subjectsAdded(const QStringList &)), SLOT(subjectsAdded(const QStringList &))); connect(signaler, SIGNAL(baseRemoveSubjectsd(const QStringList &)), SLOT(subjectsRemoved(const QStringList &))); connect(signaler, SIGNAL(subjectsChanged(const QStringList &)), SLOT(subjectsChanged(const QStringList &))); } } TrackerChangeListener::~TrackerChangeListener() { } // TEMPORARY here we'll for now extract ids from tracker contact URI. // In future need nonblocking async way to get contact ids from tracker contact urls // let's see which signals will be used from libqttracker QContactLocalId url2UniqueId(const QString &contactUrl) { QRegExp rx("(\\d+)"); bool conversion = false; QContactLocalId id = 0; if( rx.indexIn(contactUrl) != -1 ) { id = rx.cap(1).toUInt(&conversion, 10); } if( !conversion ) qWarning() << Q_FUNC_INFO << "unparsed uri to uniqueI:" << contactUrl; return id; } void TrackerChangeListener::subjectsAdded(const QStringList &subjects) { QList<QContactLocalId> added; foreach(const QString &uri, subjects) { added << url2UniqueId(uri); } qDebug() << Q_FUNC_INFO << "added contactids:" << added; emit contactsAdded(added); } void TrackerChangeListener::subjectsRemoved(const QStringList &subjects) { QList<QContactLocalId> added; foreach(const QString &uri, subjects) { added << url2UniqueId(uri); } qDebug() << Q_FUNC_INFO << "removed contactids:" << added; emit contactsRemoved(added); } // TODO data changed for full query void TrackerChangeListener::subjectsChanged(const QStringList &subjects) { QList<QContactLocalId> changed; foreach(const QString &uri, subjects) { QContactLocalId id = url2UniqueId(uri); if (changed.contains(id) == false) { changed << id; } } qDebug() << Q_FUNC_INFO << "changed contactids:" << changed; emit contactsChanged(changed); } AsyncQuery::AsyncQuery(RDFSelect selectQuery) { nodes = ::tracker()->modelQuery(selectQuery); QObject::connect(nodes.model(), SIGNAL(modelUpdated()), this, SLOT(queryReady())); } void AsyncQuery::queryReady() { emit queryReady(this); } <commit_msg>* Change URI or ImContacts<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTracker/ontologies/nco.h> #include <QDebug> #include "trackerchangelistener.h" #include "qcontact.h" using namespace SopranoLive; TrackerChangeListener::TrackerChangeListener(QObject* parent) :QObject(parent) { SopranoLive::BackEnds::Tracker::ClassUpdateSignaler *signaler = SopranoLive::BackEnds::Tracker::ClassUpdateSignaler::get( nco::Contact::iri()); // Note here that we are not using // QAbstractItemModel signals from LiveNodes::model() because // node list for which notification comes is fixed. Those are used for // async implementation if (signaler) { connect(signaler, SIGNAL(subjectsAdded(const QStringList &)), SLOT(subjectsAdded(const QStringList &))); connect(signaler, SIGNAL(baseRemoveSubjectsd(const QStringList &)), SLOT(subjectsRemoved(const QStringList &))); connect(signaler, SIGNAL(subjectsChanged(const QStringList &)), SLOT(subjectsChanged(const QStringList &))); } } TrackerChangeListener::~TrackerChangeListener() { } // TEMPORARY here we'll for now extract ids from tracker contact URI. // In future need nonblocking async way to get contact ids from tracker contact urls // let's see which signals will be used from libqttracker QContactLocalId url2UniqueId(const QString &contactUrl) { QContactLocalId id = 0; QStringList decoded = contactUrl.split(":"); qDebug() << Q_FUNC_INFO << decoded; id = qHash(decoded.value(1).remove(0,1)); return id; } void TrackerChangeListener::subjectsAdded(const QStringList &subjects) { QList<QContactLocalId> added; foreach(const QString &uri, subjects) { qDebug() << Q_FUNC_INFO << uri; added << url2UniqueId(uri); } qDebug() << Q_FUNC_INFO << "added contactids:" << added; emit contactsAdded(added); } void TrackerChangeListener::subjectsRemoved(const QStringList &subjects) { QList<QContactLocalId> added; foreach(const QString &uri, subjects) { qDebug() << Q_FUNC_INFO << uri; added << url2UniqueId(uri); } qDebug() << Q_FUNC_INFO << "removed contactids:" << added; emit contactsRemoved(added); } // TODO data changed for full query void TrackerChangeListener::subjectsChanged(const QStringList &subjects) { QList<QContactLocalId> changed; foreach(const QString &uri, subjects) { qDebug() << Q_FUNC_INFO << uri; QContactLocalId id = url2UniqueId(uri); if (changed.contains(id) == false) { changed << id; } } qDebug() << Q_FUNC_INFO << "changed contactids:" << changed; emit contactsChanged(changed); } AsyncQuery::AsyncQuery(RDFSelect selectQuery) { nodes = ::tracker()->modelQuery(selectQuery); QObject::connect(nodes.model(), SIGNAL(modelUpdated()), this, SLOT(queryReady())); } void AsyncQuery::queryReady() { emit queryReady(this); } <|endoftext|>
<commit_before>#ifndef __GLOBALS_HPP_INCLUDED #define __GLOBALS_HPP_INCLUDED #include "any_value.hpp" // GCC (at least g++ 4.7.2) and Visual Studio 2015 do support // setting default values of a struct using C++11 syntax. // Clang 3.7.0 and Visual Studio 2013 do not support // setting default values of a struct using C++11 syntax. // Visual Studio 2013 fails to compile, whereas Clang-compiled // executable with code with setting default values of a struct // causes Segmentation fault upon execution of the program. // Compilers that don't support setting default values of a struct // are handled by setting the default values in a macro. // http://stackoverflow.com/questions/16782103/initializing-default-values-in-a-struct/16783513#16783513 #ifdef __clang__ #elif defined(__GNUC__) #define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED #elif defined(_WIN32) #if (_MSC_VER >= 1900) #define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED #endif #endif // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> // GLfloat, GLuint etc. #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <cmath> // NAN, std::isnan, std::pow #include <stdint.h> // uint32_t etc. #include <string> // std::string #include <vector> // std::vector #ifndef PI #define PI 3.14159265359f #endif namespace ontology { class Universe; class Scene; class Shader; class Graph; class Material; class VectorFont; class Species; class Glyph; class Text3D; } typedef struct ShaderStruct { ShaderStruct() : parent_pointer(nullptr) { // constructor. } ontology::Scene* parent_pointer; // pointer to the scene (draw list). std::string vertex_shader; // filename of vertex shader. std::string fragment_shader; // filename of fragment shader. } ShaderStruct; typedef struct MaterialStruct { MaterialStruct() : parent_pointer(nullptr) { // constructor. } ontology::Shader* parent_pointer; // pointer to the shader. std::string texture_file_format; // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`. std::string texture_filename; // filename of the model file. std::string image_path; } MaterialStruct; typedef struct NodeStruct { NodeStruct() : parent_pointer(nullptr) { // constructor. } GLuint nodeID; ontology::Graph* parent_pointer; glm::vec3 coordinate_vector; std::vector<uint32_t> neighbor_nodeIDs; } NodeStruct; typedef struct ObjectStruct { ObjectStruct() : species_parent_pointer(nullptr), glyph_parent_pointer(nullptr), text3D_parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN), is_character(false) { // constructor. } ontology::Species* species_parent_pointer; // pointer to the parent `Species`. ontology::Glyph* glyph_parent_pointer; // pointer to the parent `Glyph`. ontology::Text3D* text3D_parent_pointer; // pointer to the parent `Text3D`. glm::vec3 original_scale_vector; // original scale vector. GLfloat rotate_angle; // rotate angle. bool is_character; // The parent of a character object is a Glyph. The parent of a regular object is a Species. glm::vec3 coordinate_vector; // coordinate vector. glm::vec3 rotate_vector; // rotate vector. glm::vec3 translate_vector; // translate vector. } ObjectStruct; typedef struct SpeciesStruct { SpeciesStruct() : parent_pointer(nullptr), is_world(false), world_radius(NAN), triangulation_type("bilinear_interpolation") { // constructor. } // used for all files (for all species). ontology::Material* parent_pointer; // pointer to the material object. bool is_world; // worlds currently do not rotate nor translate. float world_radius; // radius of sea level in kilometers. used only for worlds. std::string model_file_format; // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`. // TODO: add support for `"SRTM"`. std::string model_filename; // filename of the model file. // for `"bmp"` model files. std::string color_channel; // color channel to use for altitude data. glm::vec3 light_position; // light position. std::string coordinate_system; // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`. // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps. std::string triangulation_type; } SpeciesStruct; #define DEFAULT_VERTEX_SCALING_FACTOR (0.001f) typedef struct VectorFontStruct { VectorFontStruct() : parent_pointer(nullptr), vertex_scaling_factor(DEFAULT_VERTEX_SCALING_FACTOR) { // constructor. } // used for all files (for all font). ontology::Material* parent_pointer; // pointer to the material object. GLfloat vertex_scaling_factor; std::string font_file_format; // type of the font file. supported file formats so far: `"svg"`/`"SVG"`. std::string font_filename; // filename of the font file. } VectorFontStruct; typedef struct Text3DStruct { Text3DStruct() : parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN) { // constructor. } ontology::VectorFont* parent_pointer; // pointer to the parent `VectorFont`. std::string text_string; const char* text_string_char; glm::vec3 original_scale_vector; // original scale vector. GLfloat rotate_angle; // rotate angle. glm::vec3 coordinate_vector; // coordinate vector. glm::vec3 rotate_vector; // rotate vector. glm::vec3 translate_vector; // translate vector. } Text3DStruct; typedef struct GlyphStruct { GlyphStruct() : parent_pointer(nullptr) { // constructor. } // used for all files (for all glyph). std::vector<std::vector<glm::vec2>>* glyph_vertex_data; const char* glyph_name_pointer; // we need only a pointer, because glyphs are always created by the `VectorFont` constructor. const char* unicode_char_pointer; // we need only a pointer, because glyphs are always created by the `VectorFont` constructor. ontology::VectorFont* parent_pointer; // pointer to the font object. glm::vec3 light_position; // light position. } GlyphStruct; typedef struct { GLuint screen_width; GLuint screen_height; GLuint x; GLuint y; GLuint text_size; GLuint font_size; std::string text; const char* text_char; const char* char_font_texture_file_format; const char* horizontal_alignment; const char* vertical_alignment; } PrintingStruct; typedef struct { double rho; double theta; double phi; } SphericalCoordinatesStruct; typedef struct SphericalWorldStruct { SphericalWorldStruct() :SRTM_latitude_step_in_degrees(1.0f/1200.0f), SRTM_longitude_step_in_degrees(1.0f/1200.0f) { // constructor. } double southern_latitude; double northern_latitude; double western_longitude; double eastern_longitude; double SRTM_latitude_step_in_degrees; double SRTM_longitude_step_in_degrees; } SphericalWorldStruct; typedef struct TriangulateQuadsStruct { TriangulateQuadsStruct() : should_ylikuutio_use_real_texture_coordinates(true) { // constructor. } uint32_t image_width; uint32_t image_height; std::string triangulation_type; bool should_ylikuutio_use_real_texture_coordinates; double sphere_radius; SphericalWorldStruct spherical_world_struct; } TriangulateQuadsStruct; typedef struct TriangulatePolygonsStruct { TriangulatePolygonsStruct() : should_ylikuutio_use_real_texture_coordinates(true) { // constructor. } std::vector<std::vector<glm::vec2>>* input_vertices; bool should_ylikuutio_use_real_texture_coordinates; } TriangulatePolygonsStruct; typedef struct { uint32_t image_width; uint32_t image_height; bool should_ylikuutio_use_real_texture_coordinates; } BilinearInterpolationStruct; typedef struct { uint32_t image_width; uint32_t image_height; double sphere_radius; bool is_bilinear_interpolation_in_use; SphericalWorldStruct spherical_world_struct; } TransformationStruct; namespace callback_system { class CallbackEngine; class CallbackObject; class CallbackParameter; } typedef datatypes::AnyValue* (*InputParametersToAnyValueCallback) ( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*>&); namespace console { class Console; } typedef datatypes::AnyValue* (*InputParametersToAnyValueCallbackWithConsole) ( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*>&, console::Console*); #endif <commit_msg>Edited comments.<commit_after>#ifndef __GLOBALS_HPP_INCLUDED #define __GLOBALS_HPP_INCLUDED #include "any_value.hpp" // GCC (at least g++ 4.7.2) and Visual Studio 2015 do support // setting default values of a struct using C++11 syntax. // Clang 3.7.0 and Visual Studio 2013 do not support // setting default values of a struct using C++11 syntax. // Visual Studio 2013 fails to compile, whereas Clang-compiled // executable with code with setting default values of a struct // causes Segmentation fault upon execution of the program. // Compilers that don't support setting default values of a struct // are handled by setting the default values in a macro. // http://stackoverflow.com/questions/16782103/initializing-default-values-in-a-struct/16783513#16783513 #ifdef __clang__ #elif defined(__GNUC__) #define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED #elif defined(_WIN32) #if (_MSC_VER >= 1900) #define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED #endif #endif // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> // GLfloat, GLuint etc. #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <cmath> // NAN, std::isnan, std::pow #include <stdint.h> // uint32_t etc. #include <string> // std::string #include <vector> // std::vector #ifndef PI #define PI 3.14159265359f #endif namespace ontology { class Universe; class Scene; class Shader; class Graph; class Material; class VectorFont; class Species; class Glyph; class Text3D; } typedef struct ShaderStruct { ShaderStruct() : parent_pointer(nullptr) { // constructor. } ontology::Scene* parent_pointer; // pointer to the scene (draw list). std::string vertex_shader; // filename of vertex shader. std::string fragment_shader; // filename of fragment shader. } ShaderStruct; typedef struct MaterialStruct { MaterialStruct() : parent_pointer(nullptr) { // constructor. } ontology::Shader* parent_pointer; // pointer to the shader. std::string texture_file_format; // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`. std::string texture_filename; // filename of the model file. std::string image_path; } MaterialStruct; typedef struct NodeStruct { NodeStruct() : parent_pointer(nullptr) { // constructor. } GLuint nodeID; ontology::Graph* parent_pointer; glm::vec3 coordinate_vector; std::vector<uint32_t> neighbor_nodeIDs; } NodeStruct; typedef struct ObjectStruct { ObjectStruct() : species_parent_pointer(nullptr), glyph_parent_pointer(nullptr), text3D_parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN), is_character(false) { // constructor. } ontology::Species* species_parent_pointer; // pointer to the parent `Species`. ontology::Glyph* glyph_parent_pointer; // pointer to the parent `Glyph`. ontology::Text3D* text3D_parent_pointer; // pointer to the parent `Text3D`. glm::vec3 original_scale_vector; // original scale vector. GLfloat rotate_angle; // rotate angle. bool is_character; // The parent of a character object is a Glyph. The parent of a regular object is a Species. glm::vec3 coordinate_vector; // coordinate vector. glm::vec3 rotate_vector; // rotate vector. glm::vec3 translate_vector; // translate vector. } ObjectStruct; typedef struct SpeciesStruct { SpeciesStruct() : parent_pointer(nullptr), is_world(false), world_radius(NAN), triangulation_type("bilinear_interpolation") { // constructor. } // used for all files (for all species). ontology::Material* parent_pointer; // pointer to the material object. bool is_world; // worlds currently do not rotate nor translate. float world_radius; // radius of sea level in kilometers. used only for worlds. std::string model_file_format; // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`. // TODO: add support for `"SRTM"`. std::string model_filename; // filename of the model file. // for `"bmp"` model files. std::string color_channel; // color channel to use for altitude data. glm::vec3 light_position; // light position. std::string coordinate_system; // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`. // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps. std::string triangulation_type; } SpeciesStruct; #define DEFAULT_VERTEX_SCALING_FACTOR (0.001f) typedef struct VectorFontStruct { VectorFontStruct() : parent_pointer(nullptr), vertex_scaling_factor(DEFAULT_VERTEX_SCALING_FACTOR) { // constructor. } // used for all files (for all font). ontology::Material* parent_pointer; // pointer to the material object. GLfloat vertex_scaling_factor; std::string font_file_format; // type of the font file. supported file formats so far: `"svg"`/`"SVG"`. std::string font_filename; // filename of the font file. } VectorFontStruct; typedef struct Text3DStruct { Text3DStruct() : parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN) { // constructor. } ontology::VectorFont* parent_pointer; // pointer to the parent `VectorFont`. std::string text_string; const char* text_string_char; glm::vec3 original_scale_vector; // original scale vector. GLfloat rotate_angle; // rotate angle. glm::vec3 coordinate_vector; // coordinate vector. glm::vec3 rotate_vector; // rotate vector. glm::vec3 translate_vector; // translate vector. } Text3DStruct; typedef struct GlyphStruct { GlyphStruct() : parent_pointer(nullptr) { // constructor. } // used for all files (for all glyph). std::vector<std::vector<glm::vec2>>* glyph_vertex_data; const char* glyph_name_pointer; // we need only a pointer, because glyphs are always created by the `VectorFont` constructor. const char* unicode_char_pointer; // we need only a pointer, because glyphs are always created by the `VectorFont` constructor. ontology::VectorFont* parent_pointer; // pointer to the font object. glm::vec3 light_position; // light position. } GlyphStruct; typedef struct { GLuint screen_width; GLuint screen_height; GLuint x; GLuint y; GLuint text_size; GLuint font_size; std::string text; const char* text_char; const char* char_font_texture_file_format; const char* horizontal_alignment; const char* vertical_alignment; } PrintingStruct; typedef struct { double rho; double theta; double phi; } SphericalCoordinatesStruct; typedef struct SphericalWorldStruct { SphericalWorldStruct() :SRTM_latitude_step_in_degrees(1.0f/1200.0f), SRTM_longitude_step_in_degrees(1.0f/1200.0f) { // constructor. } double southern_latitude; double northern_latitude; double western_longitude; double eastern_longitude; double SRTM_latitude_step_in_degrees; double SRTM_longitude_step_in_degrees; } SphericalWorldStruct; typedef struct TriangulateQuadsStruct { TriangulateQuadsStruct() : should_ylikuutio_use_real_texture_coordinates(true) { // constructor. } uint32_t image_width; uint32_t image_height; std::string triangulation_type; bool should_ylikuutio_use_real_texture_coordinates; double sphere_radius; SphericalWorldStruct spherical_world_struct; } TriangulateQuadsStruct; typedef struct TriangulatePolygonsStruct { TriangulatePolygonsStruct() : should_ylikuutio_use_real_texture_coordinates(true) { // constructor. } std::vector<std::vector<glm::vec2>>* input_vertices; bool should_ylikuutio_use_real_texture_coordinates; } TriangulatePolygonsStruct; typedef struct { uint32_t image_width; uint32_t image_height; bool should_ylikuutio_use_real_texture_coordinates; } BilinearInterpolationStruct; typedef struct { uint32_t image_width; uint32_t image_height; double sphere_radius; bool is_bilinear_interpolation_in_use; SphericalWorldStruct spherical_world_struct; } TransformationStruct; namespace callback_system { class CallbackEngine; class CallbackObject; class CallbackParameter; } typedef datatypes::AnyValue* (*InputParametersToAnyValueCallback) ( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*>&); namespace console { class Console; } typedef datatypes::AnyValue* (*InputParametersToAnyValueCallbackWithConsole) ( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*>&, console::Console*); #endif <|endoftext|>
<commit_before>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2020 Antti Nuortimo. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "setting.hpp" #include "setting_master.hpp" #include "setting_struct.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include standard headers #include <cstddef> // std::size_t #include <limits> // std::numeric_limits #include <string> // std::string namespace yli { namespace config { void Setting::bind_to_parent() { yli::hierarchy::bind_child_to_parent<yli::config::Setting*>(this, this->parent->setting_pointer_vector, this->parent->free_settingID_queue, this->parent->number_of_settings); } Setting::Setting(yli::config::SettingMaster* const setting_master, const yli::config::SettingStruct& setting_struct) { // constructor. this->name = setting_struct.name; this->setting_value = setting_struct.initial_value; this->parent = setting_master; this->activate_callback = setting_struct.activate_callback; this->read_callback = setting_struct.read_callback; this->childID = std::numeric_limits<std::size_t>::max(); if (this->parent == nullptr) { return; } // get `childID` from the `SettingMaster` and set pointer to this `Setting`. this->bind_to_parent(); this->parent->setting_pointer_map[this->name] = this; if (setting_struct.should_ylikuutio_call_activate_callback_now && this->activate_callback != nullptr) { this->activate_callback(this->parent->parent, this->parent); } } Setting::~Setting() { // destructor. } std::string Setting::help() const { // this function returns the help string for this setting. std::string help_string = this->name + " TODO: create helptext for " + this->name; return help_string; } } } <commit_msg>`Setting` constructor: check `parent` of `SettingMaster` for `nullptr`.<commit_after>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2020 Antti Nuortimo. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "setting.hpp" #include "setting_master.hpp" #include "setting_struct.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include standard headers #include <cstddef> // std::size_t #include <limits> // std::numeric_limits #include <string> // std::string namespace yli { namespace config { void Setting::bind_to_parent() { yli::hierarchy::bind_child_to_parent<yli::config::Setting*>(this, this->parent->setting_pointer_vector, this->parent->free_settingID_queue, this->parent->number_of_settings); } Setting::Setting(yli::config::SettingMaster* const setting_master, const yli::config::SettingStruct& setting_struct) { // constructor. this->name = setting_struct.name; this->setting_value = setting_struct.initial_value; this->parent = setting_master; this->activate_callback = setting_struct.activate_callback; this->read_callback = setting_struct.read_callback; this->childID = std::numeric_limits<std::size_t>::max(); if (this->parent == nullptr) { return; } // get `childID` from the `SettingMaster` and set pointer to this `Setting`. this->bind_to_parent(); this->parent->setting_pointer_map[this->name] = this; if (setting_struct.should_ylikuutio_call_activate_callback_now && this->activate_callback != nullptr && this->parent->parent != nullptr) { this->activate_callback(this->parent->parent, this->parent); } } Setting::~Setting() { // destructor. } std::string Setting::help() const { // this function returns the help string for this setting. std::string help_string = this->name + " TODO: create helptext for " + this->name; return help_string; } } } <|endoftext|>
<commit_before>#include "rtkprojections_ggo.h" #include "rtkMacro.h" #include "itkProjectionsReader.h" #include <itkImageFileWriter.h> #include <itkRegularExpressionSeriesFileNames.h> #include <itkTimeProbe.h> int main(int argc, char * argv[]) { GGO(rtkprojections, args_info); typedef double OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Generate file names itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New(); names->SetDirectory(args_info.path_arg); names->SetNumericSort(false); names->SetRegularExpression(args_info.regexp_arg); names->SetSubMatch(0); // Projections reader typedef itk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileNames( names->GetFileNames() ); // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( reader->GetOutput() ); writer->UpdateOutputInformation(); writer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Use float instead of double as output<commit_after>#include "rtkprojections_ggo.h" #include "rtkMacro.h" #include "itkProjectionsReader.h" #include <itkImageFileWriter.h> #include <itkRegularExpressionSeriesFileNames.h> #include <itkTimeProbe.h> int main(int argc, char * argv[]) { GGO(rtkprojections, args_info); typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Generate file names itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New(); names->SetDirectory(args_info.path_arg); names->SetNumericSort(false); names->SetRegularExpression(args_info.regexp_arg); names->SetSubMatch(0); // Projections reader typedef itk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileNames( names->GetFileNames() ); // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( reader->GetOutput() ); writer->UpdateOutputInformation(); writer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "propacc.hxx" #include <svl/svarray.hxx> #include <basic/sbstar.hxx> #include <sbunoobj.hxx> using com::sun::star::uno::Reference; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace cppu; //======================================================================== // Declaration conversion from Sbx to UNO with known target type Any sbxToUnoValue( SbxVariable* pVar, const Type& rType, Property* pUnoProperty = NULL ); //======================================================================== #ifdef WNT #define CDECL _cdecl #endif #if defined(UNX) #define CDECL #endif int CDECL SbCompare_PropertyValues_Impl( const void *arg1, const void *arg2 ) { return ((PropertyValue*)arg1)->Name.compareTo( ((PropertyValue*)arg2)->Name ); } struct SbCompare_UString_PropertyValue_Impl { bool operator() ( const ::rtl::OUString& lhs, PropertyValue* const & rhs ) { return lhs.compareTo( rhs->Name ); } bool operator() ( PropertyValue* const & lhs, const ::rtl::OUString& rhs ) { return !rhs.compareTo( lhs->Name ); } }; int CDECL SbCompare_Properties_Impl( const void *arg1, const void *arg2 ) { return ((Property*)arg1)->Name.compareTo( ((Property*)arg2)->Name ); } extern "C" int CDECL SbCompare_UString_Property_Impl( const void *arg1, const void *arg2 ) { const ::rtl::OUString *pArg1 = (::rtl::OUString*) arg1; const Property *pArg2 = (Property*) arg2; return pArg1->compareTo( pArg2->Name ); } //---------------------------------------------------------------------------- SbPropertyValues::SbPropertyValues() { } //---------------------------------------------------------------------------- SbPropertyValues::~SbPropertyValues() { _xInfo = Reference< XPropertySetInfo >(); for ( sal_uInt16 n = 0; n < _aPropVals.size(); ++n ) delete _aPropVals[ n ]; } //---------------------------------------------------------------------------- Reference< XPropertySetInfo > SbPropertyValues::getPropertySetInfo(void) throw( RuntimeException ) { // create on demand? if ( !_xInfo.is() ) { SbPropertySetInfo *pInfo = new SbPropertySetInfo( _aPropVals ); ((SbPropertyValues*)this)->_xInfo = (XPropertySetInfo*)pInfo; } return _xInfo; } //------------------------------------------------------------------------- sal_Int32 SbPropertyValues::GetIndex_Impl( const ::rtl::OUString &rPropName ) const { SbPropertyValueArr_Impl::const_iterator it = std::lower_bound( _aPropVals.begin(), _aPropVals.end(), rPropName, SbCompare_UString_PropertyValue_Impl() ); return it != _aPropVals.end() ? it - _aPropVals.begin() : USHRT_MAX; } //---------------------------------------------------------------------------- void SbPropertyValues::setPropertyValue( const ::rtl::OUString& aPropertyName, const Any& aValue) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) { sal_Int32 nIndex = GetIndex_Impl( aPropertyName ); PropertyValue *pPropVal = _aPropVals[ sal::static_int_cast< sal_uInt16 >(nIndex)]; pPropVal->Value = aValue; } //---------------------------------------------------------------------------- Any SbPropertyValues::getPropertyValue( const ::rtl::OUString& aPropertyName) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) { sal_Int32 nIndex = GetIndex_Impl( aPropertyName ); if ( nIndex != USHRT_MAX ) return _aPropVals[ sal::static_int_cast< sal_uInt16 >(nIndex)]->Value; return Any(); } //---------------------------------------------------------------------------- void SbPropertyValues::addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XPropertyChangeListener >& ) throw () { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XPropertyChangeListener >& ) throw () { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::addVetoableChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XVetoableChangeListener >& ) throw() { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::removeVetoableChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XVetoableChangeListener >& ) throw() { (void)aPropertyName; } //---------------------------------------------------------------------------- Sequence< PropertyValue > SbPropertyValues::getPropertyValues(void) throw (::com::sun::star::uno::RuntimeException) { Sequence<PropertyValue> aRet( _aPropVals.size() ); for ( sal_uInt16 n = 0; n < _aPropVals.size(); ++n ) aRet.getArray()[n] = *_aPropVals[n]; return aRet; } //---------------------------------------------------------------------------- void SbPropertyValues::setPropertyValues(const Sequence< PropertyValue >& rPropertyValues ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) { if ( !_aPropVals.empty() ) throw PropertyExistException(); const PropertyValue *pPropVals = rPropertyValues.getConstArray(); for ( sal_Int16 n = 0; n < rPropertyValues.getLength(); ++n ) { PropertyValue *pPropVal = new PropertyValue(pPropVals[n]); _aPropVals.push_back( pPropVal ); } } //============================================================================ //PropertySetInfoImpl PropertySetInfoImpl::PropertySetInfoImpl() { } sal_Int32 PropertySetInfoImpl::GetIndex_Impl( const ::rtl::OUString &rPropName ) const { Property *pP; pP = (Property*) bsearch( &rPropName, _aProps.getConstArray(), _aProps.getLength(), sizeof( Property ), SbCompare_UString_Property_Impl ); return pP ? sal::static_int_cast<sal_Int32>( pP - _aProps.getConstArray() ) : -1; } Sequence< Property > PropertySetInfoImpl::getProperties(void) throw() { return _aProps; } Property PropertySetInfoImpl::getPropertyByName(const ::rtl::OUString& Name) throw( RuntimeException ) { sal_Int32 nIndex = GetIndex_Impl( Name ); if( USHRT_MAX != nIndex ) return _aProps.getConstArray()[ nIndex ]; return Property(); } sal_Bool PropertySetInfoImpl::hasPropertyByName(const ::rtl::OUString& Name) throw( RuntimeException ) { sal_Int32 nIndex = GetIndex_Impl( Name ); return USHRT_MAX != nIndex; } //---------------------------------------------------------------------------- SbPropertySetInfo::SbPropertySetInfo( const SbPropertyValueArr_Impl &rPropVals ) { aImpl._aProps.realloc( rPropVals.size() ); for ( sal_uInt16 n = 0; n < rPropVals.size(); ++n ) { Property &rProp = aImpl._aProps.getArray()[n]; const PropertyValue &rPropVal = *rPropVals[n]; rProp.Name = rPropVal.Name; rProp.Handle = rPropVal.Handle; rProp.Type = getCppuVoidType(); rProp.Attributes = 0; } } //---------------------------------------------------------------------------- SbPropertySetInfo::~SbPropertySetInfo() { } //------------------------------------------------------------------------- Sequence< Property > SbPropertySetInfo::getProperties(void) throw( RuntimeException ) { return aImpl.getProperties(); } Property SbPropertySetInfo::getPropertyByName(const ::rtl::OUString& Name) throw( RuntimeException ) { return aImpl.getPropertyByName( Name ); } sal_Bool SbPropertySetInfo::hasPropertyByName(const ::rtl::OUString& Name) throw( RuntimeException ) { return aImpl.hasPropertyByName( Name ); } //---------------------------------------------------------------------------- void RTL_Impl_CreatePropertySet( StarBASIC* pBasic, SbxArray& rPar, sal_Bool bWrite ) { (void)pBasic; (void)bWrite; // We need at least one parameter // TODO: In this case < 2 is not correct ;-) if ( rPar.Count() < 2 ) { StarBASIC::Error( SbERR_BAD_ARGUMENT ); return; } // Get class names of struct ::rtl::OUString aServiceName( RTL_CONSTASCII_USTRINGPARAM("stardiv.uno.beans.PropertySet") ); Reference< XInterface > xInterface = (OWeakObject*) new SbPropertyValues(); SbxVariableRef refVar = rPar.Get(0); if( xInterface.is() ) { // Set PropertyValues Any aArgAsAny = sbxToUnoValue( rPar.Get(1), getCppuType( (Sequence<PropertyValue>*)0 ) ); Sequence<PropertyValue> *pArg = (Sequence<PropertyValue>*) aArgAsAny.getValue(); Reference< XPropertyAccess > xPropAcc = Reference< XPropertyAccess >::query( xInterface ); xPropAcc->setPropertyValues( *pArg ); // Build a SbUnoObject and return it Any aAny; aAny <<= xInterface; SbUnoObjectRef xUnoObj = new SbUnoObject( aServiceName, aAny ); if( xUnoObj->getUnoAny().getValueType().getTypeClass() != TypeClass_VOID ) { // Return object refVar->PutObject( (SbUnoObject*)xUnoObj ); return; } } // Object could not be created refVar->PutObject( NULL ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fix previous commit:<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "propacc.hxx" #include <svl/svarray.hxx> #include <basic/sbstar.hxx> #include <sbunoobj.hxx> using com::sun::star::uno::Reference; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace cppu; //======================================================================== // Declaration conversion from Sbx to UNO with known target type Any sbxToUnoValue( SbxVariable* pVar, const Type& rType, Property* pUnoProperty = NULL ); //======================================================================== #ifdef WNT #define CDECL _cdecl #endif #if defined(UNX) #define CDECL #endif int CDECL SbCompare_PropertyValues_Impl( const void *arg1, const void *arg2 ) { return ((PropertyValue*)arg1)->Name.compareTo( ((PropertyValue*)arg2)->Name ); } struct SbCompare_UString_PropertyValue_Impl { bool operator() ( const ::rtl::OUString& lhs, PropertyValue* const & rhs ) { return lhs.compareTo(rhs->Name) < 0; } bool operator() ( PropertyValue* const & lhs, const ::rtl::OUString& rhs ) { return lhs->Name.compareTo(rhs) < 0; } }; int CDECL SbCompare_Properties_Impl( const void *arg1, const void *arg2 ) { return ((Property*)arg1)->Name.compareTo( ((Property*)arg2)->Name ); } extern "C" int CDECL SbCompare_UString_Property_Impl( const void *arg1, const void *arg2 ) { const ::rtl::OUString *pArg1 = (::rtl::OUString*) arg1; const Property *pArg2 = (Property*) arg2; return pArg1->compareTo( pArg2->Name ); } //---------------------------------------------------------------------------- SbPropertyValues::SbPropertyValues() { } //---------------------------------------------------------------------------- SbPropertyValues::~SbPropertyValues() { _xInfo = Reference< XPropertySetInfo >(); for ( sal_uInt16 n = 0; n < _aPropVals.size(); ++n ) delete _aPropVals[ n ]; } //---------------------------------------------------------------------------- Reference< XPropertySetInfo > SbPropertyValues::getPropertySetInfo(void) throw( RuntimeException ) { // create on demand? if ( !_xInfo.is() ) { SbPropertySetInfo *pInfo = new SbPropertySetInfo( _aPropVals ); ((SbPropertyValues*)this)->_xInfo = (XPropertySetInfo*)pInfo; } return _xInfo; } //------------------------------------------------------------------------- sal_Int32 SbPropertyValues::GetIndex_Impl( const ::rtl::OUString &rPropName ) const { SbPropertyValueArr_Impl::const_iterator it = std::lower_bound( _aPropVals.begin(), _aPropVals.end(), rPropName, SbCompare_UString_PropertyValue_Impl() ); return it != _aPropVals.end() ? it - _aPropVals.begin() : USHRT_MAX; } //---------------------------------------------------------------------------- void SbPropertyValues::setPropertyValue( const ::rtl::OUString& aPropertyName, const Any& aValue) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) { sal_Int32 nIndex = GetIndex_Impl( aPropertyName ); PropertyValue *pPropVal = _aPropVals[ sal::static_int_cast< sal_uInt16 >(nIndex)]; pPropVal->Value = aValue; } //---------------------------------------------------------------------------- Any SbPropertyValues::getPropertyValue( const ::rtl::OUString& aPropertyName) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) { sal_Int32 nIndex = GetIndex_Impl( aPropertyName ); if ( nIndex != USHRT_MAX ) return _aPropVals[ sal::static_int_cast< sal_uInt16 >(nIndex)]->Value; return Any(); } //---------------------------------------------------------------------------- void SbPropertyValues::addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XPropertyChangeListener >& ) throw () { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XPropertyChangeListener >& ) throw () { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::addVetoableChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XVetoableChangeListener >& ) throw() { (void)aPropertyName; } //---------------------------------------------------------------------------- void SbPropertyValues::removeVetoableChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XVetoableChangeListener >& ) throw() { (void)aPropertyName; } //---------------------------------------------------------------------------- Sequence< PropertyValue > SbPropertyValues::getPropertyValues(void) throw (::com::sun::star::uno::RuntimeException) { Sequence<PropertyValue> aRet( _aPropVals.size() ); for ( sal_uInt16 n = 0; n < _aPropVals.size(); ++n ) aRet.getArray()[n] = *_aPropVals[n]; return aRet; } //---------------------------------------------------------------------------- void SbPropertyValues::setPropertyValues(const Sequence< PropertyValue >& rPropertyValues ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException) { if ( !_aPropVals.empty() ) throw PropertyExistException(); const PropertyValue *pPropVals = rPropertyValues.getConstArray(); for ( sal_Int16 n = 0; n < rPropertyValues.getLength(); ++n ) { PropertyValue *pPropVal = new PropertyValue(pPropVals[n]); _aPropVals.push_back( pPropVal ); } } //============================================================================ //PropertySetInfoImpl PropertySetInfoImpl::PropertySetInfoImpl() { } sal_Int32 PropertySetInfoImpl::GetIndex_Impl( const ::rtl::OUString &rPropName ) const { Property *pP; pP = (Property*) bsearch( &rPropName, _aProps.getConstArray(), _aProps.getLength(), sizeof( Property ), SbCompare_UString_Property_Impl ); return pP ? sal::static_int_cast<sal_Int32>( pP - _aProps.getConstArray() ) : -1; } Sequence< Property > PropertySetInfoImpl::getProperties(void) throw() { return _aProps; } Property PropertySetInfoImpl::getPropertyByName(const ::rtl::OUString& Name) throw( RuntimeException ) { sal_Int32 nIndex = GetIndex_Impl( Name ); if( USHRT_MAX != nIndex ) return _aProps.getConstArray()[ nIndex ]; return Property(); } sal_Bool PropertySetInfoImpl::hasPropertyByName(const ::rtl::OUString& Name) throw( RuntimeException ) { sal_Int32 nIndex = GetIndex_Impl( Name ); return USHRT_MAX != nIndex; } //---------------------------------------------------------------------------- SbPropertySetInfo::SbPropertySetInfo( const SbPropertyValueArr_Impl &rPropVals ) { aImpl._aProps.realloc( rPropVals.size() ); for ( sal_uInt16 n = 0; n < rPropVals.size(); ++n ) { Property &rProp = aImpl._aProps.getArray()[n]; const PropertyValue &rPropVal = *rPropVals[n]; rProp.Name = rPropVal.Name; rProp.Handle = rPropVal.Handle; rProp.Type = getCppuVoidType(); rProp.Attributes = 0; } } //---------------------------------------------------------------------------- SbPropertySetInfo::~SbPropertySetInfo() { } //------------------------------------------------------------------------- Sequence< Property > SbPropertySetInfo::getProperties(void) throw( RuntimeException ) { return aImpl.getProperties(); } Property SbPropertySetInfo::getPropertyByName(const ::rtl::OUString& Name) throw( RuntimeException ) { return aImpl.getPropertyByName( Name ); } sal_Bool SbPropertySetInfo::hasPropertyByName(const ::rtl::OUString& Name) throw( RuntimeException ) { return aImpl.hasPropertyByName( Name ); } //---------------------------------------------------------------------------- void RTL_Impl_CreatePropertySet( StarBASIC* pBasic, SbxArray& rPar, sal_Bool bWrite ) { (void)pBasic; (void)bWrite; // We need at least one parameter // TODO: In this case < 2 is not correct ;-) if ( rPar.Count() < 2 ) { StarBASIC::Error( SbERR_BAD_ARGUMENT ); return; } // Get class names of struct ::rtl::OUString aServiceName( RTL_CONSTASCII_USTRINGPARAM("stardiv.uno.beans.PropertySet") ); Reference< XInterface > xInterface = (OWeakObject*) new SbPropertyValues(); SbxVariableRef refVar = rPar.Get(0); if( xInterface.is() ) { // Set PropertyValues Any aArgAsAny = sbxToUnoValue( rPar.Get(1), getCppuType( (Sequence<PropertyValue>*)0 ) ); Sequence<PropertyValue> *pArg = (Sequence<PropertyValue>*) aArgAsAny.getValue(); Reference< XPropertyAccess > xPropAcc = Reference< XPropertyAccess >::query( xInterface ); xPropAcc->setPropertyValues( *pArg ); // Build a SbUnoObject and return it Any aAny; aAny <<= xInterface; SbUnoObjectRef xUnoObj = new SbUnoObject( aServiceName, aAny ); if( xUnoObj->getUnoAny().getValueType().getTypeClass() != TypeClass_VOID ) { // Return object refVar->PutObject( (SbUnoObject*)xUnoObj ); return; } } // Object could not be created refVar->PutObject( NULL ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * This program is just for personal experiments here on AVR features and C++ stuff * to check compilation and link of FastArduino port and pin API. * It does not do anything interesting as far as hardware is concerned. */ #include <fastarduino/fast_io.h> #include <fastarduino/time.h> #include <fastarduino/timer.h> constexpr const board::Timer TIMER = board::Timer::TIMER0; using TIMER_TYPE = timer::Timer<TIMER>; // Frequency for PWM constexpr const uint16_t PWM_FREQUENCY = 500; constexpr const TIMER_TYPE::TIMER_PRESCALER PRESCALER = TIMER_TYPE::PWM_prescaler(PWM_FREQUENCY); //TODO Timer API to check adequacy of prescaler for frequency (within some min/max range) static_assert(TIMER_TYPE::PWM_frequency(PRESCALER) >= 500, "PWM Frequency is expected greater than 450"); static_assert(TIMER_TYPE::PWM_frequency(PRESCALER) < 1000, "PWM Frequency is expected less than 1000"); constexpr const uint16_t LOOP_DELAY_MS = 1000; using time::delay_ms; using timer::TimerOutputMode; using gpio::FastPinType; using gpio::PinMode; using LED_PIN = FastPinType<board::PWMPin::D6_PD6_OC0A>::TYPE; int main() { LED_PIN led{PinMode::OUTPUT}; TIMER_TYPE timer{TimerOutputMode::NON_INVERTING}; timer._begin_FastPWM(PRESCALER); sei(); TIMER_TYPE::TIMER_TYPE duty = 0; while (true) { timer.set_max_A(duty++); delay_ms(LOOP_DELAY_MS); } } <commit_msg>PWM: check dual channel in example.<commit_after>/* * This program is just for personal experiments here on AVR features and C++ stuff * to check compilation and link of FastArduino port and pin API. * It does not do anything interesting as far as hardware is concerned. */ #include <fastarduino/fast_io.h> #include <fastarduino/time.h> #include <fastarduino/timer.h> constexpr const board::Timer TIMER = board::Timer::TIMER0; using TIMER_TYPE = timer::Timer<TIMER>; // Frequency for PWM constexpr const uint16_t PWM_FREQUENCY = 500; constexpr const TIMER_TYPE::TIMER_PRESCALER PRESCALER = TIMER_TYPE::PWM_prescaler(PWM_FREQUENCY); //TODO Timer API to check adequacy of prescaler for frequency (within some min/max range) static_assert(TIMER_TYPE::PWM_frequency(PRESCALER) >= 500, "PWM Frequency is expected greater than 450"); static_assert(TIMER_TYPE::PWM_frequency(PRESCALER) < 1000, "PWM Frequency is expected less than 1000"); constexpr const uint16_t LOOP_DELAY_MS = 1000; using time::delay_ms; using timer::TimerOutputMode; using gpio::FastPinType; using gpio::PinMode; using LED1_PIN = FastPinType<board::PWMPin::D6_PD6_OC0A>::TYPE; using LED2_PIN = FastPinType<board::PWMPin::D5_PD5_OC0B>::TYPE; int main() { LED1_PIN led1{PinMode::OUTPUT}; LED2_PIN led2{PinMode::OUTPUT}; TIMER_TYPE timer{TimerOutputMode::NON_INVERTING, TimerOutputMode::NON_INVERTING}; timer._begin_FastPWM(PRESCALER); sei(); TIMER_TYPE::TIMER_TYPE duty1 = 0; TIMER_TYPE::TIMER_TYPE duty2 = 0xFF; while (true) { timer.set_max_A(duty1++); timer.set_max_B(duty2--); delay_ms(LOOP_DELAY_MS); } } <|endoftext|>
<commit_before>/* * This program is just for personal experiments here on AVR features and C++ stuff * to check compilation and link of FastArduino port and pin API. * It does not do anything interesting as far as hardware is concerned. */ #include <fastarduino/boards/board.h> #include <fastarduino/uart.h> #include <fastarduino/gpio.h> #include <fastarduino/time.h> #include <fastarduino/realtime_timer.h> #include <fastarduino/utilities.h> #include <fastarduino/flash.h> #include <fastarduino/int.h> REGISTER_RTT_ISR(0) REGISTER_UATX_ISR(0) // Conversion method static constexpr uint16_t distance_mm(uint16_t echo_us) { // 340 m/s => 340000mm in 1000000us => 340/1000 mm/us return uint16_t(echo_us * 340UL / 1000UL / 2UL); } // Utilities to handle ISR callbacks #define REGISTER_SERVO_INT_ISR(TIMER_NUM, INT_NUM, TRIGGER, ECHO) \ static_assert(board_traits::DigitalPin_trait< ECHO >::IS_INT, "PIN must be an INT pin."); \ static_assert(board_traits::ExternalInterruptPin_trait< ECHO >::INT == INT_NUM , \ "PIN INT number must match INT_NUM"); \ ISR(CAT3(INT, INT_NUM, _vect)) \ { \ static constexpr const board::Timer TIMER = CAT(board::Timer::TIMER, TIMER_NUM); \ using SERVO_HANDLER = HCSR04<TIMER, TRIGGER, ECHO >; \ CALL_HANDLER_(SERVO_HANDLER, &SERVO_HANDLER::on_echo)(); \ } //TODO non blocking ultrasonic sensor // - use RTT timer (template arg) // - use pin interrupt (either EXT or PCI, both should be supported) template<board::Timer TIMER, board::DigitalPin TRIGGER, board::DigitalPin ECHO> class HCSR04 { public: static constexpr const uint16_t DEFAULT_TIMEOUT_US = 4 * 2 * 1000000UL / 340 + 1; HCSR04(timer::RTT<TIMER>& rtt) : signal_{}, rtt_{rtt}, trigger_{gpio::PinMode::OUTPUT}, echo_{gpio::PinMode::INPUT}, start_{}, echo_pulse_{0}, ready_{false} { interrupt::register_handler(*this); } uint16_t echo_us(uint16_t timeout_us = DEFAULT_TIMEOUT_US) { rtt_.millis(0); // Pulse TRIGGER for 10us trigger_.set(); time::delay_us(TRIGGER_PULSE_US); trigger_.clear(); // Wait for echo signal start uint16_t timeout_ms = rtt_.millis() + timeout_us / 1000 + 1; while (!echo_.value()) if (rtt_.millis() >= timeout_ms) return 0; // Read current time (need RTT) time::RTTTime start = rtt_.time(); // Wait for echo signal end while (echo_.value()) if (rtt_.millis() >= timeout_ms) return 0; // Read current time (need RTT) time::RTTTime end = rtt_.time(); time::RTTTime delta = time::delta(start, end); return uint16_t(delta.millis * 1000UL + delta.micros); } void async_echo() { ready_ = false; rtt_.millis(0); signal_.enable(); // Pulse TRIGGER for 10us trigger_.set(); time::delay_us(TRIGGER_PULSE_US); trigger_.clear(); } bool ready() const { return ready_; } uint16_t await_echo_us(uint16_t timeout_us = DEFAULT_TIMEOUT_US) { // Wait for echo signal start uint16_t timeout_ms = rtt_.millis() + timeout_us / 1000 + 1; while (!ready_) if (rtt_.millis() >= timeout_ms) { signal_.disable(); ready_ = true; return 0; } return echo_pulse_; } //TODO callback from PCI/EXT void on_echo() { static time::RTTTime start; if (echo_.value()) { // pulse started start = rtt_.time(); } else { // pulse ended time::RTTTime end = rtt_.time(); time::RTTTime delta = time::delta(start, end); echo_pulse_ = uint16_t(delta.millis * 1000UL + delta.micros); ready_ = true; signal_._disable(); } } private: static constexpr const uint16_t TRIGGER_PULSE_US = 10; interrupt::INTSignal<ECHO> signal_; timer::RTT<TIMER>& rtt_; typename gpio::FastPinType<TRIGGER>::TYPE trigger_; typename gpio::FastPinType<ECHO>::TYPE echo_; time::RTTTime start_; volatile uint16_t echo_pulse_; volatile bool ready_; }; static constexpr const board::DigitalPin TRIGGER = board::DigitalPin::D2_PD2; static constexpr const board::DigitalPin ECHO = board::ExternalInterruptPin::D3_PD3_EXT1; static constexpr const board::Timer TIMER = board::Timer::TIMER0; REGISTER_SERVO_INT_ISR(0, 1, TRIGGER, ECHO) static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; // Buffers for UART static char output_buffer[OUTPUT_BUFFER_SIZE]; using RTT = timer::RTT<TIMER>; using PROXI = HCSR04<TIMER, TRIGGER, ECHO>; int main() __attribute__((OS_main)); int main() { sei(); serial::hard::UATX<board::USART::USART0> uart{output_buffer}; uart.register_handler(); uart.begin(115200); auto out = uart.fout(); RTT rtt; rtt.register_rtt_handler(); PROXI sensor{rtt}; rtt.begin(); out << F("Starting...\n") << streams::flush; while (true) { // uint16_t pulse = sensor.echo_us(); sensor.async_echo(); uint16_t pulse = sensor.await_echo_us(); uint16_t mm = distance_mm(pulse); // trace value to output out << F("Pulse: ") << pulse << F(" us. Distance: ") << mm << F(" mm\n") << streams::flush; time::delay_ms(1000); } } <commit_msg>Proceed with experiments with ultrasonic distance sensor: asynchronous mode.<commit_after>/* * This program is just for personal experiments here on AVR features and C++ stuff * to check compilation and link of FastArduino port and pin API. * It does not do anything interesting as far as hardware is concerned. */ #include <fastarduino/boards/board.h> #include <fastarduino/uart.h> #include <fastarduino/gpio.h> #include <fastarduino/time.h> #include <fastarduino/realtime_timer.h> #include <fastarduino/utilities.h> #include <fastarduino/flash.h> #include <fastarduino/int.h> REGISTER_RTT_ISR(0) REGISTER_UATX_ISR(0) // Conversion method static constexpr uint16_t distance_mm(uint16_t echo_us) { // 340 m/s => 340000mm in 1000000us => 340/1000 mm/us return uint16_t(echo_us * 340UL / 1000UL / 2UL); } // Utilities to handle ISR callbacks #define REGISTER_SERVO_INT_ISR(TIMER, INT_NUM, TRIGGER, ECHO) \ static_assert(board_traits::DigitalPin_trait< ECHO >::IS_INT, "PIN must be an INT pin."); \ static_assert(board_traits::ExternalInterruptPin_trait< ECHO >::INT == INT_NUM , \ "PIN INT number must match INT_NUM"); \ ISR(CAT3(INT, INT_NUM, _vect)) \ { \ using SERVO_HANDLER = HCSR04<TIMER, TRIGGER, ECHO >; \ CALL_HANDLER_(SERVO_HANDLER, &SERVO_HANDLER::on_echo)(); \ } //TODO non blocking ultrasonic sensor // - use RTT timer (template arg) // - use pin interrupt (either EXT or PCI, both should be supported) template<board::Timer TIMER, board::DigitalPin TRIGGER, board::DigitalPin ECHO> class HCSR04 { public: static constexpr const uint16_t DEFAULT_TIMEOUT_US = 4 * 2 * 1000000UL / 340 + 1; HCSR04(timer::RTT<TIMER>& rtt, bool async = true) : rtt_{rtt}, trigger_{gpio::PinMode::OUTPUT}, echo_{gpio::PinMode::INPUT}, start_{}, echo_pulse_{0}, ready_{false} { if (async) interrupt::register_handler(*this); } uint16_t echo_us(uint16_t timeout_us = DEFAULT_TIMEOUT_US) { rtt_.millis(0); // Pulse TRIGGER for 10us trigger_.set(); time::delay_us(TRIGGER_PULSE_US); trigger_.clear(); // Wait for echo signal start uint16_t timeout_ms = rtt_.millis() + timeout_us / 1000 + 1; while (!echo_.value()) if (rtt_.millis() >= timeout_ms) return 0; // Read current time (need RTT) time::RTTTime start = rtt_.time(); // Wait for echo signal end while (echo_.value()) if (rtt_.millis() >= timeout_ms) return 0; // Read current time (need RTT) time::RTTTime end = rtt_.time(); time::RTTTime delta = time::delta(start, end); return uint16_t(delta.millis * 1000UL + delta.micros); } void async_echo() { ready_ = false; rtt_.millis(0); // Pulse TRIGGER for 10us trigger_.set(); time::delay_us(TRIGGER_PULSE_US); trigger_.clear(); } bool ready() const { return ready_; } uint16_t await_echo_us(uint16_t timeout_us = DEFAULT_TIMEOUT_US) { // Wait for echo signal start uint16_t timeout_ms = rtt_.millis() + timeout_us / 1000 + 1; while (!ready_) if (rtt_.millis() >= timeout_ms) { ready_ = true; return 0; } return echo_pulse_; } //TODO callback from PCI/EXT void on_echo() { if (echo_.value()) { // pulse started start_ = rtt_.time(); started_ = true; } else if (started_) { // pulse ended time::RTTTime end = rtt_.time(); time::RTTTime delta = time::delta(start_, end); echo_pulse_ = uint16_t(delta.millis * 1000UL + delta.micros); ready_ = true; started_ = false; } } private: static constexpr const uint16_t TRIGGER_PULSE_US = 10; timer::RTT<TIMER>& rtt_; typename gpio::FastPinType<TRIGGER>::TYPE trigger_; typename gpio::FastPinType<ECHO>::TYPE echo_; time::RTTTime start_; volatile uint16_t echo_pulse_; //TODO optimize space: only 2 bits needed here! volatile bool ready_; volatile bool started_; }; static constexpr const board::DigitalPin TRIGGER = board::DigitalPin::D2_PD2; static constexpr const board::DigitalPin ECHO = board::ExternalInterruptPin::D3_PD3_EXT1; static constexpr const board::Timer TIMER = board::Timer::TIMER0; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64; // Buffers for UART static char output_buffer[OUTPUT_BUFFER_SIZE]; using RTT = timer::RTT<TIMER>; using PROXI = HCSR04<TIMER, TRIGGER, ECHO>; //REGISTER_SERVO_INT_ISR(TIMER, 1, TRIGGER, ECHO) ISR(INT1_vect) { CALL_HANDLER_(PROXI, &PROXI::on_echo)(); } int main() __attribute__((OS_main)); int main() { sei(); serial::hard::UATX<board::USART::USART0> uart{output_buffer}; uart.register_handler(); uart.begin(115200); auto out = uart.fout(); RTT rtt; rtt.register_rtt_handler(); rtt.begin(); interrupt::INTSignal<ECHO> signal; signal.enable(); PROXI sensor{rtt}; out << F("Starting...\n") << streams::flush; while (true) { // uint16_t pulse = sensor.echo_us(); sensor.async_echo(); uint16_t pulse = sensor.await_echo_us(); uint32_t timing = rtt.millis(); uint16_t mm = distance_mm(pulse); // trace value to output out << F("Pulse: ") << pulse << F(" us. Distance: ") << mm << F(" mm (duration = ") << timing << F(" ms)\n") << streams::flush; time::delay_ms(1000); } } <|endoftext|>
<commit_before>// Copyright (c) 2011-2016 Ryan Prichard // // 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 "BackgroundDesktop.h" #include "DebugClient.h" #include "StringUtil.h" #include "WinptyException.h" namespace { static std::wstring getObjectName(HANDLE object) { BOOL success; DWORD lengthNeeded = 0; GetUserObjectInformationW(object, UOI_NAME, nullptr, 0, &lengthNeeded); ASSERT(lengthNeeded % sizeof(wchar_t) == 0); std::unique_ptr<wchar_t[]> tmp( new wchar_t[lengthNeeded / sizeof(wchar_t)]); success = GetUserObjectInformationW(object, UOI_NAME, tmp.get(), lengthNeeded, nullptr); if (!success) { throwWindowsError(L"GetUserObjectInformationW failed"); } return std::wstring(tmp.get()); } static std::wstring getDesktopName(HWINSTA winsta, HDESK desk) { return getObjectName(winsta) + L"\\" + getObjectName(desk); } } // anonymous namespace // Get a non-interactive window station for the agent. // TODO: review security w.r.t. windowstation and desktop. BackgroundDesktop::BackgroundDesktop() { try { m_originalStation = GetProcessWindowStation(); if (m_originalStation == nullptr) { throwWindowsError( L"BackgroundDesktop ctor: " L"GetProcessWindowStation returned NULL"); } m_newStation = CreateWindowStationW(nullptr, 0, WINSTA_ALL_ACCESS, nullptr); if (m_newStation == nullptr) { throwWindowsError( L"BackgroundDesktop ctor: CreateWindowStationW returned NULL"); } if (!SetProcessWindowStation(m_newStation)) { throwWindowsError( L"BackgroundDesktop ctor: SetProcessWindowStation failed"); } m_newDesktop = CreateDesktopW( L"Default", nullptr, nullptr, 0, GENERIC_ALL, nullptr); if (m_newDesktop == nullptr) { throwWindowsError( L"BackgroundDesktop ctor: CreateDesktopW failed"); } m_newDesktopName = getDesktopName(m_newStation, m_newDesktop); trace("Created background desktop: %s", utf8FromWide(m_newDesktopName).c_str()); } catch (...) { dispose(); throw; } } void BackgroundDesktop::dispose() WINPTY_NOEXCEPT { if (m_originalStation != nullptr) { SetProcessWindowStation(m_originalStation); m_originalStation = nullptr; } if (m_newDesktop != nullptr) { CloseDesktop(m_newDesktop); m_newDesktop = nullptr; } if (m_newStation != nullptr) { CloseWindowStation(m_newStation); m_newStation = nullptr; } } std::wstring getCurrentDesktopName() { // MSDN says that the handles returned by GetProcessWindowStation and // GetThreadDesktop do not need to be passed to CloseWindowStation and // CloseDesktop, respectively. const HWINSTA winsta = GetProcessWindowStation(); if (winsta == nullptr) { throwWindowsError( L"getCurrentDesktopName: " L"GetProcessWindowStation returned NULL"); } const HDESK desk = GetThreadDesktop(GetCurrentThreadId()); if (desk == nullptr) { throwWindowsError( L"getCurrentDesktopName: " L"GetThreadDesktop returned NULL"); } return getDesktopName(winsta, desk); } <commit_msg>Add a missing header to BackgroundDesktop.cc<commit_after>// Copyright (c) 2011-2016 Ryan Prichard // // 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 "BackgroundDesktop.h" #include <memory> #include "DebugClient.h" #include "StringUtil.h" #include "WinptyException.h" namespace { static std::wstring getObjectName(HANDLE object) { BOOL success; DWORD lengthNeeded = 0; GetUserObjectInformationW(object, UOI_NAME, nullptr, 0, &lengthNeeded); ASSERT(lengthNeeded % sizeof(wchar_t) == 0); std::unique_ptr<wchar_t[]> tmp( new wchar_t[lengthNeeded / sizeof(wchar_t)]); success = GetUserObjectInformationW(object, UOI_NAME, tmp.get(), lengthNeeded, nullptr); if (!success) { throwWindowsError(L"GetUserObjectInformationW failed"); } return std::wstring(tmp.get()); } static std::wstring getDesktopName(HWINSTA winsta, HDESK desk) { return getObjectName(winsta) + L"\\" + getObjectName(desk); } } // anonymous namespace // Get a non-interactive window station for the agent. // TODO: review security w.r.t. windowstation and desktop. BackgroundDesktop::BackgroundDesktop() { try { m_originalStation = GetProcessWindowStation(); if (m_originalStation == nullptr) { throwWindowsError( L"BackgroundDesktop ctor: " L"GetProcessWindowStation returned NULL"); } m_newStation = CreateWindowStationW(nullptr, 0, WINSTA_ALL_ACCESS, nullptr); if (m_newStation == nullptr) { throwWindowsError( L"BackgroundDesktop ctor: CreateWindowStationW returned NULL"); } if (!SetProcessWindowStation(m_newStation)) { throwWindowsError( L"BackgroundDesktop ctor: SetProcessWindowStation failed"); } m_newDesktop = CreateDesktopW( L"Default", nullptr, nullptr, 0, GENERIC_ALL, nullptr); if (m_newDesktop == nullptr) { throwWindowsError( L"BackgroundDesktop ctor: CreateDesktopW failed"); } m_newDesktopName = getDesktopName(m_newStation, m_newDesktop); trace("Created background desktop: %s", utf8FromWide(m_newDesktopName).c_str()); } catch (...) { dispose(); throw; } } void BackgroundDesktop::dispose() WINPTY_NOEXCEPT { if (m_originalStation != nullptr) { SetProcessWindowStation(m_originalStation); m_originalStation = nullptr; } if (m_newDesktop != nullptr) { CloseDesktop(m_newDesktop); m_newDesktop = nullptr; } if (m_newStation != nullptr) { CloseWindowStation(m_newStation); m_newStation = nullptr; } } std::wstring getCurrentDesktopName() { // MSDN says that the handles returned by GetProcessWindowStation and // GetThreadDesktop do not need to be passed to CloseWindowStation and // CloseDesktop, respectively. const HWINSTA winsta = GetProcessWindowStation(); if (winsta == nullptr) { throwWindowsError( L"getCurrentDesktopName: " L"GetProcessWindowStation returned NULL"); } const HDESK desk = GetThreadDesktop(GetCurrentThreadId()); if (desk == nullptr) { throwWindowsError( L"getCurrentDesktopName: " L"GetThreadDesktop returned NULL"); } return getDesktopName(winsta, desk); } <|endoftext|>
<commit_before>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/gtest/gtest.h> #include <vespa/searchcore/proton/matching/unpacking_iterators_optimizer.h> #include <vespa/searchcore/proton/matching/querynodes.h> #include <vespa/searchlib/query/tree/querybuilder.h> #include <vespa/vespalib/data/smart_buffer.h> #include <vespa/vespalib/data/output_writer.h> #include <string> using namespace proton::matching; using namespace search::query; using vespalib::SmartBuffer; using vespalib::OutputWriter; struct DumpQuery : QueryVisitor { OutputWriter &out; int indent; DumpQuery(OutputWriter &out_in, int indent_in) : out(out_in), indent(indent_in) {} void visit_children(Intermediate &self) { DumpQuery sub_dump(out, indent + 2); for (Node *node: self.getChildren()) { node->accept(sub_dump); } } void visit(And &n) override { out.printf("%*s%s %zu\n", indent, "", "And", n.getChildren().size()); visit_children(n); } void visit(AndNot &) override {} void visit(Equiv &) override {} void visit(NumberTerm &) override {} void visit(LocationTerm &) override {} void visit(Near &) override {} void visit(ONear &) override {} void visit(Or &n) override { out.printf("%*s%s %zu\n", indent, "", "Or", n.getChildren().size()); visit_children(n); } void visit(Phrase &n) override { out.printf("%*s%s %zu%s\n", indent, "", "Phrase", n.getChildren().size(), n.is_expensive() ? " expensive" : ""); visit_children(n); } void visit(SameElement &n) override { out.printf("%*s%s %zu%s\n", indent, "", "SameElement", n.getChildren().size(), n.is_expensive() ? " expensive" : ""); visit_children(n); } void visit(PrefixTerm &) override {} void visit(RangeTerm &) override {} void visit(Rank &) override {} void visit(StringTerm &n) override { out.printf("%*s%s %s%s%s\n", indent, "", "Term", n.getTerm().c_str(), (!n.isRanked() && !n.usePositionData()) ? " cheap" : "", (n.isRanked() != n.usePositionData()) ? " BAD" : ""); } void visit(SubstringTerm &) override {} void visit(SuffixTerm &) override {} void visit(WeakAnd &) override {} void visit(WeightedSetTerm &) override {} void visit(DotProduct &) override {} void visit(WandTerm &) override {} void visit(PredicateQuery &) override {} void visit(RegExpTerm &) override {} }; std::string dump_query(Node &root) { SmartBuffer buffer(4096); { OutputWriter writer(buffer, 1024); DumpQuery dumper(writer, 0); root.accept(dumper); } auto mem = buffer.obtain(); return std::string(mem.data, mem.size); } std::string view("view"); uint32_t id(5); Weight weight(7); void add_phrase(QueryBuilder<ProtonNodeTypes> &builder) { builder.addPhrase(3, view, id, weight); { builder.addStringTerm("a", view, id, weight); builder.addStringTerm("b", view, id, weight); builder.addStringTerm("c", view, id, weight); } } void add_same_element(QueryBuilder<ProtonNodeTypes> &builder) { builder.addSameElement(2, view); { builder.addStringTerm("x", view, id, weight); builder.addStringTerm("y", view, id, weight); } } Node::UP make_phrase() { QueryBuilder<ProtonNodeTypes> builder; add_phrase(builder); return builder.build(); } Node::UP make_same_element() { QueryBuilder<ProtonNodeTypes> builder; add_same_element(builder); return builder.build(); } Node::UP make_query_tree() { QueryBuilder<ProtonNodeTypes> builder; builder.addAnd(4); builder.addOr(3); builder.addStringTerm("t2", view, id, weight); add_phrase(builder); add_same_element(builder); add_same_element(builder); add_phrase(builder); builder.addStringTerm("t1", view, id, weight); return builder.build(); } //----------------------------------------------------------------------------- std::string plain_phrase_dump = "Phrase 3\n" " Term a\n" " Term b\n" " Term c\n"; std::string delayed_phrase_dump = "Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n"; std::string split_phrase_dump = "And 4\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " Term a cheap\n" " Term b cheap\n" " Term c cheap\n"; //----------------------------------------------------------------------------- std::string plain_same_element_dump = "SameElement 2\n" " Term x\n" " Term y\n"; std::string delayed_same_element_dump = "SameElement 2 expensive\n" " Term x\n" " Term y\n"; std::string split_same_element_dump = "And 3\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " Term x cheap\n" " Term y cheap\n"; //----------------------------------------------------------------------------- std::string plain_query_tree_dump = "And 4\n" " Or 3\n" " Term t2\n" " Phrase 3\n" " Term a\n" " Term b\n" " Term c\n" " SameElement 2\n" " Term x\n" " Term y\n" " SameElement 2\n" " Term x\n" " Term y\n" " Phrase 3\n" " Term a\n" " Term b\n" " Term c\n" " Term t1\n"; std::string delayed_query_tree_dump = "And 4\n" " Or 3\n" " Term t2\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " Term t1\n"; std::string split_query_tree_dump = "And 9\n" " Or 3\n" " Term t2\n" " Phrase 3\n" " Term a\n" " Term b\n" " Term c\n" " SameElement 2\n" " Term x\n" " Term y\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " Term t1\n" " Term x cheap\n" " Term y cheap\n" " Term a cheap\n" " Term b cheap\n" " Term c cheap\n"; std::string delayed_split_query_tree_dump = "And 9\n" " Or 3\n" " Term t2\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " Term t1\n" " Term x cheap\n" " Term y cheap\n" " Term a cheap\n" " Term b cheap\n" " Term c cheap\n"; //----------------------------------------------------------------------------- Node::UP optimize(Node::UP root, bool white_list, bool split, bool delay) { return UnpackingIteratorsOptimizer::optimize(std::move(root), white_list, split, delay); } TEST(UnpackingIteratorsOptimizerTest, require_that_root_phrase_node_can_be_left_alone) { std::string actual1 = dump_query(*optimize(make_phrase(), false, false, false)); std::string actual2 = dump_query(*optimize(make_phrase(), false, true, false)); std::string actual3 = dump_query(*optimize(make_phrase(), true, false, false)); std::string expect = plain_phrase_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); EXPECT_EQ(actual3, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_root_phrase_node_can_be_delayed) { std::string actual1 = dump_query(*optimize(make_phrase(), false, false, true)); std::string actual2 = dump_query(*optimize(make_phrase(), false, true, true)); std::string actual3 = dump_query(*optimize(make_phrase(), true, false, true)); std::string expect = delayed_phrase_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); EXPECT_EQ(actual3, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_root_phrase_node_can_be_split) { std::string actual1 = dump_query(*optimize(make_phrase(), true, true, true)); std::string actual2 = dump_query(*optimize(make_phrase(), true, true, false)); std::string expect = split_phrase_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } //----------------------------------------------------------------------------- TEST(UnpackingIteratorsOptimizerTest, require_that_root_same_element_node_can_be_left_alone) { std::string actual1 = dump_query(*optimize(make_same_element(), false, false, false)); std::string actual2 = dump_query(*optimize(make_same_element(), false, true, false)); std::string actual3 = dump_query(*optimize(make_same_element(), true, false, false)); std::string expect = plain_same_element_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); EXPECT_EQ(actual3, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_root_same_element_node_can_be_delayed) { std::string actual1 = dump_query(*optimize(make_same_element(), false, false, true)); std::string actual2 = dump_query(*optimize(make_same_element(), false, true, true)); std::string actual3 = dump_query(*optimize(make_same_element(), true, false, true)); std::string expect = delayed_same_element_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); EXPECT_EQ(actual3, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_root_same_element_node_can_be_split) { std::string actual1 = dump_query(*optimize(make_same_element(), true, true, true)); std::string actual2 = dump_query(*optimize(make_same_element(), true, true, false)); std::string expect = split_same_element_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } //----------------------------------------------------------------------------- TEST(UnpackingIteratorsOptimizerTest, require_that_query_tree_can_be_left_alone) { std::string actual1 = dump_query(*optimize(make_query_tree(), false, false, false)); std::string actual2 = dump_query(*optimize(make_query_tree(), true, false, false)); std::string expect = plain_query_tree_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_query_tree_can_be_delayed) { std::string actual1 = dump_query(*optimize(make_query_tree(), false, false, true)); std::string actual2 = dump_query(*optimize(make_query_tree(), true, false, true)); std::string expect = delayed_query_tree_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_query_tree_can_be_split) { std::string actual1 = dump_query(*optimize(make_query_tree(), false, true, false)); std::string actual2 = dump_query(*optimize(make_query_tree(), true, true, false)); std::string expect = split_query_tree_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_query_tree_can_be_delayed_and_split) { std::string actual1 = dump_query(*optimize(make_query_tree(), false, true, true)); std::string actual2 = dump_query(*optimize(make_query_tree(), true, true, true)); std::string expect = delayed_split_query_tree_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } GTEST_MAIN_RUN_ALL_TESTS() <commit_msg>Avoid shadowing of global variables.<commit_after>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/gtest/gtest.h> #include <vespa/searchcore/proton/matching/unpacking_iterators_optimizer.h> #include <vespa/searchcore/proton/matching/querynodes.h> #include <vespa/searchlib/query/tree/querybuilder.h> #include <vespa/vespalib/data/smart_buffer.h> #include <vespa/vespalib/data/output_writer.h> #include <string> using namespace proton::matching; using namespace search::query; using vespalib::SmartBuffer; using vespalib::OutputWriter; struct DumpQuery : QueryVisitor { OutputWriter &out; int indent; DumpQuery(OutputWriter &out_in, int indent_in) : out(out_in), indent(indent_in) {} void visit_children(Intermediate &self) { DumpQuery sub_dump(out, indent + 2); for (Node *node: self.getChildren()) { node->accept(sub_dump); } } void visit(And &n) override { out.printf("%*s%s %zu\n", indent, "", "And", n.getChildren().size()); visit_children(n); } void visit(AndNot &) override {} void visit(Equiv &) override {} void visit(NumberTerm &) override {} void visit(LocationTerm &) override {} void visit(Near &) override {} void visit(ONear &) override {} void visit(Or &n) override { out.printf("%*s%s %zu\n", indent, "", "Or", n.getChildren().size()); visit_children(n); } void visit(Phrase &n) override { out.printf("%*s%s %zu%s\n", indent, "", "Phrase", n.getChildren().size(), n.is_expensive() ? " expensive" : ""); visit_children(n); } void visit(SameElement &n) override { out.printf("%*s%s %zu%s\n", indent, "", "SameElement", n.getChildren().size(), n.is_expensive() ? " expensive" : ""); visit_children(n); } void visit(PrefixTerm &) override {} void visit(RangeTerm &) override {} void visit(Rank &) override {} void visit(StringTerm &n) override { out.printf("%*s%s %s%s%s\n", indent, "", "Term", n.getTerm().c_str(), (!n.isRanked() && !n.usePositionData()) ? " cheap" : "", (n.isRanked() != n.usePositionData()) ? " BAD" : ""); } void visit(SubstringTerm &) override {} void visit(SuffixTerm &) override {} void visit(WeakAnd &) override {} void visit(WeightedSetTerm &) override {} void visit(DotProduct &) override {} void visit(WandTerm &) override {} void visit(PredicateQuery &) override {} void visit(RegExpTerm &) override {} }; std::string dump_query(Node &root) { SmartBuffer buffer(4096); { OutputWriter writer(buffer, 1024); DumpQuery dumper(writer, 0); root.accept(dumper); } auto mem = buffer.obtain(); return std::string(mem.data, mem.size); } namespace { std::string view("view"); uint32_t id(5); Weight weight(7); } void add_phrase(QueryBuilder<ProtonNodeTypes> &builder) { builder.addPhrase(3, view, id, weight); { builder.addStringTerm("a", view, id, weight); builder.addStringTerm("b", view, id, weight); builder.addStringTerm("c", view, id, weight); } } void add_same_element(QueryBuilder<ProtonNodeTypes> &builder) { builder.addSameElement(2, view); { builder.addStringTerm("x", view, id, weight); builder.addStringTerm("y", view, id, weight); } } Node::UP make_phrase() { QueryBuilder<ProtonNodeTypes> builder; add_phrase(builder); return builder.build(); } Node::UP make_same_element() { QueryBuilder<ProtonNodeTypes> builder; add_same_element(builder); return builder.build(); } Node::UP make_query_tree() { QueryBuilder<ProtonNodeTypes> builder; builder.addAnd(4); builder.addOr(3); builder.addStringTerm("t2", view, id, weight); add_phrase(builder); add_same_element(builder); add_same_element(builder); add_phrase(builder); builder.addStringTerm("t1", view, id, weight); return builder.build(); } //----------------------------------------------------------------------------- std::string plain_phrase_dump = "Phrase 3\n" " Term a\n" " Term b\n" " Term c\n"; std::string delayed_phrase_dump = "Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n"; std::string split_phrase_dump = "And 4\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " Term a cheap\n" " Term b cheap\n" " Term c cheap\n"; //----------------------------------------------------------------------------- std::string plain_same_element_dump = "SameElement 2\n" " Term x\n" " Term y\n"; std::string delayed_same_element_dump = "SameElement 2 expensive\n" " Term x\n" " Term y\n"; std::string split_same_element_dump = "And 3\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " Term x cheap\n" " Term y cheap\n"; //----------------------------------------------------------------------------- std::string plain_query_tree_dump = "And 4\n" " Or 3\n" " Term t2\n" " Phrase 3\n" " Term a\n" " Term b\n" " Term c\n" " SameElement 2\n" " Term x\n" " Term y\n" " SameElement 2\n" " Term x\n" " Term y\n" " Phrase 3\n" " Term a\n" " Term b\n" " Term c\n" " Term t1\n"; std::string delayed_query_tree_dump = "And 4\n" " Or 3\n" " Term t2\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " Term t1\n"; std::string split_query_tree_dump = "And 9\n" " Or 3\n" " Term t2\n" " Phrase 3\n" " Term a\n" " Term b\n" " Term c\n" " SameElement 2\n" " Term x\n" " Term y\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " Term t1\n" " Term x cheap\n" " Term y cheap\n" " Term a cheap\n" " Term b cheap\n" " Term c cheap\n"; std::string delayed_split_query_tree_dump = "And 9\n" " Or 3\n" " Term t2\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " SameElement 2 expensive\n" " Term x\n" " Term y\n" " Phrase 3 expensive\n" " Term a\n" " Term b\n" " Term c\n" " Term t1\n" " Term x cheap\n" " Term y cheap\n" " Term a cheap\n" " Term b cheap\n" " Term c cheap\n"; //----------------------------------------------------------------------------- Node::UP optimize(Node::UP root, bool white_list, bool split, bool delay) { return UnpackingIteratorsOptimizer::optimize(std::move(root), white_list, split, delay); } TEST(UnpackingIteratorsOptimizerTest, require_that_root_phrase_node_can_be_left_alone) { std::string actual1 = dump_query(*optimize(make_phrase(), false, false, false)); std::string actual2 = dump_query(*optimize(make_phrase(), false, true, false)); std::string actual3 = dump_query(*optimize(make_phrase(), true, false, false)); std::string expect = plain_phrase_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); EXPECT_EQ(actual3, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_root_phrase_node_can_be_delayed) { std::string actual1 = dump_query(*optimize(make_phrase(), false, false, true)); std::string actual2 = dump_query(*optimize(make_phrase(), false, true, true)); std::string actual3 = dump_query(*optimize(make_phrase(), true, false, true)); std::string expect = delayed_phrase_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); EXPECT_EQ(actual3, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_root_phrase_node_can_be_split) { std::string actual1 = dump_query(*optimize(make_phrase(), true, true, true)); std::string actual2 = dump_query(*optimize(make_phrase(), true, true, false)); std::string expect = split_phrase_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } //----------------------------------------------------------------------------- TEST(UnpackingIteratorsOptimizerTest, require_that_root_same_element_node_can_be_left_alone) { std::string actual1 = dump_query(*optimize(make_same_element(), false, false, false)); std::string actual2 = dump_query(*optimize(make_same_element(), false, true, false)); std::string actual3 = dump_query(*optimize(make_same_element(), true, false, false)); std::string expect = plain_same_element_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); EXPECT_EQ(actual3, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_root_same_element_node_can_be_delayed) { std::string actual1 = dump_query(*optimize(make_same_element(), false, false, true)); std::string actual2 = dump_query(*optimize(make_same_element(), false, true, true)); std::string actual3 = dump_query(*optimize(make_same_element(), true, false, true)); std::string expect = delayed_same_element_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); EXPECT_EQ(actual3, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_root_same_element_node_can_be_split) { std::string actual1 = dump_query(*optimize(make_same_element(), true, true, true)); std::string actual2 = dump_query(*optimize(make_same_element(), true, true, false)); std::string expect = split_same_element_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } //----------------------------------------------------------------------------- TEST(UnpackingIteratorsOptimizerTest, require_that_query_tree_can_be_left_alone) { std::string actual1 = dump_query(*optimize(make_query_tree(), false, false, false)); std::string actual2 = dump_query(*optimize(make_query_tree(), true, false, false)); std::string expect = plain_query_tree_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_query_tree_can_be_delayed) { std::string actual1 = dump_query(*optimize(make_query_tree(), false, false, true)); std::string actual2 = dump_query(*optimize(make_query_tree(), true, false, true)); std::string expect = delayed_query_tree_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_query_tree_can_be_split) { std::string actual1 = dump_query(*optimize(make_query_tree(), false, true, false)); std::string actual2 = dump_query(*optimize(make_query_tree(), true, true, false)); std::string expect = split_query_tree_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } TEST(UnpackingIteratorsOptimizerTest, require_that_query_tree_can_be_delayed_and_split) { std::string actual1 = dump_query(*optimize(make_query_tree(), false, true, true)); std::string actual2 = dump_query(*optimize(make_query_tree(), true, true, true)); std::string expect = delayed_split_query_tree_dump; EXPECT_EQ(actual1, expect); EXPECT_EQ(actual2, expect); } GTEST_MAIN_RUN_ALL_TESTS() <|endoftext|>
<commit_before>/* * Copyright (c) 2014-2015, Georgia Tech Research Corporation * All rights reserved. * * Author(s): Karen Liu <karenliu@cc.gatech.edu> * * Georgia Tech Graphics Lab and Humanoid Robotics Lab * * Directed by Prof. C. Karen Liu and Prof. Mike Stilman * <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu> * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "dart/utils/FileInfoWorld.h" #include <fstream> #include <string> #include "dart/simulation/Recording.h" namespace dart { namespace utils { //============================================================================== FileInfoWorld::FileInfoWorld() : mRecord(NULL) { } //============================================================================== FileInfoWorld::~FileInfoWorld() { delete mRecord; } //============================================================================== bool FileInfoWorld::loadFile(const char* _fName) { std::ifstream inFile(_fName); if (inFile.fail() == 1) return false; inFile.precision(8); char buffer[256]; int numFrames; int numSkeletons; int intVal; double doubleVal; std::vector<int> numDofsForSkels; std::vector<double> tempState; Eigen::VectorXd state; inFile >> buffer; inFile >> numFrames; inFile >> buffer; inFile >> numSkeletons; for (int i = 0; i < numSkeletons; i++) { inFile >> buffer; inFile >> intVal; numDofsForSkels.push_back(intVal); } mRecord = new simulation::Recording(numDofsForSkels); for (int i = 0; i < numFrames; i++) { for (int j = 0; j < numSkeletons; j++) { for (int k = 0; k < mRecord->getNumDofs(j); k++) { inFile >> doubleVal; tempState.push_back(doubleVal); } } char c = inFile.peek(); if (c == 'C') { inFile >> buffer; inFile >> intVal; for (int j = 0; j < intVal; j++) { for (int k = 0; k < 6; k++) { inFile >> doubleVal; tempState.push_back(doubleVal); } } } state.resize(tempState.size()); for (size_t j = 0; j < tempState.size(); j++) state[j] = tempState[j]; mRecord->addState(state); tempState.clear(); } inFile.close(); std::string text = _fName; int lastSlash = text.find_last_of("/"); text = text.substr(lastSlash+1); strcpy(mFileName, text.c_str()); return true; } //============================================================================== bool FileInfoWorld::saveFile(const char* _fName, simulation::Recording* _record) { std::ofstream outFile(_fName, std::ios::out); if (outFile.fail()) return false; outFile.precision(8); outFile << "numFrames " << _record->getNumFrames() << std::endl; outFile << "numSkeletons " << _record->getNumSkeletons() << std::endl; for (int i = 0; i < _record->getNumSkeletons(); i++) outFile << "Skeleton" << i << " " << _record->getNumDofs(i) << " "; outFile << std::endl; for (int i = 0; i < _record->getNumFrames(); i++) { for (int j = 0; j < _record->getNumSkeletons(); j++) { for (int k = 0; k < _record->getNumDofs(j); k++) outFile << _record->getGenCoord(i, j, k) << " "; outFile << std::endl; } outFile << "Contacts " << _record->getNumContacts(i) << std::endl; for (int j = 0; j < _record->getNumContacts(i); j++) { outFile << _record->getContactPoint(i, j) << std::endl; outFile << _record->getContactForce(i, j) << std::endl; } outFile << std::endl; } outFile.close(); std::string text = _fName; int lastSlash = text.find_last_of("/"); text = text.substr(lastSlash+1); std::strcpy(mFileName, text.c_str()); return true; } //============================================================================== simulation::Recording* FileInfoWorld::getRecording() const { return mRecord; } } // namespace utils } // namespace dart <commit_msg>Fixed a small bug in loading WorldFile<commit_after>/* * Copyright (c) 2014-2015, Georgia Tech Research Corporation * All rights reserved. * * Author(s): Karen Liu <karenliu@cc.gatech.edu> * * Georgia Tech Graphics Lab and Humanoid Robotics Lab * * Directed by Prof. C. Karen Liu and Prof. Mike Stilman * <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu> * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "dart/utils/FileInfoWorld.h" #include <fstream> #include <string> #include "dart/simulation/Recording.h" namespace dart { namespace utils { //============================================================================== FileInfoWorld::FileInfoWorld() : mRecord(NULL) { } //============================================================================== FileInfoWorld::~FileInfoWorld() { delete mRecord; } //============================================================================== bool FileInfoWorld::loadFile(const char* _fName) { std::ifstream inFile(_fName); if (inFile.fail() == 1) return false; inFile.precision(8); char buffer[256]; int numFrames; int numSkeletons; int intVal; double doubleVal; std::vector<int> numDofsForSkels; std::vector<double> tempState; Eigen::VectorXd state; inFile >> buffer; inFile >> numFrames; inFile >> buffer; inFile >> numSkeletons; for (int i = 0; i < numSkeletons; i++) { inFile >> buffer; inFile >> intVal; numDofsForSkels.push_back(intVal); } mRecord = new simulation::Recording(numDofsForSkels); for (int i = 0; i < numFrames; i++) { for (int j = 0; j < numSkeletons; j++) { for (int k = 0; k < mRecord->getNumDofs(j); k++) { inFile >> doubleVal; tempState.push_back(doubleVal); } } inFile >> buffer; inFile >> intVal; for (int j = 0; j < intVal; j++) { for (int k = 0; k < 6; k++) { inFile >> doubleVal; tempState.push_back(doubleVal); } } state.resize(tempState.size()); for (size_t j = 0; j < tempState.size(); j++) state[j] = tempState[j]; mRecord->addState(state); tempState.clear(); } inFile.close(); std::string text = _fName; int lastSlash = text.find_last_of("/"); text = text.substr(lastSlash+1); strcpy(mFileName, text.c_str()); return true; } //============================================================================== bool FileInfoWorld::saveFile(const char* _fName, simulation::Recording* _record) { std::ofstream outFile(_fName, std::ios::out); if (outFile.fail()) return false; outFile.precision(8); outFile << "numFrames " << _record->getNumFrames() << std::endl; outFile << "numSkeletons " << _record->getNumSkeletons() << std::endl; for (int i = 0; i < _record->getNumSkeletons(); i++) outFile << "Skeleton" << i << " " << _record->getNumDofs(i) << " "; outFile << std::endl; for (int i = 0; i < _record->getNumFrames(); i++) { for (int j = 0; j < _record->getNumSkeletons(); j++) { for (int k = 0; k < _record->getNumDofs(j); k++) outFile << _record->getGenCoord(i, j, k) << " "; outFile << std::endl; } outFile << "Contacts " << _record->getNumContacts(i) << std::endl; for (int j = 0; j < _record->getNumContacts(i); j++) { outFile << _record->getContactPoint(i, j) << std::endl; outFile << _record->getContactForce(i, j) << std::endl; } outFile << std::endl; } outFile.close(); std::string text = _fName; int lastSlash = text.find_last_of("/"); text = text.substr(lastSlash+1); std::strcpy(mFileName, text.c_str()); return true; } //============================================================================== simulation::Recording* FileInfoWorld::getRecording() const { return mRecord; } } // namespace utils } // namespace dart <|endoftext|>
<commit_before>#include <log.h> #include <iostream> #include <QDateTime> #include <QDir> #include <QThread> void Log::info(QString tag, QString msg){ // deprecated Log::add("INFO",tag.toStdString(), msg.toStdString()); } // --------------------------------------------------------------------- void Log::info(const std::string & sTag, const std::string &sMessage){ Log::add("INFO",sTag, sMessage); } // --------------------------------------------------------------------- void Log::err(QString tag, QString msg){ // deprecated Log::add("ERR",tag.toStdString(), msg.toStdString()); } // --------------------------------------------------------------------- void Log::err(const std::string & sTag, const std::string &sMessage){ Log::add("ERR",sTag, sMessage); } // --------------------------------------------------------------------- void Log::err(QString tag, QAbstractSocket::SocketError socketError){ // deprecated QString msg = "Unknown error"; if(socketError == QAbstractSocket::ConnectionRefusedError){ msg = "QAbstractSocket::ConnectionRefusedError, The connection was refused by the peer (or timed out)."; }else if(socketError == QAbstractSocket::RemoteHostClosedError){ msg = "QAbstractSocket::RemoteHostClosedError, The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent."; }else if(socketError == QAbstractSocket::HostNotFoundError){ msg = "QAbstractSocket::HostNotFoundError, The host address was not found."; }else if(socketError == QAbstractSocket::SocketAccessError){ msg = "QAbstractSocket::SocketAccessError, The socket operation failed because the application lacked the required privileges."; }else if(socketError == QAbstractSocket::SocketResourceError){ msg = "QAbstractSocket::SocketResourceError, The local system ran out of resources (e.g., too many sockets)."; }else if(socketError == QAbstractSocket::SocketTimeoutError){ msg = "QAbstractSocket::SocketTimeoutError, The socket operation timed out."; }else if(socketError == QAbstractSocket::DatagramTooLargeError){ msg = "QAbstractSocket::DatagramTooLargeError, The datagram was larger than the operating system's limit (which can be as low as 8192 bytes)."; }else if(socketError == QAbstractSocket::NetworkError){ msg = "QAbstractSocket::NetworkError, An error occurred with the network (e.g., the network cable was accidentally plugged out)."; }else if(socketError == QAbstractSocket::AddressInUseError){ msg = "QAbstractSocket::AddressInUseError, The address specified to QAbstractSocket::bind() is already in use and was set to be exclusive."; }else if(socketError == QAbstractSocket::SocketAddressNotAvailableError){ msg = "QAbstractSocket::SocketAddressNotAvailableError, The address specified to QAbstractSocket::bind() does not belong to the host."; }else if(socketError == QAbstractSocket::UnsupportedSocketOperationError){ msg = "QAbstractSocket::UnsupportedSocketOperationError, The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support)."; }else if(socketError == QAbstractSocket::ProxyAuthenticationRequiredError){ msg = "QAbstractSocket::ProxyAuthenticationRequiredError, The socket is using a proxy, and the proxy requires authentication."; }else if(socketError == QAbstractSocket::SslHandshakeFailedError){ msg = "QAbstractSocket::SslHandshakeFailedError, The SSL/TLS handshake failed, so the connection was closed (only used in QSslSocket)"; }else if(socketError == QAbstractSocket::UnfinishedSocketOperationError){ msg = "QAbstractSocket::UnfinishedSocketOperationError, Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background)."; }else if(socketError == QAbstractSocket::ProxyConnectionRefusedError){ msg = "QAbstractSocket::ProxyConnectionRefusedError, Could not contact the proxy server because the connection to that server was denied"; }else if(socketError == QAbstractSocket::ProxyConnectionClosedError){ msg = "QAbstractSocket::ProxyConnectionClosedError, The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)"; }else if(socketError == QAbstractSocket::ProxyConnectionTimeoutError){ msg = "QAbstractSocket::ProxyConnectionTimeoutError, The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase."; }else if(socketError == QAbstractSocket::ProxyNotFoundError){ msg = "QAbstractSocket::ProxyNotFoundError, The proxy address set with setProxy() (or the application proxy) was not found."; }else if(socketError == QAbstractSocket::ProxyProtocolError){ msg = "QAbstractSocket::ProxyProtocolError, The connection negotiation with the proxy server failed, because the response from the proxy server could not be understood."; }else if(socketError == QAbstractSocket::OperationError){ msg = "QAbstractSocket::OperationError, An operation was attempted while the socket was in a state that did not permit it."; }else if(socketError == QAbstractSocket::SslInternalError){ msg = "QAbstractSocket::SslInternalError, The SSL library being used reported an internal error. This is probably the result of a bad installation or misconfiguration of the library."; }else if(socketError == QAbstractSocket::SslInvalidUserDataError){ msg = "QAbstractSocket::SslInvalidUserDataError, Invalid data (certificate, key, cypher, etc.) was provided and its use resulted in an error in the SSL library."; }else if(socketError == QAbstractSocket::TemporaryError){ msg = "QAbstractSocket::TemporaryError, A temporary error occurred (e.g., operation would block and socket is non-blocking)."; }else if(socketError == QAbstractSocket::UnknownSocketError){ msg = "QAbstractSocket::UnknownSocketError, An unidentified error occurred."; } Log::add("ERR",tag.toStdString(), msg.toStdString()); } // --------------------------------------------------------------------- void Log::warn(QString tag, QString msg){ // deprecated Log::add("WARN",tag.toStdString(), msg.toStdString()); } // --------------------------------------------------------------------- void Log::warn(const std::string & sTag, const std::string &sMessage){ Log::add("WARN",sTag, sMessage); } // --------------------------------------------------------------------- void Log::setdir(const std::string &sDirectoryPath){ g_LOG_DIR_PATH = sDirectoryPath; } // --------------------------------------------------------------------- nlohmann::json Log::last_logs(){ g_LOG_MUTEX.lock(); auto lastLogMessages = nlohmann::json::array(); int len = g_LAST_LOG_MESSAGES.size(); for(int i = 0; i < len; i++){ lastLogMessages.push_back(g_LAST_LOG_MESSAGES[i]); } g_LOG_MUTEX.unlock(); return lastLogMessages; } // --------------------------------------------------------------------- void Log::add(const std::string &sType, const std::string &sTag, const std::string &sMessage){ g_LOG_MUTEX.lock(); // TODO write to file QString sThreadID = "0x" + QString::number((long long)QThread::currentThreadId(), 16); std::string sLogMessage = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz").toStdString() + ", " + sThreadID.toStdString() + " [" + sType + "] " + sTag + ": " + sMessage; std::cout << sLogMessage << "\r\n"; g_LAST_LOG_MESSAGES.push_front(sLogMessage); while(g_LAST_LOG_MESSAGES.size() > 50){ g_LAST_LOG_MESSAGES.pop_back(); } g_LOG_MUTEX.unlock(); } // --------------------------------------------------------------------- <commit_msg>Refactored QThread to std::thread in log<commit_after>#include <log.h> #include <iostream> #include <QDateTime> #include <QDir> #include <thread> void Log::info(QString tag, QString msg){ // deprecated Log::add("INFO",tag.toStdString(), msg.toStdString()); } // --------------------------------------------------------------------- void Log::info(const std::string & sTag, const std::string &sMessage){ Log::add("INFO",sTag, sMessage); } // --------------------------------------------------------------------- void Log::err(QString tag, QString msg){ // deprecated Log::add("ERR",tag.toStdString(), msg.toStdString()); } // --------------------------------------------------------------------- void Log::err(const std::string & sTag, const std::string &sMessage){ Log::add("ERR",sTag, sMessage); } // --------------------------------------------------------------------- void Log::err(QString tag, QAbstractSocket::SocketError socketError){ // deprecated QString msg = "Unknown error"; if(socketError == QAbstractSocket::ConnectionRefusedError){ msg = "QAbstractSocket::ConnectionRefusedError, The connection was refused by the peer (or timed out)."; }else if(socketError == QAbstractSocket::RemoteHostClosedError){ msg = "QAbstractSocket::RemoteHostClosedError, The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent."; }else if(socketError == QAbstractSocket::HostNotFoundError){ msg = "QAbstractSocket::HostNotFoundError, The host address was not found."; }else if(socketError == QAbstractSocket::SocketAccessError){ msg = "QAbstractSocket::SocketAccessError, The socket operation failed because the application lacked the required privileges."; }else if(socketError == QAbstractSocket::SocketResourceError){ msg = "QAbstractSocket::SocketResourceError, The local system ran out of resources (e.g., too many sockets)."; }else if(socketError == QAbstractSocket::SocketTimeoutError){ msg = "QAbstractSocket::SocketTimeoutError, The socket operation timed out."; }else if(socketError == QAbstractSocket::DatagramTooLargeError){ msg = "QAbstractSocket::DatagramTooLargeError, The datagram was larger than the operating system's limit (which can be as low as 8192 bytes)."; }else if(socketError == QAbstractSocket::NetworkError){ msg = "QAbstractSocket::NetworkError, An error occurred with the network (e.g., the network cable was accidentally plugged out)."; }else if(socketError == QAbstractSocket::AddressInUseError){ msg = "QAbstractSocket::AddressInUseError, The address specified to QAbstractSocket::bind() is already in use and was set to be exclusive."; }else if(socketError == QAbstractSocket::SocketAddressNotAvailableError){ msg = "QAbstractSocket::SocketAddressNotAvailableError, The address specified to QAbstractSocket::bind() does not belong to the host."; }else if(socketError == QAbstractSocket::UnsupportedSocketOperationError){ msg = "QAbstractSocket::UnsupportedSocketOperationError, The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support)."; }else if(socketError == QAbstractSocket::ProxyAuthenticationRequiredError){ msg = "QAbstractSocket::ProxyAuthenticationRequiredError, The socket is using a proxy, and the proxy requires authentication."; }else if(socketError == QAbstractSocket::SslHandshakeFailedError){ msg = "QAbstractSocket::SslHandshakeFailedError, The SSL/TLS handshake failed, so the connection was closed (only used in QSslSocket)"; }else if(socketError == QAbstractSocket::UnfinishedSocketOperationError){ msg = "QAbstractSocket::UnfinishedSocketOperationError, Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background)."; }else if(socketError == QAbstractSocket::ProxyConnectionRefusedError){ msg = "QAbstractSocket::ProxyConnectionRefusedError, Could not contact the proxy server because the connection to that server was denied"; }else if(socketError == QAbstractSocket::ProxyConnectionClosedError){ msg = "QAbstractSocket::ProxyConnectionClosedError, The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)"; }else if(socketError == QAbstractSocket::ProxyConnectionTimeoutError){ msg = "QAbstractSocket::ProxyConnectionTimeoutError, The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase."; }else if(socketError == QAbstractSocket::ProxyNotFoundError){ msg = "QAbstractSocket::ProxyNotFoundError, The proxy address set with setProxy() (or the application proxy) was not found."; }else if(socketError == QAbstractSocket::ProxyProtocolError){ msg = "QAbstractSocket::ProxyProtocolError, The connection negotiation with the proxy server failed, because the response from the proxy server could not be understood."; }else if(socketError == QAbstractSocket::OperationError){ msg = "QAbstractSocket::OperationError, An operation was attempted while the socket was in a state that did not permit it."; }else if(socketError == QAbstractSocket::SslInternalError){ msg = "QAbstractSocket::SslInternalError, The SSL library being used reported an internal error. This is probably the result of a bad installation or misconfiguration of the library."; }else if(socketError == QAbstractSocket::SslInvalidUserDataError){ msg = "QAbstractSocket::SslInvalidUserDataError, Invalid data (certificate, key, cypher, etc.) was provided and its use resulted in an error in the SSL library."; }else if(socketError == QAbstractSocket::TemporaryError){ msg = "QAbstractSocket::TemporaryError, A temporary error occurred (e.g., operation would block and socket is non-blocking)."; }else if(socketError == QAbstractSocket::UnknownSocketError){ msg = "QAbstractSocket::UnknownSocketError, An unidentified error occurred."; } Log::add("ERR",tag.toStdString(), msg.toStdString()); } // --------------------------------------------------------------------- void Log::warn(QString tag, QString msg){ // deprecated Log::add("WARN",tag.toStdString(), msg.toStdString()); } // --------------------------------------------------------------------- void Log::warn(const std::string & sTag, const std::string &sMessage){ Log::add("WARN",sTag, sMessage); } // --------------------------------------------------------------------- void Log::setdir(const std::string &sDirectoryPath){ g_LOG_DIR_PATH = sDirectoryPath; } // --------------------------------------------------------------------- nlohmann::json Log::last_logs(){ g_LOG_MUTEX.lock(); auto lastLogMessages = nlohmann::json::array(); int len = g_LAST_LOG_MESSAGES.size(); for(int i = 0; i < len; i++){ lastLogMessages.push_back(g_LAST_LOG_MESSAGES[i]); } g_LOG_MUTEX.unlock(); return lastLogMessages; } // --------------------------------------------------------------------- void Log::add(const std::string &sType, const std::string &sTag, const std::string &sMessage){ // thread id std::thread::id this_id = std::this_thread::get_id(); std::stringstream stream; stream << std::hex << this_id; std::string sThreadID( stream.str() ); g_LOG_MUTEX.lock(); // TODO write to file std::string sLogMessage = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz").toStdString() + ", 0x" + sThreadID + " [" + sType + "] " + sTag + ": " + sMessage; std::cout << sLogMessage << "\r\n"; g_LAST_LOG_MESSAGES.push_front(sLogMessage); while(g_LAST_LOG_MESSAGES.size() > 50){ g_LAST_LOG_MESSAGES.pop_back(); } g_LOG_MUTEX.unlock(); } // --------------------------------------------------------------------- <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2015 INRIA, USTL, UJF, CNRS, MGH * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Framework * * * * Authors: The SOFA Team (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "ObjectFactory.h" #include <sofa/helper/Logger.h> #include <sofa/defaulttype/TemplatesAliases.h> using sofa::helper::Logger; namespace sofa { namespace core { ObjectFactory::~ObjectFactory() { } ObjectFactory::ClassEntry& ObjectFactory::getEntry(std::string classname) { if (registry.find(classname) == registry.end()) { registry[classname] = ClassEntry::SPtr(new ClassEntry); registry[classname]->className = classname; } return *registry[classname]; } /// Test if a creator exists for a given classname bool ObjectFactory::hasCreator(std::string classname) { ClassEntryMap::iterator it = registry.find(classname); if (it == registry.end()) return false; ClassEntry::SPtr entry = it->second; return (!entry->creatorMap.empty()); } std::string ObjectFactory::shortName(std::string classname) { std::string shortname; ClassEntryMap::iterator it = registry.find(classname); if (it != registry.end()) { ClassEntry::SPtr entry = it->second; if(!entry->creatorMap.empty()) { CreatorMap::iterator it = entry->creatorMap.begin(); Creator::SPtr c = it->second; shortname = c->getClass()->shortName; } } return shortname; } bool ObjectFactory::addAlias(std::string name, std::string result, bool force, ClassEntry::SPtr* previous) { // Check that the pointed class does exist ClassEntryMap::iterator it = registry.find(result); if (it == registry.end()) { Logger::getMainLogger().log(Logger::Error, "Target class for alias '" + result + "'not found: " + name, "ObjectFactory::addAlias()"); return false; } ClassEntry::SPtr& pointedEntry = it->second; ClassEntry::SPtr& aliasEntry = registry[name]; // Check that the alias does not already exist, unless 'force' is true if (aliasEntry.get()!=NULL && !force) { Logger::getMainLogger().log(Logger::Error, "Name already exists: " + name, "ObjectFactory::addAlias()"); return false; } if (previous) { ClassEntry::SPtr& entry = aliasEntry; *previous = entry; } registry[name] = pointedEntry; pointedEntry->aliases.insert(name); return true; } void ObjectFactory::resetAlias(std::string name, ClassEntry::SPtr previous) { registry[name] = previous; } objectmodel::BaseObject::SPtr ObjectFactory::createObject(objectmodel::BaseContext* context, objectmodel::BaseObjectDescription* arg) { objectmodel::BaseObject::SPtr object = NULL; std::vector< std::pair<std::string, Creator::SPtr> > creators; std::string classname = arg->getAttribute( "type", ""); std::string usertemplatename = arg->getAttribute( "template", ""); std::string templatename = sofa::defaulttype::TemplateAliases::resolveAlias(usertemplatename); // Resolve template aliases std::string userresolved = templatename; // Copy in case we change for the default one ClassEntryMap::iterator it = registry.find(classname); if (it != registry.end()) // Found the classname { ClassEntry::SPtr entry = it->second; // If no template has been given or if the template does not exist, first try with the default one if(templatename.empty() || entry->creatorMap.find(templatename) == entry->creatorMap.end()) templatename = entry->defaultTemplate; CreatorMap::iterator it2 = entry->creatorMap.find(templatename); if (it2 != entry->creatorMap.end()) { Creator::SPtr c = it2->second; if (c->canCreate(context, arg)) creators.push_back(*it2); } // If object cannot be created with the given template (or the default one), try all possible ones if (creators.empty()) { CreatorMap::iterator it3; for (it3 = entry->creatorMap.begin(); it3 != entry->creatorMap.end(); ++it3) { Creator::SPtr c = it3->second; if (c->canCreate(context, arg)) creators.push_back(*it3); } } } if (creators.empty()) { // The object cannot be created arg->logError("Object type " + classname + std::string("<") + templatename + std::string("> creation failed")); } else { object = creators[0].second->createInstance(context, arg); // The object has been created, but not with the template given by the user if (!usertemplatename.empty() && object->getTemplateName() != userresolved) { std::string w = "Template <" + usertemplatename + std::string("> incorrect, used <") + object->getTemplateName() + std::string(">"); object->serr << w << object->sendl; } else if (creators.size() > 1) { // There was multiple possibilities, we used the first one (not necessarily the default, as it can be incompatible) std::string w = "Template <" + templatename + std::string("> incorrect, used <") + object->getTemplateName() + std::string("> in the list:"); for(unsigned int i = 0; i < creators.size(); ++i) w += std::string("\n\t* ") + creators[i].first; object->serr << w << object->sendl; } } return object; } ObjectFactory* ObjectFactory::getInstance() { static ObjectFactory instance; return &instance; } void ObjectFactory::getAllEntries(std::vector<ClassEntry::SPtr>& result) { result.clear(); for(ClassEntryMap::iterator it = registry.begin(), itEnd = registry.end(); it != itEnd; ++it) { ClassEntry::SPtr entry = it->second; // Push the entry only if it is not an alias if (entry->className == it->first) result.push_back(entry); } } void ObjectFactory::getEntriesFromTarget(std::vector<ClassEntry::SPtr>& result, std::string target) { result.clear(); for(ClassEntryMap::iterator it = registry.begin(), itEnd = registry.end(); it != itEnd; ++it) { ClassEntry::SPtr entry = it->second; bool inTarget = false; for (CreatorMap::iterator itc = entry->creatorMap.begin(), itcend = entry->creatorMap.end(); itc != itcend; ++itc) { Creator::SPtr c = itc->second; if (target == c->getTarget()) inTarget = true; } if (inTarget) result.push_back(entry); } } std::string ObjectFactory::listClassesFromTarget(std::string target, std::string separator) { std::vector<ClassEntry::SPtr> entries; getEntriesFromTarget(entries, target); std::ostringstream oss; for (unsigned int i=0; i<entries.size(); ++i) { if (i) oss << separator; oss << entries[i]->className; } std::string result = oss.str(); return result; } void ObjectFactory::dump(std::ostream& out) { for (ClassEntryMap::iterator it = registry.begin(), itend = registry.end(); it != itend; ++it) { ClassEntry::SPtr entry = it->second; if (entry->className != it->first) continue; out << "class " << entry->className <<" :\n"; if (!entry->aliases.empty()) { out << " aliases :"; for (std::set<std::string>::iterator it = entry->aliases.begin(), itend = entry->aliases.end(); it != itend; ++it) out << " " << *it; out << "\n"; } if (!entry->description.empty()) out << entry->description; if (!entry->authors.empty()) out << " authors : " << entry->authors << "\n"; if (!entry->license.empty()) out << " license : " << entry->license << "\n"; for (CreatorMap::iterator itc = entry->creatorMap.begin(), itcend = entry->creatorMap.end(); itc != itcend; ++itc) { out << " template instance : " << itc->first << "\n"; } } } static std::string xmlencode(const std::string& str) { std::string res; for (unsigned int i=0; i<str.length(); ++i) { switch(str[i]) { case '<': res += "&lt;"; break; case '>': res += "&gt;"; break; case '&': res += "&amp;"; break; case '"': res += "&quot;"; break; case '\'': res += "&apos;"; break; default: res += str[i]; } } return res; } void ObjectFactory::dumpXML(std::ostream& out) { for (ClassEntryMap::iterator it = registry.begin(), itend = registry.end(); it != itend; ++it) { ClassEntry::SPtr entry = it->second; if (entry->className != it->first) continue; out << "<class name=\"" << xmlencode(entry->className) <<"\">\n"; for (std::set<std::string>::iterator it = entry->aliases.begin(), itend = entry->aliases.end(); it != itend; ++it) out << "<alias>" << xmlencode(*it) << "</alias>\n"; if (!entry->description.empty()) out << "<description>"<<entry->description<<"</description>\n"; if (!entry->authors.empty()) out << "<authors>"<<entry->authors<<"</authors>\n"; if (!entry->license.empty()) out << "<license>"<<entry->license<<"</license>\n"; for (CreatorMap::iterator itc = entry->creatorMap.begin(), itcend = entry->creatorMap.end(); itc != itcend; ++itc) { out << "<creator"; if (!itc->first.empty()) out << " template=\"" << xmlencode(itc->first) << "\""; out << "/>\n"; } out << "</class>\n"; } } void ObjectFactory::dumpHTML(std::ostream& out) { out << "<ul>\n"; for (ClassEntryMap::iterator it = registry.begin(), itend = registry.end(); it != itend; ++it) { ClassEntry::SPtr entry = it->second; if (entry->className != it->first) continue; out << "<li><b>" << xmlencode(entry->className) <<"</b>\n"; if (!entry->description.empty()) out << "<br/>"<<entry->description<<"\n"; out << "<ul>\n"; if (!entry->aliases.empty()) { out << "<li>Aliases:<i>"; for (std::set<std::string>::iterator it = entry->aliases.begin(), itend = entry->aliases.end(); it != itend; ++it) out << " " << xmlencode(*it); out << "</i></li>\n"; } if (!entry->authors.empty()) out << "<li>Authors: <i>"<<entry->authors<<"</i></li>\n"; if (!entry->license.empty()) out << "<li>License: <i>"<<entry->license<<"</i></li>\n"; if (entry->creatorMap.size()>2 || (entry->creatorMap.size()==1 && !entry->creatorMap.begin()->first.empty())) { out << "<li>Template instances:<i>"; for (CreatorMap::iterator itc = entry->creatorMap.begin(), itcend = entry->creatorMap.end(); itc != itcend; ++itc) { if (itc->first == entry->defaultTemplate) out << " <b>" << xmlencode(itc->first) << "</b>"; else out << " " << xmlencode(itc->first); } out << "</i></li>\n"; } out << "</ul>\n"; out << "</li>\n"; } out << "</ul>\n"; } RegisterObject::RegisterObject(const std::string& description) { if (!description.empty()) { addDescription(description); } } RegisterObject& RegisterObject::addAlias(std::string val) { entry.aliases.insert(val); return *this; } RegisterObject& RegisterObject::addDescription(std::string val) { val += '\n'; entry.description += val; return *this; } RegisterObject& RegisterObject::addAuthor(std::string val) { val += ' '; entry.authors += val; return *this; } RegisterObject& RegisterObject::addLicense(std::string val) { entry.license += val; return *this; } RegisterObject& RegisterObject::addCreator(std::string classname, std::string templatename, ObjectFactory::Creator::SPtr creator) { if (!entry.className.empty() && entry.className != classname) { Logger::getMainLogger().log(Logger::Error, "Template already instanciated with a different classname: " + entry.className + " != " + classname, "ObjectFactory"); } else if (entry.creatorMap.find(templatename) != entry.creatorMap.end()) { Logger::getMainLogger().log(Logger::Error, "Component already registered: " + classname + "<" + templatename + ">", "ObjectFactory"); } else { entry.className = classname; entry.creatorMap[templatename] = creator; } return *this; } RegisterObject::operator int() { if (entry.className.empty()) { return 0; } else { ObjectFactory::ClassEntry& reg = ObjectFactory::getInstance()->getEntry(entry.className); reg.description += entry.description; reg.authors += entry.authors; reg.license += entry.license; if (!entry.defaultTemplate.empty()) { if (!reg.defaultTemplate.empty()) { Logger::getMainLogger().log(Logger::Error, "Default template for class " + entry.className + " already registered (" + reg.defaultTemplate + "), do not register " + entry.defaultTemplate + " as the default", "ObjectFactory"); } else { reg.defaultTemplate = entry.defaultTemplate; } } for (ObjectFactory::CreatorMap::iterator itc = entry.creatorMap.begin(), itcend = entry.creatorMap.end(); itc != itcend; ++itc) { if (reg.creatorMap.find(itc->first) != reg.creatorMap.end()) { Logger::getMainLogger().log(Logger::Error, "Class already registered: " + itc->first, "ObjectFactory"); } else { reg.creatorMap.insert(*itc); } } for (std::set<std::string>::iterator it = entry.aliases.begin(), itend = entry.aliases.end(); it != itend; ++it) { if (reg.aliases.find(*it) == reg.aliases.end()) { ObjectFactory::getInstance()->addAlias(*it,entry.className); } } return 1; } } } // namespace core } // namespace sofa <commit_msg>ObjectFactory: changing Errors in Warnings<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2015 INRIA, USTL, UJF, CNRS, MGH * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Framework * * * * Authors: The SOFA Team (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "ObjectFactory.h" #include <sofa/helper/Logger.h> #include <sofa/defaulttype/TemplatesAliases.h> using sofa::helper::Logger; namespace sofa { namespace core { ObjectFactory::~ObjectFactory() { } ObjectFactory::ClassEntry& ObjectFactory::getEntry(std::string classname) { if (registry.find(classname) == registry.end()) { registry[classname] = ClassEntry::SPtr(new ClassEntry); registry[classname]->className = classname; } return *registry[classname]; } /// Test if a creator exists for a given classname bool ObjectFactory::hasCreator(std::string classname) { ClassEntryMap::iterator it = registry.find(classname); if (it == registry.end()) return false; ClassEntry::SPtr entry = it->second; return (!entry->creatorMap.empty()); } std::string ObjectFactory::shortName(std::string classname) { std::string shortname; ClassEntryMap::iterator it = registry.find(classname); if (it != registry.end()) { ClassEntry::SPtr entry = it->second; if(!entry->creatorMap.empty()) { CreatorMap::iterator it = entry->creatorMap.begin(); Creator::SPtr c = it->second; shortname = c->getClass()->shortName; } } return shortname; } bool ObjectFactory::addAlias(std::string name, std::string result, bool force, ClassEntry::SPtr* previous) { // Check that the pointed class does exist ClassEntryMap::iterator it = registry.find(result); if (it == registry.end()) { Logger::getMainLogger().log(Logger::Error, "Target class for alias '" + result + "'not found: " + name, "ObjectFactory::addAlias()"); return false; } ClassEntry::SPtr& pointedEntry = it->second; ClassEntry::SPtr& aliasEntry = registry[name]; // Check that the alias does not already exist, unless 'force' is true if (aliasEntry.get()!=NULL && !force) { Logger::getMainLogger().log(Logger::Error, "Name already exists: " + name, "ObjectFactory::addAlias()"); return false; } if (previous) { ClassEntry::SPtr& entry = aliasEntry; *previous = entry; } registry[name] = pointedEntry; pointedEntry->aliases.insert(name); return true; } void ObjectFactory::resetAlias(std::string name, ClassEntry::SPtr previous) { registry[name] = previous; } objectmodel::BaseObject::SPtr ObjectFactory::createObject(objectmodel::BaseContext* context, objectmodel::BaseObjectDescription* arg) { objectmodel::BaseObject::SPtr object = NULL; std::vector< std::pair<std::string, Creator::SPtr> > creators; std::string classname = arg->getAttribute( "type", ""); std::string usertemplatename = arg->getAttribute( "template", ""); std::string templatename = sofa::defaulttype::TemplateAliases::resolveAlias(usertemplatename); // Resolve template aliases std::string userresolved = templatename; // Copy in case we change for the default one ClassEntryMap::iterator it = registry.find(classname); if (it != registry.end()) // Found the classname { ClassEntry::SPtr entry = it->second; // If no template has been given or if the template does not exist, first try with the default one if(templatename.empty() || entry->creatorMap.find(templatename) == entry->creatorMap.end()) templatename = entry->defaultTemplate; CreatorMap::iterator it2 = entry->creatorMap.find(templatename); if (it2 != entry->creatorMap.end()) { Creator::SPtr c = it2->second; if (c->canCreate(context, arg)) creators.push_back(*it2); } // If object cannot be created with the given template (or the default one), try all possible ones if (creators.empty()) { CreatorMap::iterator it3; for (it3 = entry->creatorMap.begin(); it3 != entry->creatorMap.end(); ++it3) { Creator::SPtr c = it3->second; if (c->canCreate(context, arg)) creators.push_back(*it3); } } } if (creators.empty()) { // The object cannot be created arg->logError("Object type " + classname + std::string("<") + templatename + std::string("> creation failed")); } else { object = creators[0].second->createInstance(context, arg); // The object has been created, but not with the template given by the user if (!usertemplatename.empty() && object->getTemplateName() != userresolved) { std::string w = "Template <" + usertemplatename + std::string("> incorrect, used <") + object->getTemplateName() + std::string(">"); object->serr << w << object->sendl; } else if (creators.size() > 1) { // There was multiple possibilities, we used the first one (not necessarily the default, as it can be incompatible) std::string w = "Template <" + templatename + std::string("> incorrect, used <") + object->getTemplateName() + std::string("> in the list:"); for(unsigned int i = 0; i < creators.size(); ++i) w += std::string("\n\t* ") + creators[i].first; object->serr << w << object->sendl; } } return object; } ObjectFactory* ObjectFactory::getInstance() { static ObjectFactory instance; return &instance; } void ObjectFactory::getAllEntries(std::vector<ClassEntry::SPtr>& result) { result.clear(); for(ClassEntryMap::iterator it = registry.begin(), itEnd = registry.end(); it != itEnd; ++it) { ClassEntry::SPtr entry = it->second; // Push the entry only if it is not an alias if (entry->className == it->first) result.push_back(entry); } } void ObjectFactory::getEntriesFromTarget(std::vector<ClassEntry::SPtr>& result, std::string target) { result.clear(); for(ClassEntryMap::iterator it = registry.begin(), itEnd = registry.end(); it != itEnd; ++it) { ClassEntry::SPtr entry = it->second; bool inTarget = false; for (CreatorMap::iterator itc = entry->creatorMap.begin(), itcend = entry->creatorMap.end(); itc != itcend; ++itc) { Creator::SPtr c = itc->second; if (target == c->getTarget()) inTarget = true; } if (inTarget) result.push_back(entry); } } std::string ObjectFactory::listClassesFromTarget(std::string target, std::string separator) { std::vector<ClassEntry::SPtr> entries; getEntriesFromTarget(entries, target); std::ostringstream oss; for (unsigned int i=0; i<entries.size(); ++i) { if (i) oss << separator; oss << entries[i]->className; } std::string result = oss.str(); return result; } void ObjectFactory::dump(std::ostream& out) { for (ClassEntryMap::iterator it = registry.begin(), itend = registry.end(); it != itend; ++it) { ClassEntry::SPtr entry = it->second; if (entry->className != it->first) continue; out << "class " << entry->className <<" :\n"; if (!entry->aliases.empty()) { out << " aliases :"; for (std::set<std::string>::iterator it = entry->aliases.begin(), itend = entry->aliases.end(); it != itend; ++it) out << " " << *it; out << "\n"; } if (!entry->description.empty()) out << entry->description; if (!entry->authors.empty()) out << " authors : " << entry->authors << "\n"; if (!entry->license.empty()) out << " license : " << entry->license << "\n"; for (CreatorMap::iterator itc = entry->creatorMap.begin(), itcend = entry->creatorMap.end(); itc != itcend; ++itc) { out << " template instance : " << itc->first << "\n"; } } } static std::string xmlencode(const std::string& str) { std::string res; for (unsigned int i=0; i<str.length(); ++i) { switch(str[i]) { case '<': res += "&lt;"; break; case '>': res += "&gt;"; break; case '&': res += "&amp;"; break; case '"': res += "&quot;"; break; case '\'': res += "&apos;"; break; default: res += str[i]; } } return res; } void ObjectFactory::dumpXML(std::ostream& out) { for (ClassEntryMap::iterator it = registry.begin(), itend = registry.end(); it != itend; ++it) { ClassEntry::SPtr entry = it->second; if (entry->className != it->first) continue; out << "<class name=\"" << xmlencode(entry->className) <<"\">\n"; for (std::set<std::string>::iterator it = entry->aliases.begin(), itend = entry->aliases.end(); it != itend; ++it) out << "<alias>" << xmlencode(*it) << "</alias>\n"; if (!entry->description.empty()) out << "<description>"<<entry->description<<"</description>\n"; if (!entry->authors.empty()) out << "<authors>"<<entry->authors<<"</authors>\n"; if (!entry->license.empty()) out << "<license>"<<entry->license<<"</license>\n"; for (CreatorMap::iterator itc = entry->creatorMap.begin(), itcend = entry->creatorMap.end(); itc != itcend; ++itc) { out << "<creator"; if (!itc->first.empty()) out << " template=\"" << xmlencode(itc->first) << "\""; out << "/>\n"; } out << "</class>\n"; } } void ObjectFactory::dumpHTML(std::ostream& out) { out << "<ul>\n"; for (ClassEntryMap::iterator it = registry.begin(), itend = registry.end(); it != itend; ++it) { ClassEntry::SPtr entry = it->second; if (entry->className != it->first) continue; out << "<li><b>" << xmlencode(entry->className) <<"</b>\n"; if (!entry->description.empty()) out << "<br/>"<<entry->description<<"\n"; out << "<ul>\n"; if (!entry->aliases.empty()) { out << "<li>Aliases:<i>"; for (std::set<std::string>::iterator it = entry->aliases.begin(), itend = entry->aliases.end(); it != itend; ++it) out << " " << xmlencode(*it); out << "</i></li>\n"; } if (!entry->authors.empty()) out << "<li>Authors: <i>"<<entry->authors<<"</i></li>\n"; if (!entry->license.empty()) out << "<li>License: <i>"<<entry->license<<"</i></li>\n"; if (entry->creatorMap.size()>2 || (entry->creatorMap.size()==1 && !entry->creatorMap.begin()->first.empty())) { out << "<li>Template instances:<i>"; for (CreatorMap::iterator itc = entry->creatorMap.begin(), itcend = entry->creatorMap.end(); itc != itcend; ++itc) { if (itc->first == entry->defaultTemplate) out << " <b>" << xmlencode(itc->first) << "</b>"; else out << " " << xmlencode(itc->first); } out << "</i></li>\n"; } out << "</ul>\n"; out << "</li>\n"; } out << "</ul>\n"; } RegisterObject::RegisterObject(const std::string& description) { if (!description.empty()) { addDescription(description); } } RegisterObject& RegisterObject::addAlias(std::string val) { entry.aliases.insert(val); return *this; } RegisterObject& RegisterObject::addDescription(std::string val) { val += '\n'; entry.description += val; return *this; } RegisterObject& RegisterObject::addAuthor(std::string val) { val += ' '; entry.authors += val; return *this; } RegisterObject& RegisterObject::addLicense(std::string val) { entry.license += val; return *this; } RegisterObject& RegisterObject::addCreator(std::string classname, std::string templatename, ObjectFactory::Creator::SPtr creator) { if (!entry.className.empty() && entry.className != classname) { Logger::getMainLogger().log(Logger::Error, "Template already instanciated with a different classname: " + entry.className + " != " + classname, "ObjectFactory"); } else if (entry.creatorMap.find(templatename) != entry.creatorMap.end()) { Logger::getMainLogger().log(Logger::Error, "Component already registered: " + classname + "<" + templatename + ">", "ObjectFactory"); } else { entry.className = classname; entry.creatorMap[templatename] = creator; } return *this; } RegisterObject::operator int() { if (entry.className.empty()) { return 0; } else { ObjectFactory::ClassEntry& reg = ObjectFactory::getInstance()->getEntry(entry.className); reg.description += entry.description; reg.authors += entry.authors; reg.license += entry.license; if (!entry.defaultTemplate.empty()) { if (!reg.defaultTemplate.empty()) { Logger::getMainLogger().log(Logger::Warning, "Default template for class " + entry.className + " already registered (" + reg.defaultTemplate + "), do not register " + entry.defaultTemplate + " as the default", "ObjectFactory"); } else { reg.defaultTemplate = entry.defaultTemplate; } } for (ObjectFactory::CreatorMap::iterator itc = entry.creatorMap.begin(), itcend = entry.creatorMap.end(); itc != itcend; ++itc) { if (reg.creatorMap.find(itc->first) != reg.creatorMap.end()) { Logger::getMainLogger().log(Logger::Warning, "Class already registered: entry.className " + itc->first, "ObjectFactory"); } else { reg.creatorMap.insert(*itc); } } for (std::set<std::string>::iterator it = entry.aliases.begin(), itend = entry.aliases.end(); it != itend; ++it) { if (reg.aliases.find(*it) == reg.aliases.end()) { ObjectFactory::getInstance()->addAlias(*it,entry.className); } } return 1; } } } // namespace core } // namespace sofa <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fwkresid.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:11:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #include "classes/fwkresid.hxx" #ifndef _TOOLS_STRING_HXX #include <tools/string.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #define U2S(STRING) ::rtl::OUStringToOString(STRING, RTL_TEXTENCODING_UTF8) namespace framework { ResMgr* FwkResId::GetResManager() { static ResMgr* pResMgr = NULL; String aMgrName = String::CreateFromAscii( "fwe" ); aMgrName += String::CreateFromInt32(SUPD); // current version number if ( !pResMgr ) { vos::OGuard aSolarGuard( Application::GetSolarMutex() ); pResMgr = ResMgr::CreateResMgr( U2S( aMgrName )); } return pResMgr; } // ----------------------------------------------------------------------- FwkResId::FwkResId( USHORT nId ) : ResId( nId, FwkResId::GetResManager() ) { } } <commit_msg>INTEGRATION: CWS warnings01 (1.3.32); FILE MERGED 2005/10/28 14:48:30 cd 1.3.32.1: #i55991# Warning free code changes for gcc<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fwkresid.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-19 11:13:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "classes/fwkresid.hxx" #ifndef _TOOLS_STRING_HXX #include <tools/string.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #define U2S(STRING) ::rtl::OUStringToOString(STRING, RTL_TEXTENCODING_UTF8) namespace framework { ResMgr* FwkResId::GetResManager() { static ResMgr* pResMgr = NULL; String aMgrName = String::CreateFromAscii( "fwe" ); aMgrName += String::CreateFromInt32(SUPD); // current version number if ( !pResMgr ) { vos::OGuard aSolarGuard( Application::GetSolarMutex() ); pResMgr = ResMgr::CreateResMgr( U2S( aMgrName )); } return pResMgr; } // ----------------------------------------------------------------------- FwkResId::FwkResId( USHORT nId ) : ResId( nId, FwkResId::GetResManager() ) { } } <|endoftext|>
<commit_before>#include "PorousMedia.h" template<> Parameters valid_params<PorousMedia>() { Parameters params; params.set<Real>("thermal_conductivity")=1.0; params.set<Real>("thermal_conductivity_fluid")=0.3707; //[W/(m.K)] params.set<Real>("thermal_conductivity_solid")=80.0; //[W/(m.K)] params.set<Real>("specific_heat")=1.0; params.set<Real>("specific_heat_fluid")=5195; //[J/(kg.K)] params.set<Real>("specific_heat_solid")=1725; params.set<Real>("neutron_diffusion_coefficient")=1.0; params.set<Real>("neutron_absorption_xs")=1.0; params.set<Real>("neutron_fission_xs")=1.0; params.set<Real>("neutron_per_fission")=1.0; params.set<Real>("neutron_velocity")=1.0; params.set<Real>("neutron_per_power")=1.0; params.set<Real>("heat_xfer_coefficient")=1.0; params.set<Real>("temp0")=1.0; params.set<Real>("k0")=1.0; params.set<Real>("k1")=0.0; params.set<Real>("d0")=1.0; params.set<Real>("d1")=0.0; params.set<Real>("siga0")=1.0; params.set<Real>("siga1")=0.0; params.set<Real>("sigf0")=1.0; params.set<Real>("sigf1")=0.0; params.set<Real>("fluid_resistance_coefficient")=1.0; params.set<Real>("gas_constant")=1.0; params.set<Real>("porosity")=0.5; // parameter of pebble-bed reactor params.set<Real>("vessel_cross_section")=1.0; params.set<Real>("pebble_diameter")=0.06; params.set<bool>("kta_standard")=false; return params; } void PorousMedia::computeProperties() { for(unsigned int qp=0; qp<_qrule->n_points(); qp++) { Real temp_diff = _solid_temp[qp]-_my_temp0; _thermal_conductivity[qp] = _my_thermal_conductivity; _thermal_conductivity_fluid[qp] = _my_thermal_conductivity_fluid; _thermal_conductivity_solid[qp] = _my_thermal_conductivity_solid; _specific_heat[qp] = _my_specific_heat; _specific_heat_fluid[qp] = _my_specific_heat_fluid; _specific_heat_solid[qp] = _my_specific_heat_solid; _heat_xfer_coefficient[qp] = _my_heat_xfer_coefficient; _fluid_resistance_coefficient[qp] = _my_fluid_resistance_coefficient; _gas_constant[qp] = _my_gas_constant; _porosity[qp] = _my_porosity; _neutron_diffusion_coefficient[qp] = _my_d0+_my_d1*temp_diff; _neutron_absorption_xs[qp] = _my_siga0+_my_siga1*temp_diff; _neutron_fission_xs[qp] = _my_sigf0+_my_sigf1*temp_diff; _neutron_per_power[qp] = _my_neutron_per_power; _neutron_per_fission[qp] = _my_neutron_per_fission; _neutron_velocity[qp] = _my_neutron_velocity; //KTA standard if( _my_kta_standard ) { //porosity Real porosity_inf = 0.41; Real delta_r = 0.75-0.070; Real r_m = (0.07+0.75)/2; Real dist = delta_r/2-fabs((r_m-_q_point[qp](0))); _porosity[qp] = porosity_inf*(1+(1-porosity_inf)/porosity_inf*exp(-100*dist)); Real pre_in_bar = 1.0; if( _has_pre) pre_in_bar = _pre[qp]/1e5; _thermal_conductivity_fluid[qp] = 2.682e-3*(1+1.123e-3*pre_in_bar)*pow(_fluid_temp[qp],0.71)*(1-2e-4*pre_in_bar); //Solid Real temp_in_c = _solid_temp[qp]-273.5; Real kappa_pebble = 186.021-39.5408e-2*temp_in_c+4.8852e-4*pow(temp_in_c,2)-2.91e-7*pow(temp_in_c,3)+6.6e-11*pow(temp_in_c,4); Real b = 1.25*pow((1-_porosity[qp])/_porosity[qp],1.111); Real sigma = 5.67e-8; Real emissivity = 0.8; Real lambda = kappa_pebble/(4*sigma*pow(_solid_temp[qp],3)*_my_pebble_diameter); //void radiation+solid conduction Real a1 = (1-pow(1-_porosity[qp],0.5))*_porosity[qp]; Real a2 = pow(1-_porosity[qp],0.5)/(2/emissivity-1); Real a3 = (b+1)/b; Real a4 = 1/(1+1/((2/emissivity-1)*lambda)); Real lambda_r = 4*sigma*pow(_solid_temp[qp],3)*_my_pebble_diameter*(a1+a2*a3*a4); //gas conduction+solid conduction Real b1 = pow(1-_porosity[qp],0.5); Real ratio_lambda = _thermal_conductivity_fluid[qp]/kappa_pebble; Real b2 = 2*b1/(1-ratio_lambda*b); Real b3 = (1-ratio_lambda)*b/pow(1-ratio_lambda*b,2)*log(1/(ratio_lambda*b)); Real b4 = (b+1)/2; Real b5 = (b-1)/(1-ratio_lambda*b); Real lambda_g = (1-b1+b2*(b3-b4-b5))*_thermal_conductivity_fluid[qp]; //contact conduction+solid conduction Real s = 1; Real sf = 1; Real na = 1/(pow(_my_pebble_diameter,2)); Real nl = 1/(_my_pebble_diameter); Real poisson_ratio_pebble = 0.136; Real young_modules_pebble = 9e9; Real f = 101325.0*sf/na; if( _has_pre ) f = _pre[qp]*sf/na; Real c1 = 3*(1-poisson_ratio_pebble*poisson_ratio_pebble)*f*0.03/4/young_modules_pebble; Real c2 = pow(c1,0.333); Real lambda_c = c2*na/nl/(0.531*s)*kappa_pebble; _thermal_conductivity_solid[qp] = lambda_r+lambda_g+lambda_c; //Fluid Real density = _pre[qp]/(_my_gas_constant*_fluid_temp[qp]); Real mom = 0; if( _has_xmom) { mom = _xmom[qp]*_xmom[qp]; if( _dim >=2 ) mom +=_ymom[qp]*_ymom[qp]; if( _dim == 3) mom +=_zmom[qp]*_zmom[qp]; mom = pow(mom,0.5); } if( _has_rmom) { mom = _rmom[qp]*_rmom[qp]; if( _dim >=2 ) mom +=_zmom[qp]*_zmom[qp]; if( _dim == 3) mom +=_thetamom[qp]*_thetamom[qp]; mom = pow(mom,0.5); } Real dyn_viscosity = 3.674e-7*pow(_fluid_temp[qp],0.7); Real reynolds = mom*_my_pebble_diameter/dyn_viscosity; Real prandtl = _specific_heat_fluid[qp]*dyn_viscosity/_thermal_conductivity_fluid[qp]; Real nusselt = (7-10*_porosity[qp]+5*pow(_porosity[qp],2))*(1+0.7*pow(reynolds,0.2)*pow(prandtl,0.333))+(1.33-2.4*_porosity[qp]+1.2*pow(_porosity[qp],2))*pow(reynolds,0.7)*pow(prandtl,0.333); Real area = 6*(1-_porosity[qp])/_my_pebble_diameter; _heat_xfer_coefficient[qp] = area*nusselt*_thermal_conductivity_fluid[qp]/_my_pebble_diameter; if(_has_xmom || _has_rmom ) { Real reynolds_over_1meps = reynolds/(1-_porosity[qp]); if( reynolds_over_1meps > 1 ) { Real psi = 320/reynolds_over_1meps+6/pow(reynolds_over_1meps,0.1); _fluid_resistance_coefficient[qp] = psi*(1-_porosity[qp])/pow(_porosity[qp],3)/_my_pebble_diameter/2/density*pow(mom,2); } } } } } <commit_msg>porous media property changed<commit_after>#include "PorousMedia.h" template<> Parameters valid_params<PorousMedia>() { Parameters params; params.set<Real>("thermal_conductivity")=1.0; params.set<Real>("thermal_conductivity_fluid")=0.3707; //[W/(m.K)] params.set<Real>("thermal_conductivity_solid")=80.0; //[W/(m.K)] params.set<Real>("specific_heat")=1.0; params.set<Real>("specific_heat_fluid")=5195; //[J/(kg.K)] params.set<Real>("specific_heat_solid")=1725; params.set<Real>("neutron_diffusion_coefficient")=1.0; params.set<Real>("neutron_absorption_xs")=1.0; params.set<Real>("neutron_fission_xs")=1.0; params.set<Real>("neutron_per_fission")=1.0; params.set<Real>("neutron_velocity")=1.0; params.set<Real>("neutron_per_power")=1.0; params.set<Real>("heat_xfer_coefficient")=1.0; params.set<Real>("temp0")=1.0; params.set<Real>("k0")=1.0; params.set<Real>("k1")=0.0; params.set<Real>("d0")=1.0; params.set<Real>("d1")=0.0; params.set<Real>("siga0")=1.0; params.set<Real>("siga1")=0.0; params.set<Real>("sigf0")=1.0; params.set<Real>("sigf1")=0.0; params.set<Real>("fluid_resistance_coefficient")=1.0; params.set<Real>("gas_constant")=1.0; params.set<Real>("porosity")=0.5; // parameter of pebble-bed reactor params.set<Real>("vessel_cross_section")=1.0; params.set<Real>("pebble_diameter")=0.06; params.set<bool>("kta_standard")=false; return params; } void PorousMedia::computeProperties() { for(unsigned int qp=0; qp<_qrule->n_points(); qp++) { Real temp_diff = _solid_temp[qp]-_my_temp0; _thermal_conductivity[qp] = _my_thermal_conductivity; _thermal_conductivity_fluid[qp] = _my_thermal_conductivity_fluid; _thermal_conductivity_solid[qp] = _my_thermal_conductivity_solid; _specific_heat[qp] = _my_specific_heat; _specific_heat_fluid[qp] = _my_specific_heat_fluid; _specific_heat_solid[qp] = _my_specific_heat_solid; _heat_xfer_coefficient[qp] = _my_heat_xfer_coefficient; _fluid_resistance_coefficient[qp] = _my_fluid_resistance_coefficient; _gas_constant[qp] = _my_gas_constant; _porosity[qp] = _my_porosity; _neutron_diffusion_coefficient[qp] = _my_d0+_my_d1*temp_diff; _neutron_absorption_xs[qp] = _my_siga0+_my_siga1*temp_diff; _neutron_fission_xs[qp] = _my_sigf0+_my_sigf1*temp_diff; _neutron_per_power[qp] = _my_neutron_per_power; _neutron_per_fission[qp] = _my_neutron_per_fission; _neutron_velocity[qp] = _my_neutron_velocity; //KTA standard if( _my_kta_standard ) { //porosity Real porosity_inf = 0.41; // Real delta_r = 0.75-0.0705; Real r_m = (0.0705+0.75)/2; Real delta_r = 0.80; // Real r_m = 0.8/2; Real dist = delta_r/2-fabs((r_m-_q_point[qp](0))); _porosity[qp] = porosity_inf*(1+(1-porosity_inf)/porosity_inf*exp(-100*dist)); Real pre_in_bar = 1.0; if( _has_pre) pre_in_bar = _pre[qp]/1e5; _thermal_conductivity_fluid[qp] = 2.682e-3*(1+1.123e-3*pre_in_bar)*pow(_fluid_temp[qp],0.71)*(1-2e-4*pre_in_bar); //Solid Real temp_in_c = _solid_temp[qp]-273.5; Real kappa_pebble = 186.021-39.5408e-2*temp_in_c+4.8852e-4*pow(temp_in_c,2)-2.91e-7*pow(temp_in_c,3)+6.6e-11*pow(temp_in_c,4); Real b = 1.25*pow((1-_porosity[qp])/_porosity[qp],1.111); Real sigma = 5.67e-8; Real emissivity = 0.8; Real lambda = kappa_pebble/(4*sigma*pow(_solid_temp[qp],3)*_my_pebble_diameter); //void radiation+solid conduction Real a1 = (1-pow(1-_porosity[qp],0.5))*_porosity[qp]; Real a2 = pow(1-_porosity[qp],0.5)/(2/emissivity-1); Real a3 = (b+1)/b; Real a4 = 1/(1+1/((2/emissivity-1)*lambda)); Real lambda_r = 4*sigma*pow(_solid_temp[qp],3)*_my_pebble_diameter*(a1+a2*a3*a4); //gas conduction+solid conduction Real b1 = pow(1-_porosity[qp],0.5); Real ratio_lambda = _thermal_conductivity_fluid[qp]/kappa_pebble; Real b2 = 2*b1/(1-ratio_lambda*b); Real b3 = (1-ratio_lambda)*b/pow(1-ratio_lambda*b,2)*log(1/(ratio_lambda*b)); Real b4 = (b+1)/2; Real b5 = (b-1)/(1-ratio_lambda*b); Real lambda_g = (1-b1+b2*(b3-b4-b5))*_thermal_conductivity_fluid[qp]; //contact conduction+solid conduction Real s = 1; Real sf = 1; Real na = 1/(pow(_my_pebble_diameter,2)); Real nl = 1/(_my_pebble_diameter); Real poisson_ratio_pebble = 0.136; Real young_modules_pebble = 9e9; Real f = 101325.0*sf/na; if( _has_pre ) f = _pre[qp]*sf/na; Real c1 = 3*(1-poisson_ratio_pebble*poisson_ratio_pebble)*f*0.03/4/young_modules_pebble; Real c2 = pow(c1,0.333); Real lambda_c = c2*na/nl/(0.531*s)*kappa_pebble; _thermal_conductivity_solid[qp] = lambda_r+lambda_g+lambda_c; //Fluid Real density = 101325/(_my_gas_constant*_fluid_temp[qp]); if( _has_pre) density = _pre[qp]/(_my_gas_constant*_fluid_temp[qp]); Real mom = 0; if( _has_xmom) { mom = _xmom[qp]*_xmom[qp]; if( _dim >=2 ) mom +=_ymom[qp]*_ymom[qp]; if( _dim == 3) mom +=_zmom[qp]*_zmom[qp]; mom = pow(mom,0.5); } if( _has_rmom) { mom = _rmom[qp]*_rmom[qp]; if( _dim >=2 ) mom +=_zmom[qp]*_zmom[qp]; if( _dim == 3) mom +=_thetamom[qp]*_thetamom[qp]; mom = pow(mom,0.5); } Real dyn_viscosity = 3.674e-7*pow(_fluid_temp[qp],0.7); Real reynolds = _porosity[qp]*mom*_my_pebble_diameter/dyn_viscosity; Real prandtl = _specific_heat_fluid[qp]*dyn_viscosity/_thermal_conductivity_fluid[qp]; Real nusselt = 2; nusselt = (7-10*_porosity[qp]+5*pow(_porosity[qp],2))*(1+0.7*pow(reynolds,0.2)*pow(prandtl,0.333)) +(1.33-2.4*_porosity[qp]+1.2*pow(_porosity[qp],2))*pow(reynolds,0.7)*pow(prandtl,0.333); Real area = 6*(1-_porosity[qp])/_my_pebble_diameter; _heat_xfer_coefficient[qp] = area*nusselt*_thermal_conductivity_fluid[qp]/_my_pebble_diameter; reynolds = _porosity[qp]*mom*_my_pebble_diameter/dyn_viscosity; if( _has_rmom || _has_xmom ) { Real reynolds_over_1meps = reynolds/(1-_porosity[qp]); if( reynolds_over_1meps > 1 ) { Real psi = 320/reynolds_over_1meps+6/pow(reynolds_over_1meps,0.1); _fluid_resistance_coefficient[qp] = psi*(1-_porosity[qp])/pow(_porosity[qp],3)/_my_pebble_diameter/2/density*pow(mom,2); //std::cout << "W: " << _fluid_resistance_coefficient[qp] <<" " << _porosity[qp] << " " << psi<<std::endl; } } // std::cout << dyn_viscosity << " " << reynolds << " " << prandtl << " " << nusselt << std::endl; } } } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #ifdef MOOSE_HAVE_LIBPNG #include <fstream> #include "PNGOutput.h" #include "FEProblemBase.h" #include "NonlinearSystem.h" #include "AuxiliarySystem.h" #include "libmesh/mesh_tools.h" registerMooseObject("MooseApp", PNGOutput); template <> InputParameters validParams<PNGOutput>() { InputParameters params = validParams<FileOutput>(); params.addParam<bool>("transparent_background", false, "Determination of whether the background will be transparent."); params.addRequiredParam<VariableName>("variable", "The name of the variable to use when creating the image"); params.addParam<Real>("max", 1, "The maximum for the variable we want to use"); params.addParam<Real>("min", 0, "The minimum for the variable we want to use"); MooseEnum color("GRAY BRYW BWR RWB BR"); params.addRequiredParam<MooseEnum>("color", color, "Choose the color scheme to use."); params.addRangeCheckedParam<unsigned int>( "resolution", 25, "resolution>0", "The length of the longest side of the image in pixels."); params.addRangeCheckedParam<Real>("out_bounds_shade", .5, "out_bounds_shade>=0 & out_bounds_shade<=1", "Color for the parts of the image that are out of bounds." "Value is between 1 and 0."); params.addRangeCheckedParam<Real>("transparency", 1, "transparency>=0 & transparency<=1", "Value is between 0 and 1" "where 0 is completely transparent and 1 is completely opaque. " "Default transparency of the image is no transparency."); return params; } PNGOutput::PNGOutput(const InputParameters & parameters) : FileOutput(parameters), _resolution(getParam<unsigned int>("resolution")), _color(parameters.get<MooseEnum>("color")), _transparent_background(getParam<bool>("transparent_background")), _transparency(getParam<Real>("transparency")), _use_aux(false), _variable(getParam<VariableName>("variable")), _max(getParam<Real>("max")), _min(getParam<Real>("min")), _out_bounds_shade(getParam<Real>("out_bounds_shade")) { } // Funtion for making the _mesh_function object. void PNGOutput::makeMeshFunc() { // The number assigned to the variable. Used to build the correct mesh. Default is 0. unsigned int variable_number = 0; // PNGOutput does not currently scale for running in parallel. if (processor_id() != 0) mooseInfo("PNGOutput is not currently scalable."); if (_problem_ptr->getAuxiliarySystem().hasVariable(_variable)) { variable_number = _problem_ptr->getAuxiliarySystem().getVariable(0, _variable).number(); _use_aux = true; } else if (_problem_ptr->getNonlinearSystem().hasVariable(_variable)) variable_number = _problem_ptr->getNonlinearSystem().getVariable(0, _variable).number(); else paramError("variable", "This doesn't exist."); const std::vector<unsigned int> var_nums = {variable_number}; // If we want the background to be transparent, we need a number over 1. if (_transparent_background) _out_bounds_shade = 2; // Find the values that will be used for rescaling purposes. calculateRescalingValues(); // Set up the mesh_function if (_use_aux) _mesh_function = libmesh_make_unique<MeshFunction>(*_es_ptr, _problem_ptr->getAuxiliarySystem().serializedSolution(), _problem_ptr->getAuxiliarySystem().dofMap(), var_nums); else _mesh_function = libmesh_make_unique<MeshFunction>(*_es_ptr, _problem_ptr->getNonlinearSystem().serializedSolution(), _problem_ptr->getNonlinearSystem().dofMap(), var_nums); _mesh_function->init(); // Need to enable out of mesh with the given control color scaled in reverse // so when scaling is done, this value retains it's original value. _mesh_function->enable_out_of_mesh_mode(reverseScale(_out_bounds_shade)); } // Function to find the min and max values so that all the values can be scaled between the two. void PNGOutput::calculateRescalingValues() { // The max and min. // If the max value wasn't specified in the input file, find it from the system. if (!_pars.isParamSetByUser("max")) { if (_use_aux) _scaling_max = _problem_ptr->getAuxiliarySystem().serializedSolution().max(); else _scaling_max = _problem_ptr->getNonlinearSystem().serializedSolution().max(); } else _scaling_max = _max; // If the min value wasn't specified in the input file, find it from the system. if (!_pars.isParamSetByUser("min")) { if (_use_aux) _scaling_min = _problem_ptr->getAuxiliarySystem().serializedSolution().min(); else _scaling_min = _problem_ptr->getNonlinearSystem().serializedSolution().min(); } else _scaling_min = _min; // The amount the values will need to be shifted. _shift_value = 0; // Get the shift value. if (_scaling_min != 0) { // Shiftvalue will be the same magnitude, but // going in the opposite direction of the scalingMin _shift_value -= _scaling_min; } // Shift the max. _scaling_max += _shift_value; } // Function to apply the scale to the data points. // Needed to be able to see accurate images that cover the appropriate color spectrum. inline Real PNGOutput::applyScale(Real value_to_scale) { return ((value_to_scale + _shift_value) / _scaling_max); } // Function to reverse the scaling that happens to a value. // Needed to be able to accurately control the _out_bounds_shade. inline Real PNGOutput::reverseScale(Real value_to_unscale) { return ((value_to_unscale * _scaling_max) - _shift_value); } // Function that controls the colorization of the png image for non-grayscale images. void PNGOutput::setRGB(png_byte * rgb, Real selection) { // With this system we have a color we start with when the value is 0 and another it approaches as // the value increases all the way to 255. If we want it to approach another color from that new // color, it will do so for the next 255, so the transition is from 256 - 511. For each // additional color we want to transition to, we need another 255. Transitioning from no color, or // black to Red then Green then Blue then the values of from black as it becomes Red would be 0 - // 255, Red to Green as 256 - 511 and then Green to Blue as 512 - 767 which gives us our total // colorSpectrum of 0 - 767, which includes those colors and each of their states in the // transistion. unsigned int number_of_destination_colors; switch (_color) { // BRYW. Three destination colors (R,Y,W). case 1: number_of_destination_colors = 3; break; // BWR. Two destination colors (W,R). case 2: number_of_destination_colors = 2; break; // RWB. Two destination colors (W,B). case 3: number_of_destination_colors = 2; break; // BR. One destination color (R). case 4: number_of_destination_colors = 1; break; } // We need to convert the number of colors into the spectrum max, then convert the value from the // mesh to a point somewhere in the range of 0 to color_spectrum_max. auto color_spectrum_max = (256 * number_of_destination_colors) - 1; auto color = (unsigned int)(selection * color_spectrum_max); // Unless we specifically say some part is transparent, we want the whole image to be opaque. auto tran = (unsigned int)(_transparency * 255); // Make sure everything is within our colorSpectrum. If it's bigger, then we want a // transparent background. if (color > color_spectrum_max) { color = color_spectrum_max; tran = 0; } auto magnitude = color % 256; switch (_color) { // Current color scheme: Blue->Red->Yellow->White case 1: // Blue->Red if (color < 256) { rgb[0] = magnitude; rgb[1] = 0; rgb[2] = 50; // 255 - magnitude; } // Red->Yellow else if (color < 512) { rgb[0] = 255; rgb[1] = magnitude; rgb[2] = 0; } // Yellow->White else { rgb[0] = 255; rgb[1] = 255; rgb[2] = magnitude; } break; // Color Scheme: Blue->White->Red // Using the RGB values found in Paraview case 2: // Blue->White if (color < 256) { rgb[0] = (int)(255.0 * (0.231373 + (0.002485 * (float)magnitude))); rgb[1] = (int)(255.0 * (0.298039 + (0.002223 * (float)magnitude))); rgb[2] = (int)(255.0 * (0.752941 + (0.000439 * (float)magnitude))); } // White->Red else { rgb[0] = (int)(255.0 * (0.865003 - (0.000624 * (float)magnitude))); rgb[1] = (int)(255.0 * (0.865003 - (0.003331 * (float)magnitude))); rgb[2] = (int)(255.0 * (0.865003 - (0.002808 * (float)magnitude))); } break; // Red->White->Blue case 3: // Red->White if (color < 256) { rgb[0] = 255; rgb[1] = magnitude; rgb[2] = magnitude; } // White->Blue else { rgb[0] = 255 - magnitude; rgb[1] = 255 - magnitude; rgb[2] = 255; } break; // Blue->Red case 4: // Blue->Red rgb[0] = magnitude; rgb[1] = 0; rgb[2] = 255 - magnitude; break; } // Add any transparency. rgb[3] = tran; } void PNGOutput::output(const ExecFlagType & /*type*/) { makeMeshFunc(); _box = MeshTools::create_bounding_box(*_mesh_ptr); // Make sure this happens on processor 0 if (processor_id() == 0) makePNG(); } // Function the writes the PNG out to the appropriate filename. void PNGOutput::makePNG() { // Get the max and min of the BoundingBox Point max_point = _box.max(); Point min_point = _box.min(); // The the total distance on the x and y axes. Real dist_x = max_point(0) - min_point(0); Real dist_y = max_point(1) - min_point(1); // Width and height for the PNG image. Real width; Real height; // Variable to record the resolution variable after normalized to work with pixels in longest // direction. Real normalized_resolution; // The longer dimension becomes the value to which we scale the other. if (dist_x > dist_y) { width = _resolution; height = (_resolution / dist_x) * dist_y; normalized_resolution = (((Real)_resolution) / dist_x); } else { height = _resolution; width = (_resolution / dist_y) * dist_x; normalized_resolution = (((Real)_resolution) / dist_y); } // Create the filename based on base and the test step number. std::ostringstream png_file; png_file << _file_base << "_" << std::setfill('0') << std::setw(3) << _t_step << ".png"; // libpng is built on C, so by default it takes FILE*. FILE * fp = nullptr; png_structp pngp = nullptr; png_infop infop = nullptr; // Required depth for proper image clarity. Real depth = 8; // Allocate resources. std::vector<png_byte> row((width + 1) * 4); // Check if we can open and write to the file. MooseUtils::checkFileWriteable(png_file.str()); // Open the file with write and bit modes. fp = fopen(png_file.str().c_str(), "wb"); pngp = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!pngp) mooseError("Failed to make the pointer string for the png."); infop = png_create_info_struct(pngp); if (!infop) mooseError("Failed to make an info pointer for the png."); // Initializes the IO for the png. Needs FILE* to compile. png_init_io(pngp, fp); // Set up the PNG header. png_set_IHDR(pngp, infop, width, height, depth, (_color ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_GRAY), PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(pngp, infop); // Initiallizing the point that will be used for populating the mesh values. // Initializing x, y, z to zero so that we don't access the point before it's // been set. z = 0 for all the png's. Point pt(0, 0, 0); // Dense vector that we can pass into the _mesh_function to fill with a value for a given point. DenseVector<Number> dv(0); // Loop through to create the image. for (Real y = max_point(1); y >= min_point(1); y -= 1. / normalized_resolution) { pt(1) = y; unsigned int index = 0; for (Real x = min_point(0); x <= max_point(0); x += 1. / normalized_resolution) { pt(0) = x; (*_mesh_function)(pt, _time, dv, nullptr); // Determine whether to create the PNG in color or grayscale if (_color) setRGB(&row.data()[index * 4], applyScale(dv(0))); else row.data()[index] = applyScale(dv(0)) * 255; index++; } png_write_row(pngp, row.data()); } // Close the file and take care of some other png end stuff. png_write_end(pngp, nullptr); if (fp != nullptr) fclose(fp); if (infop != nullptr) png_free_data(pngp, infop, PNG_FREE_ALL, -1); if (pngp != nullptr) png_destroy_write_struct(&pngp, &infop); } #endif <commit_msg>Fixed possible access of number_destination_colors before initialization<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #ifdef MOOSE_HAVE_LIBPNG #include <fstream> #include "PNGOutput.h" #include "FEProblemBase.h" #include "NonlinearSystem.h" #include "AuxiliarySystem.h" #include "libmesh/mesh_tools.h" registerMooseObject("MooseApp", PNGOutput); template <> InputParameters validParams<PNGOutput>() { InputParameters params = validParams<FileOutput>(); params.addParam<bool>("transparent_background", false, "Determination of whether the background will be transparent."); params.addRequiredParam<VariableName>("variable", "The name of the variable to use when creating the image"); params.addParam<Real>("max", 1, "The maximum for the variable we want to use"); params.addParam<Real>("min", 0, "The minimum for the variable we want to use"); MooseEnum color("GRAY BRYW BWR RWB BR"); params.addRequiredParam<MooseEnum>("color", color, "Choose the color scheme to use."); params.addRangeCheckedParam<unsigned int>( "resolution", 25, "resolution>0", "The length of the longest side of the image in pixels."); params.addRangeCheckedParam<Real>("out_bounds_shade", .5, "out_bounds_shade>=0 & out_bounds_shade<=1", "Color for the parts of the image that are out of bounds." "Value is between 1 and 0."); params.addRangeCheckedParam<Real>("transparency", 1, "transparency>=0 & transparency<=1", "Value is between 0 and 1" "where 0 is completely transparent and 1 is completely opaque. " "Default transparency of the image is no transparency."); return params; } PNGOutput::PNGOutput(const InputParameters & parameters) : FileOutput(parameters), _resolution(getParam<unsigned int>("resolution")), _color(parameters.get<MooseEnum>("color")), _transparent_background(getParam<bool>("transparent_background")), _transparency(getParam<Real>("transparency")), _use_aux(false), _variable(getParam<VariableName>("variable")), _max(getParam<Real>("max")), _min(getParam<Real>("min")), _out_bounds_shade(getParam<Real>("out_bounds_shade")) { } // Funtion for making the _mesh_function object. void PNGOutput::makeMeshFunc() { // The number assigned to the variable. Used to build the correct mesh. Default is 0. unsigned int variable_number = 0; // PNGOutput does not currently scale for running in parallel. if (processor_id() != 0) mooseInfo("PNGOutput is not currently scalable."); if (_problem_ptr->getAuxiliarySystem().hasVariable(_variable)) { variable_number = _problem_ptr->getAuxiliarySystem().getVariable(0, _variable).number(); _use_aux = true; } else if (_problem_ptr->getNonlinearSystem().hasVariable(_variable)) variable_number = _problem_ptr->getNonlinearSystem().getVariable(0, _variable).number(); else paramError("variable", "This doesn't exist."); const std::vector<unsigned int> var_nums = {variable_number}; // If we want the background to be transparent, we need a number over 1. if (_transparent_background) _out_bounds_shade = 2; // Find the values that will be used for rescaling purposes. calculateRescalingValues(); // Set up the mesh_function if (_use_aux) _mesh_function = libmesh_make_unique<MeshFunction>(*_es_ptr, _problem_ptr->getAuxiliarySystem().serializedSolution(), _problem_ptr->getAuxiliarySystem().dofMap(), var_nums); else _mesh_function = libmesh_make_unique<MeshFunction>(*_es_ptr, _problem_ptr->getNonlinearSystem().serializedSolution(), _problem_ptr->getNonlinearSystem().dofMap(), var_nums); _mesh_function->init(); // Need to enable out of mesh with the given control color scaled in reverse // so when scaling is done, this value retains it's original value. _mesh_function->enable_out_of_mesh_mode(reverseScale(_out_bounds_shade)); } // Function to find the min and max values so that all the values can be scaled between the two. void PNGOutput::calculateRescalingValues() { // The max and min. // If the max value wasn't specified in the input file, find it from the system. if (!_pars.isParamSetByUser("max")) { if (_use_aux) _scaling_max = _problem_ptr->getAuxiliarySystem().serializedSolution().max(); else _scaling_max = _problem_ptr->getNonlinearSystem().serializedSolution().max(); } else _scaling_max = _max; // If the min value wasn't specified in the input file, find it from the system. if (!_pars.isParamSetByUser("min")) { if (_use_aux) _scaling_min = _problem_ptr->getAuxiliarySystem().serializedSolution().min(); else _scaling_min = _problem_ptr->getNonlinearSystem().serializedSolution().min(); } else _scaling_min = _min; // The amount the values will need to be shifted. _shift_value = 0; // Get the shift value. if (_scaling_min != 0) { // Shiftvalue will be the same magnitude, but // going in the opposite direction of the scalingMin _shift_value -= _scaling_min; } // Shift the max. _scaling_max += _shift_value; } // Function to apply the scale to the data points. // Needed to be able to see accurate images that cover the appropriate color spectrum. inline Real PNGOutput::applyScale(Real value_to_scale) { return ((value_to_scale + _shift_value) / _scaling_max); } // Function to reverse the scaling that happens to a value. // Needed to be able to accurately control the _out_bounds_shade. inline Real PNGOutput::reverseScale(Real value_to_unscale) { return ((value_to_unscale * _scaling_max) - _shift_value); } // Function that controls the colorization of the png image for non-grayscale images. void PNGOutput::setRGB(png_byte * rgb, Real selection) { // With this system we have a color we start with when the value is 0 and another it approaches as // the value increases all the way to 255. If we want it to approach another color from that new // color, it will do so for the next 255, so the transition is from 256 - 511. For each // additional color we want to transition to, we need another 255. Transitioning from no color, or // black to Red then Green then Blue then the values of from black as it becomes Red would be 0 - // 255, Red to Green as 256 - 511 and then Green to Blue as 512 - 767 which gives us our total // colorSpectrum of 0 - 767, which includes those colors and each of their states in the // transistion. unsigned int number_of_destination_colors = 1; switch (_color) { // BRYW. Three destination colors (R,Y,W). case 1: number_of_destination_colors = 3; break; // BWR. Two destination colors (W,R). case 2: number_of_destination_colors = 2; break; // RWB. Two destination colors (W,B). case 3: number_of_destination_colors = 2; break; // BR. One destination color (R). case 4: number_of_destination_colors = 1; break; } // We need to convert the number of colors into the spectrum max, then convert the value from the // mesh to a point somewhere in the range of 0 to color_spectrum_max. auto color_spectrum_max = (256 * number_of_destination_colors) - 1; auto color = (unsigned int)(selection * color_spectrum_max); // Unless we specifically say some part is transparent, we want the whole image to be opaque. auto tran = (unsigned int)(_transparency * 255); // Make sure everything is within our colorSpectrum. If it's bigger, then we want a // transparent background. if (color > color_spectrum_max) { color = color_spectrum_max; tran = 0; } auto magnitude = color % 256; switch (_color) { // Current color scheme: Blue->Red->Yellow->White case 1: // Blue->Red if (color < 256) { rgb[0] = magnitude; rgb[1] = 0; rgb[2] = 50; // 255 - magnitude; } // Red->Yellow else if (color < 512) { rgb[0] = 255; rgb[1] = magnitude; rgb[2] = 0; } // Yellow->White else { rgb[0] = 255; rgb[1] = 255; rgb[2] = magnitude; } break; // Color Scheme: Blue->White->Red // Using the RGB values found in Paraview case 2: // Blue->White if (color < 256) { rgb[0] = (int)(255.0 * (0.231373 + (0.002485 * (float)magnitude))); rgb[1] = (int)(255.0 * (0.298039 + (0.002223 * (float)magnitude))); rgb[2] = (int)(255.0 * (0.752941 + (0.000439 * (float)magnitude))); } // White->Red else { rgb[0] = (int)(255.0 * (0.865003 - (0.000624 * (float)magnitude))); rgb[1] = (int)(255.0 * (0.865003 - (0.003331 * (float)magnitude))); rgb[2] = (int)(255.0 * (0.865003 - (0.002808 * (float)magnitude))); } break; // Red->White->Blue case 3: // Red->White if (color < 256) { rgb[0] = 255; rgb[1] = magnitude; rgb[2] = magnitude; } // White->Blue else { rgb[0] = 255 - magnitude; rgb[1] = 255 - magnitude; rgb[2] = 255; } break; // Blue->Red case 4: // Blue->Red rgb[0] = magnitude; rgb[1] = 0; rgb[2] = 255 - magnitude; break; } // Add any transparency. rgb[3] = tran; } void PNGOutput::output(const ExecFlagType & /*type*/) { makeMeshFunc(); _box = MeshTools::create_bounding_box(*_mesh_ptr); // Make sure this happens on processor 0 if (processor_id() == 0) makePNG(); } // Function the writes the PNG out to the appropriate filename. void PNGOutput::makePNG() { // Get the max and min of the BoundingBox Point max_point = _box.max(); Point min_point = _box.min(); // The the total distance on the x and y axes. Real dist_x = max_point(0) - min_point(0); Real dist_y = max_point(1) - min_point(1); // Width and height for the PNG image. Real width; Real height; // Variable to record the resolution variable after normalized to work with pixels in longest // direction. Real normalized_resolution; // The longer dimension becomes the value to which we scale the other. if (dist_x > dist_y) { width = _resolution; height = (_resolution / dist_x) * dist_y; normalized_resolution = (((Real)_resolution) / dist_x); } else { height = _resolution; width = (_resolution / dist_y) * dist_x; normalized_resolution = (((Real)_resolution) / dist_y); } // Create the filename based on base and the test step number. std::ostringstream png_file; png_file << _file_base << "_" << std::setfill('0') << std::setw(3) << _t_step << ".png"; // libpng is built on C, so by default it takes FILE*. FILE * fp = nullptr; png_structp pngp = nullptr; png_infop infop = nullptr; // Required depth for proper image clarity. Real depth = 8; // Allocate resources. std::vector<png_byte> row((width + 1) * 4); // Check if we can open and write to the file. MooseUtils::checkFileWriteable(png_file.str()); // Open the file with write and bit modes. fp = fopen(png_file.str().c_str(), "wb"); pngp = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!pngp) mooseError("Failed to make the pointer string for the png."); infop = png_create_info_struct(pngp); if (!infop) mooseError("Failed to make an info pointer for the png."); // Initializes the IO for the png. Needs FILE* to compile. png_init_io(pngp, fp); // Set up the PNG header. png_set_IHDR(pngp, infop, width, height, depth, (_color ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_GRAY), PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(pngp, infop); // Initiallizing the point that will be used for populating the mesh values. // Initializing x, y, z to zero so that we don't access the point before it's // been set. z = 0 for all the png's. Point pt(0, 0, 0); // Dense vector that we can pass into the _mesh_function to fill with a value for a given point. DenseVector<Number> dv(0); // Loop through to create the image. for (Real y = max_point(1); y >= min_point(1); y -= 1. / normalized_resolution) { pt(1) = y; unsigned int index = 0; for (Real x = min_point(0); x <= max_point(0); x += 1. / normalized_resolution) { pt(0) = x; (*_mesh_function)(pt, _time, dv, nullptr); // Determine whether to create the PNG in color or grayscale if (_color) setRGB(&row.data()[index * 4], applyScale(dv(0))); else row.data()[index] = applyScale(dv(0)) * 255; index++; } png_write_row(pngp, row.data()); } // Close the file and take care of some other png end stuff. png_write_end(pngp, nullptr); if (fp != nullptr) fclose(fp); if (infop != nullptr) png_free_data(pngp, infop, PNG_FREE_ALL, -1); if (pngp != nullptr) png_destroy_write_struct(&pngp, &infop); } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2016, Ford Motor Company * 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 Ford Motor Company 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 <stdint.h> #include <string> #include "gtest/gtest.h" #include "utils/shared_ptr.h" #include "smart_objects/smart_object.h" #include "application_manager/test/include/application_manager/commands/commands_test.h" #include "application_manager/test/include/application_manager/commands/command_request_test.h" #include "application_manager/application.h" #include "application_manager/mock_application_manager.h" #include "application_manager/mock_application.h" #include "application_manager/commands/mobile/list_files_request.h" #include "interfaces/MOBILE_API.h" #include "application_manager/smart_object_keys.h" namespace test { namespace components { namespace commands_test { namespace mobile_commands_test { namespace list_files_request { using ::testing::_; using ::testing::Return; using ::testing::ReturnRef; using ::testing::DoAll; using ::testing::SaveArg; namespace am = ::application_manager; using am::commands::ListFilesRequest; using am::commands::MessageSharedPtr; class ListFilesRequestTest : public CommandRequestTest<CommandsTestMocks::kIsNice> {}; TEST_F(ListFilesRequestTest, Run_AppNotRegistered_UNSUCCESS) { SharedPtr<ListFilesRequest> command(CreateCommand<ListFilesRequest>()); ON_CALL(app_mngr_, application(_)) .WillByDefault(Return(SharedPtr<am::Application>())); MessageSharedPtr result_msg(CatchMobileCommandResult(CallRun(*command))); EXPECT_EQ(mobile_apis::Result::APPLICATION_NOT_REGISTERED, static_cast<mobile_apis::Result::eType>( (*result_msg)[am::strings::msg_params][am::strings::result_code] .asInt())); } TEST_F(ListFilesRequestTest, Run_TooManyHmiNone_UNSUCCESS) { MockAppPtr app(CreateMockApp()); SharedPtr<ListFilesRequest> command(CreateCommand<ListFilesRequest>()); ON_CALL(app_mngr_, application(_)).WillByDefault(Return(app)); ON_CALL(*app, hmi_level()) .WillByDefault(Return(mobile_apis::HMILevel::HMI_NONE)); const uint32_t kListFilesInNoneAllowed = 1u; const uint32_t kListFilesInNoneCount = 2u; EXPECT_CALL(app_mngr_, get_settings()) .WillOnce(ReturnRef(app_mngr_settings_)); ON_CALL(app_mngr_settings_, list_files_in_none()) .WillByDefault(ReturnRef(kListFilesInNoneAllowed)); ON_CALL(*app, list_files_in_none_count()) .WillByDefault(Return(kListFilesInNoneCount)); MessageSharedPtr result_msg(CatchMobileCommandResult(CallRun(*command))); EXPECT_EQ(mobile_apis::Result::REJECTED, static_cast<mobile_apis::Result::eType>( (*result_msg)[am::strings::msg_params][am::strings::result_code] .asInt())); } TEST_F(ListFilesRequestTest, Run_SUCCESS) { MockAppPtr app(CreateMockApp()); SharedPtr<ListFilesRequest> command(CreateCommand<ListFilesRequest>()); EXPECT_CALL(app_mngr_, get_settings()) .WillOnce(ReturnRef(app_mngr_settings_)); ON_CALL(app_mngr_, application(_)).WillByDefault(Return(app)); ON_CALL(*app, hmi_level()) .WillByDefault(Return(mobile_apis::HMILevel::HMI_FULL)); ON_CALL(*app, increment_list_files_in_none_count()).WillByDefault(Return()); ON_CALL(*app, GetAvailableDiskSpace()).WillByDefault(Return(0)); am::AppFilesMap files_map; ON_CALL(*app, getAppFiles()).WillByDefault(ReturnRef(files_map)); MessageSharedPtr result_msg(CatchMobileCommandResult(CallRun(*command))); EXPECT_EQ(mobile_apis::Result::SUCCESS, static_cast<mobile_apis::Result::eType>( (*result_msg)[am::strings::msg_params][am::strings::result_code] .asInt())); } } // namespace list_files_request } // namespace mobile_commands_test } // namespace commands_test } // namespace components } // namespace test <commit_msg>Fixes missing expectation for happy path of ListFiles request<commit_after>/* * Copyright (c) 2016, Ford Motor Company * 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 Ford Motor Company 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 <stdint.h> #include <string> #include "gtest/gtest.h" #include "utils/shared_ptr.h" #include "smart_objects/smart_object.h" #include "application_manager/test/include/application_manager/commands/commands_test.h" #include "application_manager/test/include/application_manager/commands/command_request_test.h" #include "application_manager/application.h" #include "application_manager/mock_application_manager.h" #include "application_manager/mock_application.h" #include "application_manager/commands/mobile/list_files_request.h" #include "interfaces/MOBILE_API.h" #include "application_manager/smart_object_keys.h" namespace test { namespace components { namespace commands_test { namespace mobile_commands_test { namespace list_files_request { using ::testing::_; using ::testing::Return; using ::testing::ReturnRef; using ::testing::DoAll; using ::testing::SaveArg; namespace am = ::application_manager; using am::commands::ListFilesRequest; using am::commands::MessageSharedPtr; class ListFilesRequestTest : public CommandRequestTest<CommandsTestMocks::kIsNice> { public: ListFilesRequestTest() : kStoragePath_("storage"), kResponseSize_(1) {} const std::string kStoragePath_; const uint32_t kResponseSize_; }; TEST_F(ListFilesRequestTest, Run_AppNotRegistered_UNSUCCESS) { SharedPtr<ListFilesRequest> command(CreateCommand<ListFilesRequest>()); ON_CALL(app_mngr_, application(_)) .WillByDefault(Return(SharedPtr<am::Application>())); MessageSharedPtr result_msg(CatchMobileCommandResult(CallRun(*command))); EXPECT_EQ(mobile_apis::Result::APPLICATION_NOT_REGISTERED, static_cast<mobile_apis::Result::eType>( (*result_msg)[am::strings::msg_params][am::strings::result_code] .asInt())); } TEST_F(ListFilesRequestTest, Run_TooManyHmiNone_UNSUCCESS) { MockAppPtr app(CreateMockApp()); SharedPtr<ListFilesRequest> command(CreateCommand<ListFilesRequest>()); ON_CALL(app_mngr_, application(_)).WillByDefault(Return(app)); ON_CALL(*app, hmi_level()) .WillByDefault(Return(mobile_apis::HMILevel::HMI_NONE)); const uint32_t kListFilesInNoneAllowed = 1u; const uint32_t kListFilesInNoneCount = 2u; EXPECT_CALL(app_mngr_, get_settings()) .WillOnce(ReturnRef(app_mngr_settings_)); ON_CALL(app_mngr_settings_, list_files_in_none()) .WillByDefault(ReturnRef(kListFilesInNoneAllowed)); ON_CALL(*app, list_files_in_none_count()) .WillByDefault(Return(kListFilesInNoneCount)); MessageSharedPtr result_msg(CatchMobileCommandResult(CallRun(*command))); EXPECT_EQ(mobile_apis::Result::REJECTED, static_cast<mobile_apis::Result::eType>( (*result_msg)[am::strings::msg_params][am::strings::result_code] .asInt())); } TEST_F(ListFilesRequestTest, Run_SUCCESS) { MockAppPtr app(CreateMockApp()); SharedPtr<ListFilesRequest> command(CreateCommand<ListFilesRequest>()); EXPECT_CALL(app_mngr_, get_settings()) .WillRepeatedly(ReturnRef(app_mngr_settings_)); ON_CALL(app_mngr_settings_, app_storage_folder()) .WillByDefault(ReturnRef(kStoragePath_)); ON_CALL(app_mngr_settings_, list_files_response_size()) .WillByDefault(ReturnRef(kResponseSize_)); ON_CALL(app_mngr_, application(_)).WillByDefault(Return(app)); ON_CALL(*app, hmi_level()) .WillByDefault(Return(mobile_apis::HMILevel::HMI_FULL)); ON_CALL(*app, increment_list_files_in_none_count()).WillByDefault(Return()); ON_CALL(*app, GetAvailableDiskSpace()).WillByDefault(Return(0)); am::AppFilesMap files_map; ON_CALL(*app, getAppFiles()).WillByDefault(ReturnRef(files_map)); MessageSharedPtr result_msg(CatchMobileCommandResult(CallRun(*command))); EXPECT_EQ(mobile_apis::Result::SUCCESS, static_cast<mobile_apis::Result::eType>( (*result_msg)[am::strings::msg_params][am::strings::result_code] .asInt())); } } // namespace list_files_request } // namespace mobile_commands_test } // namespace commands_test } // namespace components } // namespace test <|endoftext|>
<commit_before>// // Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>. // All rights reserved. // // This file is part of primesieve. // Homepage: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the author nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "SieveOfEratosthenes.h" #include "PreSieve.h" #include "EratSmall.h" #include "EratMedium.h" #include "EratBig.h" #include "imath.h" #include <stdint.h> #include <stdexcept> #include <cstdlib> namespace soe { const uint_t SieveOfEratosthenes::bitValues_[8] = { 7, 11, 13, 17, 19, 23, 29, 31 }; /// De Bruijn sequence for first set bitValues_ const uint_t SieveOfEratosthenes::bruijnBitValues_[32] = { 7, 11, 109, 13, 113, 59, 97, 17, 119, 89, 79, 61, 101, 71, 19, 37, 121, 107, 53, 91, 83, 77, 67, 31, 103, 49, 73, 29, 47, 23, 43, 41 }; /// @param start Sieve the primes within the interval [start, stop]. /// @param stop Sieve the primes within the interval [start, stop]. /// @param preSieveLimit Multiples of small primes <= preSieveLimit are /// pre-sieved to speed up the sieve of Eratosthenes, /// preSieveLimit >= 13 && <= 23. /// @param sieveSize A sieve size in kilobytes, sieveSize >= 1 && <= 4096. /// SieveOfEratosthenes::SieveOfEratosthenes(uint64_t start, uint64_t stop, uint_t preSieveLimit, uint_t sieveSize) : start_(start), stop_(stop), sqrtStop_(static_cast<uint_t>(isqrt(stop))), preSieve_(preSieveLimit), isFirstSegment_(true), sieve_(NULL), sieveSize_(sieveSize * 1024), eratSmall_(NULL), eratMedium_(NULL), eratBig_(NULL) { if (start_ < 7 || start_ > stop_) throw std::logic_error("SieveOfEratosthenes: start must be >= 7 && <= stop."); // it makes no sense to use very small sieve sizes if (sieveSize_ < 1024) throw std::invalid_argument("SieveOfEratosthenes: sieveSize must be >= 1 kilobyte."); segmentLow_ = start_ - getByteRemainder(start_); // '+1' is a correction for primes of type i*30 + 31 segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1; initEratAlgorithms(); // allocate the sieve of Eratosthenes array sieve_ = new uint8_t[sieveSize_ + 8]; } SieveOfEratosthenes::~SieveOfEratosthenes() { delete eratSmall_; delete eratMedium_; delete eratBig_; delete[] sieve_; } void SieveOfEratosthenes::initEratAlgorithms() { try { if (sqrtStop_ > preSieve_.getLimit()) { eratSmall_ = new EratSmall(*this); if (sqrtStop_ > eratSmall_->getLimit()) { eratMedium_ = new EratMedium(*this); if (sqrtStop_ > eratMedium_->getLimit()) eratBig_ = new EratBig(*this); } } } catch (...) { delete eratSmall_; delete eratMedium_; delete eratBig_; throw; } } uint64_t SieveOfEratosthenes::getByteRemainder(uint64_t n) { uint_t remainder = n % NUMBERS_PER_BYTE; if (remainder <= 1) remainder += NUMBERS_PER_BYTE; return remainder; } /// Pre-sieve multiples of small primes <= preSieve_.getLimit() /// to speed up the sieve of Eratosthenes. /// @see PreSieve.cpp /// void SieveOfEratosthenes::preSieve() { preSieve_.doIt(sieve_, sieveSize_, segmentLow_); if (isFirstSegment_) { isFirstSegment_ = false; // correct preSieve_.doIt() for numbers <= 23 if (start_ <= preSieve_.getLimit()) sieve_[0] = 0xff; uint64_t remainder = getByteRemainder(start_); // unset bits (numbers) < start_ for (int i = 0; i < 8; i++) if (bitValues_[i] < remainder) sieve_[0] &= ~(1 << i); } } void SieveOfEratosthenes::crossOffMultiples() { if (eratSmall_ != NULL) { // process the sieving primes with many multiples per segment eratSmall_->crossOff(sieve_, sieveSize_); if (eratMedium_ != NULL) { // process the sieving primes with a few ... eratMedium_->crossOff(sieve_, sieveSize_); if (eratBig_ != NULL) // process the sieving primes with very few ... eratBig_->crossOff(sieve_); } } } /// Sieve the primes within the current segment i.e. /// [segmentLow_, segmentHigh_]. /// void SieveOfEratosthenes::sieveSegment() { preSieve(); crossOffMultiples(); segmentProcessed(sieve_, sieveSize_); segmentLow_ += sieveSize_ * NUMBERS_PER_BYTE; segmentHigh_ += sieveSize_ * NUMBERS_PER_BYTE; } /// Sieve the last segments remaining after that sieve(prime) has /// been called for all primes up to sqrt(stop_). /// void SieveOfEratosthenes::finish() { // sieve all segments left except the last one while (segmentHigh_ < stop_) sieveSegment(); // sieve the last segment uint64_t remainder = getByteRemainder(stop_); sieveSize_ = static_cast<uint_t>((stop_ - remainder) - segmentLow_) / NUMBERS_PER_BYTE + 1; preSieve(); crossOffMultiples(); // unset bits and bytes (numbers) > stop_ for (int i = 0; i < 8; i++) { if (bitValues_[i] > remainder) sieve_[sieveSize_ - 1] &= ~(1 << i); sieve_[sieveSize_ + i] = 0; } segmentProcessed(sieve_, sieveSize_); } } // namespace soe <commit_msg>improved code readability<commit_after>// // Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>. // All rights reserved. // // This file is part of primesieve. // Homepage: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the author nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "SieveOfEratosthenes.h" #include "PreSieve.h" #include "EratSmall.h" #include "EratMedium.h" #include "EratBig.h" #include "imath.h" #include <stdint.h> #include <stdexcept> #include <cstdlib> namespace soe { const uint_t SieveOfEratosthenes::bitValues_[8] = { 7, 11, 13, 17, 19, 23, 29, 31 }; /// De Bruijn sequence for first set bitValues_ const uint_t SieveOfEratosthenes::bruijnBitValues_[32] = { 7, 11, 109, 13, 113, 59, 97, 17, 119, 89, 79, 61, 101, 71, 19, 37, 121, 107, 53, 91, 83, 77, 67, 31, 103, 49, 73, 29, 47, 23, 43, 41 }; /// @param start Sieve the primes within the interval [start, stop]. /// @param stop Sieve the primes within the interval [start, stop]. /// @param preSieveLimit Multiples of small primes <= preSieveLimit are /// pre-sieved to speed up the sieve of Eratosthenes, /// preSieveLimit >= 13 && <= 23. /// @param sieveSize A sieve size in kilobytes, sieveSize >= 1 && <= 4096. /// SieveOfEratosthenes::SieveOfEratosthenes(uint64_t start, uint64_t stop, uint_t preSieveLimit, uint_t sieveSize) : start_(start), stop_(stop), sqrtStop_(static_cast<uint_t>(isqrt(stop))), preSieve_(preSieveLimit), isFirstSegment_(true), sieve_(NULL), sieveSize_(sieveSize * 1024), eratSmall_(NULL), eratMedium_(NULL), eratBig_(NULL) { if (start_ < 7 || start_ > stop_) throw std::logic_error("SieveOfEratosthenes: start must be >= 7 && <= stop."); // it makes no sense to use very small sieve sizes if (sieveSize_ < 1024) throw std::invalid_argument("SieveOfEratosthenes: sieveSize must be >= 1 kilobyte."); segmentLow_ = start_ - getByteRemainder(start_); // '+1' is a correction for primes of type i*30 + 31 segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1; initEratAlgorithms(); // allocate the sieve of Eratosthenes array sieve_ = new uint8_t[sieveSize_ + 8]; } SieveOfEratosthenes::~SieveOfEratosthenes() { delete eratSmall_; delete eratMedium_; delete eratBig_; delete[] sieve_; } void SieveOfEratosthenes::initEratAlgorithms() { try { if (sqrtStop_ > preSieve_.getLimit()) { eratSmall_ = new EratSmall(*this); if (sqrtStop_ > eratSmall_->getLimit()) { eratMedium_ = new EratMedium(*this); if (sqrtStop_ > eratMedium_->getLimit()) eratBig_ = new EratBig(*this); } } } catch (...) { delete eratSmall_; delete eratMedium_; delete eratBig_; throw; } } uint64_t SieveOfEratosthenes::getByteRemainder(uint64_t n) { uint_t remainder = n % NUMBERS_PER_BYTE; if (remainder <= 1) remainder += NUMBERS_PER_BYTE; return remainder; } /// Pre-sieve multiples of small primes <= preSieve_.getLimit() /// to speed up the sieve of Eratosthenes. /// @see PreSieve.cpp /// void SieveOfEratosthenes::preSieve() { preSieve_.doIt(sieve_, sieveSize_, segmentLow_); if (isFirstSegment_) { isFirstSegment_ = false; // correct preSieve_.doIt() for numbers <= 23 if (start_ <= preSieve_.getLimit()) sieve_[0] = 0xff; // unset bits (numbers) < start_ uint64_t remainder = getByteRemainder(start_); for (int i = 0; i < 8; i++) if (bitValues_[i] < remainder) sieve_[0] &= ~(1 << i); } } void SieveOfEratosthenes::crossOffMultiples() { if (eratSmall_ != NULL) { // process the sieving primes with many multiples per segment eratSmall_->crossOff(sieve_, sieveSize_); if (eratMedium_ != NULL) { // process the sieving primes with a few ... eratMedium_->crossOff(sieve_, sieveSize_); if (eratBig_ != NULL) // process the sieving primes with very few ... eratBig_->crossOff(sieve_); } } } /// Sieve the primes within the current segment i.e. /// [segmentLow_, segmentHigh_]. /// void SieveOfEratosthenes::sieveSegment() { preSieve(); crossOffMultiples(); segmentProcessed(sieve_, sieveSize_); segmentLow_ += sieveSize_ * NUMBERS_PER_BYTE; segmentHigh_ += sieveSize_ * NUMBERS_PER_BYTE; } /// Sieve the last segments remaining after that sieve(prime) has /// been called for all primes up to sqrt(stop_). /// void SieveOfEratosthenes::finish() { // sieve all segments left except the last one while (segmentHigh_ < stop_) sieveSegment(); // sieve the last segment uint64_t remainder = getByteRemainder(stop_); sieveSize_ = static_cast<uint_t>((stop_ - remainder) - segmentLow_) / NUMBERS_PER_BYTE + 1; preSieve(); crossOffMultiples(); // unset bits and bytes (numbers) > stop_ for (int i = 0; i < 8; i++) { if (bitValues_[i] > remainder) sieve_[sieveSize_ - 1] &= ~(1 << i); sieve_[sieveSize_ + i] = 0; } segmentProcessed(sieve_, sieveSize_); } } // namespace soe <|endoftext|>
<commit_before>#include "common/access_log/access_log_manager_impl.h" #include <string> #include "common/common/assert.h" #include "common/common/fmt.h" #include "common/common/lock_guard.h" #include "absl/container/fixed_array.h" namespace Envoy { namespace AccessLog { AccessLogManagerImpl::~AccessLogManagerImpl() { for (auto& [log_key, log_file_ptr] : access_logs_) { ENVOY_LOG(debug, "destroying access logger {}", log_key); log_file_ptr.reset(); } ENVOY_LOG(debug, "destroyed access loggers"); } void AccessLogManagerImpl::reopen() { for (auto& [log_key, log_file_ptr] : access_logs_) { log_file_ptr->reopen(); } } AccessLogFileSharedPtr AccessLogManagerImpl::createAccessLog(const std::string& file_name) { if (access_logs_.count(file_name)) { return access_logs_[file_name]; } access_logs_[file_name] = std::make_shared<AccessLogFileImpl>( api_.fileSystem().createFile(file_name), dispatcher_, lock_, file_stats_, file_flush_interval_msec_, api_.threadFactory()); return access_logs_[file_name]; } AccessLogFileImpl::AccessLogFileImpl(Filesystem::FilePtr&& file, Event::Dispatcher& dispatcher, Thread::BasicLockable& lock, AccessLogFileStats& stats, std::chrono::milliseconds flush_interval_msec, Thread::ThreadFactory& thread_factory) : file_(std::move(file)), file_lock_(lock), flush_timer_(dispatcher.createTimer([this]() -> void { stats_.flushed_by_timer_.inc(); flush_event_.notifyOne(); flush_timer_->enableTimer(flush_interval_msec_); })), thread_factory_(thread_factory), flush_interval_msec_(flush_interval_msec), stats_(stats) { open(); } Filesystem::FlagSet AccessLogFileImpl::defaultFlags() { static constexpr Filesystem::FlagSet default_flags{1 << Filesystem::File::Operation::Write | 1 << Filesystem::File::Operation::Create | 1 << Filesystem::File::Operation::Append}; return default_flags; } void AccessLogFileImpl::open() { const Api::IoCallBoolResult result = file_->open(defaultFlags()); if (!result.rc_) { throw EnvoyException( fmt::format("unable to open file '{}': {}", file_->path(), result.err_->getErrorDetails())); } } void AccessLogFileImpl::reopen() { reopen_file_ = true; } AccessLogFileImpl::~AccessLogFileImpl() { { Thread::LockGuard lock(write_lock_); flush_thread_exit_ = true; flush_event_.notifyOne(); } if (flush_thread_ != nullptr) { flush_thread_->join(); } // Flush any remaining data. If file was not opened for some reason, skip flushing part. if (file_->isOpen()) { if (flush_buffer_.length() > 0) { doWrite(flush_buffer_); } const Api::IoCallBoolResult result = file_->close(); ASSERT(result.rc_, fmt::format("unable to close file '{}': {}", file_->path(), result.err_->getErrorDetails())); } } void AccessLogFileImpl::doWrite(Buffer::Instance& buffer) { Buffer::RawSliceVector slices = buffer.getRawSlices(); // We must do the actual writes to disk under lock, so that we don't intermix chunks from // different AccessLogFileImpl pointing to the same underlying file. This can happen either via // hot restart or if calling code opens the same underlying file into a different // AccessLogFileImpl in the same process. // TODO PERF: Currently, we use a single cross process lock to serialize all disk writes. This // will never block network workers, but does mean that only a single flush thread can // actually flush to disk. In the future it would be nice if we did away with the cross // process lock or had multiple locks. { Thread::LockGuard lock(file_lock_); for (const Buffer::RawSlice& slice : slices) { absl::string_view data(static_cast<char*>(slice.mem_), slice.len_); const Api::IoCallSizeResult result = file_->write(data); if (result.ok() && result.rc_ == static_cast<ssize_t>(slice.len_)) { stats_.write_completed_.inc(); } else { // Probably disk full. stats_.write_failed_.inc(); } } } stats_.write_total_buffered_.sub(buffer.length()); buffer.drain(buffer.length()); } void AccessLogFileImpl::flushThreadFunc() { while (true) { std::unique_lock<Thread::BasicLockable> flush_lock; { Thread::LockGuard write_lock(write_lock_); // flush_event_ can be woken up either by large enough flush_buffer or by timer. // In case it was timer, flush_buffer_ can be empty. while (flush_buffer_.length() == 0 && !flush_thread_exit_ && !reopen_file_) { // CondVar::wait() does not throw, so it's safe to pass the mutex rather than the guard. flush_event_.wait(write_lock_); } if (flush_thread_exit_) { return; } flush_lock = std::unique_lock<Thread::BasicLockable>(flush_lock_); about_to_write_buffer_.move(flush_buffer_); ASSERT(flush_buffer_.length() == 0); } // if we failed to open file before, then simply ignore if (file_->isOpen()) { try { if (reopen_file_) { reopen_file_ = false; const Api::IoCallBoolResult result = file_->close(); ASSERT(result.rc_, fmt::format("unable to close file '{}': {}", file_->path(), result.err_->getErrorDetails())); open(); } doWrite(about_to_write_buffer_); } catch (const EnvoyException&) { stats_.reopen_failed_.inc(); } } } } void AccessLogFileImpl::flush() { std::unique_lock<Thread::BasicLockable> flush_buffer_lock; { Thread::LockGuard write_lock(write_lock_); // flush_lock_ must be held while checking this or else it is // possible that flushThreadFunc() has already moved data from // flush_buffer_ to about_to_write_buffer_, has unlocked write_lock_, // but has not yet completed doWrite(). This would allow flush() to // return before the pending data has actually been written to disk. flush_buffer_lock = std::unique_lock<Thread::BasicLockable>(flush_lock_); if (flush_buffer_.length() == 0) { return; } about_to_write_buffer_.move(flush_buffer_); ASSERT(flush_buffer_.length() == 0); } doWrite(about_to_write_buffer_); } void AccessLogFileImpl::write(absl::string_view data) { Thread::LockGuard lock(write_lock_); if (flush_thread_ == nullptr) { createFlushStructures(); } stats_.write_buffered_.inc(); stats_.write_total_buffered_.add(data.length()); flush_buffer_.add(data.data(), data.size()); if (flush_buffer_.length() > MIN_FLUSH_SIZE) { flush_event_.notifyOne(); } } void AccessLogFileImpl::createFlushStructures() { flush_thread_ = thread_factory_.createThread([this]() -> void { flushThreadFunc(); }, Thread::Options{"AccessLogFlush"}); flush_timer_->enableTimer(flush_interval_msec_); } } // namespace AccessLog } // namespace Envoy <commit_msg>Fix access_log_manager_impl unused variable warning (#12828)<commit_after>#include "common/access_log/access_log_manager_impl.h" #include <string> #include "common/common/assert.h" #include "common/common/fmt.h" #include "common/common/lock_guard.h" #include "absl/container/fixed_array.h" namespace Envoy { namespace AccessLog { AccessLogManagerImpl::~AccessLogManagerImpl() { for (auto& [log_key, log_file_ptr] : access_logs_) { ENVOY_LOG(debug, "destroying access logger {}", log_key); log_file_ptr.reset(); } ENVOY_LOG(debug, "destroyed access loggers"); } void AccessLogManagerImpl::reopen() { for (auto& iter : access_logs_) { iter.second->reopen(); } } AccessLogFileSharedPtr AccessLogManagerImpl::createAccessLog(const std::string& file_name) { if (access_logs_.count(file_name)) { return access_logs_[file_name]; } access_logs_[file_name] = std::make_shared<AccessLogFileImpl>( api_.fileSystem().createFile(file_name), dispatcher_, lock_, file_stats_, file_flush_interval_msec_, api_.threadFactory()); return access_logs_[file_name]; } AccessLogFileImpl::AccessLogFileImpl(Filesystem::FilePtr&& file, Event::Dispatcher& dispatcher, Thread::BasicLockable& lock, AccessLogFileStats& stats, std::chrono::milliseconds flush_interval_msec, Thread::ThreadFactory& thread_factory) : file_(std::move(file)), file_lock_(lock), flush_timer_(dispatcher.createTimer([this]() -> void { stats_.flushed_by_timer_.inc(); flush_event_.notifyOne(); flush_timer_->enableTimer(flush_interval_msec_); })), thread_factory_(thread_factory), flush_interval_msec_(flush_interval_msec), stats_(stats) { open(); } Filesystem::FlagSet AccessLogFileImpl::defaultFlags() { static constexpr Filesystem::FlagSet default_flags{1 << Filesystem::File::Operation::Write | 1 << Filesystem::File::Operation::Create | 1 << Filesystem::File::Operation::Append}; return default_flags; } void AccessLogFileImpl::open() { const Api::IoCallBoolResult result = file_->open(defaultFlags()); if (!result.rc_) { throw EnvoyException( fmt::format("unable to open file '{}': {}", file_->path(), result.err_->getErrorDetails())); } } void AccessLogFileImpl::reopen() { reopen_file_ = true; } AccessLogFileImpl::~AccessLogFileImpl() { { Thread::LockGuard lock(write_lock_); flush_thread_exit_ = true; flush_event_.notifyOne(); } if (flush_thread_ != nullptr) { flush_thread_->join(); } // Flush any remaining data. If file was not opened for some reason, skip flushing part. if (file_->isOpen()) { if (flush_buffer_.length() > 0) { doWrite(flush_buffer_); } const Api::IoCallBoolResult result = file_->close(); ASSERT(result.rc_, fmt::format("unable to close file '{}': {}", file_->path(), result.err_->getErrorDetails())); } } void AccessLogFileImpl::doWrite(Buffer::Instance& buffer) { Buffer::RawSliceVector slices = buffer.getRawSlices(); // We must do the actual writes to disk under lock, so that we don't intermix chunks from // different AccessLogFileImpl pointing to the same underlying file. This can happen either via // hot restart or if calling code opens the same underlying file into a different // AccessLogFileImpl in the same process. // TODO PERF: Currently, we use a single cross process lock to serialize all disk writes. This // will never block network workers, but does mean that only a single flush thread can // actually flush to disk. In the future it would be nice if we did away with the cross // process lock or had multiple locks. { Thread::LockGuard lock(file_lock_); for (const Buffer::RawSlice& slice : slices) { absl::string_view data(static_cast<char*>(slice.mem_), slice.len_); const Api::IoCallSizeResult result = file_->write(data); if (result.ok() && result.rc_ == static_cast<ssize_t>(slice.len_)) { stats_.write_completed_.inc(); } else { // Probably disk full. stats_.write_failed_.inc(); } } } stats_.write_total_buffered_.sub(buffer.length()); buffer.drain(buffer.length()); } void AccessLogFileImpl::flushThreadFunc() { while (true) { std::unique_lock<Thread::BasicLockable> flush_lock; { Thread::LockGuard write_lock(write_lock_); // flush_event_ can be woken up either by large enough flush_buffer or by timer. // In case it was timer, flush_buffer_ can be empty. while (flush_buffer_.length() == 0 && !flush_thread_exit_ && !reopen_file_) { // CondVar::wait() does not throw, so it's safe to pass the mutex rather than the guard. flush_event_.wait(write_lock_); } if (flush_thread_exit_) { return; } flush_lock = std::unique_lock<Thread::BasicLockable>(flush_lock_); about_to_write_buffer_.move(flush_buffer_); ASSERT(flush_buffer_.length() == 0); } // if we failed to open file before, then simply ignore if (file_->isOpen()) { try { if (reopen_file_) { reopen_file_ = false; const Api::IoCallBoolResult result = file_->close(); ASSERT(result.rc_, fmt::format("unable to close file '{}': {}", file_->path(), result.err_->getErrorDetails())); open(); } doWrite(about_to_write_buffer_); } catch (const EnvoyException&) { stats_.reopen_failed_.inc(); } } } } void AccessLogFileImpl::flush() { std::unique_lock<Thread::BasicLockable> flush_buffer_lock; { Thread::LockGuard write_lock(write_lock_); // flush_lock_ must be held while checking this or else it is // possible that flushThreadFunc() has already moved data from // flush_buffer_ to about_to_write_buffer_, has unlocked write_lock_, // but has not yet completed doWrite(). This would allow flush() to // return before the pending data has actually been written to disk. flush_buffer_lock = std::unique_lock<Thread::BasicLockable>(flush_lock_); if (flush_buffer_.length() == 0) { return; } about_to_write_buffer_.move(flush_buffer_); ASSERT(flush_buffer_.length() == 0); } doWrite(about_to_write_buffer_); } void AccessLogFileImpl::write(absl::string_view data) { Thread::LockGuard lock(write_lock_); if (flush_thread_ == nullptr) { createFlushStructures(); } stats_.write_buffered_.inc(); stats_.write_total_buffered_.add(data.length()); flush_buffer_.add(data.data(), data.size()); if (flush_buffer_.length() > MIN_FLUSH_SIZE) { flush_event_.notifyOne(); } } void AccessLogFileImpl::createFlushStructures() { flush_thread_ = thread_factory_.createThread([this]() -> void { flushThreadFunc(); }, Thread::Options{"AccessLogFlush"}); flush_timer_->enableTimer(flush_interval_msec_); } } // namespace AccessLog } // namespace Envoy <|endoftext|>
<commit_before>/* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #include "deferred_shading_demo/game_state_manager.h" #include "common/math.h" #include "common/camera.h" #include "common/d3d_util.h" #include "common/geometry_generator.h" namespace DeferredShadingDemo { GameStateManager::GameStateManager() : GameStateManagerBase(), m_camera(1.5f * DirectX::XM_PI, 0.25f * DirectX::XM_PI, 50.0f) { } bool GameStateManager::Initialize(HWND hwnd, ID3D11Device **device) { GameStateManagerBase::Initialize(hwnd, device); BuildGeometryBuffers(); CreateLights(); // Set the view matrices to identity DirectX::XMMATRIX identity = DirectX::XMMatrixIdentity(); WorldViewProj.world = identity; WorldViewProj.view = identity; WorldViewProj.view = identity; return true; } void GameStateManager::Shutdown() { } void GameStateManager::Update() { WorldViewProj.view = m_camera.CreateViewMatrix(DirectX::XMVectorZero()); } void GameStateManager::OnResize(int newClientWidth, int newClientHeight) { // Update the aspect ratio and the projection matrix WorldViewProj.projection = DirectX::XMMatrixPerspectiveFovLH(0.25f * DirectX::XM_PI, float(newClientWidth) / newClientHeight, 1.0f, 1000.0f); } void GameStateManager::GamePaused() { } void GameStateManager::GameUnpaused() { } void GameStateManager::MouseDown(WPARAM buttonState, int x, int y) { m_mouseLastPos.x = x; m_mouseLastPos.y = y; SetCapture(m_hwnd); } void GameStateManager::MouseUp(WPARAM buttonState, int x, int y) { ReleaseCapture(); } void GameStateManager::MouseMove(WPARAM buttonState, int x, int y) { if ((buttonState & MK_LBUTTON) != 0) { // Calculate the new phi and theta based on mouse position relative to where the user clicked // Four mouse pixel movements is 1 degree float dPhi = ((float)(m_mouseLastPos.y - y) / 300); float dTheta = ((float)(x - m_mouseLastPos.x) / 300); m_camera.MoveCamera(dTheta, dPhi, 0.0f); } m_mouseLastPos.x = x; m_mouseLastPos.y = y; } void GameStateManager::MouseWheel(int zDelta) { // Make each wheel dedent correspond to 0.01 units m_camera.MoveCamera(0.0f, 0.0f, -0.01f * (float)zDelta); } void GameStateManager::BuildGeometryBuffers() { Models.push_back(Common::Model<Vertex>()); Common::Model<Vertex> *model = &Models.back(); Common::GeometryGenerator::MeshData meshData; Common::GeometryGenerator::CreateGrid(160.0f, 160.0f, 50, 50, &meshData); uint vertexCount = meshData.Vertices.size(); uint indexCount = meshData.Indices.size(); Vertex *vertices = new Vertex[vertexCount]; for (uint i = 0; i < vertexCount; ++i) { vertices[i].pos = meshData.Vertices[i].Position; vertices[i].pos.y = GetHillHeight(vertices[i].pos.x, vertices[i].pos.z); vertices[i].normal = GetHillNormal(vertices[i].pos.x, vertices[i].pos.z); vertices[i].texCoord = meshData.Vertices[i].TexCoord; } model->SetVertices(*m_device, vertices, vertexCount); uint *indices = new uint[indexCount]; for (uint i = 0; i < indexCount; ++i) { indices[i] = meshData.Indices[i]; } model->SetIndices(*m_device, indices, indexCount); // Create subsets Common::ModelSubset *subsets = new Common::ModelSubset[1] { {0, vertexCount, 0, indexCount / 3, {DirectX::XMFLOAT4(0.48f, 0.77f, 0.46f, 0.0f), DirectX::XMFLOAT4(0.48f, 0.77f, 0.46f, 1.0f), DirectX::XMFLOAT4(0.2f, 0.2f, 0.2f, 0.0f)}, m_textureManager.GetSRVFromDDSFile(*m_device, "grass.dds", D3D11_USAGE_IMMUTABLE) } }; model->SetSubsets(subsets, 1); } void GameStateManager::CreateLights() { Common::DirectionalLight *directionalLight = LightManager.GetDirectionalLight(); directionalLight->Ambient = DirectX::XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f); directionalLight->Diffuse = DirectX::XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); directionalLight->Specular = DirectX::XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); directionalLight->Direction = DirectX::XMFLOAT3(0.57735f, -0.57735f, 0.57735f); } float GameStateManager::GetHillHeight(float x, float z) const { return 0.3f * ((z * sinf(0.1f * x)) + (x * cosf(0.1f * z))); } DirectX::XMFLOAT3 GameStateManager::GetHillNormal(float x, float z) const { DirectX::XMFLOAT3 normal( -0.03f * z * cosf(0.1f * x) - 0.3f * cosf(0.1f * z), 1.0f, 0.3f * sinf(0.1f * x) + 0.03f * x * sinf(0.1f * z)); DirectX::XMVECTOR unitNormal = DirectX::XMVector3Normalize(DirectX::XMLoadFloat3(&normal)); DirectX::XMStoreFloat3(&normal, unitNormal); return normal; } } // End of namespace DeferredShadingDemo <commit_msg>DEFERRED_SHADING_DEMO: Set the specular power to 1.0<commit_after>/* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #include "deferred_shading_demo/game_state_manager.h" #include "common/math.h" #include "common/camera.h" #include "common/d3d_util.h" #include "common/geometry_generator.h" namespace DeferredShadingDemo { GameStateManager::GameStateManager() : GameStateManagerBase(), m_camera(1.5f * DirectX::XM_PI, 0.25f * DirectX::XM_PI, 50.0f) { } bool GameStateManager::Initialize(HWND hwnd, ID3D11Device **device) { GameStateManagerBase::Initialize(hwnd, device); BuildGeometryBuffers(); CreateLights(); // Set the view matrices to identity DirectX::XMMATRIX identity = DirectX::XMMatrixIdentity(); WorldViewProj.world = identity; WorldViewProj.view = identity; WorldViewProj.view = identity; return true; } void GameStateManager::Shutdown() { } void GameStateManager::Update() { WorldViewProj.view = m_camera.CreateViewMatrix(DirectX::XMVectorZero()); } void GameStateManager::OnResize(int newClientWidth, int newClientHeight) { // Update the aspect ratio and the projection matrix WorldViewProj.projection = DirectX::XMMatrixPerspectiveFovLH(0.25f * DirectX::XM_PI, float(newClientWidth) / newClientHeight, 1.0f, 1000.0f); } void GameStateManager::GamePaused() { } void GameStateManager::GameUnpaused() { } void GameStateManager::MouseDown(WPARAM buttonState, int x, int y) { m_mouseLastPos.x = x; m_mouseLastPos.y = y; SetCapture(m_hwnd); } void GameStateManager::MouseUp(WPARAM buttonState, int x, int y) { ReleaseCapture(); } void GameStateManager::MouseMove(WPARAM buttonState, int x, int y) { if ((buttonState & MK_LBUTTON) != 0) { // Calculate the new phi and theta based on mouse position relative to where the user clicked // Four mouse pixel movements is 1 degree float dPhi = ((float)(m_mouseLastPos.y - y) / 300); float dTheta = ((float)(x - m_mouseLastPos.x) / 300); m_camera.MoveCamera(dTheta, dPhi, 0.0f); } m_mouseLastPos.x = x; m_mouseLastPos.y = y; } void GameStateManager::MouseWheel(int zDelta) { // Make each wheel dedent correspond to 0.01 units m_camera.MoveCamera(0.0f, 0.0f, -0.01f * (float)zDelta); } void GameStateManager::BuildGeometryBuffers() { Models.push_back(Common::Model<Vertex>()); Common::Model<Vertex> *model = &Models.back(); Common::GeometryGenerator::MeshData meshData; Common::GeometryGenerator::CreateGrid(160.0f, 160.0f, 50, 50, &meshData); uint vertexCount = meshData.Vertices.size(); uint indexCount = meshData.Indices.size(); Vertex *vertices = new Vertex[vertexCount]; for (uint i = 0; i < vertexCount; ++i) { vertices[i].pos = meshData.Vertices[i].Position; vertices[i].pos.y = GetHillHeight(vertices[i].pos.x, vertices[i].pos.z); vertices[i].normal = GetHillNormal(vertices[i].pos.x, vertices[i].pos.z); vertices[i].texCoord = meshData.Vertices[i].TexCoord; } model->SetVertices(*m_device, vertices, vertexCount); uint *indices = new uint[indexCount]; for (uint i = 0; i < indexCount; ++i) { indices[i] = meshData.Indices[i]; } model->SetIndices(*m_device, indices, indexCount); // Create subsets Common::ModelSubset *subsets = new Common::ModelSubset[1] { {0, vertexCount, 0, indexCount / 3, {DirectX::XMFLOAT4(0.48f, 0.77f, 0.46f, 0.0f), DirectX::XMFLOAT4(0.48f, 0.77f, 0.46f, 1.0f), DirectX::XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f)}, m_textureManager.GetSRVFromDDSFile(*m_device, "grass.dds", D3D11_USAGE_IMMUTABLE) } }; model->SetSubsets(subsets, 1); } void GameStateManager::CreateLights() { Common::DirectionalLight *directionalLight = LightManager.GetDirectionalLight(); directionalLight->Ambient = DirectX::XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f); directionalLight->Diffuse = DirectX::XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); directionalLight->Specular = DirectX::XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); directionalLight->Direction = DirectX::XMFLOAT3(0.57735f, -0.57735f, 0.57735f); } float GameStateManager::GetHillHeight(float x, float z) const { return 0.3f * ((z * sinf(0.1f * x)) + (x * cosf(0.1f * z))); } DirectX::XMFLOAT3 GameStateManager::GetHillNormal(float x, float z) const { DirectX::XMFLOAT3 normal( -0.03f * z * cosf(0.1f * x) - 0.3f * cosf(0.1f * z), 1.0f, 0.3f * sinf(0.1f * x) + 0.03f * x * sinf(0.1f * z)); DirectX::XMVECTOR unitNormal = DirectX::XMVector3Normalize(DirectX::XMLoadFloat3(&normal)); DirectX::XMStoreFloat3(&normal, unitNormal); return normal; } } // End of namespace DeferredShadingDemo <|endoftext|>
<commit_before>#ifndef STAN_IO_STAN_CSV_READER_HPP #define STAN_IO_STAN_CSV_READER_HPP #include <boost/algorithm/string.hpp> #include <stan/math/prim.hpp> #include <istream> #include <iostream> #include <sstream> #include <string> #include <vector> #include <ctype> namespace stan { namespace io { // FIXME: should consolidate with the options from // the command line in stan::lang struct stan_csv_metadata { int stan_version_major; int stan_version_minor; int stan_version_patch; std::string model; std::string data; std::string init; size_t chain_id; size_t seed; bool random_seed; size_t num_samples; size_t num_warmup; bool save_warmup; size_t thin; bool append_samples; std::string algorithm; std::string engine; int max_depth; stan_csv_metadata() : stan_version_major(0), stan_version_minor(0), stan_version_patch(0), model(""), data(""), init(""), chain_id(1), seed(0), random_seed(false), num_samples(0), num_warmup(0), save_warmup(false), thin(0), append_samples(false), algorithm(""), engine(""), max_depth(10) {} }; struct stan_csv_adaptation { double step_size; Eigen::MatrixXd metric; stan_csv_adaptation() : step_size(0), metric(0, 0) {} }; struct stan_csv_timing { double warmup; double sampling; stan_csv_timing() : warmup(0), sampling(0) {} }; struct stan_csv { stan_csv_metadata metadata; std::vector<std::string> header; stan_csv_adaptation adaptation; Eigen::MatrixXd samples; stan_csv_timing timing; }; /** * Reads from a Stan output csv file. */ class stan_csv_reader { public: stan_csv_reader() {} ~stan_csv_reader() {} static bool read_metadata(std::istream& in, stan_csv_metadata& metadata, std::ostream* out) { std::stringstream ss; std::string line; if (in.peek() != '#') return false; while (in.peek() == '#') { std::getline(in, line); ss << line << '\n'; } ss.seekg(std::ios_base::beg); char comment; std::string lhs; std::string name; std::string value; while (ss.good()) { ss >> comment; std::getline(ss, lhs); size_t equal = lhs.find("="); if (equal != std::string::npos) { name = lhs.substr(0, equal); boost::trim(name); value = lhs.substr(equal + 1, lhs.size()); boost::trim(value); boost::replace_first(value, " (Default)", ""); } else { if (lhs.compare(" data") == 0) { ss >> comment; std::getline(ss, lhs); size_t equal = lhs.find("="); if (equal != std::string::npos) { name = lhs.substr(0, equal); boost::trim(name); value = lhs.substr(equal + 2, lhs.size()); boost::replace_first(value, " (Default)", ""); } if (name.compare("file") == 0) metadata.data = value; continue; } } if (name.compare("stan_version_major") == 0) { std::stringstream(value) >> metadata.stan_version_major; } else if (name.compare("stan_version_minor") == 0) { std::stringstream(value) >> metadata.stan_version_minor; } else if (name.compare("stan_version_patch") == 0) { std::stringstream(value) >> metadata.stan_version_patch; } else if (name.compare("model") == 0) { metadata.model = value; } else if (name.compare("num_samples") == 0) { std::stringstream(value) >> metadata.num_samples; } else if (name.compare("num_warmup") == 0) { std::stringstream(value) >> metadata.num_warmup; } else if (name.compare("save_warmup") == 0) { std::stringstream(value) >> metadata.save_warmup; } else if (name.compare("thin") == 0) { std::stringstream(value) >> metadata.thin; } else if (name.compare("id") == 0) { std::stringstream(value) >> metadata.chain_id; } else if (name.compare("init") == 0) { metadata.init = value; boost::trim(metadata.init); } else if (name.compare("seed") == 0) { std::stringstream(value) >> metadata.seed; metadata.random_seed = false; } else if (name.compare("append_samples") == 0) { std::stringstream(value) >> metadata.append_samples; } else if (name.compare("algorithm") == 0) { metadata.algorithm = value; } else if (name.compare("engine") == 0) { metadata.engine = value; } else if (name.compare("max_depth") == 0) { std::stringstream(value) >> metadata.max_depth; } } if (ss.good() == true) return false; return true; } // read_metadata static bool read_header(std::istream& in, std::vector<std::string>& header, std::ostream* out, bool prettify_name = true) { std::string line; if (!std::isalpha(in.peek())) return false; std::getline(in, line); std::stringstream ss(line); header.resize(std::count(line.begin(), line.end(), ',') + 1); int idx = 0; while (ss.good()) { std::string token; std::getline(ss, token, ','); boost::trim(token); int pos = token.find('.'); if (pos > 0 && prettify_name) { token.replace(pos, 1, "["); std::replace(token.begin(), token.end(), '.', ','); token += "]"; } header[idx++] = token; } return true; } static bool read_adaptation(std::istream& in, stan_csv_adaptation& adaptation, std::ostream* out) { std::stringstream ss; std::string line; int lines = 0; if (in.peek() != '#' || in.good() == false) return false; while (in.peek() == '#') { std::getline(in, line); ss << line << std::endl; lines++; } ss.seekg(std::ios_base::beg); if (lines < 4) return false; char comment; // Buffer for comment indicator, # // Skip first two lines std::getline(ss, line); // Stepsize std::getline(ss, line, '='); boost::trim(line); ss >> adaptation.step_size; // Metric parameters std::getline(ss, line); std::getline(ss, line); std::getline(ss, line); int rows = lines - 3; int cols = std::count(line.begin(), line.end(), ',') + 1; adaptation.metric.resize(rows, cols); for (int row = 0; row < rows; row++) { std::stringstream line_ss; line_ss.str(line); line_ss >> comment; for (int col = 0; col < cols; col++) { std::string token; std::getline(line_ss, token, ','); boost::trim(token); std::stringstream(token) >> adaptation.metric(row, col); } std::getline(ss, line); // Read in next line } if (ss.good()) return false; else return true; } static bool read_samples(std::istream& in, Eigen::MatrixXd& samples, stan_csv_timing& timing, std::ostream* out) { std::stringstream ss; std::string line; int rows = 0; int cols = -1; if (in.peek() == '#' || in.good() == false) return false; while (in.good()) { bool comment_line = (in.peek() == '#'); bool empty_line = (in.peek() == '\n'); std::getline(in, line); if (empty_line) continue; if (!line.length()) break; if (comment_line) { if (line.find("(Warm-up)") != std::string::npos) { int left = 17; int right = line.find(" seconds"); double warmup; std::stringstream(line.substr(left, right - left)) >> warmup; timing.warmup += warmup; } else if (line.find("(Sampling)") != std::string::npos) { int left = 17; int right = line.find(" seconds"); double sampling; std::stringstream(line.substr(left, right - left)) >> sampling; timing.sampling += sampling; } } else { ss << line << '\n'; int current_cols = std::count(line.begin(), line.end(), ',') + 1; if (cols == -1) { cols = current_cols; } else if (cols != current_cols) { if (out) *out << "Error: expected " << cols << " columns, but found " << current_cols << " instead for row " << rows + 1 << std::endl; return false; } rows++; } in.peek(); } ss.seekg(std::ios_base::beg); if (rows > 0) { samples.resize(rows, cols); for (int row = 0; row < rows; row++) { std::getline(ss, line); std::stringstream ls(line); for (int col = 0; col < cols; col++) { std::getline(ls, line, ','); boost::trim(line); std::stringstream(line) >> samples(row, col); } } } return true; } /** * Parses the file. * * @param[in] in input stream to parse * @param[out] out output stream to send messages */ static stan_csv parse(std::istream& in, std::ostream* out) { stan_csv data; if (!read_metadata(in, data.metadata, out)) { if (out) *out << "Warning: non-fatal error reading metadata" << std::endl; } if (!read_header(in, data.header, out)) { if (out) *out << "Error: error reading header" << std::endl; throw std::invalid_argument("Error with header of input file in parse"); } if (!read_adaptation(in, data.adaptation, out)) { if (out) *out << "Warning: non-fatal error reading adapation data" << std::endl; } data.timing.warmup = 0; data.timing.sampling = 0; if (!read_samples(in, data.samples, data.timing, out)) { if (out) *out << "Warning: non-fatal error reading samples" << std::endl; } return data; } }; } // namespace io } // namespace stan #endif <commit_msg>ctype -> cctype<commit_after>#ifndef STAN_IO_STAN_CSV_READER_HPP #define STAN_IO_STAN_CSV_READER_HPP #include <boost/algorithm/string.hpp> #include <stan/math/prim.hpp> #include <cctype> #include <istream> #include <iostream> #include <sstream> #include <string> #include <vector> namespace stan { namespace io { // FIXME: should consolidate with the options from // the command line in stan::lang struct stan_csv_metadata { int stan_version_major; int stan_version_minor; int stan_version_patch; std::string model; std::string data; std::string init; size_t chain_id; size_t seed; bool random_seed; size_t num_samples; size_t num_warmup; bool save_warmup; size_t thin; bool append_samples; std::string algorithm; std::string engine; int max_depth; stan_csv_metadata() : stan_version_major(0), stan_version_minor(0), stan_version_patch(0), model(""), data(""), init(""), chain_id(1), seed(0), random_seed(false), num_samples(0), num_warmup(0), save_warmup(false), thin(0), append_samples(false), algorithm(""), engine(""), max_depth(10) {} }; struct stan_csv_adaptation { double step_size; Eigen::MatrixXd metric; stan_csv_adaptation() : step_size(0), metric(0, 0) {} }; struct stan_csv_timing { double warmup; double sampling; stan_csv_timing() : warmup(0), sampling(0) {} }; struct stan_csv { stan_csv_metadata metadata; std::vector<std::string> header; stan_csv_adaptation adaptation; Eigen::MatrixXd samples; stan_csv_timing timing; }; /** * Reads from a Stan output csv file. */ class stan_csv_reader { public: stan_csv_reader() {} ~stan_csv_reader() {} static bool read_metadata(std::istream& in, stan_csv_metadata& metadata, std::ostream* out) { std::stringstream ss; std::string line; if (in.peek() != '#') return false; while (in.peek() == '#') { std::getline(in, line); ss << line << '\n'; } ss.seekg(std::ios_base::beg); char comment; std::string lhs; std::string name; std::string value; while (ss.good()) { ss >> comment; std::getline(ss, lhs); size_t equal = lhs.find("="); if (equal != std::string::npos) { name = lhs.substr(0, equal); boost::trim(name); value = lhs.substr(equal + 1, lhs.size()); boost::trim(value); boost::replace_first(value, " (Default)", ""); } else { if (lhs.compare(" data") == 0) { ss >> comment; std::getline(ss, lhs); size_t equal = lhs.find("="); if (equal != std::string::npos) { name = lhs.substr(0, equal); boost::trim(name); value = lhs.substr(equal + 2, lhs.size()); boost::replace_first(value, " (Default)", ""); } if (name.compare("file") == 0) metadata.data = value; continue; } } if (name.compare("stan_version_major") == 0) { std::stringstream(value) >> metadata.stan_version_major; } else if (name.compare("stan_version_minor") == 0) { std::stringstream(value) >> metadata.stan_version_minor; } else if (name.compare("stan_version_patch") == 0) { std::stringstream(value) >> metadata.stan_version_patch; } else if (name.compare("model") == 0) { metadata.model = value; } else if (name.compare("num_samples") == 0) { std::stringstream(value) >> metadata.num_samples; } else if (name.compare("num_warmup") == 0) { std::stringstream(value) >> metadata.num_warmup; } else if (name.compare("save_warmup") == 0) { std::stringstream(value) >> metadata.save_warmup; } else if (name.compare("thin") == 0) { std::stringstream(value) >> metadata.thin; } else if (name.compare("id") == 0) { std::stringstream(value) >> metadata.chain_id; } else if (name.compare("init") == 0) { metadata.init = value; boost::trim(metadata.init); } else if (name.compare("seed") == 0) { std::stringstream(value) >> metadata.seed; metadata.random_seed = false; } else if (name.compare("append_samples") == 0) { std::stringstream(value) >> metadata.append_samples; } else if (name.compare("algorithm") == 0) { metadata.algorithm = value; } else if (name.compare("engine") == 0) { metadata.engine = value; } else if (name.compare("max_depth") == 0) { std::stringstream(value) >> metadata.max_depth; } } if (ss.good() == true) return false; return true; } // read_metadata static bool read_header(std::istream& in, std::vector<std::string>& header, std::ostream* out, bool prettify_name = true) { std::string line; if (!std::isalpha(in.peek())) return false; std::getline(in, line); std::stringstream ss(line); header.resize(std::count(line.begin(), line.end(), ',') + 1); int idx = 0; while (ss.good()) { std::string token; std::getline(ss, token, ','); boost::trim(token); int pos = token.find('.'); if (pos > 0 && prettify_name) { token.replace(pos, 1, "["); std::replace(token.begin(), token.end(), '.', ','); token += "]"; } header[idx++] = token; } return true; } static bool read_adaptation(std::istream& in, stan_csv_adaptation& adaptation, std::ostream* out) { std::stringstream ss; std::string line; int lines = 0; if (in.peek() != '#' || in.good() == false) return false; while (in.peek() == '#') { std::getline(in, line); ss << line << std::endl; lines++; } ss.seekg(std::ios_base::beg); if (lines < 4) return false; char comment; // Buffer for comment indicator, # // Skip first two lines std::getline(ss, line); // Stepsize std::getline(ss, line, '='); boost::trim(line); ss >> adaptation.step_size; // Metric parameters std::getline(ss, line); std::getline(ss, line); std::getline(ss, line); int rows = lines - 3; int cols = std::count(line.begin(), line.end(), ',') + 1; adaptation.metric.resize(rows, cols); for (int row = 0; row < rows; row++) { std::stringstream line_ss; line_ss.str(line); line_ss >> comment; for (int col = 0; col < cols; col++) { std::string token; std::getline(line_ss, token, ','); boost::trim(token); std::stringstream(token) >> adaptation.metric(row, col); } std::getline(ss, line); // Read in next line } if (ss.good()) return false; else return true; } static bool read_samples(std::istream& in, Eigen::MatrixXd& samples, stan_csv_timing& timing, std::ostream* out) { std::stringstream ss; std::string line; int rows = 0; int cols = -1; if (in.peek() == '#' || in.good() == false) return false; while (in.good()) { bool comment_line = (in.peek() == '#'); bool empty_line = (in.peek() == '\n'); std::getline(in, line); if (empty_line) continue; if (!line.length()) break; if (comment_line) { if (line.find("(Warm-up)") != std::string::npos) { int left = 17; int right = line.find(" seconds"); double warmup; std::stringstream(line.substr(left, right - left)) >> warmup; timing.warmup += warmup; } else if (line.find("(Sampling)") != std::string::npos) { int left = 17; int right = line.find(" seconds"); double sampling; std::stringstream(line.substr(left, right - left)) >> sampling; timing.sampling += sampling; } } else { ss << line << '\n'; int current_cols = std::count(line.begin(), line.end(), ',') + 1; if (cols == -1) { cols = current_cols; } else if (cols != current_cols) { if (out) *out << "Error: expected " << cols << " columns, but found " << current_cols << " instead for row " << rows + 1 << std::endl; return false; } rows++; } in.peek(); } ss.seekg(std::ios_base::beg); if (rows > 0) { samples.resize(rows, cols); for (int row = 0; row < rows; row++) { std::getline(ss, line); std::stringstream ls(line); for (int col = 0; col < cols; col++) { std::getline(ls, line, ','); boost::trim(line); std::stringstream(line) >> samples(row, col); } } } return true; } /** * Parses the file. * * @param[in] in input stream to parse * @param[out] out output stream to send messages */ static stan_csv parse(std::istream& in, std::ostream* out) { stan_csv data; if (!read_metadata(in, data.metadata, out)) { if (out) *out << "Warning: non-fatal error reading metadata" << std::endl; } if (!read_header(in, data.header, out)) { if (out) *out << "Error: error reading header" << std::endl; throw std::invalid_argument("Error with header of input file in parse"); } if (!read_adaptation(in, data.adaptation, out)) { if (out) *out << "Warning: non-fatal error reading adapation data" << std::endl; } data.timing.warmup = 0; data.timing.sampling = 0; if (!read_samples(in, data.samples, data.timing, out)) { if (out) *out << "Warning: non-fatal error reading samples" << std::endl; } return data; } }; } // namespace io } // namespace stan #endif <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <string> #include <vector> typedef std::pair<std::string, bool> list_item; std::string title(list_item const& item) { return item.first + std::string(item.second, '*'); } bool is_selected(list_item const& item) { return item.second; } bool is_not_selected(list_item const& item) { return not is_selected(item); } template <typename It> void move_selected_to(It first, It last, It dest) { std::stable_partition(first, dest, is_not_selected); std::stable_partition(dest, last, is_selected); } int main() { std::vector<list_item> people { { "David", true }, { "Jane", false }, { "Martha", false }, { "Peter", false }, { "Rose", true }, { "Tom", true } }; move_selected_to(people.begin(), people.end(), people.begin() + 3); for (auto const& person : people) std::cout << title(person) << std::endl; return 0; } <commit_msg>[i_cukic-func_progr_in_cpp][ch 02] slightly rewrite the example with std::stable_partion usage<commit_after>#include <algorithm> #include <string> #include <utility> #include <vector> #include <cassert> namespace test { typedef std::pair<std::string, bool> ListItem; std::string title(ListItem const& item) { return item.first + std::string(item.second, '*'); } bool isSelected(ListItem const& item) { return item.second; } bool isNotSelected(ListItem const& item) { return not isSelected(item); } template <typename It> void moveSelectedTo(It first, It last, It dest) { std::stable_partition(first, dest, isNotSelected); std::stable_partition(dest, last, isSelected); } void run() { std::vector<ListItem> people { { "David", true }, { "Jane", false }, { "Martha", false }, { "Peter", false }, { "Rose", true }, { "Tom", true } }; moveSelectedTo(std::begin(people), std::end(people), std::begin(people) + 3); const std::vector<ListItem> expected { { "Jane", false }, { "Martha", false }, { "David", true }, { "Rose", true }, { "Tom", true }, { "Peter", false } }; assert(expected == people); } } // test #include <iostream> int main() { std::cout << "test => [ok]" << std::endl; test::run(); std::cout << std::endl; return 0; } <|endoftext|>
<commit_before>#ifndef VG_STREAM_PROTOBUF_EMITTER_HPP_INCLUDED #define VG_STREAM_PROTOBUF_EMITTER_HPP_INCLUDED /** * \file protobuf_emitter.hpp * Defines an output cursor for writing Protobuf data to files. */ #include <cassert> #include <iostream> #include <istream> #include <fstream> #include <functional> #include <vector> #include <list> #include "message_emitter.hpp" #include "registry.hpp" #include "../json2pb.h" namespace vg { namespace stream { using namespace std; /** * Class that wraps an output stream and allows emitting groups of Protobuf * objects to it, with internal buffering. Handles finishing the file on its * own, and allows tracking of BGZF virtual offsets within a non-seekable * stream (as long as the entire stream is controlled by one instance). Cannot * be copied, but can be moved. * * Can call callbacks with the groups emitted and their virtual offsets, for * indexing purposes. * * Note that the callbacks may be called by the ProtobufEmitter's destructor, * so anything they reference needs to outlive the ProtobufEmitter. * * Not thread-safe. May be more efficient than repeated write/write_buffered * calls because a single BGZF stream can be used. */ template <typename T> class ProtobufEmitter { public: /// Constructor ProtobufEmitter(std::ostream& out, size_t max_group_size = 1000); /// Destructor that finishes the file ~ProtobufEmitter(); // Prohibit copy ProtobufEmitter(const ProtobufEmitter& other) = delete; ProtobufEmitter& operator=(const ProtobufEmitter& other) = delete; // Allow default move ProtobufEmitter(ProtobufEmitter&& other) = default; ProtobufEmitter& operator=(ProtobufEmitter&& other) = default; /// Emit the given item. /// TODO: May not really be any more efficient. /// We serialize to string right away in either case. void write(T&& item); /// Emit a copy of the given item. /// To use when you have something you can't move. void write_copy(const T& item); /// Define a type for group emission event listeners. /// The arguments are the start virtual offset and the past-end virtual offset. using group_listener_t = std::function<void(int64_t, int64_t)>; /// Add an event listener that listens for emitted groups. The listener /// will be called with the start virtual offset, and the /// past-end virtual offset. Moves the function passed in. /// Anything the function uses by reference must outlive this object! void on_group(group_listener_t&& listener); /// Define a type for message emission event listeners. /// This gets called for every message we emit, and then the group listeners get called for the whole group. using message_listener_t = std::function<void(const T&)>; /// Add an event listener that will be called every time a message is emitted. void on_message(message_listener_t&& listener); /// Actually write out everything in the buffer. /// Doesn't actually flush the underlying streams to disk. /// Assumes that no more than one group's worht of items are in the buffer. void emit_group(); private: /// We wrap a MessageEmitter that handles tagged message IO MessageEmitter message_emitter; /// And a single precomputed copy of the tag string to use string tag; /// And all the group handler functions. These need to never move; they are /// captured by reference to listeners in our MessageEmitter. list<group_listener_t> group_handlers; /// These we invoke ourselves per message. vector<message_listener_t> message_handlers; /// Make sure the given Protobuf-library bool return value is true, and fail otherwise with a message. void handle(bool ok); }; /// Produce an std::function that can be invoked with Protobuf objects and save them to the given stream. /// Easy way to get a dumping callback to feed to something that wants a callback. /// The passed stream must outlive the resulting function. template<typename Item> std::function<void(const Item&)> emit_to(ostream& out); ///////// // Template implementations ///////// template<typename T> ProtobufEmitter<T>::ProtobufEmitter(std::ostream& out, size_t max_group_size) : message_emitter(out, max_group_size), tag(Registry::get_protobuf_tag<T>()) { // Nothing to do! } template<typename T> ProtobufEmitter<T>::~ProtobufEmitter() { #ifdef debug cerr << "Destroying ProtobufEmitter" << endl; #endif // Emit the final group, so the MessageEmitter is empty when it destructs // and doesn't try to call any callbacks. // TODO: The whole callback ownership system is weird and should be re-done better somehow. emit_group(); #ifdef debug cerr << "ProtobufEmitter destroyed" << endl; #endif } template<typename T> auto ProtobufEmitter<T>::write(T&& item) -> void { // Grab the item T to_encode = std::move(item); for (auto& handler : message_handlers) { // Fire the handlers handler(to_encode); } // Encode it to a string string encoded; handle(to_encode.SerializeToString(&encoded)); // Write it with the correct tag. message_emitter.write(tag, std::move(encoded)); } template<typename T> auto ProtobufEmitter<T>::write_copy(const T& item) -> void { for (auto& handler : message_handlers) { // Fire the handlers handler(item); } // Encode it to a string string encoded; handle(item.SerializeToString(&encoded)); #ifdef debug cerr << "Write Protobuf: " << pb2json(item) << " to " << encoded.size() << " bytes" << endl; #endif // Write it with the correct tag. message_emitter.write(tag, std::move(encoded)); } template<typename T> auto ProtobufEmitter<T>::on_group(group_listener_t&& listener) -> void { // Take custody group_handlers.emplace_back(std::move(listener)); // Grab a reference auto& owned_listener = group_handlers.back(); // Capture by reference in another listener. // TODO: This isn't going to work at all if we want to ever use the same MessageEmitter with multiple ProtobufEmitters... message_emitter.on_group([&owned_listener](const string& tag, int64_t start_vo, int64_t past_end_vo) { // Call back with the group info. owned_listener(start_vo, past_end_vo); }); } template<typename T> auto ProtobufEmitter<T>::on_message(message_listener_t&& listener) -> void { // Put in the collection to loop through on every message. message_handlers.emplace_back(std::move(listener)); } template<typename T> auto ProtobufEmitter<T>::emit_group() -> void { message_emitter.emit_group(); } template<typename T> auto ProtobufEmitter<T>::handle(bool ok) -> void { if (!ok) { throw std::runtime_error("stream::ProtobufEmitter: could not write Protobuf"); } } template<typename Item> auto emit_to(ostream& out) -> std::function<void(const Item&)> { // We are going to be clever and make a lambda capture a shared_ptr to an // emitter, so we can have the emitter last as long as the function we // return. shared_ptr<ProtobufEmitter<Item>> emitter(new ProtobufEmitter<Item>(out)); return [emitter](const Item& item) { // Write out each item. // TODO: Set up so we can use the move operation the cursors support // Not easy because of https://stackoverflow.com/a/30394755 emitter->write_copy(item); }; } } } #endif <commit_msg>Allow the ProtobufEmitter to multithread<commit_after>#ifndef VG_STREAM_PROTOBUF_EMITTER_HPP_INCLUDED #define VG_STREAM_PROTOBUF_EMITTER_HPP_INCLUDED /** * \file protobuf_emitter.hpp * Defines an output cursor for writing Protobuf data to files. */ #include <cassert> #include <iostream> #include <istream> #include <fstream> #include <functional> #include <vector> #include <list> #include <mutex> #include "message_emitter.hpp" #include "registry.hpp" #include "../json2pb.h" namespace vg { namespace stream { using namespace std; /** * Class that wraps an output stream and allows emitting groups of Protobuf * objects to it, with internal buffering. Handles finishing the file on its * own, and allows tracking of BGZF virtual offsets within a non-seekable * stream (as long as the entire stream is controlled by one instance). Cannot * be copied, but can be moved. * * Can call callbacks with the groups emitted and their virtual offsets, for * indexing purposes. * * Note that the callbacks may be called by the ProtobufEmitter's destructor, * so anything they reference needs to outlive the ProtobufEmitter. * * May be more efficient than repeated write/write_buffered calls because a * single BGZF stream can be used. * * Thread-safe to call into. Serialization is done before locking. If a * particular order is needed between objects, use the multi-object write * functions. Listeners will be called inside the lock, so only one will be in * progress at a time. */ template <typename T> class ProtobufEmitter { public: /// Constructor ProtobufEmitter(std::ostream& out, size_t max_group_size = 1000); /// Destructor that finishes the file ~ProtobufEmitter(); // Prohibit copy ProtobufEmitter(const ProtobufEmitter& other) = delete; ProtobufEmitter& operator=(const ProtobufEmitter& other) = delete; // Allow default move ProtobufEmitter(ProtobufEmitter&& other) = default; ProtobufEmitter& operator=(ProtobufEmitter&& other) = default; /// Emit the given item. /// TODO: May not really be any more efficient. /// We serialize to string right away in either case. void write(T&& item); /// Emit the given collection of items in order, with no other intervening /// items between them. void write_many(vector<T>&& ordered_items); /// Emit a copy of the given item. /// To use when you have something you can't move. void write_copy(const T& item); /// Define a type for group emission event listeners. /// The arguments are the start virtual offset and the past-end virtual offset. using group_listener_t = std::function<void(int64_t, int64_t)>; /// Add an event listener that listens for emitted groups. The listener /// will be called with the start virtual offset, and the /// past-end virtual offset. Moves the function passed in. /// Anything the function uses by reference must outlive this object! void on_group(group_listener_t&& listener); /// Define a type for message emission event listeners. /// This gets called for every message we emit, and then the group listeners get called for the whole group. using message_listener_t = std::function<void(const T&)>; /// Add an event listener that will be called every time a message is emitted. void on_message(message_listener_t&& listener); /// Actually write out everything in the buffer. /// Doesn't actually flush the underlying streams to disk. /// Assumes that no more than one group's worht of items are in the buffer. void emit_group(); private: /// Mutex to controll access to the backing MessageEmitter. /// Also needs to control access to the listener lists. mutex out_mutex; /// We wrap a MessageEmitter that handles tagged message IO MessageEmitter message_emitter; /// And a single precomputed copy of the tag string to use string tag; /// And all the group handler functions. These need to never move; they are /// captured by reference to listeners in our MessageEmitter. list<group_listener_t> group_handlers; /// These we invoke ourselves per message. vector<message_listener_t> message_handlers; /// Make sure the given Protobuf-library bool return value is true, and fail otherwise with a message. void handle(bool ok); }; /// Produce an std::function that can be invoked with Protobuf objects and save them to the given stream. /// Easy way to get a dumping callback to feed to something that wants a callback. /// The passed stream must outlive the resulting function. template<typename Item> std::function<void(const Item&)> emit_to(ostream& out); ///////// // Template implementations ///////// template<typename T> ProtobufEmitter<T>::ProtobufEmitter(std::ostream& out, size_t max_group_size) : message_emitter(out, max_group_size), tag(Registry::get_protobuf_tag<T>()) { // Nothing to do! } template<typename T> ProtobufEmitter<T>::~ProtobufEmitter() { #ifdef debug cerr << "Destroying ProtobufEmitter" << endl; #endif // Emit the final group, so the MessageEmitter is empty when it destructs // and doesn't try to call any callbacks. // TODO: The whole callback ownership system is weird and should be re-done better somehow. emit_group(); #ifdef debug cerr << "ProtobufEmitter destroyed" << endl; #endif } template<typename T> auto ProtobufEmitter<T>::write(T&& item) -> void { // Grab the item T to_encode = std::move(item); // Encode it to a string string encoded; handle(to_encode.SerializeToString(&encoded)); // Lock the backing emitter lock_guard<mutex> lock(out_mutex); // Write it with the correct tag. message_emitter.write(tag, std::move(encoded)); for (auto& handler : message_handlers) { // Fire the handlers in serial handler(to_encode); } } template<typename T> auto ProtobufEmitter<T>::write_many(vector<T>&& ordered_items) -> void { // Grab the items vector<T> to_encode = std::move(ordered_items); // Encode them all to strings vector<string> encoded(to_encode.size()); for (size_t i = 0; i < to_encode.size(); i++) { handle(to_encode[i].SerializeToString(&encoded[i])); } // Lock the backing emitter lock_guard<mutex> lock(out_mutex); for (auto& s : encoded) { // Write each message with the correct tag. message_emitter.write(tag, std::move(s)); for (auto& handler : message_handlers) { // Fire the handlers in serial handler(to_encode); } } } template<typename T> auto ProtobufEmitter<T>::write_copy(const T& item) -> void { // Encode it to a string string encoded; handle(item.SerializeToString(&encoded)); #ifdef debug cerr << "Write Protobuf: " << pb2json(item) << " to " << encoded.size() << " bytes" << endl; #endif // Lock the backing emitter lock_guard<mutex> lock(out_mutex); // Write it with the correct tag. message_emitter.write(tag, std::move(encoded)); for (auto& handler : message_handlers) { // Fire the handlers in serial handler(item); } } template<typename T> auto ProtobufEmitter<T>::on_group(group_listener_t&& listener) -> void { // Lock the handler list lock_guard<mutex> lock(out_mutex); // Take custody group_handlers.emplace_back(std::move(listener)); // Grab a reference auto& owned_listener = group_handlers.back(); // Capture by reference in another listener. // TODO: This isn't going to work at all if we want to ever use the same MessageEmitter with multiple ProtobufEmitters... message_emitter.on_group([&owned_listener](const string& tag, int64_t start_vo, int64_t past_end_vo) { // Call back with the group info. owned_listener(start_vo, past_end_vo); }); } template<typename T> auto ProtobufEmitter<T>::on_message(message_listener_t&& listener) -> void { // Lock the handler list lock_guard<mutex> lock(out_mutex); // Put in the collection to loop through on every message. message_handlers.emplace_back(std::move(listener)); } template<typename T> auto ProtobufEmitter<T>::emit_group() -> void { // Lock the backing emitter lock_guard<mutex> lock(out_mutex); message_emitter.emit_group(); } template<typename T> auto ProtobufEmitter<T>::handle(bool ok) -> void { if (!ok) { throw std::runtime_error("stream::ProtobufEmitter: could not write Protobuf"); } } template<typename Item> auto emit_to(ostream& out) -> std::function<void(const Item&)> { // We are going to be clever and make a lambda capture a shared_ptr to an // emitter, so we can have the emitter last as long as the function we // return. shared_ptr<ProtobufEmitter<Item>> emitter(new ProtobufEmitter<Item>(out)); return [emitter](const Item& item) { // Write out each item. // TODO: Set up so we can use the move operation the cursors support // Not easy because of https://stackoverflow.com/a/30394755 emitter->write_copy(item); }; } } } #endif <|endoftext|>
<commit_before> #include <iostream> #include <utility> #include <cstdlib> #include <X11/Xlib.h> #include <boost/scope_exit.hpp> // According to the xmodmap, there are eight bits of buttons. #define MAX_BUTTON_CODES 256 int main() { // Define a delayed release of the display pointer. Display* display; BOOST_SCOPE_EXIT( (&display) ) { if(display) { XCloseDisplay (display); display = NULL; } } BOOST_SCOPE_EXIT_END // Get default display. display = XOpenDisplay(NULL); if (!display) { std::cerr << "Cannot open default display." << std::endl; return 1; } // Get current pointer mapping. unsigned char pointer_map[MAX_BUTTON_CODES]; int buttons_count = XGetPointerMapping(display, pointer_map, MAX_BUTTON_CODES); // We need at least three buttons to make the swap. if (buttons_count < 3) { std::cerr << "Not enough pointer buttons in the system. Need at least 3, " << "while only " << buttons_count << " are defined." << std::endl; return 2; } // According to some internet sources, left and right mouse buttons correspond to // codes 1 and 3 respectively. First check that physical left and right buttons // are mapped to logical left or right buttons in order not to break the behaviour // on systems where left and / or right buttons are used for different purpose. if (((pointer_map[0] != 1) && (pointer_map[0] != 3)) || ((pointer_map[2] != 1) && (pointer_map[2] != 3))) { std::cerr << "A non-standard button mapping detected, automatic swap may be " << "dangerous, use xmodmap to do the swap manually." << std::endl; return 3; } // Now we are good to swap. std::swap(pointer_map[0], pointer_map[2]); // Set the updated mapping. Note that XSetPointerMapping can return MappingBusy, // that indicates, that at least one of the affected buttons is currently in the // down state. Mapping is not changed in this case. for (int retries = 5; retries > 0; --retries) { int result = XSetPointerMapping(display, pointer_map, buttons_count); switch (result) { case MappingSuccess: return 0; case MappingBusy: sleep(1); continue; default: std::cerr << "Unable to set pointer mapping. XSetPointerMapping() returned " << result << std::endl; return 4; } } // If we reached this part, mapping is not set due to busy pointer button. std::cerr << "Unable to set pointer mapping. One of the affected buttons is busy." << std::endl; return 5; } <commit_msg>Put return codes in global constants.<commit_after> #include <iostream> #include <utility> #include <cstdlib> #include <X11/Xlib.h> #include <boost/scope_exit.hpp> // According to the xmodmap, there are eight bits of buttons. const unsigned kMaxButtonCodes = 256; // Define meaningful return codes so that the binary can be used in scripting. const int kSuccess = 0; const int kXOpenDisplayFailed = 1; const int kInsufficientMouseButtons = 2; const int kNonStandardButtonMapping = 3; const int kXSetPointerMappingFailed = 4; const int kMouseButtonsBusy = 5; int main() { // Define a delayed release of the display pointer. Display* display; BOOST_SCOPE_EXIT( (&display) ) { if(display) { XCloseDisplay (display); display = NULL; } } BOOST_SCOPE_EXIT_END // Get default display. display = XOpenDisplay(NULL); if (!display) { std::cerr << "Cannot open default display." << std::endl; return kXOpenDisplayFailed; } // Get current pointer mapping. unsigned char pointer_map[kMaxButtonCodes]; int buttons_count = XGetPointerMapping(display, pointer_map, kMaxButtonCodes); // We need at least three buttons to make the swap. if (buttons_count < 3) { std::cerr << "Not enough pointer buttons in the system. Need at least 3, " << "while only " << buttons_count << " are defined." << std::endl; return kInsufficientMouseButtons; } // According to some internet sources, left and right mouse buttons correspond to // codes 1 and 3 respectively. First check that physical left and right buttons // are mapped to logical left or right buttons in order not to break the behaviour // on systems where left and/or right buttons are used for different purpose. if (((pointer_map[0] != 1) && (pointer_map[0] != 3)) || ((pointer_map[2] != 1) && (pointer_map[2] != 3))) { std::cerr << "A non-standard button mapping detected, automatic swap may be " << "dangerous, use xmodmap to do the swap manually." << std::endl; return kNonStandardButtonMapping; } // Now we are good to swap. std::swap(pointer_map[0], pointer_map[2]); // Set the updated mapping. Note that XSetPointerMapping can return MappingBusy, // that indicates, that at least one of the affected buttons is currently in the // down state. Mapping is not changed in this case. for (int retries = 3; retries > 0; --retries) { int result = XSetPointerMapping(display, pointer_map, buttons_count); switch (result) { case MappingSuccess: return kSuccess; case MappingBusy: sleep(1); continue; default: std::cerr << "Unable to set pointer mapping. XSetPointerMapping() returned " << result << std::endl; return kXSetPointerMappingFailed; } } // If we reached this part, mapping is not set due to busy pointer button. std::cerr << "Unable to set pointer mapping. One of the affected buttons is busy." << std::endl; return kMouseButtonsBusy; } <|endoftext|>
<commit_before>#include "itkImage.h" #include "itkRandomImageSource.h" #include "itkGradientRecursiveGaussianImageFilter.h" #include "itkGradientMagnitudeImageFilter.h" #include "itkImageFileReader.h" #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkActor2D.h> #include <vtkSmartPointer.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkDoubleArray.h> #include <vtkPoints.h> #include <vtkPolyLine.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper2D.h> #include <opencv2/core.hpp> #include <iostream> #ifndef M_PI #define M_PI 3.14159265358979323846 /* pi */ #endif // M_PI namespace { typedef itk::Image< unsigned char, 2 > ImageType; typedef itk::Image< float, 2 > FloatImageType; typedef ImageType::IndexType IndexType; typedef itk::CovariantVector< float, 2 > OutputPixelType; typedef itk::Image< OutputPixelType, 2 > OutputImageType; typedef itk::GradientRecursiveGaussianImageFilter< FloatImageType, OutputImageType> FilterType; typedef itk::GradientMagnitudeImageFilter< ImageType, FloatImageType > GradMagfilterType; typedef itk::ImageFileReader< ImageType > ReaderType; } cv::Mat1d generateCircle( double cx, double cy, double rx, double ry, int n); void createImage(ImageType::Pointer image, int w, int h, double cx, double cy, double rx, double ry); cv::Mat1d computeP(double alpha, double beta, double gamma, double N) throw (int); cv::Mat1d sampleImage(cv::Mat1d x, cv::Mat1d y, OutputImageType::Pointer gradient, int position); vtkSmartPointer<vtkPolyData> createPolydataLine( cv::Mat1d const & v ) { // Create a vtkPoints object and store the points in it vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); for( int i = 0; i < v.rows; ++i ) { points->InsertNextPoint( v(2*i+0), v(2*i+1), 0 ); } vtkSmartPointer<vtkPolyLine> polyLine = vtkSmartPointer<vtkPolyLine>::New(); polyLine->GetPointIds()->SetNumberOfIds(v.rows); for(unsigned int i = 0; i < v.rows; i++) { polyLine->GetPointIds()->SetId(i,i); } // Create a cell array to store the lines in and add the lines to it vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); cells->InsertNextCell( polyLine ); // Create a polydata to store everything in vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); // Add the points to the dataset polyData->SetPoints(points); // Add the lines to the dataset polyData->SetLines(cells); return polyData; } int main( int argc, char* argv[] ) { //Image dimensions int w = 300; int h = 300; ImageType::Pointer image; if (argc < 7) { std::cout << "Usage " << argv[0] << " points alpha beta gamma sigma iterations [image]" << std::endl; return EXIT_SUCCESS;; } else if (argc < 8) { //Synthesize the image image = ImageType::New(); createImage(image, w, h, 150, 150, 50, 50); } else if (argc == 8) { //Open the image ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[7] ); try { reader->Update(); image = reader->GetOutput(); w = image->GetLargestPossibleRegion().GetSize()[0]; h = image->GetLargestPossibleRegion().GetSize()[1]; } catch( itk::ExceptionObject & err ) { std::cerr << "Caught unexpected exception " << err; return EXIT_FAILURE; } } //Snake parameters double alpha = 0.001; double beta = 0.4; double gamma = 100; double iterations = 1; int nPoints = 20; double sigma; nPoints = atoi(argv[1]); alpha = atof(argv[2]); beta = atof(argv[3]); gamma = atof(argv[4]); sigma = atof(argv[5]); iterations = atoi(argv[6]); //Temporal variables cv::Mat1d P; cv::Mat1d v; double N; //Generate initial snake circle v = generateCircle(130, 130, 50, 50, nPoints); vtkSmartPointer<vtkPolyData> polyData = createPolydataLine( v ); // Setup actor and mapper vtkSmartPointer<vtkPolyDataMapper2D> mapper = vtkSmartPointer<vtkPolyDataMapper2D>::New(); mapper->SetInputData(polyData); vtkSmartPointer<vtkActor2D> actor = vtkSmartPointer<vtkActor2D>::New(); actor->SetMapper(mapper); // Setup render window, renderer, and interactor vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor(actor); renderWindow->Render(); //Computes P matrix. N = v.rows/2; try { P = computeP(alpha, beta, gamma, N); } catch (int n) { return EXIT_FAILURE;; } //Computes the magnitude gradient GradMagfilterType::Pointer gradientMagnitudeFilter = GradMagfilterType::New(); gradientMagnitudeFilter->SetInput( image ); gradientMagnitudeFilter->Update(); //Computes the gradient of the gradient magnitude FilterType::Pointer gradientFilter = FilterType::New(); gradientFilter->SetInput( gradientMagnitudeFilter->GetOutput() ); gradientFilter->SetSigma( sigma ); gradientFilter->Update(); //Loop cv::Mat1d x(N,1); cv::Mat1d y(N,1); std::cout << "Initial snake" << std::endl; for (int i = 0; i < N; i++) { x(i) = v(2*i); y(i) = v(2*i+1); std::cout << "(" << x(i) << ", " << y(i) << ")" << std::endl; } for (int i = 0; i < iterations; i++) { x = (x+gamma*sampleImage(x, y, gradientFilter->GetOutput(), 0)); x = (x.t() * P).t(); y = (y+gamma*sampleImage(x, y, gradientFilter->GetOutput(), 1)); y = ( y.t() * P ).t(); } //Display the answer std::cout << "Final snake after " << iterations << " iterations" << std::endl; cv::Mat1d v2(2*N,1); for (int i=0; i<N; i++) { v2(2*i) = x(i); v2(2*i+1) = y(i); std::cout << "(" << x(i) << ", " << y(i) << ")" << std::endl; } return EXIT_SUCCESS;; } cv::Mat1d generateCircle( double cx, double cy, double rx, double ry, int n) { cv::Mat1d v(2*(n+1),1); for (int i=0; i<n; i++) { v(2*i) = cx + rx*cos(2*M_PI*i/n); v(2*i+1) = cy + ry*sin(2*M_PI*i/n); } v(2*n)=v(0); v(2*n+1)=v(1); return v; } void createImage(ImageType::Pointer image, int w, int h, double cx, double cy, double rx, double ry) { itk::Size<2> size; size[0] = w; size[1] = h; itk::RandomImageSource<ImageType>::Pointer randomImageSource = itk::RandomImageSource<ImageType>::New(); randomImageSource->SetNumberOfThreads(1); // to produce non-random results randomImageSource->SetSize(size); randomImageSource->SetMin(200); randomImageSource->SetMax(255); randomImageSource->Update(); image->SetRegions(randomImageSource->GetOutput()->GetLargestPossibleRegion()); image->Allocate(); IndexType index; //Draw oval. for (int i=0; i<w; i++) { for (int j=0; j<h; j++) { index[0] = i; index[1] = j; if ( ((i-cx)*(i-cx)/(rx*rx) + (j-cy)*(j-cy)/(ry*ry) ) < 1) { image->SetPixel(index, randomImageSource->GetOutput()->GetPixel(index)-100); } else { image->SetPixel(index, randomImageSource->GetOutput()->GetPixel(index)); } } } } cv::Mat1d computeP(double alpha, double beta, double gamma, double N) throw (int) { double a = gamma*(2*alpha+6*beta)+1; double b = gamma*(-alpha-4*beta); double c = gamma*beta; cv::Mat1d P( N, N, 0.0 ); //fill diagonal cv::Mat1d diag = P.diag(); diag.setTo( cv::Scalar( a ) ); //fill next two diagonals for (int i=0; i<(N-1); i++) { P(i+1,i) = b; P(i,i+1) = b; } //Moreover P(0, N-1)=b; P(N-1, 0)=b; //fill next two diagonals for (int i=0; i<(N-2); i++) { P(i+2,i) = c; P(i,i+2) = c; } //Moreover P(0, N-2)=c; P(1, N-1)=c; P(N-2, 0)=c; P(N-1, 1)=c; if ( cv::determinant( P ) == 0.0 ) { std::cerr << "Singular matrix. Determinant is 0." << std::endl; throw 2; } //Compute the inverse of the matrix P cv::Mat1d Pinv; Pinv = P.inv(); return Pinv.t(); } cv::Mat1d sampleImage(cv::Mat1d x, cv::Mat1d y, OutputImageType::Pointer gradient, int position) { int size; size = x.rows; cv::Mat1d ans(size,1); IndexType index; for (int i=0; i<size; i++) { index[0] = x(i); index[1] = y(i); ans(i) = gradient->GetPixel(index)[position]; } return ans; } <commit_msg>#8 Added visualization of active contours test<commit_after>#include "itkImage.h" #include "itkRandomImageSource.h" #include "itkGradientRecursiveGaussianImageFilter.h" #include "itkGradientMagnitudeImageFilter.h" #include "itkImageFileReader.h" #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkActor2D.h> #include <vtkSmartPointer.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkDoubleArray.h> #include <vtkPoints.h> #include <vtkPolyLine.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper2D.h> #include <vtkProperty2D.h> #include <vtkDataSetMapper.h> #include <vtkImageMapper.h> #include <itkImageToVTKImageFilter.h> #include <opencv2/core.hpp> #include <iostream> #ifndef M_PI #define M_PI 3.14159265358979323846 /* pi */ #endif // M_PI namespace { typedef itk::Image< unsigned char, 2 > ImageType; typedef itk::Image< float, 2 > FloatImageType; typedef ImageType::IndexType IndexType; typedef itk::CovariantVector< float, 2 > OutputPixelType; typedef itk::Image< OutputPixelType, 2 > OutputImageType; typedef itk::GradientRecursiveGaussianImageFilter< FloatImageType, OutputImageType> FilterType; typedef itk::GradientMagnitudeImageFilter< ImageType, FloatImageType > GradMagfilterType; typedef itk::ImageFileReader< ImageType > ReaderType; } cv::Mat1d generateCircle( double cx, double cy, double rx, double ry, int n); void createImage(ImageType::Pointer image, int w, int h, double cx, double cy, double rx, double ry); cv::Mat1d computeP(double alpha, double beta, double gamma, double N) throw (int); cv::Mat1d sampleImage(cv::Mat1d x, cv::Mat1d y, OutputImageType::Pointer gradient, int position); vtkSmartPointer<vtkPolyData> createPolydataLine( cv::Mat1d const & v ) { // Create a vtkPoints object and store the points in it vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); for( int i = 0; i < v.rows/2; ++i ) { points->InsertNextPoint( v(2*i+0), v(2*i+1), 0 ); } vtkSmartPointer<vtkPolyLine> polyLine = vtkSmartPointer<vtkPolyLine>::New(); polyLine->GetPointIds()->SetNumberOfIds(v.rows/2); for(unsigned int i = 0; i < v.rows/2; i++) { polyLine->GetPointIds()->SetId(i,i); } // Create a cell array to store the lines in and add the lines to it vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); cells->InsertNextCell( polyLine ); // Create a polydata to store everything in vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); // Add the points to the dataset polyData->SetPoints(points); // Add the lines to the dataset polyData->SetLines(cells); return polyData; } void updatePolydata( vtkSmartPointer<vtkPolyData> polyData, cv::Mat1d const & x, cv::Mat1d const & y ) { vtkSmartPointer<vtkPoints> points = polyData->GetPoints(); for( int i = 0; i < x.rows; ++i ) { points->SetPoint( i, x(i), y(i), 0 ); } polyData->SetPoints( points ); } int main( int argc, char* argv[] ) { //Image dimensions int w = 300; int h = 300; ImageType::Pointer image; if (argc < 7) { std::cout << "Usage " << argv[0] << " points alpha beta gamma sigma iterations [image]" << std::endl; return EXIT_SUCCESS;; } else if (argc < 8) { //Synthesize the image image = ImageType::New(); createImage(image, w, h, 150, 150, 50, 50); } else if (argc == 8) { //Open the image ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[7] ); try { reader->Update(); image = reader->GetOutput(); w = image->GetLargestPossibleRegion().GetSize()[0]; h = image->GetLargestPossibleRegion().GetSize()[1]; } catch( itk::ExceptionObject & err ) { std::cerr << "Caught unexpected exception " << err; return EXIT_FAILURE; } } //Snake parameters double alpha = 0.001; double beta = 0.4; double gamma = 100; double iterations = 1; int nPoints = 20; double sigma; nPoints = atoi(argv[1]); alpha = atof(argv[2]); beta = atof(argv[3]); gamma = atof(argv[4]); sigma = atof(argv[5]); iterations = atoi(argv[6]); //Temporal variables cv::Mat1d P; cv::Mat1d v; double N; //Generate initial snake circle v = generateCircle(130, 130, 50, 50, nPoints); vtkSmartPointer<vtkPolyData> polyData = createPolydataLine( v ); // Setup actor and mapper vtkSmartPointer<vtkPolyDataMapper2D> mapper = vtkSmartPointer<vtkPolyDataMapper2D>::New(); mapper->SetInputData(polyData); vtkSmartPointer<vtkActor2D> actor = vtkSmartPointer<vtkActor2D>::New(); actor->SetMapper(mapper); actor->GetProperty()->SetColor( 1.0, 0.0, 0.0 ); actor->GetProperty()->SetLineWidth( 3 ); typedef itk::ImageToVTKImageFilter<ImageType> ConnectorType; ConnectorType::Pointer connector = ConnectorType::New(); connector->SetInput(image); connector->Update(); vtkSmartPointer<vtkImageData> imageData = vtkSmartPointer<vtkImageData>::New(); imageData->DeepCopy(connector->GetOutput()); vtkSmartPointer<vtkImageMapper> imageMapper = vtkSmartPointer<vtkImageMapper>::New(); imageMapper->SetColorLevel(225); imageMapper->SetColorWindow( 100 ); imageMapper->SetInputData( imageData ); vtkSmartPointer<vtkActor2D> imageActor = vtkSmartPointer<vtkActor2D>::New(); imageActor->SetMapper(imageMapper); // Setup render window, renderer, and interactor vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor(imageActor); renderer->AddActor(actor); renderWindow->Render(); //Computes P matrix. N = v.rows/2; try { P = computeP(alpha, beta, gamma, N); } catch (int n) { return EXIT_FAILURE;; } //Computes the magnitude gradient GradMagfilterType::Pointer gradientMagnitudeFilter = GradMagfilterType::New(); gradientMagnitudeFilter->SetInput( image ); gradientMagnitudeFilter->Update(); //Computes the gradient of the gradient magnitude FilterType::Pointer gradientFilter = FilterType::New(); gradientFilter->SetInput( gradientMagnitudeFilter->GetOutput() ); gradientFilter->SetSigma( sigma ); gradientFilter->Update(); //Loop cv::Mat1d x(N,1); cv::Mat1d y(N,1); std::cout << "Initial snake" << std::endl; for (int i = 0; i < N; i++) { x(i) = v(2*i); y(i) = v(2*i+1); } for (int i = 0; i < iterations; i++) { x = (x+gamma*sampleImage(x, y, gradientFilter->GetOutput(), 0)); x = (x.t() * P).t(); y = (y+gamma*sampleImage(x, y, gradientFilter->GetOutput(), 1)); y = (y.t() * P).t(); std::cout << "(" << x(0) << ", " << y(0) << ")" << std::endl; updatePolydata( polyData, x, y ); polyData->Modified(); mapper->Modified(); renderer->Modified(); if( i % 10 == 0 ) renderWindow->Render(); } return EXIT_SUCCESS;; } cv::Mat1d generateCircle( double cx, double cy, double rx, double ry, int n) { cv::Mat1d v(2*(n+1),1); for (int i=0; i<n; i++) { v(2*i+0) = cx + rx*cos(2*M_PI*i/n); v(2*i+1) = cy + ry*sin(2*M_PI*i/n); } v(2*n)=v(0); v(2*n+1)=v(1); return v; } void createImage(ImageType::Pointer image, int w, int h, double cx, double cy, double rx, double ry) { itk::Size<2> size; size[0] = w; size[1] = h; itk::RandomImageSource<ImageType>::Pointer randomImageSource = itk::RandomImageSource<ImageType>::New(); randomImageSource->SetNumberOfThreads(1); // to produce non-random results randomImageSource->SetSize(size); randomImageSource->SetMin(200); randomImageSource->SetMax(255); randomImageSource->Update(); image->SetRegions(randomImageSource->GetOutput()->GetLargestPossibleRegion()); image->Allocate(); IndexType index; //Draw oval. for (int i=0; i<w; i++) { for (int j=0; j<h; j++) { index[0] = i; index[1] = j; if ( ((i-cx)*(i-cx)/(rx*rx) + (j-cy)*(j-cy)/(ry*ry) ) < 1) { image->SetPixel(index, randomImageSource->GetOutput()->GetPixel(index)-100); } else { image->SetPixel(index, randomImageSource->GetOutput()->GetPixel(index)); } } } } cv::Mat1d computeP(double alpha, double beta, double gamma, double N) throw (int) { double a = gamma*(2*alpha+6*beta)+1; double b = gamma*(-alpha-4*beta); double c = gamma*beta; cv::Mat1d P( N, N, 0.0 ); //fill diagonal cv::Mat1d diag = P.diag(); diag.setTo( cv::Scalar( a ) ); //fill next two diagonals for (int i=0; i<(N-1); i++) { P(i+1,i) = b; P(i,i+1) = b; } //Moreover P(0, N-1)=b; P(N-1, 0)=b; //fill next two diagonals for (int i=0; i<(N-2); i++) { P(i+2,i) = c; P(i,i+2) = c; } //Moreover P(0, N-2)=c; P(1, N-1)=c; P(N-2, 0)=c; P(N-1, 1)=c; if ( cv::determinant( P ) == 0.0 ) { std::cerr << "Singular matrix. Determinant is 0." << std::endl; throw 2; } //Compute the inverse of the matrix P cv::Mat1d Pinv; Pinv = P.inv(); return Pinv.t(); } cv::Mat1d sampleImage(cv::Mat1d x, cv::Mat1d y, OutputImageType::Pointer gradient, int position) { int size; size = x.rows; cv::Mat1d ans(size,1); IndexType index; for (int i=0; i<size; i++) { index[0] = x(i); index[1] = y(i); ans(i) = gradient->GetPixel(index)[position]; } return ans; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2014 Kajetan Swierk <k0zmo@outlook.com> * * 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. * */ #if defined(HAVE_OPENCL) #include "GpuNode.h" #include "Logic/NodeFactory.h" class GpuUploadImageNodeType : public GpuNodeType { public: GpuUploadImageNodeType() : _usePinnedMemory(false) { addInput("Host image", ENodeFlowDataType::Image); addOutput("Device image", ENodeFlowDataType::DeviceImage); addProperty("Use pinned memory", _usePinnedMemory); setDescription("Uploads given image from host to device (GPU) memory"); setModule("opencl"); } bool postInit() override { _kidConvertBufferRgbToImageRgba = _gpuComputeModule->registerKernel("convertBufferRgbToImageRgba", "color.cl"); return _kidConvertBufferRgbToImageRgba != InvalidKernelID; } ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override { const cv::Mat& hostImage = reader.readSocket(0).getImage(); clw::Image2D& deviceImage = writer.acquireSocket(0).getDeviceImage(); if(hostImage.channels() != 1 && hostImage.channels() != 3) return ExecutionStatus(EStatus::Error, "Invalid number of channels (should be 1 or 3)"); if(deviceImage.isNull() || deviceImage.width() != hostImage.cols || deviceImage.height() != hostImage.rows || deviceImage.bytesPerElement() != hostImage.channels()) { clw::EChannelOrder channelOrder = hostImage.channels() == 1 ? clw::EChannelOrder::R : clw::EChannelOrder::RGBA; deviceImage = _gpuComputeModule->context().createImage2D( clw::EAccess::ReadOnly, clw::EMemoryLocation::Device, clw::ImageFormat(channelOrder, clw::EChannelType::Normalized_UInt8), hostImage.cols, hostImage.rows); } if(_usePinnedMemory) { size_t pinnedBufferSize = hostImage.cols * hostImage.rows * hostImage.channels() * sizeof(uchar); if(_pinnedBuffer.isNull() || pinnedBufferSize != _pinnedBuffer.size()) { _pinnedBuffer = _gpuComputeModule->context().createBuffer(clw::EAccess::ReadOnly, clw::EMemoryLocation::AllocHostMemory, pinnedBufferSize); } } if(hostImage.channels() == 1) { if(!_usePinnedMemory) { // Simple copy will suffice bool result = _gpuComputeModule->queue().writeImage2D(deviceImage, hostImage.data, clw::Rect(0, 0, hostImage.cols, hostImage.rows), static_cast<int>(hostImage.step)); return ExecutionStatus(result ? EStatus::Ok : EStatus::Error); } else { if(!copyToPinnedBufferAsync(hostImage)) return ExecutionStatus(EStatus::Error, "Couldn't mapped pinned memory for device image transfer"); _gpuComputeModule->queue().asyncCopyBufferToImage(_pinnedBuffer, deviceImage); return ExecutionStatus(EStatus::Ok); } } else { // Copy to intermediate buffer (BGR) and run kernel to convert it to RGBA image clw::Kernel kernelConvertBufferRgbToImageRgba = _gpuComputeModule->acquireKernel(_kidConvertBufferRgbToImageRgba); int intermediateBufferPitch = hostImage.cols * hostImage.channels() * sizeof(uchar); int intermediateBufferSize = intermediateBufferPitch * hostImage.rows; if(_intermediateBuffer.isNull() || _intermediateBuffer.size() != intermediateBufferSize) { _intermediateBuffer = _gpuComputeModule->context().createBuffer(clw::EAccess::ReadOnly, clw::EMemoryLocation::Device, intermediateBufferSize); } if(!_usePinnedMemory) { _gpuComputeModule->queue().asyncWriteBuffer(_intermediateBuffer, hostImage.data); } else { if(!copyToPinnedBufferAsync(hostImage)) return ExecutionStatus(EStatus::Error, "Couldn't mapped pinned memory for device image transfer"); _gpuComputeModule->queue().asyncCopyBuffer(_pinnedBuffer, _intermediateBuffer); } kernelConvertBufferRgbToImageRgba.setLocalWorkSize(16, 16); kernelConvertBufferRgbToImageRgba.setRoundedGlobalWorkSize(hostImage.cols, hostImage.rows); kernelConvertBufferRgbToImageRgba.setArg(0, _intermediateBuffer); kernelConvertBufferRgbToImageRgba.setArg(1, intermediateBufferPitch); kernelConvertBufferRgbToImageRgba.setArg(2, deviceImage); _gpuComputeModule->queue().asyncRunKernel(kernelConvertBufferRgbToImageRgba); // FIXME: this causes stall and makes pinned memory pretty useless _gpuComputeModule->queue().finish(); return ExecutionStatus(EStatus::Ok); } } private: bool copyToPinnedBufferAsync(const cv::Mat& hostImage) { void* ptr = _gpuComputeModule->queue().mapBuffer(_pinnedBuffer, clw::EMapAccess::Write); if(!ptr) return false; if((int) hostImage.step != hostImage.cols) { for(int row = 0; row < hostImage.rows; ++row) memcpy((uchar*)ptr + row*hostImage.step, (uchar*)hostImage.data + row*hostImage.step, hostImage.step); } else { memcpy(ptr, hostImage.data, hostImage.step * hostImage.rows); } _gpuComputeModule->queue().asyncUnmap(_pinnedBuffer, ptr); return true; } private: clw::Buffer _pinnedBuffer; clw::Buffer _intermediateBuffer; KernelID _kidConvertBufferRgbToImageRgba; TypedNodeProperty<bool> _usePinnedMemory; }; class GpuDownloadImageNodeType : public GpuNodeType { public: GpuDownloadImageNodeType() : _usePinnedMemory(false) { addInput("Device image", ENodeFlowDataType::DeviceImage); addOutput("Host image", ENodeFlowDataType::Image); addProperty("Use pinned memory", _usePinnedMemory); setDescription("Download given image device (GPU) to host memory"); setModule("opencl"); } bool postInit() override { _kidConvertImageRgbaToBufferRgb = _gpuComputeModule->registerKernel("convertImageRgbaToBufferRgb", "color.cl"); return _kidConvertImageRgbaToBufferRgb != InvalidKernelID; } ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override { const clw::Image2D& deviceImage = reader.readSocket(0).getDeviceImage(); cv::Mat& hostImage = writer.acquireSocket(0).getImage(); if(deviceImage.isNull() || deviceImage.size() == 0) return ExecutionStatus(EStatus::Ok); clw::ImageFormat imageFormat = deviceImage.format(); if(imageFormat.order != clw::EChannelOrder::R && imageFormat.order != clw::EChannelOrder::RGBA) return ExecutionStatus(EStatus::Error, "Wrong data type (should be one or four channel device image)"); int width = deviceImage.width(); int height = deviceImage.height(); int channels = imageFormat.order == clw::EChannelOrder::R ? 1 : 3; hostImage.create(height, width, CV_MAKETYPE(CV_8U, channels)); if(_usePinnedMemory) { size_t pinnedBufferSize = hostImage.cols * hostImage.rows * hostImage.channels() * sizeof(uchar); if(_pinnedBuffer.isNull() || pinnedBufferSize != _pinnedBuffer.size()) { _pinnedBuffer = _gpuComputeModule->context().createBuffer(clw::EAccess::ReadOnly, clw::EMemoryLocation::AllocHostMemory, pinnedBufferSize); } } if(channels == 1) { if(!_usePinnedMemory) { // Simple copy will suffice bool res = _gpuComputeModule->queue().readImage2D(deviceImage, hostImage.data, clw::Rect(0, 0, hostImage.cols, hostImage.rows), static_cast<int>(hostImage.step)); return ExecutionStatus(res ? EStatus::Ok : EStatus::Error); } else { _gpuComputeModule->queue().asyncCopyImageToBuffer(deviceImage, _pinnedBuffer); if(!copyFromPinnedBufferAsync(hostImage)) return ExecutionStatus(EStatus::Error, "Couldn't mapped pinned memory for device image transfer"); return ExecutionStatus(EStatus::Ok); } } else { // Convert image RGBA to intermediate buffer (BGR) and copy it to host image clw::Kernel kernelConvertImageRgbaToBufferRgb = _gpuComputeModule->acquireKernel(_kidConvertImageRgbaToBufferRgb); int intermediateBufferPitch = hostImage.cols * hostImage.channels() * sizeof(uchar); int intermediateBufferSize = intermediateBufferPitch * hostImage.rows; if(_intermediateBuffer.isNull() || _intermediateBuffer.size() != intermediateBufferSize) { _intermediateBuffer = _gpuComputeModule->context().createBuffer(clw::EAccess::WriteOnly, clw::EMemoryLocation::Device, intermediateBufferSize); } kernelConvertImageRgbaToBufferRgb.setLocalWorkSize(16, 16); kernelConvertImageRgbaToBufferRgb.setRoundedGlobalWorkSize(hostImage.cols, hostImage.rows); kernelConvertImageRgbaToBufferRgb.setArg(0, deviceImage); kernelConvertImageRgbaToBufferRgb.setArg(1, _intermediateBuffer); kernelConvertImageRgbaToBufferRgb.setArg(2, intermediateBufferPitch); _gpuComputeModule->queue().asyncRunKernel(kernelConvertImageRgbaToBufferRgb); if(!_usePinnedMemory) { _gpuComputeModule->queue().asyncReadBuffer(_intermediateBuffer, hostImage.data); } else { _gpuComputeModule->queue().asyncCopyBuffer(_intermediateBuffer, _pinnedBuffer); if(!copyFromPinnedBufferAsync(hostImage)) return ExecutionStatus(EStatus::Error, "Couldn't mapped pinned memory for device image transfer"); } // FIXME: this causes stall and makes pinned memory pretty useless _gpuComputeModule->queue().finish(); return ExecutionStatus(EStatus::Ok); } } private: bool copyFromPinnedBufferAsync(cv::Mat& hostImage) { void* ptr = _gpuComputeModule->queue().mapBuffer(_pinnedBuffer, clw::EMapAccess::Read); if(!ptr) return false; if((int) hostImage.step != hostImage.cols) { for(int row = 0; row < hostImage.rows; ++row) memcpy((uchar*)hostImage.data + row*hostImage.step, (uchar*)ptr + row*hostImage.step, hostImage.step); } else { memcpy(hostImage.data, ptr, hostImage.step * hostImage.rows); } // Unmapping device memory when reading is practically 'no-cost' _gpuComputeModule->queue().asyncUnmap(_pinnedBuffer, ptr); return true; } private: clw::Buffer _pinnedBuffer; clw::Buffer _intermediateBuffer; KernelID _kidConvertImageRgbaToBufferRgb; TypedNodeProperty<bool> _usePinnedMemory; }; class GpuUploadArrayNodeType : public GpuNodeType { public: GpuUploadArrayNodeType() { addInput("Host array", ENodeFlowDataType::Array); addOutput("Device array", ENodeFlowDataType::DeviceArray); setDescription("Uploads given array from host to device (GPU) memory"); setModule("opencl"); } ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override { const cv::Mat& hostArray = reader.readSocket(0).getArray(); DeviceArray& deviceArray = writer.acquireSocket(0).getDeviceArray(); if(hostArray.empty()) return ExecutionStatus(EStatus::Ok); deviceArray = DeviceArray::create(_gpuComputeModule->context(), clw::EAccess::ReadWrite, clw::EMemoryLocation::Device, hostArray.cols, hostArray.rows, DeviceArray::matToDeviceType(hostArray.type())); clw::Event evt = deviceArray.upload(_gpuComputeModule->queue(), hostArray.data); evt.waitForFinished(); return ExecutionStatus(EStatus::Ok); } }; class GpuDownloadArrayNodeType : public GpuNodeType { public: GpuDownloadArrayNodeType() { addInput("Device array", ENodeFlowDataType::DeviceArray); addOutput("Host array", ENodeFlowDataType::Array); setDescription("Download given array device (GPU) to host memory"); setModule("opencl"); } ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override { const DeviceArray& deviceArray = reader.readSocket(0).getDeviceArray(); cv::Mat& hostArray = writer.acquireSocket(0).getArray(); if(deviceArray.isNull() || deviceArray.size() == 0) return ExecutionStatus(EStatus::Ok); clw::Event evt = deviceArray.download(_gpuComputeModule->queue(), hostArray); evt.waitForFinished(); return ExecutionStatus(EStatus::Ok); } }; REGISTER_NODE("OpenCL/Download array", GpuDownloadArrayNodeType) REGISTER_NODE("OpenCL/Upload array", GpuUploadArrayNodeType) REGISTER_NODE("OpenCL/Download image", GpuDownloadImageNodeType) REGISTER_NODE("OpenCL/Upload image", GpuUploadImageNodeType) #endif <commit_msg>dont recreate opencl image on every execute step<commit_after>/* * Copyright (c) 2013-2014 Kajetan Swierk <k0zmo@outlook.com> * * 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. * */ #if defined(HAVE_OPENCL) #include "GpuNode.h" #include "Logic/NodeFactory.h" class GpuUploadImageNodeType : public GpuNodeType { public: GpuUploadImageNodeType() : _usePinnedMemory(false) { addInput("Host image", ENodeFlowDataType::Image); addOutput("Device image", ENodeFlowDataType::DeviceImage); addProperty("Use pinned memory", _usePinnedMemory); setDescription("Uploads given image from host to device (GPU) memory"); setModule("opencl"); } bool postInit() override { _kidConvertBufferRgbToImageRgba = _gpuComputeModule->registerKernel("convertBufferRgbToImageRgba", "color.cl"); return _kidConvertBufferRgbToImageRgba != InvalidKernelID; } ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override { const cv::Mat& hostImage = reader.readSocket(0).getImage(); clw::Image2D& deviceImage = writer.acquireSocket(0).getDeviceImage(); if(hostImage.channels() != 1 && hostImage.channels() != 3) return ExecutionStatus(EStatus::Error, "Invalid number of channels (should be 1 or 3)"); auto devChannels = [](clw::Image2D& image) { // Make 4 bytes per elem 3-channel image, otherwise its ok return image.bytesPerElement() == 4 ? 3 : image.bytesPerElement(); }; if(deviceImage.isNull() || deviceImage.width() != hostImage.cols || deviceImage.height() != hostImage.rows || devChannels(deviceImage) != hostImage.channels()) { clw::EChannelOrder channelOrder = hostImage.channels() == 1 ? clw::EChannelOrder::R : clw::EChannelOrder::RGBA; deviceImage = _gpuComputeModule->context().createImage2D( clw::EAccess::ReadOnly, clw::EMemoryLocation::Device, clw::ImageFormat(channelOrder, clw::EChannelType::Normalized_UInt8), hostImage.cols, hostImage.rows); } if(_usePinnedMemory) { size_t pinnedBufferSize = hostImage.cols * hostImage.rows * hostImage.channels() * sizeof(uchar); if(_pinnedBuffer.isNull() || pinnedBufferSize != _pinnedBuffer.size()) { _pinnedBuffer = _gpuComputeModule->context().createBuffer(clw::EAccess::ReadOnly, clw::EMemoryLocation::AllocHostMemory, pinnedBufferSize); } } if(hostImage.channels() == 1) { if(!_usePinnedMemory) { // Simple copy will suffice bool result = _gpuComputeModule->queue().writeImage2D(deviceImage, hostImage.data, clw::Rect(0, 0, hostImage.cols, hostImage.rows), static_cast<int>(hostImage.step)); return ExecutionStatus(result ? EStatus::Ok : EStatus::Error); } else { if(!copyToPinnedBufferAsync(hostImage)) return ExecutionStatus(EStatus::Error, "Couldn't mapped pinned memory for device image transfer"); _gpuComputeModule->queue().asyncCopyBufferToImage(_pinnedBuffer, deviceImage); return ExecutionStatus(EStatus::Ok); } } else { // Copy to intermediate buffer (BGR) and run kernel to convert it to RGBA image clw::Kernel kernelConvertBufferRgbToImageRgba = _gpuComputeModule->acquireKernel(_kidConvertBufferRgbToImageRgba); int intermediateBufferPitch = hostImage.cols * hostImage.channels() * sizeof(uchar); int intermediateBufferSize = intermediateBufferPitch * hostImage.rows; if(_intermediateBuffer.isNull() || _intermediateBuffer.size() != intermediateBufferSize) { _intermediateBuffer = _gpuComputeModule->context().createBuffer(clw::EAccess::ReadOnly, clw::EMemoryLocation::Device, intermediateBufferSize); } if(!_usePinnedMemory) { _gpuComputeModule->queue().asyncWriteBuffer(_intermediateBuffer, hostImage.data); } else { if(!copyToPinnedBufferAsync(hostImage)) return ExecutionStatus(EStatus::Error, "Couldn't mapped pinned memory for device image transfer"); _gpuComputeModule->queue().asyncCopyBuffer(_pinnedBuffer, _intermediateBuffer); } kernelConvertBufferRgbToImageRgba.setLocalWorkSize(16, 16); kernelConvertBufferRgbToImageRgba.setRoundedGlobalWorkSize(hostImage.cols, hostImage.rows); kernelConvertBufferRgbToImageRgba.setArg(0, _intermediateBuffer); kernelConvertBufferRgbToImageRgba.setArg(1, intermediateBufferPitch); kernelConvertBufferRgbToImageRgba.setArg(2, deviceImage); _gpuComputeModule->queue().asyncRunKernel(kernelConvertBufferRgbToImageRgba); // FIXME: this causes stall and makes pinned memory pretty useless _gpuComputeModule->queue().finish(); return ExecutionStatus(EStatus::Ok); } } private: bool copyToPinnedBufferAsync(const cv::Mat& hostImage) { void* ptr = _gpuComputeModule->queue().mapBuffer(_pinnedBuffer, clw::EMapAccess::Write); if(!ptr) return false; if((int) hostImage.step != hostImage.cols) { for(int row = 0; row < hostImage.rows; ++row) memcpy((uchar*)ptr + row*hostImage.step, (uchar*)hostImage.data + row*hostImage.step, hostImage.step); } else { memcpy(ptr, hostImage.data, hostImage.step * hostImage.rows); } _gpuComputeModule->queue().asyncUnmap(_pinnedBuffer, ptr); return true; } private: clw::Buffer _pinnedBuffer; clw::Buffer _intermediateBuffer; KernelID _kidConvertBufferRgbToImageRgba; TypedNodeProperty<bool> _usePinnedMemory; }; class GpuDownloadImageNodeType : public GpuNodeType { public: GpuDownloadImageNodeType() : _usePinnedMemory(false) { addInput("Device image", ENodeFlowDataType::DeviceImage); addOutput("Host image", ENodeFlowDataType::Image); addProperty("Use pinned memory", _usePinnedMemory); setDescription("Download given image device (GPU) to host memory"); setModule("opencl"); } bool postInit() override { _kidConvertImageRgbaToBufferRgb = _gpuComputeModule->registerKernel("convertImageRgbaToBufferRgb", "color.cl"); return _kidConvertImageRgbaToBufferRgb != InvalidKernelID; } ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override { const clw::Image2D& deviceImage = reader.readSocket(0).getDeviceImage(); cv::Mat& hostImage = writer.acquireSocket(0).getImage(); if(deviceImage.isNull() || deviceImage.size() == 0) return ExecutionStatus(EStatus::Ok); clw::ImageFormat imageFormat = deviceImage.format(); if(imageFormat.order != clw::EChannelOrder::R && imageFormat.order != clw::EChannelOrder::RGBA) return ExecutionStatus(EStatus::Error, "Wrong data type (should be one or four channel device image)"); int width = deviceImage.width(); int height = deviceImage.height(); int channels = imageFormat.order == clw::EChannelOrder::R ? 1 : 3; hostImage.create(height, width, CV_MAKETYPE(CV_8U, channels)); if(_usePinnedMemory) { size_t pinnedBufferSize = hostImage.cols * hostImage.rows * hostImage.channels() * sizeof(uchar); if(_pinnedBuffer.isNull() || pinnedBufferSize != _pinnedBuffer.size()) { _pinnedBuffer = _gpuComputeModule->context().createBuffer(clw::EAccess::ReadOnly, clw::EMemoryLocation::AllocHostMemory, pinnedBufferSize); } } if(channels == 1) { if(!_usePinnedMemory) { // Simple copy will suffice bool res = _gpuComputeModule->queue().readImage2D(deviceImage, hostImage.data, clw::Rect(0, 0, hostImage.cols, hostImage.rows), static_cast<int>(hostImage.step)); return ExecutionStatus(res ? EStatus::Ok : EStatus::Error); } else { _gpuComputeModule->queue().asyncCopyImageToBuffer(deviceImage, _pinnedBuffer); if(!copyFromPinnedBufferAsync(hostImage)) return ExecutionStatus(EStatus::Error, "Couldn't mapped pinned memory for device image transfer"); return ExecutionStatus(EStatus::Ok); } } else { // Convert image RGBA to intermediate buffer (BGR) and copy it to host image clw::Kernel kernelConvertImageRgbaToBufferRgb = _gpuComputeModule->acquireKernel(_kidConvertImageRgbaToBufferRgb); int intermediateBufferPitch = hostImage.cols * hostImage.channels() * sizeof(uchar); int intermediateBufferSize = intermediateBufferPitch * hostImage.rows; if(_intermediateBuffer.isNull() || _intermediateBuffer.size() != intermediateBufferSize) { _intermediateBuffer = _gpuComputeModule->context().createBuffer(clw::EAccess::WriteOnly, clw::EMemoryLocation::Device, intermediateBufferSize); } kernelConvertImageRgbaToBufferRgb.setLocalWorkSize(16, 16); kernelConvertImageRgbaToBufferRgb.setRoundedGlobalWorkSize(hostImage.cols, hostImage.rows); kernelConvertImageRgbaToBufferRgb.setArg(0, deviceImage); kernelConvertImageRgbaToBufferRgb.setArg(1, _intermediateBuffer); kernelConvertImageRgbaToBufferRgb.setArg(2, intermediateBufferPitch); _gpuComputeModule->queue().asyncRunKernel(kernelConvertImageRgbaToBufferRgb); if(!_usePinnedMemory) { _gpuComputeModule->queue().asyncReadBuffer(_intermediateBuffer, hostImage.data); } else { _gpuComputeModule->queue().asyncCopyBuffer(_intermediateBuffer, _pinnedBuffer); if(!copyFromPinnedBufferAsync(hostImage)) return ExecutionStatus(EStatus::Error, "Couldn't mapped pinned memory for device image transfer"); } // FIXME: this causes stall and makes pinned memory pretty useless _gpuComputeModule->queue().finish(); return ExecutionStatus(EStatus::Ok); } } private: bool copyFromPinnedBufferAsync(cv::Mat& hostImage) { void* ptr = _gpuComputeModule->queue().mapBuffer(_pinnedBuffer, clw::EMapAccess::Read); if(!ptr) return false; if((int) hostImage.step != hostImage.cols) { for(int row = 0; row < hostImage.rows; ++row) memcpy((uchar*)hostImage.data + row*hostImage.step, (uchar*)ptr + row*hostImage.step, hostImage.step); } else { memcpy(hostImage.data, ptr, hostImage.step * hostImage.rows); } // Unmapping device memory when reading is practically 'no-cost' _gpuComputeModule->queue().asyncUnmap(_pinnedBuffer, ptr); return true; } private: clw::Buffer _pinnedBuffer; clw::Buffer _intermediateBuffer; KernelID _kidConvertImageRgbaToBufferRgb; TypedNodeProperty<bool> _usePinnedMemory; }; class GpuUploadArrayNodeType : public GpuNodeType { public: GpuUploadArrayNodeType() { addInput("Host array", ENodeFlowDataType::Array); addOutput("Device array", ENodeFlowDataType::DeviceArray); setDescription("Uploads given array from host to device (GPU) memory"); setModule("opencl"); } ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override { const cv::Mat& hostArray = reader.readSocket(0).getArray(); DeviceArray& deviceArray = writer.acquireSocket(0).getDeviceArray(); if(hostArray.empty()) return ExecutionStatus(EStatus::Ok); deviceArray = DeviceArray::create(_gpuComputeModule->context(), clw::EAccess::ReadWrite, clw::EMemoryLocation::Device, hostArray.cols, hostArray.rows, DeviceArray::matToDeviceType(hostArray.type())); clw::Event evt = deviceArray.upload(_gpuComputeModule->queue(), hostArray.data); evt.waitForFinished(); return ExecutionStatus(EStatus::Ok); } }; class GpuDownloadArrayNodeType : public GpuNodeType { public: GpuDownloadArrayNodeType() { addInput("Device array", ENodeFlowDataType::DeviceArray); addOutput("Host array", ENodeFlowDataType::Array); setDescription("Download given array device (GPU) to host memory"); setModule("opencl"); } ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override { const DeviceArray& deviceArray = reader.readSocket(0).getDeviceArray(); cv::Mat& hostArray = writer.acquireSocket(0).getArray(); if(deviceArray.isNull() || deviceArray.size() == 0) return ExecutionStatus(EStatus::Ok); clw::Event evt = deviceArray.download(_gpuComputeModule->queue(), hostArray); evt.waitForFinished(); return ExecutionStatus(EStatus::Ok); } }; REGISTER_NODE("OpenCL/Download array", GpuDownloadArrayNodeType) REGISTER_NODE("OpenCL/Upload array", GpuUploadArrayNodeType) REGISTER_NODE("OpenCL/Download image", GpuDownloadImageNodeType) REGISTER_NODE("OpenCL/Upload image", GpuUploadImageNodeType) #endif <|endoftext|>
<commit_before>#include <catch.hpp> #include "../coap-decoder.h" #include "test-data.h" //#include "../mc/pipeline.h" using namespace moducom::coap; using namespace moducom::pipeline; TEST_CASE("CoAP decoder tests", "[coap-decoder]") { //layer3::MemoryChunk<1024> buffer_in; //buffer_in.memcpy(buffer_16bit_delta, sizeof(buffer_16bit_delta)); MemoryChunk::readonly_t buffer_in(buffer_16bit_delta); layer3::SimpleBufferedPipeline net_in(buffer_in); SECTION("Basic test 1") { OptionDecoder decoder; OptionDecoder::OptionExperimental option; // pretty much ready to TRY testing, just need to load in appropriate data into buffer_in //decoder.process_iterate(net_in, &option); } SECTION("Payload only test") { Decoder decoder; MemoryChunk::readonly_t chunk(buffer_payload_only); // FIX: not quite handling payload-only correctly yet decoder.process(chunk); } }<commit_msg>Building out proper unit test for payload-only processing<commit_after>#include <catch.hpp> #include "../coap-decoder.h" #include "test-data.h" //#include "../mc/pipeline.h" using namespace moducom::coap; using namespace moducom::pipeline; TEST_CASE("CoAP decoder tests", "[coap-decoder]") { //layer3::MemoryChunk<1024> buffer_in; //buffer_in.memcpy(buffer_16bit_delta, sizeof(buffer_16bit_delta)); MemoryChunk::readonly_t buffer_in(buffer_16bit_delta); layer3::SimpleBufferedPipeline net_in(buffer_in); SECTION("Basic test 1") { OptionDecoder decoder; OptionDecoder::OptionExperimental option; // pretty much ready to TRY testing, just need to load in appropriate data into buffer_in //decoder.process_iterate(net_in, &option); } SECTION("Payload only test") { Decoder decoder; MemoryChunk::readonly_t chunk(buffer_payload_only); Decoder::Context context(chunk, true); REQUIRE(decoder.process_iterate(context) == false); REQUIRE(decoder.state() == Decoder::Header); REQUIRE(decoder.process_iterate(context) == false); REQUIRE(decoder.state() == Decoder::HeaderDone); REQUIRE(decoder.process_iterate(context) == false); REQUIRE(decoder.state() == Decoder::OptionsStart); REQUIRE(decoder.process_iterate(context) == false); // FIX: Really shouldn't have an Options stage with an overall // decoder if no options present. This may be a case where a little // code overlap is desired - just because OptionsDecoder *can* detect // payload marker doesn't need we *should* utilize it, though reuse // dictates we must consider it REQUIRE(decoder.state() == Decoder::Options); // FIX: in any case, we shouldn't be done with the buffer at this point, // so failing unit test here is a bug REQUIRE(decoder.process_iterate(context) == false); REQUIRE(decoder.state() == Decoder::OptionsDone); REQUIRE(decoder.process_iterate(context) == true); REQUIRE(decoder.state() == Decoder::Payload); } }<|endoftext|>
<commit_before>// Copyright 2010 Google Inc. All Rights Reserved. // Author: jacobsa@google.com (Aaron Jacobs) // // 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 <gmock/gmock.h> #include <gtest/gtest.h> #include <v8.h> #include "gjstest/internal/cpp/v8_utils.h" #include "base/callback.h" #include "base/integral_types.h" #include "base/logging.h" #include "base/macros.h" using testing::ContainsRegex; using testing::ElementsAre; using testing::HasSubstr; using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::Handle; using v8::HandleScope; using v8::Integer; using v8::Isolate; using v8::Local; using v8::Number; using v8::ObjectTemplate; using v8::Persistent; using v8::String; using v8::TryCatch; using v8::Value; namespace gjstest { // A test case that automatically creates and enters a context before the test // body. Subclasses should set any properties they want globally exposed through // the context on the the object template before calling V8UtilsTest::SetUp. class V8UtilsTest : public ::testing::Test { protected: V8UtilsTest() : handle_scope_(CHECK_NOTNULL(Isolate::GetCurrent())), global_template_(ObjectTemplate::New()), context_( Context::New( CHECK_NOTNULL(Isolate::GetCurrent()), NULL, // No extensions global_template_)), context_scope_(context_) { } const HandleScope handle_scope_; const Handle<ObjectTemplate> global_template_; const Handle<Context> context_; const Context::Scope context_scope_; }; //////////////////////////////////////////////////////////////////////// // ConvertToString //////////////////////////////////////////////////////////////////////// typedef V8UtilsTest ConvertToStringTest; TEST_F(ConvertToStringTest, Empty) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_EQ("", ConvertToString(Local<Value>())); } TEST_F(ConvertToStringTest, Strings) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_EQ("", ConvertToString(String::New(""))); EXPECT_EQ("taco", ConvertToString(String::New("taco"))); const uint16 kUtf16Chars[] = { 0xd0c0, 0xcf54 }; EXPECT_EQ("타코", ConvertToString(String::New(kUtf16Chars, 2))); } TEST_F(ConvertToStringTest, Numbers) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_EQ("-3", ConvertToString(Number::New(-3))); EXPECT_EQ("4", ConvertToString(Number::New(4))); EXPECT_EQ("3.14", ConvertToString(Number::New(3.14))); } //////////////////////////////////////////////////////////////////////// // ExecuteJs //////////////////////////////////////////////////////////////////////// typedef V8UtilsTest ExecuteJsTest; static std::string GetResultAsString( const std::string& js, std::string filename = "") { return ConvertToString(ExecuteJs(js, filename)); } TEST_F(ConvertToStringTest, EmptyString) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_EQ("undefined", GetResultAsString("")); } TEST_F(ConvertToStringTest, BadSyntax) { HandleScope handle_owner(Isolate::GetCurrent()); const Local<Value> result = ExecuteJs("(2", ""); EXPECT_TRUE(result.IsEmpty()); } TEST_F(ConvertToStringTest, SingleValue) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_EQ("2", GetResultAsString("2")); EXPECT_EQ("foo", GetResultAsString("'foo'")); } TEST_F(ConvertToStringTest, FunctionReturnValue) { HandleScope handle_owner(Isolate::GetCurrent()); const std::string js = "var addTwo = function(a, b) { return a + b; };\n" "addTwo(2, 3)"; EXPECT_EQ("5", GetResultAsString(js)); } TEST_F(ConvertToStringTest, StackWithFilename) { HandleScope handle_owner(Isolate::GetCurrent()); const std::string js = "2+2\n" "new Error().stack"; EXPECT_THAT(GetResultAsString(js, "taco.js"), HasSubstr("at taco.js:2")); } TEST_F(ConvertToStringTest, StackWithoutFilename) { HandleScope handle_owner(Isolate::GetCurrent()); const std::string js = "2+2\n" "new Error().stack"; EXPECT_THAT(GetResultAsString(js), ContainsRegex("at (unknown|<anonymous>)")); } //////////////////////////////////////////////////////////////////////// // DescribeError //////////////////////////////////////////////////////////////////////// typedef V8UtilsTest DescribeErrorTest; TEST_F(DescribeErrorTest, NoError) { HandleScope handle_owner(Isolate::GetCurrent()); TryCatch try_catch; EXPECT_EQ("", DescribeError(try_catch)); } TEST_F(DescribeErrorTest, NoMessage) { HandleScope handle_owner(Isolate::GetCurrent()); const std::string js = "throw new Error();"; TryCatch try_catch; ASSERT_TRUE(ExecuteJs(js, "taco.js").IsEmpty()); EXPECT_EQ("taco.js:1: Error", DescribeError(try_catch)); } TEST_F(DescribeErrorTest, WithMessage) { HandleScope handle_owner(Isolate::GetCurrent()); const std::string js = "throw new Error('foo');"; TryCatch try_catch; ASSERT_TRUE(ExecuteJs(js, "taco.js").IsEmpty()); EXPECT_EQ("taco.js:1: Error: foo", DescribeError(try_catch)); } TEST_F(DescribeErrorTest, NoLineNumber) { HandleScope handle_owner(Isolate::GetCurrent()); // Missing end curly brace. const std::string js = "var foo = {\n 'taco': 1\n"; TryCatch try_catch; ASSERT_TRUE(ExecuteJs(js, "taco.js").IsEmpty()); EXPECT_EQ("taco.js: SyntaxError: Unexpected end of input", DescribeError(try_catch)); } //////////////////////////////////////////////////////////////////////// // ConvertToStringVector //////////////////////////////////////////////////////////////////////// typedef V8UtilsTest ConvertToStringVectorTest; static std::vector<std::string> ConvertToStringVector( const std::string& js) { std::vector<std::string> result; ConvertToStringVector(ExecuteJs(js, ""), &result); return result; } TEST_F(ConvertToStringVectorTest, EmptyValue) { HandleScope handle_owner(Isolate::GetCurrent()); std::vector<std::string> result; EXPECT_DEATH(ConvertToStringVector(Local<Value>(), &result), "non-empty"); } TEST_F(ConvertToStringVectorTest, NonArray) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_DEATH(ConvertToStringVector("'foo'"), "must be an array"); } TEST_F(ConvertToStringVectorTest, EmptyArray) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_THAT(ConvertToStringVector("[]"), ElementsAre()); } TEST_F(ConvertToStringVectorTest, NonEmptyArray) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_THAT(ConvertToStringVector("['', 'foo', 2]"), ElementsAre("", "foo", "2")); } //////////////////////////////////////////////////////////////////////// // Helpers //////////////////////////////////////////////////////////////////////// static Handle<Value> AddToCounter( uint32* counter, const FunctionCallbackInfo<Value>& cb_info) { CHECK_EQ(1, cb_info.Length()); *counter += cb_info[0]->ToUint32()->Value(); return v8::Undefined(); } // An implementation of V8FunctionCallback that sets a bool when it is // destructed. class WatchForDeletionCallback : public V8FunctionCallback { public: explicit WatchForDeletionCallback(bool* deleted) : deleted_(deleted) {} ~WatchForDeletionCallback() { *deleted_ = true; } virtual bool IsRepeatable() const { return true; } virtual Handle<Value> Run(const FunctionCallbackInfo<Value>& cb_info) { return v8::Undefined(); } bool* deleted_; }; //////////////////////////////////////////////////////////////////////// // RegisterFunction //////////////////////////////////////////////////////////////////////// TEST(RegisterFunctionTest, CallsAppropriateCallback) { HandleScope handle_owner(Isolate::GetCurrent()); uint32 counter_1 = 0; uint32 counter_2 = 0; // Create a template that exports two functions to add to the two counters. Handle<ObjectTemplate> global_template = ObjectTemplate::New(); RegisterFunction( "addToCounter1", NewPermanentCallback(&AddToCounter, &counter_1), &global_template); RegisterFunction( "addToCounter2", NewPermanentCallback(&AddToCounter, &counter_2), &global_template); // Create a context in which to run scripts and ensure that it's used whenever // a context is needed below. Export the global functions configured above. const Handle<Context> context( Context::New( CHECK_NOTNULL(Isolate::GetCurrent()), NULL, // No extensions global_template)); const Context::Scope context_scope(context); // Add different amounts to the two counters. const std::string js = "addToCounter1(3); addToCounter2(7)"; ExecuteJs(js, ""); EXPECT_EQ(3, counter_1); EXPECT_EQ(7, counter_2); } TEST(RegisterFunctionTest, GarbageCollectsCallbacks) { // Create a handle scope and a template within that scope, and register a // couple of callbacks allocated on the heap. Have the callbacks keep track of // whether they were deleted. bool callback_1_deleted = false; bool callback_2_deleted = false; { HandleScope handle_owner(Isolate::GetCurrent()); Handle<ObjectTemplate> tmpl = ObjectTemplate::New(); RegisterFunction( "taco", new WatchForDeletionCallback(&callback_1_deleted), &tmpl); RegisterFunction( "burrito", new WatchForDeletionCallback(&callback_2_deleted), &tmpl); } // No more references to tmpl // Force a garbage collection run. See the comments in v8.h and this thread // (which has a bug in its advice): // // http://www.mail-archive.com/v8-users@googlegroups.com/msg01789.html // while (!v8::V8::IdleNotification()); // The two callbacks should have been deleted when the template was garbage // collected. EXPECT_TRUE(callback_1_deleted); EXPECT_TRUE(callback_2_deleted); } //////////////////////////////////////////////////////////////////////// // MakeFunction //////////////////////////////////////////////////////////////////////// class MakeFunctionTest : public V8UtilsTest { protected: MakeFunctionTest() : counter_(0) { } void SetUpFunction() { func_ = MakeFunction("taco", NewPermanentCallback(&AddToCounter, &counter_)); } uint32 counter_; Local<Function> func_; }; TEST_F(MakeFunctionTest, Name) { HandleScope handle_owner(Isolate::GetCurrent()); SetUpFunction(); ASSERT_FALSE(func_.IsEmpty()); EXPECT_EQ("taco", ConvertToString(func_->GetName())); } TEST_F(MakeFunctionTest, CallsCallback) { HandleScope handle_owner(Isolate::GetCurrent()); SetUpFunction(); ASSERT_FALSE(func_.IsEmpty()); Handle<Value> one_args[] = { Integer::New(1) }; Handle<Value> seventeen_args[] = { Integer::New(17) }; func_->Call(Context::GetCurrent()->Global(), 1, one_args); func_->Call(Context::GetCurrent()->Global(), 1, seventeen_args); EXPECT_EQ(18, counter_); } TEST_F(MakeFunctionTest, GarbageCollectsCallback) { // Create a handle scope and make a function using a callback allocated on the // heap. Have the callback keep track of when it's deleted. bool callback_deleted = false; { const HandleScope handle_owner(Isolate::GetCurrent()); const Handle<Context> context( Context::New( CHECK_NOTNULL(Isolate::GetCurrent()))); const Context::Scope context_scope(context); const Local<Function> function = MakeFunction("taco", new WatchForDeletionCallback(&callback_deleted)); } // No more references to function // Notify V8 that a context has been disposed. On OS X this seems to be // necessary since at least V8 3.21.17. v8::V8::ContextDisposedNotification(); // Force a garbage collection run. See the comments in v8.h and this thread // (which has a bug in its advice): // // http://www.mail-archive.com/v8-users@googlegroups.com/msg01789.html // while (!v8::V8::IdleNotification()); // On Linux, it seems we also need to send a low-memory notification to make // sure the garbage collection run happens. v8::V8::LowMemoryNotification(); // The callback should have been deleted when the function was garbage // collected. EXPECT_TRUE(callback_deleted); } } // namespace gjstest <commit_msg>Explicitly qualified v8::FunctionCallbackInfo in another place.<commit_after>// Copyright 2010 Google Inc. All Rights Reserved. // Author: jacobsa@google.com (Aaron Jacobs) // // 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 <gmock/gmock.h> #include <gtest/gtest.h> #include <v8.h> #include "gjstest/internal/cpp/v8_utils.h" #include "base/callback.h" #include "base/integral_types.h" #include "base/logging.h" #include "base/macros.h" using testing::ContainsRegex; using testing::ElementsAre; using testing::HasSubstr; using v8::Context; using v8::Function; using v8::Handle; using v8::HandleScope; using v8::Integer; using v8::Isolate; using v8::Local; using v8::Number; using v8::ObjectTemplate; using v8::Persistent; using v8::String; using v8::TryCatch; using v8::Value; namespace gjstest { // A test case that automatically creates and enters a context before the test // body. Subclasses should set any properties they want globally exposed through // the context on the the object template before calling V8UtilsTest::SetUp. class V8UtilsTest : public ::testing::Test { protected: V8UtilsTest() : handle_scope_(CHECK_NOTNULL(Isolate::GetCurrent())), global_template_(ObjectTemplate::New()), context_( Context::New( CHECK_NOTNULL(Isolate::GetCurrent()), NULL, // No extensions global_template_)), context_scope_(context_) { } const HandleScope handle_scope_; const Handle<ObjectTemplate> global_template_; const Handle<Context> context_; const Context::Scope context_scope_; }; //////////////////////////////////////////////////////////////////////// // ConvertToString //////////////////////////////////////////////////////////////////////// typedef V8UtilsTest ConvertToStringTest; TEST_F(ConvertToStringTest, Empty) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_EQ("", ConvertToString(Local<Value>())); } TEST_F(ConvertToStringTest, Strings) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_EQ("", ConvertToString(String::New(""))); EXPECT_EQ("taco", ConvertToString(String::New("taco"))); const uint16 kUtf16Chars[] = { 0xd0c0, 0xcf54 }; EXPECT_EQ("타코", ConvertToString(String::New(kUtf16Chars, 2))); } TEST_F(ConvertToStringTest, Numbers) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_EQ("-3", ConvertToString(Number::New(-3))); EXPECT_EQ("4", ConvertToString(Number::New(4))); EXPECT_EQ("3.14", ConvertToString(Number::New(3.14))); } //////////////////////////////////////////////////////////////////////// // ExecuteJs //////////////////////////////////////////////////////////////////////// typedef V8UtilsTest ExecuteJsTest; static std::string GetResultAsString( const std::string& js, std::string filename = "") { return ConvertToString(ExecuteJs(js, filename)); } TEST_F(ConvertToStringTest, EmptyString) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_EQ("undefined", GetResultAsString("")); } TEST_F(ConvertToStringTest, BadSyntax) { HandleScope handle_owner(Isolate::GetCurrent()); const Local<Value> result = ExecuteJs("(2", ""); EXPECT_TRUE(result.IsEmpty()); } TEST_F(ConvertToStringTest, SingleValue) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_EQ("2", GetResultAsString("2")); EXPECT_EQ("foo", GetResultAsString("'foo'")); } TEST_F(ConvertToStringTest, FunctionReturnValue) { HandleScope handle_owner(Isolate::GetCurrent()); const std::string js = "var addTwo = function(a, b) { return a + b; };\n" "addTwo(2, 3)"; EXPECT_EQ("5", GetResultAsString(js)); } TEST_F(ConvertToStringTest, StackWithFilename) { HandleScope handle_owner(Isolate::GetCurrent()); const std::string js = "2+2\n" "new Error().stack"; EXPECT_THAT(GetResultAsString(js, "taco.js"), HasSubstr("at taco.js:2")); } TEST_F(ConvertToStringTest, StackWithoutFilename) { HandleScope handle_owner(Isolate::GetCurrent()); const std::string js = "2+2\n" "new Error().stack"; EXPECT_THAT(GetResultAsString(js), ContainsRegex("at (unknown|<anonymous>)")); } //////////////////////////////////////////////////////////////////////// // DescribeError //////////////////////////////////////////////////////////////////////// typedef V8UtilsTest DescribeErrorTest; TEST_F(DescribeErrorTest, NoError) { HandleScope handle_owner(Isolate::GetCurrent()); TryCatch try_catch; EXPECT_EQ("", DescribeError(try_catch)); } TEST_F(DescribeErrorTest, NoMessage) { HandleScope handle_owner(Isolate::GetCurrent()); const std::string js = "throw new Error();"; TryCatch try_catch; ASSERT_TRUE(ExecuteJs(js, "taco.js").IsEmpty()); EXPECT_EQ("taco.js:1: Error", DescribeError(try_catch)); } TEST_F(DescribeErrorTest, WithMessage) { HandleScope handle_owner(Isolate::GetCurrent()); const std::string js = "throw new Error('foo');"; TryCatch try_catch; ASSERT_TRUE(ExecuteJs(js, "taco.js").IsEmpty()); EXPECT_EQ("taco.js:1: Error: foo", DescribeError(try_catch)); } TEST_F(DescribeErrorTest, NoLineNumber) { HandleScope handle_owner(Isolate::GetCurrent()); // Missing end curly brace. const std::string js = "var foo = {\n 'taco': 1\n"; TryCatch try_catch; ASSERT_TRUE(ExecuteJs(js, "taco.js").IsEmpty()); EXPECT_EQ("taco.js: SyntaxError: Unexpected end of input", DescribeError(try_catch)); } //////////////////////////////////////////////////////////////////////// // ConvertToStringVector //////////////////////////////////////////////////////////////////////// typedef V8UtilsTest ConvertToStringVectorTest; static std::vector<std::string> ConvertToStringVector( const std::string& js) { std::vector<std::string> result; ConvertToStringVector(ExecuteJs(js, ""), &result); return result; } TEST_F(ConvertToStringVectorTest, EmptyValue) { HandleScope handle_owner(Isolate::GetCurrent()); std::vector<std::string> result; EXPECT_DEATH(ConvertToStringVector(Local<Value>(), &result), "non-empty"); } TEST_F(ConvertToStringVectorTest, NonArray) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_DEATH(ConvertToStringVector("'foo'"), "must be an array"); } TEST_F(ConvertToStringVectorTest, EmptyArray) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_THAT(ConvertToStringVector("[]"), ElementsAre()); } TEST_F(ConvertToStringVectorTest, NonEmptyArray) { HandleScope handle_owner(Isolate::GetCurrent()); EXPECT_THAT(ConvertToStringVector("['', 'foo', 2]"), ElementsAre("", "foo", "2")); } //////////////////////////////////////////////////////////////////////// // Helpers //////////////////////////////////////////////////////////////////////// static Handle<Value> AddToCounter( uint32* counter, const v8::FunctionCallbackInfo<Value>& cb_info) { CHECK_EQ(1, cb_info.Length()); *counter += cb_info[0]->ToUint32()->Value(); return v8::Undefined(); } // An implementation of V8FunctionCallback that sets a bool when it is // destructed. class WatchForDeletionCallback : public V8FunctionCallback { public: explicit WatchForDeletionCallback(bool* deleted) : deleted_(deleted) {} ~WatchForDeletionCallback() { *deleted_ = true; } virtual bool IsRepeatable() const { return true; } virtual Handle<Value> Run(const v8::FunctionCallbackInfo<Value>& cb_info) { return v8::Undefined(); } bool* deleted_; }; //////////////////////////////////////////////////////////////////////// // RegisterFunction //////////////////////////////////////////////////////////////////////// TEST(RegisterFunctionTest, CallsAppropriateCallback) { HandleScope handle_owner(Isolate::GetCurrent()); uint32 counter_1 = 0; uint32 counter_2 = 0; // Create a template that exports two functions to add to the two counters. Handle<ObjectTemplate> global_template = ObjectTemplate::New(); RegisterFunction( "addToCounter1", NewPermanentCallback(&AddToCounter, &counter_1), &global_template); RegisterFunction( "addToCounter2", NewPermanentCallback(&AddToCounter, &counter_2), &global_template); // Create a context in which to run scripts and ensure that it's used whenever // a context is needed below. Export the global functions configured above. const Handle<Context> context( Context::New( CHECK_NOTNULL(Isolate::GetCurrent()), NULL, // No extensions global_template)); const Context::Scope context_scope(context); // Add different amounts to the two counters. const std::string js = "addToCounter1(3); addToCounter2(7)"; ExecuteJs(js, ""); EXPECT_EQ(3, counter_1); EXPECT_EQ(7, counter_2); } TEST(RegisterFunctionTest, GarbageCollectsCallbacks) { // Create a handle scope and a template within that scope, and register a // couple of callbacks allocated on the heap. Have the callbacks keep track of // whether they were deleted. bool callback_1_deleted = false; bool callback_2_deleted = false; { HandleScope handle_owner(Isolate::GetCurrent()); Handle<ObjectTemplate> tmpl = ObjectTemplate::New(); RegisterFunction( "taco", new WatchForDeletionCallback(&callback_1_deleted), &tmpl); RegisterFunction( "burrito", new WatchForDeletionCallback(&callback_2_deleted), &tmpl); } // No more references to tmpl // Force a garbage collection run. See the comments in v8.h and this thread // (which has a bug in its advice): // // http://www.mail-archive.com/v8-users@googlegroups.com/msg01789.html // while (!v8::V8::IdleNotification()); // The two callbacks should have been deleted when the template was garbage // collected. EXPECT_TRUE(callback_1_deleted); EXPECT_TRUE(callback_2_deleted); } //////////////////////////////////////////////////////////////////////// // MakeFunction //////////////////////////////////////////////////////////////////////// class MakeFunctionTest : public V8UtilsTest { protected: MakeFunctionTest() : counter_(0) { } void SetUpFunction() { func_ = MakeFunction("taco", NewPermanentCallback(&AddToCounter, &counter_)); } uint32 counter_; Local<Function> func_; }; TEST_F(MakeFunctionTest, Name) { HandleScope handle_owner(Isolate::GetCurrent()); SetUpFunction(); ASSERT_FALSE(func_.IsEmpty()); EXPECT_EQ("taco", ConvertToString(func_->GetName())); } TEST_F(MakeFunctionTest, CallsCallback) { HandleScope handle_owner(Isolate::GetCurrent()); SetUpFunction(); ASSERT_FALSE(func_.IsEmpty()); Handle<Value> one_args[] = { Integer::New(1) }; Handle<Value> seventeen_args[] = { Integer::New(17) }; func_->Call(Context::GetCurrent()->Global(), 1, one_args); func_->Call(Context::GetCurrent()->Global(), 1, seventeen_args); EXPECT_EQ(18, counter_); } TEST_F(MakeFunctionTest, GarbageCollectsCallback) { // Create a handle scope and make a function using a callback allocated on the // heap. Have the callback keep track of when it's deleted. bool callback_deleted = false; { const HandleScope handle_owner(Isolate::GetCurrent()); const Handle<Context> context( Context::New( CHECK_NOTNULL(Isolate::GetCurrent()))); const Context::Scope context_scope(context); const Local<Function> function = MakeFunction("taco", new WatchForDeletionCallback(&callback_deleted)); } // No more references to function // Notify V8 that a context has been disposed. On OS X this seems to be // necessary since at least V8 3.21.17. v8::V8::ContextDisposedNotification(); // Force a garbage collection run. See the comments in v8.h and this thread // (which has a bug in its advice): // // http://www.mail-archive.com/v8-users@googlegroups.com/msg01789.html // while (!v8::V8::IdleNotification()); // On Linux, it seems we also need to send a low-memory notification to make // sure the garbage collection run happens. v8::V8::LowMemoryNotification(); // The callback should have been deleted when the function was garbage // collected. EXPECT_TRUE(callback_deleted); } } // namespace gjstest <|endoftext|>
<commit_before>#include "himan_unit.h" #include "util.h" #define BOOST_TEST_MODULE util using namespace std; using namespace himan; const double kEpsilon = 1e-3; BOOST_AUTO_TEST_CASE(UV_TO_GEOGRAPHICAL) { // Transform grid coordinates to lat and lon in stereographic projection himan::point stereoUV(8.484046, 3.804569); double lon = 72.79; himan::point latlon = util::UVToGeographical(lon, stereoUV); BOOST_CHECK_CLOSE(latlon.X(), 6.144442, kEpsilon); BOOST_CHECK_CLOSE(latlon.Y(), -6.978511, kEpsilon); stereoUV.X(-0.2453410); stereoUV.Y(0.5808838); lon = 23.39; latlon = util::UVToGeographical(lon, stereoUV); BOOST_CHECK_CLOSE(latlon.X(), 5.4238806e-03, kEpsilon); BOOST_CHECK_CLOSE(latlon.Y(), 0.6305464, kEpsilon); } <commit_msg>Add Filter2D testcase to unit-tests.<commit_after>#include "himan_unit.h" #include "util.h" #define BOOST_TEST_MODULE util using namespace std; using namespace himan; const double kEpsilon = 1e-3; BOOST_AUTO_TEST_CASE(UV_TO_GEOGRAPHICAL) { // Transform grid coordinates to lat and lon in stereographic projection himan::point stereoUV(8.484046, 3.804569); double lon = 72.79; himan::point latlon = util::UVToGeographical(lon, stereoUV); BOOST_CHECK_CLOSE(latlon.X(), 6.144442, kEpsilon); BOOST_CHECK_CLOSE(latlon.Y(), -6.978511, kEpsilon); stereoUV.X(-0.2453410); stereoUV.Y(0.5808838); lon = 23.39; latlon = util::UVToGeographical(lon, stereoUV); BOOST_CHECK_CLOSE(latlon.X(), 5.4238806e-03, kEpsilon); BOOST_CHECK_CLOSE(latlon.Y(), 0.6305464, kEpsilon); } BOOST_AUTO_TEST_CASE(FILTER2D) { // Filter a plane with given filter kernel // Declare matrices himan::matrix<double> A(11,8,1); himan::matrix<double> B(3,3,1); himan::matrix<double> C; himan::matrix<double> D(11,8,1); // Fill matrix A that will be smoothend with checker-board pattern for(size_t i=0; i < A.Size(); ++i) { if(i % 2 == 0) { A.Set(i, 0); } else { A.Set(i, 36); } } // Fill matrix D with solution of the smoothened matrix Filter2D(A,B) for(size_t i=0; i < D.SizeX(); ++i) { for(size_t j=0; j < D.SizeY(); ++j) { if(i == 0 || i == A.SizeX()-1 || j == 0 || j == A.SizeY()-1) { D.Set(i,j,0,18); } else if ((i % 2 != 0 && j % 2 != 0) || (i % 2 == 0 && j % 2 == 0)) { D.Set(i,j,0,16); } else { D.Set(i,j,0,20); } } } // Fill matrix B (filter kernel) with constant values 1/9 so that sum(B) == 1 double filter_coeff(1.0/9.0); B.Fill(filter_coeff); // Compute smoothened matrix C = himan::util::Filter2D(A,B); // Compare results for(size_t i=0; i < C.Size(); ++i) { BOOST_CHECK_CLOSE(C.At(i),D.At(i),kEpsilon); } // computed filtered matrix std::cout << "Matrix C computed with Filter2D:" << std::endl; for (size_t i=0; i < C.SizeX();++i){ for (size_t j=0; j < C.SizeY();++j){ std::cout << C.At(i,j,0) << " "; } std::cout << std::endl; } std::cout << std::endl << "Matrix D as reference case for Filter2D computation:" << std::endl; for (size_t i=0; i < D.SizeX();++i){ for (size_t j=0; j < D.SizeY();++j){ std::cout << D.At(i,j,0) << " "; } std::cout << std::endl; } } <|endoftext|>
<commit_before>#include <QNetworkRequest> #include <QNetworkReply> #include <QDir> #include <QFile> #include "program-updater.h" #include "functions.h" #include "json.h" ProgramUpdater::ProgramUpdater() : ProgramUpdater("https://api.github.com/repos/Bionus/imgbrd-grabber") { } ProgramUpdater::ProgramUpdater(QString baseUrl) : m_baseUrl(baseUrl) { } void ProgramUpdater::checkForUpdates() { QUrl url(m_baseUrl + "/releases"); QNetworkRequest request(url); m_checkForUpdatesReply = m_networkAccessManager.get(request); connect(m_checkForUpdatesReply, &QNetworkReply::finished, this, &ProgramUpdater::checkForUpdatesDone); } void ProgramUpdater::checkForUpdatesDone() { m_source = m_checkForUpdatesReply->readAll(); QVariant json = Json::parse(m_source); QMap<QString, QVariant> lastRelease = json.toList().first().toMap(); QString latest = lastRelease["name"].toString().mid(1); QString changelog = lastRelease["body"].toString(); int max = versionToInt(latest); int current = versionToInt(QString(VERSION)) - 1; bool isNew = max > current; m_newVersion = latest; emit finished(latest, isNew, changelog); } void ProgramUpdater::downloadUpdate() { QVariant json = Json::parse(m_source); QMap<QString, QVariant> lastRelease = json.toList().first().toMap(); QMap<QString, QVariant> lastAsset = lastRelease["assets"].toList().first().toMap(); QUrl url(lastAsset["browser_download_url"].toString()); m_updateFilename = m_downloadReply->url().fileName(); QNetworkRequest request(url); log(QString("Downloading installer from \"%1\".").arg(url.toString())); m_downloadReply = m_networkAccessManager.get(request); connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress); connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone); } void ProgramUpdater::downloadDone() { QUrl redir = m_downloadReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!redir.isEmpty()) { log(QString("Installer download redirected to \"%1\".").arg(redir.toString())); QNetworkRequest request(redir); m_downloadReply = m_networkAccessManager.get(request); connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress); connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone); return; } QFile file(QDir::tempPath() + QDir::separator() + m_updateFilename); if (!file.open(QFile::WriteOnly | QFile::Truncate)) { log(QString("Error opening installer file \"%1\".").arg(file.fileName())); return; } file.write(m_downloadReply->readAll()); file.close(); log(QString("Installer file written to \"%1\"").arg(file.fileName())); emit downloadFinished(file.fileName()); } <commit_msg>Fix debug update version and crash on update download<commit_after>#include <QNetworkRequest> #include <QNetworkReply> #include <QDir> #include <QFile> #include "program-updater.h" #include "functions.h" #include "json.h" ProgramUpdater::ProgramUpdater() : ProgramUpdater("https://api.github.com/repos/Bionus/imgbrd-grabber") { } ProgramUpdater::ProgramUpdater(QString baseUrl) : m_baseUrl(baseUrl) { } void ProgramUpdater::checkForUpdates() { QUrl url(m_baseUrl + "/releases"); QNetworkRequest request(url); m_checkForUpdatesReply = m_networkAccessManager.get(request); connect(m_checkForUpdatesReply, &QNetworkReply::finished, this, &ProgramUpdater::checkForUpdatesDone); } void ProgramUpdater::checkForUpdatesDone() { m_source = m_checkForUpdatesReply->readAll(); QVariant json = Json::parse(m_source); QMap<QString, QVariant> lastRelease = json.toList().first().toMap(); QString latest = lastRelease["name"].toString().mid(1); QString changelog = lastRelease["body"].toString(); int max = versionToInt(latest); int current = versionToInt(QString(VERSION)); bool isNew = max > current; m_newVersion = latest; emit finished(latest, isNew, changelog); } void ProgramUpdater::downloadUpdate() { QVariant json = Json::parse(m_source); QMap<QString, QVariant> lastRelease = json.toList().first().toMap(); QMap<QString, QVariant> lastAsset = lastRelease["assets"].toList().first().toMap(); QUrl url(lastAsset["browser_download_url"].toString()); m_updateFilename = url.fileName(); QNetworkRequest request(url); log(QString("Downloading installer from \"%1\".").arg(url.toString())); m_downloadReply = m_networkAccessManager.get(request); connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress); connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone); } void ProgramUpdater::downloadDone() { QUrl redir = m_downloadReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!redir.isEmpty()) { log(QString("Installer download redirected to \"%1\".").arg(redir.toString())); QNetworkRequest request(redir); m_downloadReply = m_networkAccessManager.get(request); connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress); connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone); return; } QFile file(QDir::tempPath() + QDir::separator() + m_updateFilename); if (!file.open(QFile::WriteOnly | QFile::Truncate)) { log(QString("Error opening installer file \"%1\".").arg(file.fileName())); return; } file.write(m_downloadReply->readAll()); file.close(); log(QString("Installer file written to \"%1\"").arg(file.fileName())); emit downloadFinished(file.fileName()); } <|endoftext|>
<commit_before>/* Copyright (C) 2017 Axel Waggershauser This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "RawSpeed-API.h" #include <chrono> // for milliseconds, steady_clock, duration #include <cstdint> // for uint8_t #include <cstdio> // for snprintf, size_t, fclose, fopen, fpr... #include <cstdlib> // for system #include <cstring> // for memset #include <fstream> // IWYU pragma: keep #include <iomanip> // for setw #include <iostream> // for cout #include <map> // for map #include <memory> // for unique_ptr, allocator #include <sstream> // IWYU pragma: keep #include <stdexcept> // for runtime_error #include <string> // for string, operator+, operator<<, char_... #include <type_traits> // for enable_if<>::type #include <utility> // for pair #ifdef _OPENMP #include <omp.h> #endif // define this function, it is only declared in rawspeed: int rawspeed_get_number_of_processor_cores() { #ifdef _OPENMP return omp_get_num_procs(); #else return 1; #endif } using namespace std; using namespace RawSpeed; std::string md5_hash(const uint8_t *message, size_t len); struct Timer { mutable chrono::steady_clock::time_point start = chrono::steady_clock::now(); size_t operator()() const { auto ms = chrono::duration_cast<chrono::milliseconds>( chrono::steady_clock::now() - start) .count(); start = chrono::steady_clock::now(); return ms; } }; string img_hash(RawImage &r) { ostringstream oss; char line[256]; #define APPEND(...) \ do { \ snprintf(line, sizeof(line), __VA_ARGS__); \ oss << line; \ } while (false) APPEND("make: %s\n", r->metadata.make.c_str()); APPEND("model: %s\n", r->metadata.model.c_str()); APPEND("mode: %s\n", r->metadata.mode.c_str()); APPEND("canonical_make: %s\n", r->metadata.canonical_make.c_str()); APPEND("canonical_model: %s\n", r->metadata.canonical_model.c_str()); APPEND("canonical_alias: %s\n", r->metadata.canonical_alias.c_str()); APPEND("canonical_id: %s\n", r->metadata.canonical_id.c_str()); APPEND("isoSpeed: %d\n", r->metadata.isoSpeed); APPEND("blackLevel: %d\n", r->blackLevel); APPEND("whitePoint: %d\n", r->whitePoint); APPEND("blackLevelSeparate: %d %d %d %d\n", r->blackLevelSeparate[0], r->blackLevelSeparate[1], r->blackLevelSeparate[2], r->blackLevelSeparate[3]); APPEND("wbCoeffs: %f %f %f %f\n", r->metadata.wbCoeffs[0], r->metadata.wbCoeffs[1], r->metadata.wbCoeffs[2], r->metadata.wbCoeffs[3]); APPEND("isCFA: %d\n", r->isCFA); APPEND("cfa: %s\n", r->cfa.asString().c_str()); APPEND("filters: 0x%x\n", r->cfa.getDcrawFilter()); APPEND("bpp: %d\n", r->getBpp()); APPEND("cpp: %d\n", r->getCpp()); APPEND("dataType: %d\n", r->getDataType()); const iPoint2D dimUncropped = r->getUncroppedDim(); APPEND("dimUncropped: %dx%d\n", dimUncropped.x, dimUncropped.y); APPEND("dimCropped: %dx%d\n", r->dim.x, r->dim.y); const iPoint2D cropTL = r->getCropOffset(); APPEND("cropOffset: %dx%d\n", cropTL.x, cropTL.y); APPEND("pitch: %d\n", r->pitch); APPEND("blackAreas: "); for (auto ba : r->blackAreas) APPEND("%d:%dx%d, ", ba.isVertical, ba.offset, ba.size); APPEND("\n"); APPEND("fuji_rotation_pos: %d\n", r->metadata.fujiRotationPos); APPEND("pixel_aspect_ratio: %f\n", r->metadata.pixelAspectRatio); APPEND("badPixelPositions: "); for (uint32 p : r->mBadPixelPositions) APPEND("%d, ", p); APPEND("\n"); // clear the bytes at the end of each line, so we get a consistent hash size_t padding = r->pitch - dimUncropped.x * r->getBpp(); if (padding) { uint8_t *d = r->getDataUncropped(0, 1) - padding; for (int i = 0; i < r->getUncroppedDim().y; ++i, d += r->pitch) memset(d, 0, padding); } string hash = md5_hash(r->getDataUncropped(0, 0), static_cast<size_t>(r->pitch) * r->getUncroppedDim().y); APPEND("data md5sum: %s\n", hash.c_str()); for (const char *e : r->errors) APPEND("WARNING: [rawspeed] %s\n", e); #undef APPEND return oss.str(); } void writePPM(const RawImage& raw, const string& fn) { FILE *f = fopen(fn.c_str(), "wb"); int width = raw->dim.x; int height = raw->dim.y; // Write PPM header fprintf(f, "P5\n%d %d\n65535\n", width, height); // Write pixels for (int y = 0; y < height; ++y) { auto *row = reinterpret_cast<unsigned short *>(raw->getData(0, y)); // Swap for PPM format byte ordering if (getHostEndianness() == little) for (int x = 0; x < width; ++x) row[x] = __builtin_bswap16(row[x]); fwrite(row, 2, width, f); } fclose(f); } size_t process(const string &filename, CameraMetaData *metadata, bool create, bool dump) { const string hashfile(filename + ".hash"); // if creating hash and hash exists -> skip current file // if not creating and hash is missing -> skip as well ifstream hf(hashfile); if (!(hf.good() ^ create)) { #ifdef _OPENMP #pragma omp critical(io) #endif cout << left << setw(55) << filename << ": hash " << (create ? "exists" : "missing") << ", skipping" << endl; return 0; } // to narrow down the list of files that could have causes the crash #ifdef _OPENMP #pragma omp critical(io) #endif cout << left << setw(55) << filename << ": starting decoding ... " << endl; FileReader reader(filename.c_str()); unique_ptr<FileMap> map = unique_ptr<FileMap>(reader.readFile()); // FileMap* map = readFile( argv[1] ); Timer t; RawParser parser(map.get()); unique_ptr<RawDecoder> decoder = unique_ptr<RawDecoder>(parser.getDecoder(metadata)); // RawDecoder* decoder = parseRaw( map ); decoder->failOnUnknown = false; decoder->checkSupport(metadata); decoder->decodeRaw(); decoder->decodeMetaData(metadata); RawImage raw = decoder->mRaw; // RawImage raw = decoder->decode(); auto time = t(); #ifdef _OPENMP #pragma omp critical(io) #endif cout << left << setw(55) << filename << ": " << internal << setw(3) << map->getSize() / 1000000 << " MB / " << setw(4) << time << " ms" << endl; if (create) { ofstream f(hashfile); f << img_hash(raw); if (dump) writePPM(raw, filename + ".ppm"); } else { string truth((istreambuf_iterator<char>(hf)), istreambuf_iterator<char>()); string h = img_hash(raw); if (h != truth) { ofstream f(filename + ".hash.failed"); f << h; if (dump) writePPM(raw, filename + ".failed.ppm"); throw std::runtime_error("hash/metadata mismatch"); } } return time; } static int usage(const char *progname) { cout << "usage: " << progname << R"( [-h] print this help [-c] for each file: decode, compute hash and store it. If hash exists, it does not recompute it! [-d] store decoded image as PPM <FILE[S]> the file[s] to work on. With no options given, each raw with an accompanying hash will be decoded and compared to the existing hash. A summary of all errors/failed hash comparisons will be reported at the end. Suggested workflow for easy regression testing: 1. remove all .hash files and build 'trusted' version of this program 2. run with option '-c' -> creates .hash for all supported files 3. build new version to test for regressions 4. run with no option -> checks files with existing .hash If the second run shows no errors, you have no regressions, otherwise, the diff between hashes is appended to rstest.log )"; return 0; } int main(int argc, char **argv) { auto hasFlag = [&](string flag) { bool found = false; for (int i = 1; i < argc; ++i) { if (!argv[i] || argv[i] != flag) continue; found = true; argv[i] = nullptr; } return found; }; bool help = hasFlag("-h"); bool create = hasFlag("-c"); bool dump = hasFlag("-d"); if (1 == argc || help) return usage(argv[0]); CameraMetaData metadata(CMAKE_SOURCE_DIR "/data/cameras.xml"); size_t time = 0; map<string, string> failedTests; #ifdef _OPENMP #pragma omp parallel for default(shared) schedule(static, 1) reduction(+ : time) #endif for (int i = 1; i < argc; ++i) { if (!argv[i]) continue; try { time += process(argv[i], &metadata, create, dump); } catch (std::runtime_error &e) { #ifdef _OPENMP #pragma omp critical(io) #endif { string msg = string(argv[i]) + " failed: " + e.what(); cerr << msg << endl; failedTests.emplace(argv[i], msg); } } } cout << "Total decoding time: " << time / 1000.0 << "s" << endl << endl; if (!failedTests.empty()) { cerr << "WARNING: the following " << failedTests.size() << " tests have failed:\n"; for (const auto &i : failedTests) { cerr << i.second << "\n"; #ifndef WIN32 const string oldhash(i.first + ".hash"); const string newhash(oldhash + ".failed"); ifstream oldfile(oldhash), newfile(newhash); // if neither hashes exist, nothing to append... if (oldfile.good() || newfile.good()) { // DIFF(1): -N, --new-file treat absent files as empty string cmd(R"(diff -N -u0 ")"); cmd += oldhash; cmd += R"(" ")"; cmd += newhash; cmd += R"(" >> rstest.log)"; if (system(cmd.c_str())) ; // NOLINT } #endif } cerr << "See rstest.log for details.\n"; } cout << "All good, no tests failed!" << endl; return failedTests.empty() ? 0 : 1; } <commit_msg>rstest: ugh, print "all good" only if all good<commit_after>/* Copyright (C) 2017 Axel Waggershauser This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "RawSpeed-API.h" #include <chrono> // for milliseconds, steady_clock, duration #include <cstdint> // for uint8_t #include <cstdio> // for snprintf, size_t, fclose, fopen, fpr... #include <cstdlib> // for system #include <cstring> // for memset #include <fstream> // IWYU pragma: keep #include <iomanip> // for setw #include <iostream> // for cout #include <map> // for map #include <memory> // for unique_ptr, allocator #include <sstream> // IWYU pragma: keep #include <stdexcept> // for runtime_error #include <string> // for string, operator+, operator<<, char_... #include <type_traits> // for enable_if<>::type #include <utility> // for pair #ifdef _OPENMP #include <omp.h> #endif // define this function, it is only declared in rawspeed: int rawspeed_get_number_of_processor_cores() { #ifdef _OPENMP return omp_get_num_procs(); #else return 1; #endif } using namespace std; using namespace RawSpeed; std::string md5_hash(const uint8_t *message, size_t len); struct Timer { mutable chrono::steady_clock::time_point start = chrono::steady_clock::now(); size_t operator()() const { auto ms = chrono::duration_cast<chrono::milliseconds>( chrono::steady_clock::now() - start) .count(); start = chrono::steady_clock::now(); return ms; } }; string img_hash(RawImage &r) { ostringstream oss; char line[256]; #define APPEND(...) \ do { \ snprintf(line, sizeof(line), __VA_ARGS__); \ oss << line; \ } while (false) APPEND("make: %s\n", r->metadata.make.c_str()); APPEND("model: %s\n", r->metadata.model.c_str()); APPEND("mode: %s\n", r->metadata.mode.c_str()); APPEND("canonical_make: %s\n", r->metadata.canonical_make.c_str()); APPEND("canonical_model: %s\n", r->metadata.canonical_model.c_str()); APPEND("canonical_alias: %s\n", r->metadata.canonical_alias.c_str()); APPEND("canonical_id: %s\n", r->metadata.canonical_id.c_str()); APPEND("isoSpeed: %d\n", r->metadata.isoSpeed); APPEND("blackLevel: %d\n", r->blackLevel); APPEND("whitePoint: %d\n", r->whitePoint); APPEND("blackLevelSeparate: %d %d %d %d\n", r->blackLevelSeparate[0], r->blackLevelSeparate[1], r->blackLevelSeparate[2], r->blackLevelSeparate[3]); APPEND("wbCoeffs: %f %f %f %f\n", r->metadata.wbCoeffs[0], r->metadata.wbCoeffs[1], r->metadata.wbCoeffs[2], r->metadata.wbCoeffs[3]); APPEND("isCFA: %d\n", r->isCFA); APPEND("cfa: %s\n", r->cfa.asString().c_str()); APPEND("filters: 0x%x\n", r->cfa.getDcrawFilter()); APPEND("bpp: %d\n", r->getBpp()); APPEND("cpp: %d\n", r->getCpp()); APPEND("dataType: %d\n", r->getDataType()); const iPoint2D dimUncropped = r->getUncroppedDim(); APPEND("dimUncropped: %dx%d\n", dimUncropped.x, dimUncropped.y); APPEND("dimCropped: %dx%d\n", r->dim.x, r->dim.y); const iPoint2D cropTL = r->getCropOffset(); APPEND("cropOffset: %dx%d\n", cropTL.x, cropTL.y); APPEND("pitch: %d\n", r->pitch); APPEND("blackAreas: "); for (auto ba : r->blackAreas) APPEND("%d:%dx%d, ", ba.isVertical, ba.offset, ba.size); APPEND("\n"); APPEND("fuji_rotation_pos: %d\n", r->metadata.fujiRotationPos); APPEND("pixel_aspect_ratio: %f\n", r->metadata.pixelAspectRatio); APPEND("badPixelPositions: "); for (uint32 p : r->mBadPixelPositions) APPEND("%d, ", p); APPEND("\n"); // clear the bytes at the end of each line, so we get a consistent hash size_t padding = r->pitch - dimUncropped.x * r->getBpp(); if (padding) { uint8_t *d = r->getDataUncropped(0, 1) - padding; for (int i = 0; i < r->getUncroppedDim().y; ++i, d += r->pitch) memset(d, 0, padding); } string hash = md5_hash(r->getDataUncropped(0, 0), static_cast<size_t>(r->pitch) * r->getUncroppedDim().y); APPEND("data md5sum: %s\n", hash.c_str()); for (const char *e : r->errors) APPEND("WARNING: [rawspeed] %s\n", e); #undef APPEND return oss.str(); } void writePPM(const RawImage& raw, const string& fn) { FILE *f = fopen(fn.c_str(), "wb"); int width = raw->dim.x; int height = raw->dim.y; // Write PPM header fprintf(f, "P5\n%d %d\n65535\n", width, height); // Write pixels for (int y = 0; y < height; ++y) { auto *row = reinterpret_cast<unsigned short *>(raw->getData(0, y)); // Swap for PPM format byte ordering if (getHostEndianness() == little) for (int x = 0; x < width; ++x) row[x] = __builtin_bswap16(row[x]); fwrite(row, 2, width, f); } fclose(f); } size_t process(const string &filename, CameraMetaData *metadata, bool create, bool dump) { const string hashfile(filename + ".hash"); // if creating hash and hash exists -> skip current file // if not creating and hash is missing -> skip as well ifstream hf(hashfile); if (!(hf.good() ^ create)) { #ifdef _OPENMP #pragma omp critical(io) #endif cout << left << setw(55) << filename << ": hash " << (create ? "exists" : "missing") << ", skipping" << endl; return 0; } // to narrow down the list of files that could have causes the crash #ifdef _OPENMP #pragma omp critical(io) #endif cout << left << setw(55) << filename << ": starting decoding ... " << endl; FileReader reader(filename.c_str()); unique_ptr<FileMap> map = unique_ptr<FileMap>(reader.readFile()); // FileMap* map = readFile( argv[1] ); Timer t; RawParser parser(map.get()); unique_ptr<RawDecoder> decoder = unique_ptr<RawDecoder>(parser.getDecoder(metadata)); // RawDecoder* decoder = parseRaw( map ); decoder->failOnUnknown = false; decoder->checkSupport(metadata); decoder->decodeRaw(); decoder->decodeMetaData(metadata); RawImage raw = decoder->mRaw; // RawImage raw = decoder->decode(); auto time = t(); #ifdef _OPENMP #pragma omp critical(io) #endif cout << left << setw(55) << filename << ": " << internal << setw(3) << map->getSize() / 1000000 << " MB / " << setw(4) << time << " ms" << endl; if (create) { ofstream f(hashfile); f << img_hash(raw); if (dump) writePPM(raw, filename + ".ppm"); } else { string truth((istreambuf_iterator<char>(hf)), istreambuf_iterator<char>()); string h = img_hash(raw); if (h != truth) { ofstream f(filename + ".hash.failed"); f << h; if (dump) writePPM(raw, filename + ".failed.ppm"); throw std::runtime_error("hash/metadata mismatch"); } } return time; } static int usage(const char *progname) { cout << "usage: " << progname << R"( [-h] print this help [-c] for each file: decode, compute hash and store it. If hash exists, it does not recompute it! [-d] store decoded image as PPM <FILE[S]> the file[s] to work on. With no options given, each raw with an accompanying hash will be decoded and compared to the existing hash. A summary of all errors/failed hash comparisons will be reported at the end. Suggested workflow for easy regression testing: 1. remove all .hash files and build 'trusted' version of this program 2. run with option '-c' -> creates .hash for all supported files 3. build new version to test for regressions 4. run with no option -> checks files with existing .hash If the second run shows no errors, you have no regressions, otherwise, the diff between hashes is appended to rstest.log )"; return 0; } int main(int argc, char **argv) { auto hasFlag = [&](string flag) { bool found = false; for (int i = 1; i < argc; ++i) { if (!argv[i] || argv[i] != flag) continue; found = true; argv[i] = nullptr; } return found; }; bool help = hasFlag("-h"); bool create = hasFlag("-c"); bool dump = hasFlag("-d"); if (1 == argc || help) return usage(argv[0]); CameraMetaData metadata(CMAKE_SOURCE_DIR "/data/cameras.xml"); size_t time = 0; map<string, string> failedTests; #ifdef _OPENMP #pragma omp parallel for default(shared) schedule(static, 1) reduction(+ : time) #endif for (int i = 1; i < argc; ++i) { if (!argv[i]) continue; try { time += process(argv[i], &metadata, create, dump); } catch (std::runtime_error &e) { #ifdef _OPENMP #pragma omp critical(io) #endif { string msg = string(argv[i]) + " failed: " + e.what(); cerr << msg << endl; failedTests.emplace(argv[i], msg); } } } cout << "Total decoding time: " << time / 1000.0 << "s" << endl << endl; if (!failedTests.empty()) { cerr << "WARNING: the following " << failedTests.size() << " tests have failed:\n"; for (const auto &i : failedTests) { cerr << i.second << "\n"; #ifndef WIN32 const string oldhash(i.first + ".hash"); const string newhash(oldhash + ".failed"); ifstream oldfile(oldhash), newfile(newhash); // if neither hashes exist, nothing to append... if (oldfile.good() || newfile.good()) { // DIFF(1): -N, --new-file treat absent files as empty string cmd(R"(diff -N -u0 ")"); cmd += oldhash; cmd += R"(" ")"; cmd += newhash; cmd += R"(" >> rstest.log)"; if (system(cmd.c_str())) ; // NOLINT } #endif } cerr << "See rstest.log for details.\n"; } else cout << "All good, no tests failed!" << endl; return failedTests.empty() ? 0 : 1; } <|endoftext|>
<commit_before>/* Purple Nurple Emulator WARNING: Nurple only in good conscience. The code loads an image and creates an ofVboMesh from it. Two nipple positions are defined. The potentiometers (or keyboard presses [z/x and n/m]) adjusts the pressure on the left and right nipples. The mesh vertices are rotated around the nipples. Nipples. I feel like I can't comment this code seriously. */ #include "testApp.h" void testApp::addFace(ofMesh& mesh, ofVec3f a, ofVec3f b, ofVec3f c) { mesh.addVertex(a); mesh.addVertex(b); mesh.addVertex(c); } //-------------------------------------------------------------- void testApp::addFace(ofMesh& mesh, ofVec3f a, ofVec3f b, ofVec3f c, ofVec3f d) { addFace(mesh, a, b, c); addFace(mesh, a, c, d); } //-------------------------------------------------------------- void testApp::addTexCoords(ofMesh& mesh, ofVec2f a, ofVec2f b, ofVec2f c) { mesh.addTexCoord(a); mesh.addTexCoord(b); mesh.addTexCoord(c); } //-------------------------------------------------------------- void testApp::addTexCoords(ofMesh& mesh, ofVec2f a, ofVec2f b, ofVec2f c, ofVec2f d) { addTexCoords(mesh, a, b, c); addTexCoords(mesh, a, c, d); } void testApp::generateVboMesh() { vboMesh.clear(); vboMesh.setMode(OF_PRIMITIVE_TRIANGLES); int w = image.width; int h = image.height; int s = meshResolution; for(int y=0; y < h-s; y+=s) { for(int x=0; x < w-s; x+=s) { float d = 0; ofVec3f nw(x, y, d); ofVec3f ne(x+s, y, d); ofVec3f sw(x, y+s, d); ofVec3f se(x+s, y+s, d); ofVec2f nwi(x, y); ofVec2f nei(x+s, y); ofVec2f swi(x, y+s); ofVec2f sei(x+s, y+s); addFace(vboMesh, nw, ne, se, sw); addTexCoords(vboMesh, nwi, nei, sei, swi); } } warppedVboMesh = vboMesh; } //-------------------------------------------------------------- void testApp::setup(){ image.loadImage("GorillaSmall.jpg"); imageInterested.loadImage("GorillaFace1.jpg"); imagePleased.loadImage("GorillaFace2.jpg"); imagePissed.loadImage("GorillaFace3.jpg"); imageScrewYou.loadImage("GorillaFace4.jpg"); leftPotValue = 0; rightPotValue = 0; serial.setup("COM5", BAUD_RATE); isArduinoConnected = true; leftNipple.set(380.f, 490.f, 0.f); rightNipple.set(575.f, 510.f, 0.f); generateVboMesh(); } //-------------------------------------------------------------- void testApp::update(){ if (isArduinoConnected) { processSerial(); leftRotation = ofMap(leftPotValue,0,1023,-twistRange,twistRange); rightRotation = ofMap(rightPotValue,0,1023,-twistRange,twistRange); } warpMeshAroundNipples(z_axis); } void testApp::warpMeshAroundNipples(ofVec3f rotationAxis) { float maxDistance = ofDist(0, 0, image.width, image.height); int numVertices = vboMesh.getNumVertices(); for (int i=0; i<numVertices; i++) { ofVec3f v = vboMesh.getVertex(i); float distance = ofDist(leftNipple.x, leftNipple.y, v.x, v.y); float rotation = leftRotation * pow(0.95, distance); v = rotateVectorAroundPoint(v, leftNipple, rotation, z_axis); distance = ofDist(rightNipple.x, rightNipple.y, v.x, v.y); rotation = rightRotation * pow(0.95, distance); v = rotateVectorAroundPoint(v, rightNipple, rotation, z_axis); warppedVboMesh.setVertex(i, v); } } ofVec3f testApp::rotateVectorAroundPoint(ofVec3f v, ofVec3f centerVector, float degrees, ofVec3f rotationAxis) { ofVec3f rotated = v - centerVector; rotated = rotated.getRotated(degrees, rotationAxis); rotated = rotated + centerVector; return rotated; } //-------------------------------------------------------------- void testApp::draw(){ ofBackground(ofColor::black); image.bind(); warppedVboMesh.draw(); image.unbind(); // Update the gorilla's face depending on how acceptable he finds // your purple nurple abilities float currentTwist = abs(leftRotation)+abs(rightRotation); float maxTwist = 2*twistRange; if (currentTwist<maxTwist/5) { /* Leave original face */ } else if (currentTwist<2*maxTwist/5) imageInterested.draw(300, 0); else if (currentTwist<3*maxTwist/5) imagePleased.draw(300, 0); else if (currentTwist<4*maxTwist/5) imagePissed.draw(300, 0); else imageScrewYou.draw(300, 0); } void testApp::processSerial() { // We read as many bytes as we can while(serial.available() > 0) { char myByte = serial.readByte(); // Read a single byte if(myByte == '\r') {} // Ignore carriage return else if(myByte == '\n') // Newline signals the end of a potentiometer value { vector<string> line = ofSplitString(buffer, ","); leftPotValue = ofToInt(line[0]); rightPotValue = ofToInt(line[1]); buffer.clear(); } else buffer += myByte; // Append current char to our buffer } } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if (key=='e') leftPotValue -= 1; else if (key=='r') leftPotValue += 1; else if (key=='u') leftPotValue -= 1; else if (key=='i') leftPotValue += 1; else if (key==OF_KEY_RETURN) { ofImage screenshot; int w, h = ofGetWindowWidth(), ofGetWindowHeight(); screenshot.allocate(w, h, OF_IMAGE_COLOR); screenshot.grabScreen(0, 0, w, h); screenshot.saveImage("screenshot_"+ofGetTimestampString()+".png"); } if (key=='x') leftRotation += 90; if (key=='z') leftRotation -= 90; if (key=='m') rightRotation += 90; if (key=='n') rightRotation -= 90; } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ // mouseAngle = ofRadToDeg(atan2(y-leftNipple.y, x-leftNipple.x)); // if (mouseAngle < 0) mouseAngle += 360; // // float clockwiseDistance; // float counterClockwiseDistance; // if (mouseAngle > lastMouseAngle) { // clockwiseDistance = mouseAngle - lastMouseAngle; // counterClockwiseDistance = lastMouseAngle + (360-mouseAngle); // } // else { // clockwiseDistance = mouseAngle + (360-lastMouseAngle); // counterClockwiseDistance = lastMouseAngle - mouseAngle; // } // // if (clockwiseDistance < counterClockwiseDistance) { // leftRotation += 4*clockwiseDistance; // } // else { // leftRotation += 4*-counterClockwiseDistance; // } // // // lastMouseAngle = mouseAngle; } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>Fixed grabbing of pot values from ofSplitString to first check if there are 2 elements in the vector<string> retruned by ofSplitString<commit_after>/* Purple Nurple Emulator WARNING: Nurple only in good conscience. The code loads an image and creates an ofVboMesh from it. Two nipple positions are defined. The potentiometers (or keyboard presses [z/x and n/m]) adjusts the pressure on the left and right nipples. The mesh vertices are rotated around the nipples. Nipples. I feel like I can't comment this code seriously. */ #include "testApp.h" void testApp::addFace(ofMesh& mesh, ofVec3f a, ofVec3f b, ofVec3f c) { mesh.addVertex(a); mesh.addVertex(b); mesh.addVertex(c); } //-------------------------------------------------------------- void testApp::addFace(ofMesh& mesh, ofVec3f a, ofVec3f b, ofVec3f c, ofVec3f d) { addFace(mesh, a, b, c); addFace(mesh, a, c, d); } //-------------------------------------------------------------- void testApp::addTexCoords(ofMesh& mesh, ofVec2f a, ofVec2f b, ofVec2f c) { mesh.addTexCoord(a); mesh.addTexCoord(b); mesh.addTexCoord(c); } //-------------------------------------------------------------- void testApp::addTexCoords(ofMesh& mesh, ofVec2f a, ofVec2f b, ofVec2f c, ofVec2f d) { addTexCoords(mesh, a, b, c); addTexCoords(mesh, a, c, d); } void testApp::generateVboMesh() { vboMesh.clear(); vboMesh.setMode(OF_PRIMITIVE_TRIANGLES); int w = image.width; int h = image.height; int s = meshResolution; for(int y=0; y < h-s; y+=s) { for(int x=0; x < w-s; x+=s) { float d = 0; ofVec3f nw(x, y, d); ofVec3f ne(x+s, y, d); ofVec3f sw(x, y+s, d); ofVec3f se(x+s, y+s, d); ofVec2f nwi(x, y); ofVec2f nei(x+s, y); ofVec2f swi(x, y+s); ofVec2f sei(x+s, y+s); addFace(vboMesh, nw, ne, se, sw); addTexCoords(vboMesh, nwi, nei, sei, swi); } } warppedVboMesh = vboMesh; } //-------------------------------------------------------------- void testApp::setup(){ image.loadImage("GorillaSmall.jpg"); imageInterested.loadImage("GorillaFace1.jpg"); imagePleased.loadImage("GorillaFace2.jpg"); imagePissed.loadImage("GorillaFace3.jpg"); imageScrewYou.loadImage("GorillaFace4.jpg"); leftPotValue = 0; rightPotValue = 0; serial.setup("COM5", BAUD_RATE); isArduinoConnected = false; leftNipple.set(380.f, 490.f, 0.f); rightNipple.set(575.f, 510.f, 0.f); generateVboMesh(); } //-------------------------------------------------------------- void testApp::update(){ if (isArduinoConnected) { processSerial(); leftRotation = ofMap(leftPotValue,0,1023,-twistRange,twistRange); rightRotation = ofMap(rightPotValue,0,1023,-twistRange,twistRange); } warpMeshAroundNipples(z_axis); } void testApp::warpMeshAroundNipples(ofVec3f rotationAxis) { float maxDistance = ofDist(0, 0, image.width, image.height); int numVertices = vboMesh.getNumVertices(); for (int i=0; i<numVertices; i++) { ofVec3f v = vboMesh.getVertex(i); float distance = ofDist(leftNipple.x, leftNipple.y, v.x, v.y); float rotation = leftRotation * pow(0.95, distance); v = rotateVectorAroundPoint(v, leftNipple, rotation, z_axis); distance = ofDist(rightNipple.x, rightNipple.y, v.x, v.y); rotation = rightRotation * pow(0.95, distance); v = rotateVectorAroundPoint(v, rightNipple, rotation, z_axis); warppedVboMesh.setVertex(i, v); } } ofVec3f testApp::rotateVectorAroundPoint(ofVec3f v, ofVec3f centerVector, float degrees, ofVec3f rotationAxis) { ofVec3f rotated = v - centerVector; rotated = rotated.getRotated(degrees, rotationAxis); rotated = rotated + centerVector; return rotated; } //-------------------------------------------------------------- void testApp::draw(){ ofBackground(ofColor::black); image.bind(); warppedVboMesh.draw(); image.unbind(); // Update the gorilla's face depending on how acceptable he finds // your purple nurple abilities float currentTwist = abs(leftRotation)+abs(rightRotation); float maxTwist = 2*twistRange; if (currentTwist<maxTwist/5) { /* Leave original face */ } else if (currentTwist<2*maxTwist/5) imageInterested.draw(300, 0); else if (currentTwist<3*maxTwist/5) imagePleased.draw(300, 0); else if (currentTwist<4*maxTwist/5) imagePissed.draw(300, 0); else imageScrewYou.draw(300, 0); } void testApp::processSerial() { // We read as many bytes as we can while(serial.available() > 0) { char myByte = serial.readByte(); // Read a single byte if(myByte == '\r') {} // Ignore carriage return else if(myByte == '\n') // Newline signals the end of a potentiometer value { vector<string> line = ofSplitString(buffer, ","); if (line.size()==2) { leftPotValue = ofToInt(line[0]); rightPotValue = ofToInt(line[1]); } buffer.clear(); } else buffer += myByte; // Append current char to our buffer } } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if (key=='e') leftPotValue -= 1; else if (key=='r') leftPotValue += 1; else if (key=='u') leftPotValue -= 1; else if (key=='i') leftPotValue += 1; else if (key==OF_KEY_RETURN) { ofImage screenshot; int w, h = ofGetWindowWidth(), ofGetWindowHeight(); screenshot.allocate(w, h, OF_IMAGE_COLOR); screenshot.grabScreen(0, 0, w, h); screenshot.saveImage("screenshot_"+ofGetTimestampString()+".png"); } if (key=='x') leftRotation += 90; if (key=='z') leftRotation -= 90; if (key=='m') rightRotation += 90; if (key=='n') rightRotation -= 90; } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include <armnn/Types.hpp> #include <armnn/IRuntime.hpp> #include <armnn/Deprecated.hpp> #include <ISubgraphViewConverter.hpp> #include <SubgraphView.hpp> #include <optimizations/Optimization.hpp> #include <armnn/backends/IBackendContext.hpp> #include <armnn/backends/IMemoryManager.hpp> #include <armnn/backends/ITensorHandleFactory.hpp> #include <armnn/backends/OptimizationViews.hpp> #include <armnn/backends/profiling/IBackendProfiling.hpp> #include <armnn/backends/profiling/IBackendProfilingContext.hpp> #include <vector> #include <memory> namespace armnn { class IWorkloadFactory; class IMemoryManager; class ILayerSupport; struct BackendVersion { uint32_t m_Major; uint32_t m_Minor; constexpr BackendVersion() : m_Major(0) , m_Minor(0) {} constexpr BackendVersion(uint32_t major, uint32_t minor) : m_Major(major) , m_Minor(minor) {} bool operator==(const BackendVersion& other) const { return this == &other || (this->m_Major == other.m_Major && this->m_Minor == other.m_Minor); } bool operator<=(const BackendVersion& other) const { return this->m_Major < other.m_Major || (this->m_Major == other.m_Major && this->m_Minor <= other.m_Minor); } bool operator>=(const BackendVersion& other) const { return this->m_Major > other.m_Major || (this->m_Major == other.m_Major && this->m_Minor >= other.m_Minor); } }; inline std::ostream& operator<<(std::ostream& os, const BackendVersion& backendVersion) { os << "[" << backendVersion.m_Major << "." << backendVersion.m_Minor << "]"; return os; } class IBackendInternal : public IBackend { protected: /// Creation must be done through a specific /// backend interface. IBackendInternal() = default; public: /// Allow backends created by the factory function /// to be destroyed through IBackendInternal. ~IBackendInternal() override = default; using IWorkloadFactoryPtr = std::unique_ptr<IWorkloadFactory>; using IBackendContextPtr = std::unique_ptr<IBackendContext>; /// This is the bridge between backend and backend profiling we'll keep it in the backend namespace. using IBackendProfilingContextPtr = std::shared_ptr<armnn::profiling::IBackendProfilingContext>; using IBackendProfilingPtr = std::unique_ptr<armnn::profiling::IBackendProfiling>; using OptimizationPtr = std::unique_ptr<Optimization>; using Optimizations = std::vector<OptimizationPtr>; using ILayerSupportSharedPtr = std::shared_ptr<ILayerSupport>; using IBackendSpecificModelContextPtr = std::shared_ptr<IBackendModelContext>; using IMemoryManagerUniquePtr = std::unique_ptr<IMemoryManager>; using IMemoryManagerSharedPtr = std::shared_ptr<IMemoryManager>; virtual IMemoryManagerUniquePtr CreateMemoryManager() const; virtual IWorkloadFactoryPtr CreateWorkloadFactory( const IMemoryManagerSharedPtr& memoryManager = nullptr) const = 0; virtual IWorkloadFactoryPtr CreateWorkloadFactory( class TensorHandleFactoryRegistry& tensorHandleFactoryRegistry) const; virtual IWorkloadFactoryPtr CreateWorkloadFactory( const IMemoryManagerSharedPtr& memoryManager, const ModelOptions& modelOptions) const; virtual IWorkloadFactoryPtr CreateWorkloadFactory( class TensorHandleFactoryRegistry& tensorHandleFactoryRegistry, const ModelOptions& modelOptions) const; virtual IWorkloadFactoryPtr CreateWorkloadFactory( class TensorHandleFactoryRegistry& tensorHandleFactoryRegistry, const ModelOptions& modelOptions, MemorySourceFlags inputFlags, MemorySourceFlags outputFlags) const; /// Create the runtime context of the backend /// /// Implementations may return a default-constructed IBackendContextPtr if /// no context is needed at runtime. /// Implementations must throw BackendUnavailableException if the backend /// cannot be used (for example, necessary accelerator hardware is not present). /// The default implementation always returns a default-constructed pointer. virtual IBackendContextPtr CreateBackendContext(const IRuntime::CreationOptions&) const; virtual IBackendSpecificModelContextPtr CreateBackendSpecificModelContext(const ModelOptions& modelOptions) const; /// Create context specifically used for profiling interaction from backends. virtual IBackendProfilingContextPtr CreateBackendProfilingContext(const IRuntime::CreationOptions& creationOptions, IBackendProfilingPtr& backendProfiling); virtual ILayerSupportSharedPtr GetLayerSupport() const = 0; virtual ILayerSupportSharedPtr GetLayerSupport(const ModelOptions& modelOptions) const; virtual OptimizationViews OptimizeSubgraphView(const SubgraphView& subgraph) const; virtual OptimizationViews OptimizeSubgraphView(const SubgraphView& subgraph, const ModelOptions& modelOptions) const; bool SupportsTensorAllocatorAPI() const; ITensorHandleFactory::FactoryId GetBackwardCompatibleFavoriteHandleFactory(); /// (Optional) Returns a vector of supported TensorHandleFactory ids in preference order. virtual std::vector<ITensorHandleFactory::FactoryId> GetHandleFactoryPreferences() const; /// (Optional) Register TensorHandleFactories /// Either this method or CreateMemoryManager() and /// IWorkloadFactory::CreateTensor()/IWorkloadFactory::CreateSubtensor() methods must be implemented. virtual void RegisterTensorHandleFactories(class TensorHandleFactoryRegistry& /*registry*/) {} /// (Optional) Register TensorHandleFactories /// Either this method or CreateMemoryManager() and /// IWorkloadFactory::CreateTensor()/IWorkloadFactory::CreateSubtensor() methods must be implemented. virtual void RegisterTensorHandleFactories(class TensorHandleFactoryRegistry& registry, MemorySourceFlags inputFlags, MemorySourceFlags outputFlags); /// Returns the version of the Backend API static constexpr BackendVersion GetApiVersion() { return BackendVersion(1, 0); } /// Returns a BackendCapability if the backend lists the capability /// The BackendCapability must then be inspected to check whether or not that BackendCapability is supported /// Otherwise returns an EmptyOptional if the BackendCapability is unlisted virtual BackendCapabilities GetCapabilities() const { return BackendCapabilities("IBackendInternal NullCapabilities"); }; /// Returns true if backend support the capability false otherwise ARMNN_DEPRECATED_MSG_REMOVAL_DATE("This function has been deprecated in favour of GetCapability", "22.05") virtual bool HasCapability(BackendCapability /*capabilityClass*/) const { return false; } /// Signals the backend to use a custom memory allocator provided by the user /// /// \param allocator - a pointer to the provided ICustomAllocator to use with this backend /// \param errMsg - Optional string variable to return error messages /// \return - Returns true if switching to custom allocator was successful virtual bool UseCustomMemoryAllocator(std::shared_ptr<ICustomAllocator> allocator, armnn::Optional<std::string&> errMsg) { IgnoreUnused(allocator); if (errMsg) { std::stringstream message; message << "The backend " << GetId() << " doesn't support using a custom allocator. This error might" " be related with the protected mode if the backend doesn't" " fully support it."; errMsg.value() = message.str(); } return false; } /// Returns the default memory allocator for the backend /// /// \return - Returns unique pointer to the Default Allocator of the Backend virtual std::unique_ptr<ICustomAllocator> GetDefaultAllocator() const { throw armnn::Exception("GetDefaultAllocator: Function has not been implemented in backend."); } /// Returns the number of files cached if backend supports caching /// /// \return - Returns 0 if backend does not support caching otherwise number of files cached virtual unsigned int GetNumberOfCacheFiles() const { return 0; } }; using IBackendInternalUniquePtr = std::unique_ptr<IBackendInternal>; } // namespace armnn <commit_msg>IVGCVSW-6582 Remove Optimization.hpp from IBackendInternal<commit_after>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include <armnn/Types.hpp> #include <armnn/IRuntime.hpp> #include <armnn/Deprecated.hpp> #include <ISubgraphViewConverter.hpp> #include <SubgraphView.hpp> #include <armnn/backends/IBackendContext.hpp> #include <armnn/backends/IMemoryManager.hpp> #include <armnn/backends/ITensorHandleFactory.hpp> #include <armnn/backends/OptimizationViews.hpp> #include <armnn/backends/profiling/IBackendProfiling.hpp> #include <armnn/backends/profiling/IBackendProfilingContext.hpp> #include <vector> #include <memory> namespace armnn { class IWorkloadFactory; class IMemoryManager; class ILayerSupport; struct BackendVersion { uint32_t m_Major; uint32_t m_Minor; constexpr BackendVersion() : m_Major(0) , m_Minor(0) {} constexpr BackendVersion(uint32_t major, uint32_t minor) : m_Major(major) , m_Minor(minor) {} bool operator==(const BackendVersion& other) const { return this == &other || (this->m_Major == other.m_Major && this->m_Minor == other.m_Minor); } bool operator<=(const BackendVersion& other) const { return this->m_Major < other.m_Major || (this->m_Major == other.m_Major && this->m_Minor <= other.m_Minor); } bool operator>=(const BackendVersion& other) const { return this->m_Major > other.m_Major || (this->m_Major == other.m_Major && this->m_Minor >= other.m_Minor); } }; inline std::ostream& operator<<(std::ostream& os, const BackendVersion& backendVersion) { os << "[" << backendVersion.m_Major << "." << backendVersion.m_Minor << "]"; return os; } class IBackendInternal : public IBackend { protected: /// Creation must be done through a specific /// backend interface. IBackendInternal() = default; public: /// Allow backends created by the factory function /// to be destroyed through IBackendInternal. ~IBackendInternal() override = default; using IWorkloadFactoryPtr = std::unique_ptr<IWorkloadFactory>; using IBackendContextPtr = std::unique_ptr<IBackendContext>; /// This is the bridge between backend and backend profiling we'll keep it in the backend namespace. using IBackendProfilingContextPtr = std::shared_ptr<armnn::profiling::IBackendProfilingContext>; using IBackendProfilingPtr = std::unique_ptr<armnn::profiling::IBackendProfiling>; using ILayerSupportSharedPtr = std::shared_ptr<ILayerSupport>; using IBackendSpecificModelContextPtr = std::shared_ptr<IBackendModelContext>; using IMemoryManagerUniquePtr = std::unique_ptr<IMemoryManager>; using IMemoryManagerSharedPtr = std::shared_ptr<IMemoryManager>; virtual IMemoryManagerUniquePtr CreateMemoryManager() const; virtual IWorkloadFactoryPtr CreateWorkloadFactory( const IMemoryManagerSharedPtr& memoryManager = nullptr) const = 0; virtual IWorkloadFactoryPtr CreateWorkloadFactory( class TensorHandleFactoryRegistry& tensorHandleFactoryRegistry) const; virtual IWorkloadFactoryPtr CreateWorkloadFactory( const IMemoryManagerSharedPtr& memoryManager, const ModelOptions& modelOptions) const; virtual IWorkloadFactoryPtr CreateWorkloadFactory( class TensorHandleFactoryRegistry& tensorHandleFactoryRegistry, const ModelOptions& modelOptions) const; virtual IWorkloadFactoryPtr CreateWorkloadFactory( class TensorHandleFactoryRegistry& tensorHandleFactoryRegistry, const ModelOptions& modelOptions, MemorySourceFlags inputFlags, MemorySourceFlags outputFlags) const; /// Create the runtime context of the backend /// /// Implementations may return a default-constructed IBackendContextPtr if /// no context is needed at runtime. /// Implementations must throw BackendUnavailableException if the backend /// cannot be used (for example, necessary accelerator hardware is not present). /// The default implementation always returns a default-constructed pointer. virtual IBackendContextPtr CreateBackendContext(const IRuntime::CreationOptions&) const; virtual IBackendSpecificModelContextPtr CreateBackendSpecificModelContext(const ModelOptions& modelOptions) const; /// Create context specifically used for profiling interaction from backends. virtual IBackendProfilingContextPtr CreateBackendProfilingContext(const IRuntime::CreationOptions& creationOptions, IBackendProfilingPtr& backendProfiling); virtual ILayerSupportSharedPtr GetLayerSupport() const = 0; virtual ILayerSupportSharedPtr GetLayerSupport(const ModelOptions& modelOptions) const; virtual OptimizationViews OptimizeSubgraphView(const SubgraphView& subgraph) const; virtual OptimizationViews OptimizeSubgraphView(const SubgraphView& subgraph, const ModelOptions& modelOptions) const; bool SupportsTensorAllocatorAPI() const; ITensorHandleFactory::FactoryId GetBackwardCompatibleFavoriteHandleFactory(); /// (Optional) Returns a vector of supported TensorHandleFactory ids in preference order. virtual std::vector<ITensorHandleFactory::FactoryId> GetHandleFactoryPreferences() const; /// (Optional) Register TensorHandleFactories /// Either this method or CreateMemoryManager() and /// IWorkloadFactory::CreateTensor()/IWorkloadFactory::CreateSubtensor() methods must be implemented. virtual void RegisterTensorHandleFactories(class TensorHandleFactoryRegistry& /*registry*/) {} /// (Optional) Register TensorHandleFactories /// Either this method or CreateMemoryManager() and /// IWorkloadFactory::CreateTensor()/IWorkloadFactory::CreateSubtensor() methods must be implemented. virtual void RegisterTensorHandleFactories(class TensorHandleFactoryRegistry& registry, MemorySourceFlags inputFlags, MemorySourceFlags outputFlags); /// Returns the version of the Backend API static constexpr BackendVersion GetApiVersion() { return BackendVersion(1, 0); } /// Returns a BackendCapability if the backend lists the capability /// The BackendCapability must then be inspected to check whether or not that BackendCapability is supported /// Otherwise returns an EmptyOptional if the BackendCapability is unlisted virtual BackendCapabilities GetCapabilities() const { return BackendCapabilities("IBackendInternal NullCapabilities"); }; /// Returns true if backend support the capability false otherwise ARMNN_DEPRECATED_MSG_REMOVAL_DATE("This function has been deprecated in favour of GetCapability", "22.05") virtual bool HasCapability(BackendCapability /*capabilityClass*/) const { return false; } /// Signals the backend to use a custom memory allocator provided by the user /// /// \param allocator - a pointer to the provided ICustomAllocator to use with this backend /// \param errMsg - Optional string variable to return error messages /// \return - Returns true if switching to custom allocator was successful virtual bool UseCustomMemoryAllocator(std::shared_ptr<ICustomAllocator> allocator, armnn::Optional<std::string&> errMsg) { IgnoreUnused(allocator); if (errMsg) { std::stringstream message; message << "The backend " << GetId() << " doesn't support using a custom allocator. This error might" " be related with the protected mode if the backend doesn't" " fully support it."; errMsg.value() = message.str(); } return false; } /// Returns the default memory allocator for the backend /// /// \return - Returns unique pointer to the Default Allocator of the Backend virtual std::unique_ptr<ICustomAllocator> GetDefaultAllocator() const { throw armnn::Exception("GetDefaultAllocator: Function has not been implemented in backend."); } /// Returns the number of files cached if backend supports caching /// /// \return - Returns 0 if backend does not support caching otherwise number of files cached virtual unsigned int GetNumberOfCacheFiles() const { return 0; } }; using IBackendInternalUniquePtr = std::unique_ptr<IBackendInternal>; } // namespace armnn <|endoftext|>