text
stringlengths
54
60.6k
<commit_before>{ // //This macro produces the flowchart of TFormula::Analyze //Author: Rene Brun gROOT->Reset(); c1 = new TCanvas("c1","Analyze.mac",620,790); c1->Range(-1,0,19,30); TPaveLabel pl1(0,27,3.5,29,"Analyze"); pl1.SetFillColor(42); pl1.Draw(); TPaveText pt1(0,22.8,4,25.2); TText *t1=pt1.AddText("Parenthesis matching"); TText *t2=pt1.AddText("Remove unnecessary"); TText *t2a=pt1.AddText("parenthesis"); pt1.Draw(); TPaveText pt2(6,23,10,25); TText *t3=pt2.AddText("break of"); TText *t4=pt2.AddText("Analyze"); pt2.Draw(); TPaveText pt3(0,19,4,21); t4=pt3.AddText("look for simple"); TText *t5=pt3.AddText("operators"); pt3.Draw(); TPaveText pt4(0,15,4,17); TText *t6=pt4.AddText("look for an already"); TText *t7=pt4.AddText("defined expression"); pt4.Draw(); TPaveText pt5(0,11,4,13); TText *t8=pt5.AddText("look for usual"); TText *t9=pt5.AddText("functions :cos sin .."); pt5.Draw(); TPaveText pt6(0,7,4,9); TText *t10=pt6.AddText("look for a"); TText *t11=pt6.AddText("numeric value"); pt6.Draw(); TPaveText pt7(6,18.5,10,21.5); TText *t12=pt7.AddText("Analyze left and"); TText *t13=pt7.AddText("right part of"); TText *t14=pt7.AddText("the expression"); pt7.Draw(); TPaveText pt8(6,15,10,17); TText *t15=pt8.AddText("Replace expression"); pt8.Draw(); TPaveText pt9(6,11,10,13); TText *t16=pt9.AddText("Analyze"); pt9.SetFillColor(42); pt9.Draw(); TPaveText pt10(6,7,10,9); TText *t17=pt10.AddText("Error"); TText *t18=pt10.AddText("Break of Analyze"); pt10.Draw(); TPaveText pt11(14,22,17,24); pt11.SetFillColor(42); TText *t19=pt11.AddText("Analyze"); TText *t19a=pt11.AddText("Left"); pt11.Draw(); TPaveText pt12(14,19,17,21); pt12.SetFillColor(42); TText *t20=pt12.AddText("Analyze"); TText *t20a=pt12.AddText("Right"); pt12.Draw(); TPaveText pt13(14,15,18,18); TText *t21=pt13.AddText("StackNumber++"); TText *t22=pt13.AddText("operator[StackNumber]"); TText *t23=pt13.AddText("= operator found"); pt13.Draw(); TPaveText pt14(12,10.8,17,13.2); TText *t24=pt14.AddText("StackNumber++"); TText *t25=pt14.AddText("operator[StackNumber]"); TText *t26=pt14.AddText("= function found"); pt14.Draw(); TPaveText pt15(6,7,10,9); TText *t27=pt15.AddText("Error"); TText *t28=pt15.AddText("break of Analyze"); pt15.Draw(); TPaveText pt16(0,2,7,5); TText *t29=pt16.AddText("StackNumber++"); TText *t30=pt16.AddText("operator[StackNumber] = 0"); TText *t31=pt16.AddText("value[StackNumber] = value found"); pt16.Draw(); TArrow ar(2,27,2,25.4,0.012,"|>"); ar.SetFillColor(1); ar.Draw(); ar.DrawArrow(2,22.8,2,21.2,0.012,"|>"); ar.DrawArrow(2,19,2,17.2,0.012,"|>"); ar.DrawArrow(2,15,2,13.2,0.012,"|>"); ar.DrawArrow(2,11,2, 9.2,0.012,"|>"); ar.DrawArrow(2, 7,2, 5.2,0.012,"|>"); ar.DrawArrow(4,24,6,24,0.012,"|>"); ar.DrawArrow(4,20,6,20,0.012,"|>"); ar.DrawArrow(4,16,6,16,0.012,"|>"); ar.DrawArrow(4,12,6,12,0.012,"|>"); ar.DrawArrow(4, 8,6, 8,0.012,"|>"); ar.DrawArrow(10,20,14,20,0.012,"|>"); ar.DrawArrow(12,23,14,23,0.012,"|>"); ar.DrawArrow(12,16.5,14,16.5,0.012,"|>"); ar.DrawArrow(10,12,12,12,0.012,"|>"); TText ta(2.2,22.2,"err = 0"); ta.SetTextFont(71); ta.SetTextSize(0.015); ta.SetTextColor(4); ta.SetTextAlign(12); ta.Draw(); ta.DrawText(2.2,18.2,"not found"); ta.DrawText(2.2,6.2,"found"); TText tb(4.2,24.1,"err != 0"); tb.SetTextFont(71); tb.SetTextSize(0.015); tb.SetTextColor(4); tb.SetTextAlign(11); tb.Draw(); tb.DrawText(4.2,20.1,"found"); tb.DrawText(4.2,16.1,"found"); tb.DrawText(4.2,12.1,"found"); tb.DrawText(4.2, 8.1,"not found"); TLine l1(12,16.5,12,23); l1.Draw(); } <commit_msg>make sure this macro can be executed several time.s<commit_after>void analyze() { // //This macro produces the flowchart of TFormula::Analyze //Author: Rene Brun TCanvas *c1 = new TCanvas("c1","Analyze.mac",620,790); c1->Range(-1,0,19,30); TPaveLabel *pl1 = new TPaveLabel(0,27,3.5,29,"Analyze"); pl1->SetFillColor(42); pl1->Draw(); TPaveText *pt1 = new TPaveText(0,22.8,4,25.2); TText *t1 = pt1->AddText("Parenthesis matching"); TText *t2 = pt1->AddText("Remove unnecessary"); TText *t2a = pt1->AddText("parenthesis"); pt1->Draw(); TPaveText *pt2 = new TPaveText(6,23,10,25); TText *t3 = pt2->AddText("break of"); TText *t4 = pt2->AddText("Analyze"); pt2->Draw(); TPaveText *pt3 = new TPaveText(0,19,4,21); t4=pt3->AddText("look for simple"); TText *t5 = pt3->AddText("operators"); pt3->Draw(); TPaveText *pt4 = new TPaveText(0,15,4,17); TText *t6 = pt4->AddText("look for an already"); TText *t7 = pt4->AddText("defined expression"); pt4->Draw(); TPaveText *pt5 = new TPaveText(0,11,4,13); TText *t8 = pt5->AddText("look for usual"); TText *t9 = pt5->AddText("functions :cos sin .."); pt5->Draw(); TPaveText *pt6 = new TPaveText(0,7,4,9); TText *t10 = pt6->AddText("look for a"); TText *t11 = pt6->AddText("numeric value"); pt6->Draw(); TPaveText *pt7 = new TPaveText(6,18.5,10,21.5); TText *t12 = pt7->AddText("Analyze left and"); TText *t13 = pt7->AddText("right part of"); TText *t14 = pt7->AddText("the expression"); pt7->Draw(); TPaveText *pt8 = new TPaveText(6,15,10,17); TText *t15 = pt8->AddText("Replace expression"); pt8->Draw(); TPaveText *pt9 = new TPaveText(6,11,10,13); TText *t16 = pt9->AddText("Analyze"); pt9->SetFillColor(42); pt9->Draw(); TPaveText *pt10 = new TPaveText(6,7,10,9); TText *t17 = pt10->AddText("Error"); TText *t18 = pt10->AddText("Break of Analyze"); pt10->Draw(); TPaveText *pt11 = new TPaveText(14,22,17,24); pt11->SetFillColor(42); TText *t19 = pt11->AddText("Analyze"); TText *t19a = pt11->AddText("Left"); pt11->Draw(); TPaveText *pt12 = new TPaveText(14,19,17,21); pt12->SetFillColor(42); TText *t20 = pt12->AddText("Analyze"); TText *t20a = pt12->AddText("Right"); pt12->Draw(); TPaveText *pt13 = new TPaveText(14,15,18,18); TText *t21 = pt13->AddText("StackNumber++"); TText *t22 = pt13->AddText("operator[StackNumber]"); TText *t23 = pt13->AddText("= operator found"); pt13->Draw(); TPaveText *pt14 = new TPaveText(12,10.8,17,13.2); TText *t24 = pt14->AddText("StackNumber++"); TText *t25 = pt14->AddText("operator[StackNumber]"); TText *t26 = pt14->AddText("= function found"); pt14->Draw(); TPaveText *pt15 = new TPaveText(6,7,10,9); TText *t27 = pt15->AddText("Error"); TText *t28 = pt15->AddText("break of Analyze"); pt15->Draw(); TPaveText *pt16 = new TPaveText(0,2,7,5); TText *t29 = pt16->AddText("StackNumber++"); TText *t30 = pt16->AddText("operator[StackNumber] = 0"); TText *t31 = pt16->AddText("value[StackNumber] = value found"); pt16->Draw(); TArrow *ar = new TArrow(2,27,2,25.4,0.012,"|>"); ar->SetFillColor(1); ar->Draw(); ar->DrawArrow(2,22.8,2,21.2,0.012,"|>"); ar->DrawArrow(2,19,2,17.2,0.012,"|>"); ar->DrawArrow(2,15,2,13.2,0.012,"|>"); ar->DrawArrow(2,11,2, 9.2,0.012,"|>"); ar->DrawArrow(2, 7,2, 5.2,0.012,"|>"); ar->DrawArrow(4,24,6,24,0.012,"|>"); ar->DrawArrow(4,20,6,20,0.012,"|>"); ar->DrawArrow(4,16,6,16,0.012,"|>"); ar->DrawArrow(4,12,6,12,0.012,"|>"); ar->DrawArrow(4, 8,6, 8,0.012,"|>"); ar->DrawArrow(10,20,14,20,0.012,"|>"); ar->DrawArrow(12,23,14,23,0.012,"|>"); ar->DrawArrow(12,16.5,14,16.5,0.012,"|>"); ar->DrawArrow(10,12,12,12,0.012,"|>"); TText *ta = new TText(2.2,22.2,"err = 0"); ta->SetTextFont(71); ta->SetTextSize(0.015); ta->SetTextColor(4); ta->SetTextAlign(12); ta->Draw(); ta->DrawText(2.2,18.2,"not found"); ta->DrawText(2.2,6.2,"found"); TText *tb = new TText(4.2,24.1,"err != 0"); tb->SetTextFont(71); tb->SetTextSize(0.015); tb->SetTextColor(4); tb->SetTextAlign(11); tb->Draw(); tb->DrawText(4.2,20.1,"found"); tb->DrawText(4.2,16.1,"found"); tb->DrawText(4.2,12.1,"found"); tb->DrawText(4.2, 8.1,"not found"); TLine *l1 = new TLine(12,16.5,12,23); l1->Draw(); } <|endoftext|>
<commit_before>#include "../demo_addresses.hpp" #include "messages/op_codes.h" #include <chrono> #include <component.hpp> #include <iostream> #include <local_communicator.hpp> #include <local_component_routing_table.hpp> #include <messages/local/local_hello.h> #include <messages/spa/spa_data.h> #include <messages/spa/subscription_reply.h> #include <messages/spa/subscription_request.h> #include <socket/clientSocket.hpp> #include <thread> #include <unistd.h> #include "medianFilterStream.h" class MedianFilter; void messageCallback(std::shared_ptr<Component> comp, cubiumClientSocket_t* sock); class MedianFilter : public Component { public: MedianFilter(std::shared_ptr<SpaCommunicator> com = nullptr) : Component(com) { const int filterOrder = 32; int readingsByTime[filterOrder] = {0}; int readingsByValue[filterOrder] = {0}; lightStream = MedianFilterStream<int>(readingsByTime, readingsByValue, filterOrder); tempStream = MedianFilterStream<int>(readingsByTime, readingsByValue, filterOrder); } virtual void handleSpaData(SpaMessage* message) { auto op = message->spaHeader.opcode; std::cout << "Received SpaMessage with opcode: " << (int)op << '\n'; if (op == op_SPA_SUBSCRIPTION_REQUEST) { SubscriptionReply reply(message->spaHeader.source, la_medianFilter); communicator->send((SpaMessage*)&reply); if (addSubscriber(message->spaHeader.source, 0)) { std::cout << "Added " << message->spaHeader.source << " as a subscriber" << std::endl; } publish(); } else if (op == op_SPA_DATA) { auto dataMessage = (SpaData*)message; std::cout << "Received data with payload: " << (int)dataMessage->payload << " from " << message->spaHeader.source << std::endl; auto payload = (int)dataMessage->payload; if (message->spaHeader.source == la_temp) { tempStream.addDataPoint(payload); } else if (message->spaHeader.source == la_light) { lightStream.addDataPoint(payload); } } } virtual void sendSpaData(LogicalAddress address) { auto payload = 1; auto light = lightStream.getFilteredDataPoint(); auto temp = tempStream.getFilteredDataPoint(); if (light > 80 && light <= 100 && temp > 0) // Arbitrary condition { payload = 0; } std::cout << "Sending SpaData: " << payload << std::endl; SpaData dataMessage(address, la_medianFilter, payload); communicator->send((SpaMessage*)&dataMessage); } virtual void appInit() { std::cout << "Median filter initializing!" << '\n'; LocalHello hello(0, 0, la_LSM, la_medianFilter, 0, 0, 0, 0); communicator->getLocalCommunicator()->clientConnect((SpaMessage*)&hello, sizeof(hello), [=](cubiumClientSocket_t* s) { messageCallback(shared_from_this(), s); }); SubscriptionRequest request1(la_light, la_medianFilter, la_LSM); communicator->getLocalCommunicator()->initSubDialogue((SpaMessage*)&request1, sizeof(request1), [=](cubiumClientSocket_t* s) { messageCallback(shared_from_this(), s); }); SubscriptionRequest request2(la_temp, la_medianFilter, la_LSM); communicator->getLocalCommunicator()->initSubDialogue((SpaMessage*)&request2, sizeof(request2), [=](cubiumClientSocket_t* s) { messageCallback(shared_from_this(), s); }); communicator->getLocalCommunicator()->clientListen( [=](cubiumClientSocket_t* s) { messageCallback(shared_from_this(), s); }); } private: MedianFilterStream<int> lightStream; MedianFilterStream<int> tempStream; }; void messageCallback(std::shared_ptr<Component> comp, cubiumClientSocket_t* sock) { SpaMessage* message = (SpaMessage*)sock->buf; comp->handleSpaData(message); return; } int main() { cubiumClientSocket_t sock = clientSocket_openSocket(3500); auto routingTable = std::make_shared<RoutingTable<cubiumServerSocket_t>>(); std::vector<std::shared_ptr<PhysicalCommunicator>> comms = { std::make_shared<LocalCommunicator>(&sock, routingTable, la_medianFilter)}; std::shared_ptr<SpaCommunicator> spaCom = std::make_shared<SpaCommunicator>(la_medianFilter, comms); auto comp = std::make_shared<MedianFilter>(spaCom); comp->appInit(); return 0; } <commit_msg>fix medianFilter segfault<commit_after>#include "../demo_addresses.hpp" #include "messages/op_codes.h" #include <chrono> #include <component.hpp> #include <iostream> #include <local_communicator.hpp> #include <local_component_routing_table.hpp> #include <messages/local/local_hello.h> #include <messages/spa/spa_data.h> #include <messages/spa/subscription_reply.h> #include <messages/spa/subscription_request.h> #include <socket/clientSocket.hpp> #include <thread> #include <unistd.h> #include "medianFilterStream.h" class MedianFilter; void messageCallback(std::shared_ptr<Component> comp, cubiumClientSocket_t* sock); class MedianFilter : public Component { public: MedianFilter(std::shared_ptr<SpaCommunicator> com = nullptr) : Component(com) { const int filterOrder = 32; float readingsByTime[filterOrder] = {0}; float readingsByValue[filterOrder] = {0}; lightStream = MedianFilterStream<float>(readingsByTime, readingsByValue, filterOrder); tempStream = MedianFilterStream<float>(readingsByTime, readingsByValue, filterOrder); } virtual void handleSpaData(SpaMessage* message) { auto op = message->spaHeader.opcode; std::cout << "Received SpaMessage with opcode: " << (int)op << '\n'; if (op == op_SPA_SUBSCRIPTION_REQUEST) { SubscriptionReply reply(message->spaHeader.source, la_medianFilter); communicator->send((SpaMessage*)&reply); if (addSubscriber(message->spaHeader.source, 0)) { std::cout << "Added " << message->spaHeader.source << " as a subscriber" << std::endl; } publish(); } else if (op == op_SPA_DATA) { auto dataMessage = (SpaData*)message; std::cout << "Received data with payload: " << (int)dataMessage->payload << " from " << message->spaHeader.source << std::endl; auto payload = (float)dataMessage->payload; if (message->spaHeader.source == la_temp) { tempStream.addDataPoint(payload); } else if (message->spaHeader.source == la_light) { lightStream.addDataPoint(payload); } } } virtual void sendSpaData(LogicalAddress address) { auto payload = 0; auto light = lightStream.getFilteredDataPoint(); auto temp = tempStream.getFilteredDataPoint(); if (light > 80 && light <= 100 && temp > 0) // Arbitrary condition { payload = 1; } std::cout << "Sending SpaData: " << payload << std::endl; SpaData dataMessage(address, la_medianFilter, payload); communicator->send((SpaMessage*)&dataMessage); } virtual void appInit() { std::cout << "Median filter initializing!" << '\n'; LocalHello hello(0, 0, la_LSM, la_medianFilter, 0, 0, 0, 0); communicator->getLocalCommunicator()->clientConnect((SpaMessage*)&hello, sizeof(hello), [=](cubiumClientSocket_t* s) { messageCallback(shared_from_this(), s); }); SubscriptionRequest request1(la_light, la_medianFilter, la_LSM); communicator->getLocalCommunicator()->initSubDialogue((SpaMessage*)&request1, sizeof(request1), [=](cubiumClientSocket_t* s) { messageCallback(shared_from_this(), s); }); SubscriptionRequest request2(la_temp, la_medianFilter, la_LSM); communicator->getLocalCommunicator()->initSubDialogue((SpaMessage*)&request2, sizeof(request2), [=](cubiumClientSocket_t* s) { messageCallback(shared_from_this(), s); }); communicator->getLocalCommunicator()->clientListen( [=](cubiumClientSocket_t* s) { messageCallback(shared_from_this(), s); }); } private: MedianFilterStream<float> lightStream; MedianFilterStream<float> tempStream; }; void messageCallback(std::shared_ptr<Component> comp, cubiumClientSocket_t* sock) { SpaMessage* message = (SpaMessage*)sock->buf; comp->handleSpaData(message); return; } int main() { cubiumClientSocket_t sock = clientSocket_openSocket(3500); auto routingTable = std::make_shared<RoutingTable<cubiumServerSocket_t>>(); std::vector<std::shared_ptr<PhysicalCommunicator>> comms = { std::make_shared<LocalCommunicator>(&sock, routingTable, la_medianFilter)}; std::shared_ptr<SpaCommunicator> spaCom = std::make_shared<SpaCommunicator>(la_medianFilter, comms); auto comp = std::make_shared<MedianFilter>(spaCom); comp->appInit(); return 0; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #ifndef _Stroika_Foundation_Streams_InputOutputStream_inl_ #define _Stroika_Foundation_Streams_InputOutputStream_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ namespace Stroika { namespace Foundation { namespace Streams { /* ******************************************************************************** ********************** InputOutputStream<ELEMENT_TYPE> ************************* ******************************************************************************** */ template <typename ELEMENT_TYPE> inline InputOutputStream<ELEMENT_TYPE>::InputOutputStream (const _SharedIRep& rep) : InputStream<ELEMENT_TYPE> (rep) , OutputStream<ELEMENT_TYPE> (rep) { } template <typename ELEMENT_TYPE> inline InputOutputStream<ELEMENT_TYPE>::InputOutputStream (nullptr_t) : InputStream<ELEMENT_TYPE> (nullptr) , OutputStream<ELEMENT_TYPE> (nullptr) { } template <typename ELEMENT_TYPE> inline auto InputOutputStream<ELEMENT_TYPE>::_GetSharedRep () const -> _SharedIRep { Ensure (dynamic_pointer_cast<_IRep> (InputStream<ELEMENT_TYPE>::_GetSharedRep ()) == dynamic_pointer_cast<_IRep> (OutputStream<ELEMENT_TYPE>::_GetSharedRep ())); return dynamic_pointer_cast<_IRep> (InputStream<ELEMENT_TYPE>::_GetSharedRep ()); } template <typename ELEMENT_TYPE> inline auto InputOutputStream<ELEMENT_TYPE>::_GetRepConstRef () const -> const _IRep& { Ensure (&InputStream<ELEMENT_TYPE>::_GetRepConstRef () == &OutputStream<ELEMENT_TYPE>::_GetRepConstRef ()); EnsureMember (&InputStream<ELEMENT_TYPE>::_GetRepConstRef (), _IRep); return *reinterpret_cast<const _IRep*> (&InputStream<ELEMENT_TYPE>::_GetRepConstRef ()); // faster than dynamic_cast, and if not equivilent, add caching later here } template <typename ELEMENT_TYPE> inline auto InputOutputStream<ELEMENT_TYPE>::_GetRepRWRef () const -> _IRep& { Ensure (&InputStream<ELEMENT_TYPE>::_GetRepRWRef () == &OutputStream<ELEMENT_TYPE>::_GetRepRWRef ()); EnsureMember (&InputStream<ELEMENT_TYPE>::_GetRepRWRef (), _IRep); return *reinterpret_cast<_IRep*> (&InputStream<ELEMENT_TYPE>::_GetRepRWRef ()); // faster than dynamic_cast, and if not equivilent, add caching later here } template <typename ELEMENT_TYPE> inline bool InputOutputStream<ELEMENT_TYPE>::empty () const { Ensure (InputStream<ELEMENT_TYPE>::empty () == OutputStream<ELEMENT_TYPE>::empty ()); return InputStream<ELEMENT_TYPE>::empty (); } template <typename ELEMENT_TYPE> inline bool InputOutputStream<ELEMENT_TYPE>::IsSeekable () const { Require (InputStream<ELEMENT_TYPE>::IsSeekable () == OutputStream<ELEMENT_TYPE>::IsSeekable ()); return InputStream<ELEMENT_TYPE>::IsSeekable (); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::GetReadOffset () const { return InputStream<ELEMENT_TYPE>::GetOffset (); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::GetWriteOffset () const { return OutputStream<ELEMENT_TYPE>::GetOffset (); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::SeekWrite (SignedSeekOffsetType offset) const { return OutputStream<ELEMENT_TYPE>::Seek (offset); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::SeekWrite (Whence whence, SignedSeekOffsetType offset) const { return OutputStream<ELEMENT_TYPE>::Seek (whence, offset); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::SeekRead (SignedSeekOffsetType offset) const { return InputStream<ELEMENT_TYPE>::Seek (offset); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::SeekRead (Whence whence, SignedSeekOffsetType offset) const { return InputStream<ELEMENT_TYPE>::Seek (whence, offset); } } } } #endif /*_Stroika_Foundation_Streams_InputOutputStream_inl_*/ <commit_msg>fixed ensure check in InputOutputStream<ELEMENT_TYPE>::_GetRepConstRef ()<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #ifndef _Stroika_Foundation_Streams_InputOutputStream_inl_ #define _Stroika_Foundation_Streams_InputOutputStream_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ namespace Stroika { namespace Foundation { namespace Streams { /* ******************************************************************************** ********************** InputOutputStream<ELEMENT_TYPE> ************************* ******************************************************************************** */ template <typename ELEMENT_TYPE> inline InputOutputStream<ELEMENT_TYPE>::InputOutputStream (const _SharedIRep& rep) : InputStream<ELEMENT_TYPE> (rep) , OutputStream<ELEMENT_TYPE> (rep) { } template <typename ELEMENT_TYPE> inline InputOutputStream<ELEMENT_TYPE>::InputOutputStream (nullptr_t) : InputStream<ELEMENT_TYPE> (nullptr) , OutputStream<ELEMENT_TYPE> (nullptr) { } template <typename ELEMENT_TYPE> inline auto InputOutputStream<ELEMENT_TYPE>::_GetSharedRep () const -> _SharedIRep { Ensure (dynamic_pointer_cast<_IRep> (InputStream<ELEMENT_TYPE>::_GetSharedRep ()) == dynamic_pointer_cast<_IRep> (OutputStream<ELEMENT_TYPE>::_GetSharedRep ())); return dynamic_pointer_cast<_IRep> (InputStream<ELEMENT_TYPE>::_GetSharedRep ()); } template <typename ELEMENT_TYPE> inline auto InputOutputStream<ELEMENT_TYPE>::_GetRepConstRef () const -> const _IRep& { Ensure (dynamic_cast<const _IRep*> (&InputStream<ELEMENT_TYPE>::_GetRepConstRef ()) == dynamic_cast<const _IRep*> (&OutputStream<ELEMENT_TYPE>::_GetRepConstRef ())); EnsureMember (&InputStream<ELEMENT_TYPE>::_GetRepConstRef (), _IRep); return *reinterpret_cast<const _IRep*> (&InputStream<ELEMENT_TYPE>::_GetRepConstRef ()); // faster than dynamic_cast, and if not equivilent, add caching later here } template <typename ELEMENT_TYPE> inline auto InputOutputStream<ELEMENT_TYPE>::_GetRepRWRef () const -> _IRep& { Ensure (&InputStream<ELEMENT_TYPE>::_GetRepRWRef () == &OutputStream<ELEMENT_TYPE>::_GetRepRWRef ()); EnsureMember (&InputStream<ELEMENT_TYPE>::_GetRepRWRef (), _IRep); return *reinterpret_cast<_IRep*> (&InputStream<ELEMENT_TYPE>::_GetRepRWRef ()); // faster than dynamic_cast, and if not equivilent, add caching later here } template <typename ELEMENT_TYPE> inline bool InputOutputStream<ELEMENT_TYPE>::empty () const { Ensure (InputStream<ELEMENT_TYPE>::empty () == OutputStream<ELEMENT_TYPE>::empty ()); return InputStream<ELEMENT_TYPE>::empty (); } template <typename ELEMENT_TYPE> inline bool InputOutputStream<ELEMENT_TYPE>::IsSeekable () const { Require (InputStream<ELEMENT_TYPE>::IsSeekable () == OutputStream<ELEMENT_TYPE>::IsSeekable ()); return InputStream<ELEMENT_TYPE>::IsSeekable (); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::GetReadOffset () const { return InputStream<ELEMENT_TYPE>::GetOffset (); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::GetWriteOffset () const { return OutputStream<ELEMENT_TYPE>::GetOffset (); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::SeekWrite (SignedSeekOffsetType offset) const { return OutputStream<ELEMENT_TYPE>::Seek (offset); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::SeekWrite (Whence whence, SignedSeekOffsetType offset) const { return OutputStream<ELEMENT_TYPE>::Seek (whence, offset); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::SeekRead (SignedSeekOffsetType offset) const { return InputStream<ELEMENT_TYPE>::Seek (offset); } template <typename ELEMENT_TYPE> inline SeekOffsetType InputOutputStream<ELEMENT_TYPE>::SeekRead (Whence whence, SignedSeekOffsetType offset) const { return InputStream<ELEMENT_TYPE>::Seek (whence, offset); } } } } #endif /*_Stroika_Foundation_Streams_InputOutputStream_inl_*/ <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbSarImageMetadataInterface.h" #include "otbRadarsat2ImageMetadataInterface.h" #include "otbMacro.h" #include "itkMetaDataObject.h" #include "otbImageKeywordlist.h" //useful constants #include <otbMath.h> namespace otb { Radarsat2ImageMetadataInterface ::Radarsat2ImageMetadataInterface() { } bool Radarsat2ImageMetadataInterface::CanRead() const { std::string sensorID = GetSensorID(); if (sensorID.find("RADARSAT-2") != std::string::npos) { return true; } else return false; } void Radarsat2ImageMetadataInterface:: CreateCalibrationLookupData(const short type) { std::string lut = "SigmaNought"; switch (type) { case SarCalibrationLookupData::BETA: { lut = "BetaNought"; } break; case SarCalibrationLookupData::GAMMA: { lut = "GammaNought"; } break; case SarCalibrationLookupData::DN: { lut = "DN"; } break; case SarCalibrationLookupData::SIGMA: default: { lut = "SigmaNought"; } break; } const ImageKeywordlistType imageKeywordlist = this->GetImageKeywordlist(); const std::string key = "referenceNoiseLevel[" + lut + "].gain"; Radarsat2CalibrationLookupData::GainListType glist; int offset = 0; Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey("referenceNoiseLevel[" + lut + "].gain"), glist, "referenceNoiseLevel[" + lut + "].gain"); Utils::LexicalCast<int>(imageKeywordlist.GetMetadataByKey("referenceNoiseLevel[" + lut + "].offset"), "referenceNoiseLevel[" + lut + "].offset"); Radarsat2CalibrationLookupData::Pointer sarLut; sarLut = Radarsat2CalibrationLookupData::New(); sarLut->InitParameters(type, offset, glist); this->SetCalibrationLookupData(sarLut); } void Radarsat2ImageMetadataInterface ::ParseDateTime(const char* key, std::vector<int>& dateFields) const { if(dateFields.size() < 1 ) { //parse from keyword list if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, not a valid product"); } const ImageKeywordlistType imageKeywordlist = this->GetImageKeywordlist(); if (!imageKeywordlist.HasKey(key)) { itkExceptionMacro( << "no key named " << key ); } const std::string date_time_str = imageKeywordlist.GetMetadataByKey(key); Utils::ConvertStringToVector(date_time_str, dateFields, " T:.Z" "T:.Z"); } } int Radarsat2ImageMetadataInterface::GetYear() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if(m_AcquisitionDateFields.size() > 0 ) { value = Utils::LexicalCast<int>( m_AcquisitionDateFields[0], "support_data.image_date(year)" ); } return value; } int Radarsat2ImageMetadataInterface::GetMonth() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if(m_AcquisitionDateFields.size() > 1 ) { value = Utils::LexicalCast<int>( m_AcquisitionDateFields[1], "support_data.image_date(month)" ); } return value; } int Radarsat2ImageMetadataInterface::GetDay() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if(m_AcquisitionDateFields.size() > 2 ) { value = Utils::LexicalCast<int>( m_AcquisitionDateFields[2], "support_data.image_date(day)" ); } return value; } int Radarsat2ImageMetadataInterface::GetHour() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if(m_AcquisitionDateFields.size() > 3 ) { value = Utils::LexicalCast<int>( m_AcquisitionDateFields[3], "support_data.image_date(hour)" ); } return value; } int Radarsat2ImageMetadataInterface::GetMinute() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if(m_AcquisitionDateFields.size() > 4 ) { value = Utils::LexicalCast<int>( m_AcquisitionDateFields[4], "support_data.image_date(minute)" ); } return value; } int Radarsat2ImageMetadataInterface::GetProductionYear() const { int value = 0; ParseDateTime("support_data.date", m_ProductionDateFields); if(m_ProductionDateFields.size() > 0 ) { value = Utils::LexicalCast<int>( m_ProductionDateFields[0], "support_data.image_date(year)" ); } return value; } int Radarsat2ImageMetadataInterface::GetProductionMonth() const { int value = 0; ParseDateTime("support_data.date", m_ProductionDateFields); if(m_ProductionDateFields.size() > 1 ) { value = Utils::LexicalCast<int>( m_ProductionDateFields[1], "support_data.image_date(production month)" ); } return value; } int Radarsat2ImageMetadataInterface::GetProductionDay() const { int value = 0; ParseDateTime("support_data.date", m_ProductionDateFields); if(m_ProductionDateFields.size() > 2 ) { value = Utils::LexicalCast<int>( m_ProductionDateFields[2], "support_data.image_date(production day)" ); } return value; } double Radarsat2ImageMetadataInterface::GetPRF() const { return 0; } double Radarsat2ImageMetadataInterface::GetRSF() const { return 0; } double Radarsat2ImageMetadataInterface::GetRadarFrequency() const { return 0; } double Radarsat2ImageMetadataInterface::GetCenterIncidenceAngle() const { return 0; } Radarsat2ImageMetadataInterface::UIntVectorType Radarsat2ImageMetadataInterface:: GetDefaultDisplay() const { UIntVectorType rgb(3); rgb[0] = 0; rgb[1] = 0; rgb[2] = 0; return rgb; } } // end namespace otb <commit_msg>ENH: pass substring of data_time utc string<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbSarImageMetadataInterface.h" #include "otbRadarsat2ImageMetadataInterface.h" #include "otbMacro.h" #include "itkMetaDataObject.h" #include "otbImageKeywordlist.h" //useful constants #include <otbMath.h> namespace otb { Radarsat2ImageMetadataInterface ::Radarsat2ImageMetadataInterface() { } bool Radarsat2ImageMetadataInterface::CanRead() const { std::string sensorID = GetSensorID(); if (sensorID.find("RADARSAT-2") != std::string::npos) { return true; } else return false; } void Radarsat2ImageMetadataInterface:: CreateCalibrationLookupData(const short type) { std::string lut = "SigmaNought"; switch (type) { case SarCalibrationLookupData::BETA: { lut = "BetaNought"; } break; case SarCalibrationLookupData::GAMMA: { lut = "GammaNought"; } break; case SarCalibrationLookupData::DN: { lut = "DN"; } break; case SarCalibrationLookupData::SIGMA: default: { lut = "SigmaNought"; } break; } const ImageKeywordlistType imageKeywordlist = this->GetImageKeywordlist(); const std::string key = "referenceNoiseLevel[" + lut + "].gain"; Radarsat2CalibrationLookupData::GainListType glist; int offset = 0; Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey("referenceNoiseLevel[" + lut + "].gain"), glist, "referenceNoiseLevel[" + lut + "].gain"); Utils::LexicalCast<int>(imageKeywordlist.GetMetadataByKey("referenceNoiseLevel[" + lut + "].offset"), "referenceNoiseLevel[" + lut + "].offset"); Radarsat2CalibrationLookupData::Pointer sarLut; sarLut = Radarsat2CalibrationLookupData::New(); sarLut->InitParameters(type, offset, glist); this->SetCalibrationLookupData(sarLut); } void Radarsat2ImageMetadataInterface ::ParseDateTime(const char* key, std::vector<int>& dateFields) const { if(dateFields.size() < 1 ) { //parse from keyword list if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, not a valid product"); } const ImageKeywordlistType imageKeywordlist = this->GetImageKeywordlist(); if (!imageKeywordlist.HasKey(key)) { itkExceptionMacro( << "no key named '" << key << "'"); } const std::string date_time_str = imageKeywordlist.GetMetadataByKey(key); Utils::ConvertStringToVector(date_time_str.substr(0, date_time_str.size()-1), dateFields, key, "-T:."); } } int Radarsat2ImageMetadataInterface::GetYear() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if(m_AcquisitionDateFields.size() > 0 ) { value = Utils::LexicalCast<int>( m_AcquisitionDateFields[0], "support_data.image_date(year)" ); } return value; } int Radarsat2ImageMetadataInterface::GetMonth() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if(m_AcquisitionDateFields.size() > 1 ) { value = Utils::LexicalCast<int>( m_AcquisitionDateFields[1], "support_data.image_date(month)" ); } return value; } int Radarsat2ImageMetadataInterface::GetDay() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if(m_AcquisitionDateFields.size() > 2 ) { value = Utils::LexicalCast<int>( m_AcquisitionDateFields[2], "support_data.image_date(day)" ); } return value; } int Radarsat2ImageMetadataInterface::GetHour() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if(m_AcquisitionDateFields.size() > 3 ) { value = Utils::LexicalCast<int>( m_AcquisitionDateFields[3], "support_data.image_date(hour)" ); } return value; } int Radarsat2ImageMetadataInterface::GetMinute() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if(m_AcquisitionDateFields.size() > 4 ) { value = Utils::LexicalCast<int>( m_AcquisitionDateFields[4], "support_data.image_date(minute)" ); } return value; } int Radarsat2ImageMetadataInterface::GetProductionYear() const { int value = 0; ParseDateTime("support_data.date", m_ProductionDateFields); if(m_ProductionDateFields.size() > 0 ) { value = Utils::LexicalCast<int>( m_ProductionDateFields[0], "support_data.image_date(year)" ); } return value; } int Radarsat2ImageMetadataInterface::GetProductionMonth() const { int value = 0; ParseDateTime("support_data.date", m_ProductionDateFields); if(m_ProductionDateFields.size() > 1 ) { value = Utils::LexicalCast<int>( m_ProductionDateFields[1], "support_data.image_date(production month)" ); } return value; } int Radarsat2ImageMetadataInterface::GetProductionDay() const { int value = 0; ParseDateTime("support_data.date", m_ProductionDateFields); if(m_ProductionDateFields.size() > 2 ) { value = Utils::LexicalCast<int>( m_ProductionDateFields[2], "support_data.image_date(production day)" ); } return value; } double Radarsat2ImageMetadataInterface::GetPRF() const { return 0; } double Radarsat2ImageMetadataInterface::GetRSF() const { return 0; } double Radarsat2ImageMetadataInterface::GetRadarFrequency() const { return 0; } double Radarsat2ImageMetadataInterface::GetCenterIncidenceAngle() const { return 0; } Radarsat2ImageMetadataInterface::UIntVectorType Radarsat2ImageMetadataInterface:: GetDefaultDisplay() const { UIntVectorType rgb(3); rgb[0] = 0; rgb[1] = 0; rgb[2] = 0; return rgb; } } // end namespace otb <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkGTest.h" #include "itkSLICImageFilter.h" #include "itkVectorImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkCommand.h" #include "itkImageFileWriter.h" #include "itkTestDriverIncludeRequiredIOFactories.h" #include "itkTestingHashImageFilter.h" namespace { class SLICFixture : public ::testing::Test { public: SLICFixture() {} ~SLICFixture() override {} protected: void SetUp() override { RegisterRequiredFactories(); } template<typename TImageType> static void WriteImage(const TImageType * inputImage, const std::string & fileName) { auto writer = itk::ImageFileWriter<TImageType>::New(); writer->SetFileName(fileName); writer->SetInput(inputImage); writer->Update(); } template<typename TImageType> static std::string MD5Hash(const TImageType *image) { using HashFilter = itk::Testing::HashImageFilter<TImageType>; typename HashFilter::Pointer hasher = HashFilter::New(); hasher->SetInput( image ); hasher->Update(); return hasher->GetHash(); } template<unsigned int D, typename TPixelType = unsigned short> struct FixtureUtilities { static const unsigned int Dimension = D; using PixelType = TPixelType; using OutputPixelType = unsigned int; using InputImageType = itk::Image<PixelType, Dimension>; using OutputImageType = itk::Image<OutputPixelType, Dimension>; using FilterType = itk::SLICImageFilter<InputImageType, OutputImageType>; // Create a black image or empty static typename InputImageType::Pointer CreateImage(unsigned int size = 100) { typename InputImageType::Pointer image = InputImageType::New(); typename InputImageType::SizeType imageSize; imageSize.Fill(size); image->SetRegions(typename InputImageType::RegionType(imageSize)); image->Allocate(); image->FillBuffer(0); return image; } }; }; } TEST_F(SLICFixture, SetGetPrint) { using namespace itk::GTest::TypedefsAndConstructors::Dimension3; using Utils = FixtureUtilities<3>; auto filter = Utils::FilterType::New(); filter->Print(std::cout); typename Utils::FilterType::ConstPointer constfilter = (const Utils::FilterType*)(filter.GetPointer()); EXPECT_STREQ("SLICImageFilter", filter->GetNameOfClass()); EXPECT_STREQ("ImageToImageFilter", filter->Superclass::GetNameOfClass()); Utils::FilterType:: SuperGridSizeType gridSize3(3); EXPECT_NO_THROW(filter->SetSuperGridSize(gridSize3)); EXPECT_VECTOR_NEAR(gridSize3, filter->GetSuperGridSize(), 0); EXPECT_NO_THROW(filter->SetSuperGridSize(4)); EXPECT_VECTOR_NEAR(Utils::FilterType:: SuperGridSizeType(4), filter->GetSuperGridSize(), 0); EXPECT_NO_THROW(filter->SetMaximumNumberOfIterations(6)); EXPECT_EQ(6, filter->GetMaximumNumberOfIterations()); EXPECT_NO_THROW(filter->SetSpatialProximityWeight(9.1)); EXPECT_EQ(9.1, filter->GetSpatialProximityWeight()); EXPECT_NO_THROW(filter->EnforceConnectivityOn()); EXPECT_TRUE(filter->GetEnforceConnectivity()); EXPECT_NO_THROW(filter->EnforceConnectivityOff()); EXPECT_FALSE(filter->GetEnforceConnectivity()); EXPECT_NO_THROW(filter->SetEnforceConnectivity(true)); EXPECT_TRUE(filter->GetEnforceConnectivity()); EXPECT_NO_THROW(filter->InitializationPerturbationOn()); EXPECT_TRUE(filter->GetInitializationPerturbation()); EXPECT_NO_THROW(filter->InitializationPerturbationOff()); EXPECT_FALSE(filter->GetInitializationPerturbation()); EXPECT_NO_THROW(filter->SetInitializationPerturbation(true)); EXPECT_TRUE(filter->GetInitializationPerturbation()); } TEST_F(SLICFixture, Blank2DImage) { using namespace itk::GTest::TypedefsAndConstructors::Dimension2; using Utils = FixtureUtilities<2>; auto filter = Utils::FilterType::New(); auto image = Utils::CreateImage(100); filter->SetInput(image); filter->SetSuperGridSize(10); filter->Update(); EXPECT_EQ("68707adc3df2f7d210b1db96847fc3c5", MD5Hash(filter->GetOutput())); filter->SetSuperGridSize(1); filter->Update(); EXPECT_EQ("10d461742d48d15b8df75387187de426", MD5Hash(filter->GetOutput())); filter->SetSuperGridSize(200); filter->Update(); EXPECT_EQ("4e0a293a5b638f0aba2c4fe2c3418d0e", MD5Hash(filter->GetOutput())); } <commit_msg>COMP: Remove unused testing function and headers<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkGTest.h" #include "itkSLICImageFilter.h" #include "itkVectorImage.h" #include "itkCommand.h" #include "itkTestDriverIncludeRequiredIOFactories.h" #include "itkTestingHashImageFilter.h" namespace { class SLICFixture : public ::testing::Test { public: SLICFixture() {} ~SLICFixture() override {} protected: void SetUp() override { RegisterRequiredFactories(); } template<typename TImageType> static std::string MD5Hash(const TImageType *image) { using HashFilter = itk::Testing::HashImageFilter<TImageType>; typename HashFilter::Pointer hasher = HashFilter::New(); hasher->SetInput( image ); hasher->Update(); return hasher->GetHash(); } template<unsigned int D, typename TPixelType = unsigned short> struct FixtureUtilities { static const unsigned int Dimension = D; using PixelType = TPixelType; using OutputPixelType = unsigned int; using InputImageType = itk::Image<PixelType, Dimension>; using OutputImageType = itk::Image<OutputPixelType, Dimension>; using FilterType = itk::SLICImageFilter<InputImageType, OutputImageType>; // Create a black image or empty static typename InputImageType::Pointer CreateImage(unsigned int size = 100) { typename InputImageType::Pointer image = InputImageType::New(); typename InputImageType::SizeType imageSize; imageSize.Fill(size); image->SetRegions(typename InputImageType::RegionType(imageSize)); image->Allocate(); image->FillBuffer(0); return image; } }; }; } TEST_F(SLICFixture, SetGetPrint) { using namespace itk::GTest::TypedefsAndConstructors::Dimension3; using Utils = FixtureUtilities<3>; auto filter = Utils::FilterType::New(); filter->Print(std::cout); typename Utils::FilterType::ConstPointer constfilter = (const Utils::FilterType*)(filter.GetPointer()); EXPECT_STREQ("SLICImageFilter", filter->GetNameOfClass()); EXPECT_STREQ("ImageToImageFilter", filter->Superclass::GetNameOfClass()); Utils::FilterType:: SuperGridSizeType gridSize3(3); EXPECT_NO_THROW(filter->SetSuperGridSize(gridSize3)); EXPECT_VECTOR_NEAR(gridSize3, filter->GetSuperGridSize(), 0); EXPECT_NO_THROW(filter->SetSuperGridSize(4)); EXPECT_VECTOR_NEAR(Utils::FilterType:: SuperGridSizeType(4), filter->GetSuperGridSize(), 0); EXPECT_NO_THROW(filter->SetMaximumNumberOfIterations(6)); EXPECT_EQ(6, filter->GetMaximumNumberOfIterations()); EXPECT_NO_THROW(filter->SetSpatialProximityWeight(9.1)); EXPECT_EQ(9.1, filter->GetSpatialProximityWeight()); EXPECT_NO_THROW(filter->EnforceConnectivityOn()); EXPECT_TRUE(filter->GetEnforceConnectivity()); EXPECT_NO_THROW(filter->EnforceConnectivityOff()); EXPECT_FALSE(filter->GetEnforceConnectivity()); EXPECT_NO_THROW(filter->SetEnforceConnectivity(true)); EXPECT_TRUE(filter->GetEnforceConnectivity()); EXPECT_NO_THROW(filter->InitializationPerturbationOn()); EXPECT_TRUE(filter->GetInitializationPerturbation()); EXPECT_NO_THROW(filter->InitializationPerturbationOff()); EXPECT_FALSE(filter->GetInitializationPerturbation()); EXPECT_NO_THROW(filter->SetInitializationPerturbation(true)); EXPECT_TRUE(filter->GetInitializationPerturbation()); } TEST_F(SLICFixture, Blank2DImage) { using namespace itk::GTest::TypedefsAndConstructors::Dimension2; using Utils = FixtureUtilities<2>; auto filter = Utils::FilterType::New(); auto image = Utils::CreateImage(100); filter->SetInput(image); filter->SetSuperGridSize(10); filter->Update(); EXPECT_EQ("68707adc3df2f7d210b1db96847fc3c5", MD5Hash(filter->GetOutput())); filter->SetSuperGridSize(1); filter->Update(); EXPECT_EQ("10d461742d48d15b8df75387187de426", MD5Hash(filter->GetOutput())); filter->SetSuperGridSize(200); filter->Update(); EXPECT_EQ("4e0a293a5b638f0aba2c4fe2c3418d0e", MD5Hash(filter->GetOutput())); } <|endoftext|>
<commit_before> #include <zorba/zorba_api.h> #ifdef HAVE_PTHREAD_H # include <pthread.h> #else # include "win32_pthread/pthread.h" #endif #include <iostream> using namespace std; using namespace xqp; /* Using Zorba in full api mode. Init the engine, create a query in main thread and execute it in parallel threads. This way we optimize on compiling time. The xquery from main thread is cloned in the parallel threads. Each function is checked for errors. No try catch mechanism is demonstrated here. */ void* query_thread(void *param); string make_absolute_file_name(const char *target_file_name, const char *this_file_name); #define NR_THREADS 20 static XQuery_t xquery; int uc7_multithread(int argc, char* argv[]) { //init the engine in full api mode ZorbaEngine_t zorba_engine = ZorbaEngine::getInstance(); unsigned int i; pthread_t pt[NR_THREADS]; //ensure the single thread engine is shutdown zorba_engine->shutdown(); zorba_engine = ZorbaEngine::getInstance(); //in full api mode you have to call initThread() / uninitThread() zorba_engine->initThread(); //create and compile a query with the static context xquery = zorba_engine->createQuery("declare variable $var1 external; .//chapter[@id=$var1]"); if(xquery == NULL) { cout << "Error creating and compiling query1" << endl; exit(1); return 1; } for(i=0;i<NR_THREADS;i++) { pthread_create(&pt[i], NULL, query_thread, (void*)i); } ///now wait for threads to finish for(i=0;i<NR_THREADS;i++) { void *thread_result; pthread_join(pt[i], &thread_result); } //close the engine for this thread and shutdown completely zorba_engine->uninitThread(); zorba_engine->shutdown(); return 0; } void* query_thread(void *param) { //ZorbaEngine::getInstance can be called at any time //only first call initializes the engine ZorbaEngine_t zorba_engine = ZorbaEngine::getInstance(); DynamicQueryContext_t dctx; unsigned int iparam = (unsigned int)param; XQuery_t xquery_clone; //must call initThread before using any of Zorba features (other than getInstance()) zorba_engine->initThread(); xquery_clone = xquery->clone(); if(xquery_clone == NULL) { cout << "cannot clone xquery object" << endl; exit(1); zorba_engine->uninitThread(); return (void*)1; } XmlDataManager_t zorba_store = zorba_engine->getXmlDataManager(); //load a document into xml data manager //and then load it into a variable zorba_store->loadDocument(make_absolute_file_name("books.xml", __FILE__)); dctx = zorba_engine->createDynamicContext(); //context item is set as variable with reserved name "." if(!dctx->setContextItemAsDocument(make_absolute_file_name("books.xml", __FILE__))) { cout << "cannot load document into context item" << endl; exit(1); zorba_engine->uninitThread(); return (void*)1; } if(!dctx->setVariableAsInt("var1", iparam)) { cout << "cannot set var1 to iparam " << iparam << endl; exit(1); zorba_engine->uninitThread(); return (void*)1; } //execute the query and serialize its result if(!xquery_clone->initExecution(dctx) || !xquery_clone->serializeXML(std::cout))//output will be a little scrammbled { cout << "Error executing and serializing query" << endl; exit(1); zorba_engine->uninitThread(); return (void*)1; } //must uninit the thread zorba_engine->uninitThread(); //using zorba objects after this moment is prohibited return (void*)0; } <commit_msg>read-only multithreaded zorba<commit_after> #include <zorba/zorba_api.h> #ifdef HAVE_PTHREAD_H # include <pthread.h> #else # include "win32_pthread/pthread.h" #endif #include <iostream> using namespace std; using namespace xqp; /* Using Zorba in full api mode. Init the engine, create a query in main thread and execute it in parallel threads. This way we optimize on compiling time. The xquery from main thread is cloned in the parallel threads. Each function is checked for errors. No try catch mechanism is demonstrated here. */ void* query_thread(void *param); string make_absolute_file_name(const char *target_file_name, const char *this_file_name); #define NR_THREADS 20 struct ThreadArgs { unsigned int theId; XQuery* theQuery; }; int uc7_multithread(int argc, char* argv[]) { //init the engine in full api mode ZorbaEngine_t zorba_engine = ZorbaEngine::getInstance(); unsigned int i; pthread_t pt[NR_THREADS]; //ensure the single thread engine is shutdown zorba_engine->shutdown(); zorba_engine = ZorbaEngine::getInstance(); //in full api mode you have to call initThread() / uninitThread() zorba_engine->initThread(); //create and compile a query with the static context XQuery_t xquery = zorba_engine->createQuery("declare variable $var1 external; .//chapter[@id=$var1]"); if(xquery == NULL) { cout << "Error creating and compiling query1" << endl; exit(1); return 1; } ThreadArgs targs[NR_THREADS]; for(i = 0; i < NR_THREADS; i++) { targs[i].theId = i; targs[i].theQuery = xquery; pthread_create(&pt[i], NULL, query_thread, (void*)(&targs[i])); } ///now wait for threads to finish for(i=0;i<NR_THREADS;i++) { void *thread_result; pthread_join(pt[i], &thread_result); } xquery = 0; //close the engine for this thread and shutdown completely zorba_engine->uninitThread(); zorba_engine->shutdown(); return 0; } void* query_thread(void *param) { //ZorbaEngine::getInstance can be called at any time //only first call initializes the engine ZorbaEngine_t zorba_engine = ZorbaEngine::getInstance(); DynamicQueryContext_t dctx; XQuery_t xquery_clone; ThreadArgs* args = (ThreadArgs*)param; //must call initThread before using any of Zorba features (other than getInstance()) zorba_engine->initThread(); xquery_clone = args->theQuery->clone(); if(xquery_clone == NULL) { cout << "cannot clone xquery object" << endl; exit(1); zorba_engine->uninitThread(); return (void*)1; } XmlDataManager_t zorba_store = zorba_engine->getXmlDataManager(); //load a document into xml data manager //and then load it into a variable zorba_store->loadDocument(make_absolute_file_name("books.xml", __FILE__)); dctx = zorba_engine->createDynamicContext(); //context item is set as variable with reserved name "." if(!dctx->setContextItemAsDocument(make_absolute_file_name("books.xml", __FILE__))) { cout << "cannot load document into context item" << endl; exit(1); zorba_engine->uninitThread(); return (void*)1; } if(!dctx->setVariableAsInt("var1", args->theId)) { cout << "cannot set var1 to iparam " << args->theId << endl; exit(1); zorba_engine->uninitThread(); return (void*)1; } //execute the query and serialize its result if(!xquery_clone->initExecution(dctx) || !xquery_clone->serializeXML(std::cout))//output will be a little scrammbled { cout << "Error executing and serializing query" << endl; exit(1); zorba_engine->uninitThread(); return (void*)1; } //must uninit the thread zorba_engine->uninitThread(); //using zorba objects after this moment is prohibited return (void*)0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 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 "video_engine/vie_sync_module.h" #include "modules/rtp_rtcp/interface/rtp_rtcp.h" #include "modules/video_coding/main/interface/video_coding.h" #include "system_wrappers/interface/critical_section_wrapper.h" #include "system_wrappers/interface/trace.h" #include "video_engine/stream_synchronization.h" #include "video_engine/vie_channel.h" #include "voice_engine/include/voe_video_sync.h" namespace webrtc { enum { kSyncInterval = 1000}; int UpdateMeasurements(StreamSynchronization::Measurements* stream, const RtpRtcp* rtp_rtcp) { stream->latest_timestamp = rtp_rtcp->RemoteTimestamp(); stream->latest_receive_time_ms = rtp_rtcp->LocalTimeOfRemoteTimeStamp(); synchronization::RtcpMeasurement measurement; if (0 != rtp_rtcp->RemoteNTP(&measurement.ntp_secs, &measurement.ntp_frac, NULL, NULL, &measurement.rtp_timestamp)) { return -1; } if (measurement.ntp_secs == 0 && measurement.ntp_frac == 0) { return -1; } for (synchronization::RtcpList::iterator it = stream->rtcp.begin(); it != stream->rtcp.end(); ++it) { if (measurement.ntp_secs == (*it).ntp_secs && measurement.ntp_frac == (*it).ntp_frac) { // This RTCP has already been added to the list. return 0; } } // We need two RTCP SR reports to map between RTP and NTP. More than two will // not improve the mapping. if (stream->rtcp.size() == 2) { stream->rtcp.pop_back(); } stream->rtcp.push_front(measurement); return 0; } ViESyncModule::ViESyncModule(VideoCodingModule* vcm, ViEChannel* vie_channel) : data_cs_(CriticalSectionWrapper::CreateCriticalSection()), vcm_(vcm), vie_channel_(vie_channel), video_rtp_rtcp_(NULL), voe_channel_id_(-1), voe_sync_interface_(NULL), last_sync_time_(TickTime::Now()), sync_() { } ViESyncModule::~ViESyncModule() { } int ViESyncModule::ConfigureSync(int voe_channel_id, VoEVideoSync* voe_sync_interface, RtpRtcp* video_rtcp_module) { CriticalSectionScoped cs(data_cs_.get()); voe_channel_id_ = voe_channel_id; voe_sync_interface_ = voe_sync_interface; video_rtp_rtcp_ = video_rtcp_module; sync_.reset(new StreamSynchronization(voe_channel_id, vie_channel_->Id())); if (!voe_sync_interface) { voe_channel_id_ = -1; if (voe_channel_id >= 0) { // Trying to set a voice channel but no interface exist. return -1; } return 0; } return 0; } int ViESyncModule::VoiceChannel() { return voe_channel_id_; } WebRtc_Word32 ViESyncModule::TimeUntilNextProcess() { return static_cast<WebRtc_Word32>(kSyncInterval - (TickTime::Now() - last_sync_time_).Milliseconds()); } WebRtc_Word32 ViESyncModule::Process() { CriticalSectionScoped cs(data_cs_.get()); last_sync_time_ = TickTime::Now(); int total_video_delay_target_ms = vcm_->Delay(); WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, vie_channel_->Id(), "Video delay (JB + decoder) is %d ms", total_video_delay_target_ms); if (voe_channel_id_ == -1) { return 0; } assert(video_rtp_rtcp_ && voe_sync_interface_); assert(sync_.get()); int current_audio_delay_ms = 0; if (voe_sync_interface_->GetDelayEstimate(voe_channel_id_, current_audio_delay_ms) != 0) { // Could not get VoE delay value, probably not a valid channel Id. WEBRTC_TRACE(webrtc::kTraceStream, webrtc::kTraceVideo, vie_channel_->Id(), "%s: VE_GetDelayEstimate error for voice_channel %d", __FUNCTION__, voe_channel_id_); return 0; } // VoiceEngine report delay estimates even when not started, ignore if the // reported value is lower than 40 ms. if (current_audio_delay_ms < 40) { WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, vie_channel_->Id(), "A/V Sync: Audio delay < 40, skipping."); return 0; } RtpRtcp* voice_rtp_rtcp = NULL; if (0 != voe_sync_interface_->GetRtpRtcp(voe_channel_id_, voice_rtp_rtcp)) { return 0; } assert(voice_rtp_rtcp); if (UpdateMeasurements(&video_measurement_, video_rtp_rtcp_) != 0) { return 0; } if (UpdateMeasurements(&audio_measurement_, voice_rtp_rtcp) != 0) { return 0; } int relative_delay_ms; // Calculate how much later or earlier the audio stream is compared to video. if (!sync_->ComputeRelativeDelay(audio_measurement_, video_measurement_, &relative_delay_ms)) { return 0; } int extra_audio_delay_ms = 0; // Calculate the necessary extra audio delay and desired total video // delay to get the streams in sync. if (sync_->ComputeDelays(relative_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_target_ms) != 0) { return 0; } if (voe_sync_interface_->SetMinimumPlayoutDelay( voe_channel_id_, extra_audio_delay_ms) == -1) { WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, vie_channel_->Id(), "Error setting voice delay"); } vcm_->SetMinimumPlayoutDelay(total_video_delay_target_ms); WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, vie_channel_->Id(), "New Video delay target is: %d", total_video_delay_target_ms); return 0; } } // namespace webrtc <commit_msg>Fixes an incorrect if statement in vie_sync_module.cc.<commit_after>/* * Copyright (c) 2012 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 "video_engine/vie_sync_module.h" #include "modules/rtp_rtcp/interface/rtp_rtcp.h" #include "modules/video_coding/main/interface/video_coding.h" #include "system_wrappers/interface/critical_section_wrapper.h" #include "system_wrappers/interface/trace.h" #include "video_engine/stream_synchronization.h" #include "video_engine/vie_channel.h" #include "voice_engine/include/voe_video_sync.h" namespace webrtc { enum { kSyncInterval = 1000}; int UpdateMeasurements(StreamSynchronization::Measurements* stream, const RtpRtcp* rtp_rtcp) { stream->latest_timestamp = rtp_rtcp->RemoteTimestamp(); stream->latest_receive_time_ms = rtp_rtcp->LocalTimeOfRemoteTimeStamp(); synchronization::RtcpMeasurement measurement; if (0 != rtp_rtcp->RemoteNTP(&measurement.ntp_secs, &measurement.ntp_frac, NULL, NULL, &measurement.rtp_timestamp)) { return -1; } if (measurement.ntp_secs == 0 && measurement.ntp_frac == 0) { return -1; } for (synchronization::RtcpList::iterator it = stream->rtcp.begin(); it != stream->rtcp.end(); ++it) { if (measurement.ntp_secs == (*it).ntp_secs && measurement.ntp_frac == (*it).ntp_frac) { // This RTCP has already been added to the list. return 0; } } // We need two RTCP SR reports to map between RTP and NTP. More than two will // not improve the mapping. if (stream->rtcp.size() == 2) { stream->rtcp.pop_back(); } stream->rtcp.push_front(measurement); return 0; } ViESyncModule::ViESyncModule(VideoCodingModule* vcm, ViEChannel* vie_channel) : data_cs_(CriticalSectionWrapper::CreateCriticalSection()), vcm_(vcm), vie_channel_(vie_channel), video_rtp_rtcp_(NULL), voe_channel_id_(-1), voe_sync_interface_(NULL), last_sync_time_(TickTime::Now()), sync_() { } ViESyncModule::~ViESyncModule() { } int ViESyncModule::ConfigureSync(int voe_channel_id, VoEVideoSync* voe_sync_interface, RtpRtcp* video_rtcp_module) { CriticalSectionScoped cs(data_cs_.get()); voe_channel_id_ = voe_channel_id; voe_sync_interface_ = voe_sync_interface; video_rtp_rtcp_ = video_rtcp_module; sync_.reset(new StreamSynchronization(voe_channel_id, vie_channel_->Id())); if (!voe_sync_interface) { voe_channel_id_ = -1; if (voe_channel_id >= 0) { // Trying to set a voice channel but no interface exist. return -1; } return 0; } return 0; } int ViESyncModule::VoiceChannel() { return voe_channel_id_; } WebRtc_Word32 ViESyncModule::TimeUntilNextProcess() { return static_cast<WebRtc_Word32>(kSyncInterval - (TickTime::Now() - last_sync_time_).Milliseconds()); } WebRtc_Word32 ViESyncModule::Process() { CriticalSectionScoped cs(data_cs_.get()); last_sync_time_ = TickTime::Now(); int total_video_delay_target_ms = vcm_->Delay(); WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, vie_channel_->Id(), "Video delay (JB + decoder) is %d ms", total_video_delay_target_ms); if (voe_channel_id_ == -1) { return 0; } assert(video_rtp_rtcp_ && voe_sync_interface_); assert(sync_.get()); int current_audio_delay_ms = 0; if (voe_sync_interface_->GetDelayEstimate(voe_channel_id_, current_audio_delay_ms) != 0) { // Could not get VoE delay value, probably not a valid channel Id. WEBRTC_TRACE(webrtc::kTraceStream, webrtc::kTraceVideo, vie_channel_->Id(), "%s: VE_GetDelayEstimate error for voice_channel %d", __FUNCTION__, voe_channel_id_); return 0; } // VoiceEngine report delay estimates even when not started, ignore if the // reported value is lower than 40 ms. if (current_audio_delay_ms < 40) { WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, vie_channel_->Id(), "A/V Sync: Audio delay < 40, skipping."); return 0; } RtpRtcp* voice_rtp_rtcp = NULL; if (0 != voe_sync_interface_->GetRtpRtcp(voe_channel_id_, voice_rtp_rtcp)) { return 0; } assert(voice_rtp_rtcp); if (UpdateMeasurements(&video_measurement_, video_rtp_rtcp_) != 0) { return 0; } if (UpdateMeasurements(&audio_measurement_, voice_rtp_rtcp) != 0) { return 0; } int relative_delay_ms; // Calculate how much later or earlier the audio stream is compared to video. if (!sync_->ComputeRelativeDelay(audio_measurement_, video_measurement_, &relative_delay_ms)) { return 0; } int extra_audio_delay_ms = 0; // Calculate the necessary extra audio delay and desired total video // delay to get the streams in sync. if (!sync_->ComputeDelays(relative_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_target_ms)) { return 0; } if (voe_sync_interface_->SetMinimumPlayoutDelay( voe_channel_id_, extra_audio_delay_ms) == -1) { WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, vie_channel_->Id(), "Error setting voice delay"); } vcm_->SetMinimumPlayoutDelay(total_video_delay_target_ms); WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, vie_channel_->Id(), "New Video delay target is: %d", total_video_delay_target_ms); return 0; } } // namespace webrtc <|endoftext|>
<commit_before>/// @file /// @author Boris Mikic /// @version 2.0 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php #if HAVE_SDL #include <SDL/SDL.h> #include "Buffer.h" #include "SDL_AudioManager.h" #include "SDL_Player.h" #include "Sound.h" #include "xal.h" namespace xal { SDL_Player::SDL_Player(Sound* sound, Buffer* buffer) : Player(sound, buffer), playing(false), position(0), currentGain(1.0f), readPosition(0), writePosition(0) { memset(this->circleBuffer, 0, STREAM_BUFFER * sizeof(unsigned char)); } SDL_Player::~SDL_Player() { } void SDL_Player::_getData(int size, unsigned char** data1, int* size1, unsigned char** data2, int* size2) { if (!this->sound->isStreamed()) { int streamSize = this->buffer->load(this->looping, size); unsigned char* stream = this->buffer->getStream(); *data1 = &stream[this->readPosition]; *size1 = hmin(hmin(streamSize, streamSize - this->readPosition), size); *data2 = NULL; *size2 = 0; if (this->looping && this->readPosition + size > streamSize) { *data2 = stream; *size2 = size - *size1; } this->readPosition = (this->readPosition + size) % streamSize; return; } *data1 = &this->circleBuffer[this->readPosition]; *size1 = size; *data2 = NULL; *size2 = 0; if (this->readPosition + size > STREAM_BUFFER) { *size1 = STREAM_BUFFER - this->readPosition; *data2 = this->circleBuffer; *size2 = size - *size1; } this->readPosition = (this->readPosition + size) % STREAM_BUFFER; } void SDL_Player::_update(float k) { Player::_update(k); int size = this->buffer->getSize(); if (this->position >= size) { if (this->looping) { this->position -= this->position / size * size; } else if (this->playing) { this->_sysStop(); } } } void SDL_Player::mixAudio(unsigned char* stream, int length, bool first) { if (!this->playing) { return; } unsigned char* data1; unsigned char* data2; int size1; int size2; this->_getData(length, &data1, &size1, &data2, &size2); if (size1 > 0) { if (first && this->currentGain == 1.0f) { memcpy(stream, data1, size1); if (size2 > 0) { memcpy(&stream[size1], data2, size2); } } else { short* sStream = (short*)stream; short* sData = (short*)data1; // TODO - normalize endianess here? size1 = size1 * sizeof(unsigned char) / sizeof(short); size2 = size2 * sizeof(unsigned char) / sizeof(short); if (!first) { for (int i = 0; i < size1; i++) { sStream[i] = (short)hclamp((int)(sStream[i] + this->currentGain * sData[i]), -32768, 32767); } sData = (short*)data2; for (int i = 0; i < size2; i++) { sStream[size1 + i] = (short)hclamp((int)(sStream[size1 + i] + this->currentGain * sData[i]), -32768, 32767); } } else { for (int i = 0; i < size1; i++) { sStream[i] = (short)(sData[i] * this->currentGain); } sData = (short*)data2; for (int i = 0; i < size2; i++) { sStream[size1 + i] = (short)(sData[i] * this->currentGain); } } } this->position += size1 + size2; } } float SDL_Player::_sysGetOffset() { return this->offset; } void SDL_Player::_sysSetOffset(float value) { this->offset = value; } bool SDL_Player::_sysPreparePlay() { return true; } void SDL_Player::_sysPrepareBuffer() { if (!this->sound->isStreamed()) { this->buffer->load(this->looping, this->buffer->getSize()); return; } if (!this->paused) { this->readPosition = 0; this->writePosition = 0; int size = this->_fillBuffer(STREAM_BUFFER_SIZE); if (size < STREAM_BUFFER) { memset(&this->circleBuffer[size], 0, (STREAM_BUFFER - size) * sizeof(unsigned char)); } } } void SDL_Player::_sysUpdateGain() { this->currentGain = this->_calcGain(); } void SDL_Player::_sysUpdateFadeGain() { this->currentGain = this->_calcFadeGain(); } void SDL_Player::_sysPlay() { this->playing = true; } void SDL_Player::_sysStop() { this->playing = false; if (!this->paused) { this->position = 0; this->readPosition = 0; this->writePosition = 0; this->buffer->rewind(); } } void SDL_Player::_sysUpdateStream() { int count = 0; if (this->readPosition > this->writePosition) { count = (this->readPosition - this->writePosition) / STREAM_BUFFER_SIZE; } else if (this->readPosition < this->writePosition) { count = (STREAM_BUFFER - this->writePosition + this->readPosition) / STREAM_BUFFER_SIZE; } xal::log("WHAT"); if (count >= STREAM_BUFFER_COUNT / 2) { this->_fillBuffer(STREAM_BUFFER_SIZE); } } int SDL_Player::_fillBuffer(int size) { xal::log(this->looping); int streamSize = this->buffer->load(this->looping, size); unsigned char* stream = this->buffer->getStream(); if (this->writePosition + streamSize <= STREAM_BUFFER) { memcpy(&this->circleBuffer[this->writePosition], stream, streamSize * sizeof(unsigned char)); } else { int remaining = STREAM_BUFFER - this->writePosition; memcpy(&this->circleBuffer[this->writePosition], stream, remaining * sizeof(unsigned char)); memcpy(this->circleBuffer, stream, (streamSize - remaining) * sizeof(unsigned char)); } this->writePosition = (this->writePosition + streamSize) % STREAM_BUFFER; if (!this->looping && streamSize < size) // fill with silence if source is at the end { streamSize = size - streamSize; if (this->writePosition + streamSize <= STREAM_BUFFER) { memset(&this->circleBuffer[this->writePosition], 0, streamSize * sizeof(unsigned char)); } else { int remaining = STREAM_BUFFER - this->writePosition; memset(&this->circleBuffer[this->writePosition], 0, remaining * sizeof(unsigned char)); memset(this->circleBuffer, 0, (streamSize - remaining) * sizeof(unsigned char)); } this->writePosition = (this->writePosition + streamSize) % STREAM_BUFFER; streamSize = size; } return streamSize; } } #endif<commit_msg>- merged endianess fix (for big endian) from branches/2.0<commit_after>/// @file /// @author Boris Mikic /// @version 2.0 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php #if HAVE_SDL #include <SDL/SDL.h> #include "Buffer.h" #include "SDL_AudioManager.h" #include "SDL_Player.h" #include "Sound.h" #include "Endianess.h" #include "xal.h" namespace xal { SDL_Player::SDL_Player(Sound* sound, Buffer* buffer) : Player(sound, buffer), playing(false), position(0), currentGain(1.0f), readPosition(0), writePosition(0) { memset(this->circleBuffer, 0, STREAM_BUFFER * sizeof(unsigned char)); } SDL_Player::~SDL_Player() { } void SDL_Player::_getData(int size, unsigned char** data1, int* size1, unsigned char** data2, int* size2) { if (!this->sound->isStreamed()) { int streamSize = this->buffer->load(this->looping, size); unsigned char* stream = this->buffer->getStream(); *data1 = &stream[this->readPosition]; *size1 = hmin(hmin(streamSize, streamSize - this->readPosition), size); *data2 = NULL; *size2 = 0; if (this->looping && this->readPosition + size > streamSize) { *data2 = stream; *size2 = size - *size1; } this->readPosition = (this->readPosition + size) % streamSize; return; } *data1 = &this->circleBuffer[this->readPosition]; *size1 = size; *data2 = NULL; *size2 = 0; if (this->readPosition + size > STREAM_BUFFER) { *size1 = STREAM_BUFFER - this->readPosition; *data2 = this->circleBuffer; *size2 = size - *size1; } this->readPosition = (this->readPosition + size) % STREAM_BUFFER; } void SDL_Player::_update(float k) { Player::_update(k); int size = this->buffer->getSize(); if (this->position >= size) { if (this->looping) { this->position -= this->position / size * size; } else if (this->playing) { this->_sysStop(); } } } void SDL_Player::mixAudio(unsigned char* stream, int length, bool first) { if (!this->playing) { return; } unsigned char* data1; unsigned char* data2; int size1; int size2; this->_getData(length, &data1, &size1, &data2, &size2); if (size1 > 0) { if (first && this->currentGain == 1.0f) { memcpy(stream, data1, size1); if (size2 > 0) { memcpy(&stream[size1], data2, size2); } } else { short* sStream = (short*)stream; short* sData1 = (short*)data1; short* sData2 = (short*)data2; size1 = size1 * sizeof(unsigned char) / sizeof(short); size2 = size2 * sizeof(unsigned char) / sizeof(short); if (!first) { for (int i = 0; i < size1; i++) { XAL_NORMALIZE_ENDIAN(sStream[i]); sStream[i] = (short)hclamp((int)(sStream[i] + this->currentGain * sData1[i]), -32768, 32767); XAL_NORMALIZE_ENDIAN(sStream[i]); } for (int i = 0; i < size2; i++) { XAL_NORMALIZE_ENDIAN(sStream[size1 + i]); sStream[size1 + i] = (short)hclamp((int)(sStream[size1 + i] + this->currentGain * sData2[i]), -32768, 32767); XAL_NORMALIZE_ENDIAN(sStream[size1 + i]); } } else { for (int i = 0; i < size1; i++) { XAL_NORMALIZE_ENDIAN(sStream[i]); sStream[i] = (short)(sData1[i] * this->currentGain); XAL_NORMALIZE_ENDIAN(sStream[i]); } for (int i = 0; i < size2; i++) { XAL_NORMALIZE_ENDIAN(sStream[size1 + i]); sStream[size1 + i] = (short)(sData2[i] * this->currentGain); XAL_NORMALIZE_ENDIAN(sStream[size1 + i]); } } } this->position += size1 + size2; } } float SDL_Player::_sysGetOffset() { return this->offset; } void SDL_Player::_sysSetOffset(float value) { this->offset = value; } bool SDL_Player::_sysPreparePlay() { return true; } void SDL_Player::_sysPrepareBuffer() { if (!this->sound->isStreamed()) { this->buffer->load(this->looping, this->buffer->getSize()); return; } if (!this->paused) { this->readPosition = 0; this->writePosition = 0; int size = this->_fillBuffer(STREAM_BUFFER_SIZE); if (size < STREAM_BUFFER) { memset(&this->circleBuffer[size], 0, (STREAM_BUFFER - size) * sizeof(unsigned char)); } } } void SDL_Player::_sysUpdateGain() { this->currentGain = this->_calcGain(); } void SDL_Player::_sysUpdateFadeGain() { this->currentGain = this->_calcFadeGain(); } void SDL_Player::_sysPlay() { this->playing = true; } void SDL_Player::_sysStop() { this->playing = false; if (!this->paused) { this->position = 0; this->readPosition = 0; this->writePosition = 0; this->buffer->rewind(); } } void SDL_Player::_sysUpdateStream() { int count = 0; if (this->readPosition > this->writePosition) { count = (this->readPosition - this->writePosition) / STREAM_BUFFER_SIZE; } else if (this->readPosition < this->writePosition) { count = (STREAM_BUFFER - this->writePosition + this->readPosition) / STREAM_BUFFER_SIZE; } if (count >= STREAM_BUFFER_COUNT / 2) { this->_fillBuffer(STREAM_BUFFER_SIZE); } } int SDL_Player::_fillBuffer(int size) { xal::log(this->looping); int streamSize = this->buffer->load(this->looping, size); unsigned char* stream = this->buffer->getStream(); if (this->writePosition + streamSize <= STREAM_BUFFER) { memcpy(&this->circleBuffer[this->writePosition], stream, streamSize * sizeof(unsigned char)); } else { int remaining = STREAM_BUFFER - this->writePosition; memcpy(&this->circleBuffer[this->writePosition], stream, remaining * sizeof(unsigned char)); memcpy(this->circleBuffer, stream, (streamSize - remaining) * sizeof(unsigned char)); } this->writePosition = (this->writePosition + streamSize) % STREAM_BUFFER; if (!this->looping && streamSize < size) // fill with silence if source is at the end { streamSize = size - streamSize; if (this->writePosition + streamSize <= STREAM_BUFFER) { memset(&this->circleBuffer[this->writePosition], 0, streamSize * sizeof(unsigned char)); } else { int remaining = STREAM_BUFFER - this->writePosition; memset(&this->circleBuffer[this->writePosition], 0, remaining * sizeof(unsigned char)); memset(this->circleBuffer, 0, (streamSize - remaining) * sizeof(unsigned char)); } this->writePosition = (this->writePosition + streamSize) % STREAM_BUFFER; streamSize = size; } return streamSize; } } #endif<|endoftext|>
<commit_before>#include "SearchNormalBatch.h" #include "LM/Base.h" #include "Manager.h" #include <google/profiler.h> using namespace std; namespace Moses { SearchNormalBatch::SearchNormalBatch(Manager& manager, const InputType &source, const TranslationOptionCollection &transOptColl) :SearchNormal(manager, source, transOptColl) ,m_batch_size(10000) { // Split the feature functions into sets of stateless, stateful // distributed lm, and stateful non-distributed. const vector<const StatefulFeatureFunction*>& ffs = m_manager.GetTranslationSystem()->GetStatefulFeatureFunctions(); for (unsigned i = 0; i < ffs.size(); ++i) { if (ffs[i]->GetScoreProducerDescription() == "DLM_5gram") { m_dlm_ffs[i] = const_cast<LanguageModel*>(static_cast<const LanguageModel* const>(ffs[i])); m_dlm_ffs[i]->SetFFStateIdx(i); } else { m_stateful_ffs[i] = const_cast<StatefulFeatureFunction*>(ffs[i]); } } m_stateless_ffs = const_cast< vector<const StatelessFeatureFunction*>& >(m_manager.GetTranslationSystem()->GetStatelessFeatureFunctions()); } SearchNormalBatch::~SearchNormalBatch() { } /** * Main decoder loop that translates a sentence by expanding * hypotheses stack by stack, until the end of the sentence. */ void SearchNormalBatch::ProcessSentence() { const StaticData &staticData = StaticData::Instance(); SentenceStats &stats = m_manager.GetSentenceStats(); clock_t t=0; // used to track time for steps // initial seed hypothesis: nothing translated, no words produced Hypothesis *hypo = Hypothesis::Create(m_manager,m_source, m_initialTargetPhrase); m_hypoStackColl[0]->AddPrune(hypo); // go through each stack std::vector < HypothesisStack* >::iterator iterStack; for (iterStack = m_hypoStackColl.begin() ; iterStack != m_hypoStackColl.end() ; ++iterStack) { // check if decoding ran out of time double _elapsed_time = GetUserTime(); if (_elapsed_time > staticData.GetTimeoutThreshold()) { VERBOSE(1,"Decoding is out of time (" << _elapsed_time << "," << staticData.GetTimeoutThreshold() << ")" << std::endl); interrupted_flag = 1; return; } HypothesisStackNormal &sourceHypoColl = *static_cast<HypothesisStackNormal*>(*iterStack); // the stack is pruned before processing (lazy pruning): VERBOSE(3,"processing hypothesis from next stack"); IFVERBOSE(2) { t = clock(); } sourceHypoColl.PruneToSize(staticData.GetMaxHypoStackSize()); VERBOSE(3,std::endl); sourceHypoColl.CleanupArcList(); IFVERBOSE(2) { stats.AddTimeStack( clock()-t ); } // go through each hypothesis on the stack and try to expand it HypothesisStackNormal::const_iterator iterHypo; for (iterHypo = sourceHypoColl.begin() ; iterHypo != sourceHypoColl.end() ; ++iterHypo) { Hypothesis &hypothesis = **iterHypo; ProcessOneHypothesis(hypothesis); // expand the hypothesis } // some logging IFVERBOSE(2) { OutputHypoStackSize(); } // this stack is fully expanded; actual_hypoStack = &sourceHypoColl; } // some more logging IFVERBOSE(2) { m_manager.GetSentenceStats().SetTimeTotal( clock()-m_start ); } VERBOSE(2, m_manager.GetSentenceStats()); } /** * Expand one hypothesis with a translation option. * this involves initial creation, scoring and adding it to the proper stack * \param hypothesis hypothesis to be expanded upon * \param transOpt translation option (phrase translation) * that is applied to create the new hypothesis * \param expectedScore base score for early discarding * (base hypothesis score plus future score estimation) */ void SearchNormalBatch::ExpandHypothesis(const Hypothesis &hypothesis, const TranslationOption &transOpt, float expectedScore) { // Check if the number of partial hypotheses exceeds the batch size. if (m_partial_hypos.size() >= m_batch_size) { EvalAndMergePartialHypos(); } const StaticData &staticData = StaticData::Instance(); SentenceStats &stats = m_manager.GetSentenceStats(); clock_t t=0; // used to track time for steps Hypothesis *newHypo; if (! staticData.UseEarlyDiscarding()) { // simple build, no questions asked IFVERBOSE(2) { t = clock(); } newHypo = hypothesis.CreateNext(transOpt, m_constraint); IFVERBOSE(2) { stats.AddTimeBuildHyp( clock()-t ); } if (newHypo==NULL) return; //newHypo->CalcScore(m_transOptColl.GetFutureScore()); // Issue DLM requests for new hypothesis and put into the list of // partial hypotheses. std::map<int, LanguageModel*>::iterator dlm_iter; for (dlm_iter = m_dlm_ffs.begin(); dlm_iter != m_dlm_ffs.end(); ++dlm_iter) { const FFState* input_state = newHypo->GetPrevHypo() ? newHypo->GetPrevHypo()->GetFFState((*dlm_iter).first) : NULL; (*dlm_iter).second->IssueRequestsFor(*newHypo, input_state); } m_partial_hypos.push_back(newHypo); } else { std::cerr << "can't use early discarding with batch decoding!" << std::endl; abort(); } } void SearchNormalBatch::EvalAndMergePartialHypos() { std::vector<Hypothesis*>::iterator partial_hypo_iter; for (partial_hypo_iter = m_partial_hypos.begin(); partial_hypo_iter != m_partial_hypos.end(); ++partial_hypo_iter) { Hypothesis* hypo = *partial_hypo_iter; // Incorporate the translation option scores. hypo->IncorporateTransOptScores(); // Evaluate with other ffs. std::map<int, StatefulFeatureFunction*>::iterator sfff_iter; for (sfff_iter = m_stateful_ffs.begin(); sfff_iter != m_stateful_ffs.end(); ++sfff_iter) { hypo->EvaluateWith((*sfff_iter).second, (*sfff_iter).first); } std::vector<const StatelessFeatureFunction*>::iterator slff_iter; for (slff_iter = m_stateless_ffs.begin(); slff_iter != m_stateless_ffs.end(); ++slff_iter) { hypo->EvaluateWith(*slff_iter); } // Calculate future score. hypo->CalculateFutureScore(m_transOptColl.GetFutureScore()); } // Wait for all requests from the distributed LM to come back. std::map<int, LanguageModel*>::iterator dlm_iter; for (dlm_iter = m_dlm_ffs.begin(); dlm_iter != m_dlm_ffs.end(); ++dlm_iter) { (*dlm_iter).second->sync(); } // Incorporate the DLM scores into all hypotheses and put into their // stacks. for (partial_hypo_iter = m_partial_hypos.begin(); partial_hypo_iter != m_partial_hypos.end(); ++partial_hypo_iter) { Hypothesis* hypo = *partial_hypo_iter; // Calculate DLM scores. std::map<int, LanguageModel*>::iterator dlm_iter; for (dlm_iter = m_dlm_ffs.begin(); dlm_iter != m_dlm_ffs.end(); ++dlm_iter) { hypo->EvaluateWith((*dlm_iter).second, (*dlm_iter).first); } // Calculate the final score. hypo->CalculateFinalScore(); // Put completed hypothesis onto its stack. size_t wordsTranslated = hypo->GetWordsBitmap().GetNumWordsCovered(); m_hypoStackColl[wordsTranslated]->AddPrune(hypo); } m_partial_hypos.clear(); std::vector < HypothesisStack* >::iterator stack_iter; HypothesisStackNormal* stack; for (stack_iter = m_hypoStackColl.begin(); stack_iter != m_hypoStackColl.end(); ++stack_iter) { stack = static_cast<HypothesisStackNormal*>(*stack_iter); stack->PruneToSize(m_max_stack_size); } } } <commit_msg>comment out include to google profiler<commit_after>#include "SearchNormalBatch.h" #include "LM/Base.h" #include "Manager.h" //#include <google/profiler.h> using namespace std; namespace Moses { SearchNormalBatch::SearchNormalBatch(Manager& manager, const InputType &source, const TranslationOptionCollection &transOptColl) :SearchNormal(manager, source, transOptColl) ,m_batch_size(10000) { // Split the feature functions into sets of stateless, stateful // distributed lm, and stateful non-distributed. const vector<const StatefulFeatureFunction*>& ffs = m_manager.GetTranslationSystem()->GetStatefulFeatureFunctions(); for (unsigned i = 0; i < ffs.size(); ++i) { if (ffs[i]->GetScoreProducerDescription() == "DLM_5gram") { m_dlm_ffs[i] = const_cast<LanguageModel*>(static_cast<const LanguageModel* const>(ffs[i])); m_dlm_ffs[i]->SetFFStateIdx(i); } else { m_stateful_ffs[i] = const_cast<StatefulFeatureFunction*>(ffs[i]); } } m_stateless_ffs = const_cast< vector<const StatelessFeatureFunction*>& >(m_manager.GetTranslationSystem()->GetStatelessFeatureFunctions()); } SearchNormalBatch::~SearchNormalBatch() { } /** * Main decoder loop that translates a sentence by expanding * hypotheses stack by stack, until the end of the sentence. */ void SearchNormalBatch::ProcessSentence() { const StaticData &staticData = StaticData::Instance(); SentenceStats &stats = m_manager.GetSentenceStats(); clock_t t=0; // used to track time for steps // initial seed hypothesis: nothing translated, no words produced Hypothesis *hypo = Hypothesis::Create(m_manager,m_source, m_initialTargetPhrase); m_hypoStackColl[0]->AddPrune(hypo); // go through each stack std::vector < HypothesisStack* >::iterator iterStack; for (iterStack = m_hypoStackColl.begin() ; iterStack != m_hypoStackColl.end() ; ++iterStack) { // check if decoding ran out of time double _elapsed_time = GetUserTime(); if (_elapsed_time > staticData.GetTimeoutThreshold()) { VERBOSE(1,"Decoding is out of time (" << _elapsed_time << "," << staticData.GetTimeoutThreshold() << ")" << std::endl); interrupted_flag = 1; return; } HypothesisStackNormal &sourceHypoColl = *static_cast<HypothesisStackNormal*>(*iterStack); // the stack is pruned before processing (lazy pruning): VERBOSE(3,"processing hypothesis from next stack"); IFVERBOSE(2) { t = clock(); } sourceHypoColl.PruneToSize(staticData.GetMaxHypoStackSize()); VERBOSE(3,std::endl); sourceHypoColl.CleanupArcList(); IFVERBOSE(2) { stats.AddTimeStack( clock()-t ); } // go through each hypothesis on the stack and try to expand it HypothesisStackNormal::const_iterator iterHypo; for (iterHypo = sourceHypoColl.begin() ; iterHypo != sourceHypoColl.end() ; ++iterHypo) { Hypothesis &hypothesis = **iterHypo; ProcessOneHypothesis(hypothesis); // expand the hypothesis } // some logging IFVERBOSE(2) { OutputHypoStackSize(); } // this stack is fully expanded; actual_hypoStack = &sourceHypoColl; } // some more logging IFVERBOSE(2) { m_manager.GetSentenceStats().SetTimeTotal( clock()-m_start ); } VERBOSE(2, m_manager.GetSentenceStats()); } /** * Expand one hypothesis with a translation option. * this involves initial creation, scoring and adding it to the proper stack * \param hypothesis hypothesis to be expanded upon * \param transOpt translation option (phrase translation) * that is applied to create the new hypothesis * \param expectedScore base score for early discarding * (base hypothesis score plus future score estimation) */ void SearchNormalBatch::ExpandHypothesis(const Hypothesis &hypothesis, const TranslationOption &transOpt, float expectedScore) { // Check if the number of partial hypotheses exceeds the batch size. if (m_partial_hypos.size() >= m_batch_size) { EvalAndMergePartialHypos(); } const StaticData &staticData = StaticData::Instance(); SentenceStats &stats = m_manager.GetSentenceStats(); clock_t t=0; // used to track time for steps Hypothesis *newHypo; if (! staticData.UseEarlyDiscarding()) { // simple build, no questions asked IFVERBOSE(2) { t = clock(); } newHypo = hypothesis.CreateNext(transOpt, m_constraint); IFVERBOSE(2) { stats.AddTimeBuildHyp( clock()-t ); } if (newHypo==NULL) return; //newHypo->CalcScore(m_transOptColl.GetFutureScore()); // Issue DLM requests for new hypothesis and put into the list of // partial hypotheses. std::map<int, LanguageModel*>::iterator dlm_iter; for (dlm_iter = m_dlm_ffs.begin(); dlm_iter != m_dlm_ffs.end(); ++dlm_iter) { const FFState* input_state = newHypo->GetPrevHypo() ? newHypo->GetPrevHypo()->GetFFState((*dlm_iter).first) : NULL; (*dlm_iter).second->IssueRequestsFor(*newHypo, input_state); } m_partial_hypos.push_back(newHypo); } else { std::cerr << "can't use early discarding with batch decoding!" << std::endl; abort(); } } void SearchNormalBatch::EvalAndMergePartialHypos() { std::vector<Hypothesis*>::iterator partial_hypo_iter; for (partial_hypo_iter = m_partial_hypos.begin(); partial_hypo_iter != m_partial_hypos.end(); ++partial_hypo_iter) { Hypothesis* hypo = *partial_hypo_iter; // Incorporate the translation option scores. hypo->IncorporateTransOptScores(); // Evaluate with other ffs. std::map<int, StatefulFeatureFunction*>::iterator sfff_iter; for (sfff_iter = m_stateful_ffs.begin(); sfff_iter != m_stateful_ffs.end(); ++sfff_iter) { hypo->EvaluateWith((*sfff_iter).second, (*sfff_iter).first); } std::vector<const StatelessFeatureFunction*>::iterator slff_iter; for (slff_iter = m_stateless_ffs.begin(); slff_iter != m_stateless_ffs.end(); ++slff_iter) { hypo->EvaluateWith(*slff_iter); } // Calculate future score. hypo->CalculateFutureScore(m_transOptColl.GetFutureScore()); } // Wait for all requests from the distributed LM to come back. std::map<int, LanguageModel*>::iterator dlm_iter; for (dlm_iter = m_dlm_ffs.begin(); dlm_iter != m_dlm_ffs.end(); ++dlm_iter) { (*dlm_iter).second->sync(); } // Incorporate the DLM scores into all hypotheses and put into their // stacks. for (partial_hypo_iter = m_partial_hypos.begin(); partial_hypo_iter != m_partial_hypos.end(); ++partial_hypo_iter) { Hypothesis* hypo = *partial_hypo_iter; // Calculate DLM scores. std::map<int, LanguageModel*>::iterator dlm_iter; for (dlm_iter = m_dlm_ffs.begin(); dlm_iter != m_dlm_ffs.end(); ++dlm_iter) { hypo->EvaluateWith((*dlm_iter).second, (*dlm_iter).first); } // Calculate the final score. hypo->CalculateFinalScore(); // Put completed hypothesis onto its stack. size_t wordsTranslated = hypo->GetWordsBitmap().GetNumWordsCovered(); m_hypoStackColl[wordsTranslated]->AddPrune(hypo); } m_partial_hypos.clear(); std::vector < HypothesisStack* >::iterator stack_iter; HypothesisStackNormal* stack; for (stack_iter = m_hypoStackColl.begin(); stack_iter != m_hypoStackColl.end(); ++stack_iter) { stack = static_cast<HypothesisStackNormal*>(*stack_iter); stack->PruneToSize(m_max_stack_size); } } } <|endoftext|>
<commit_before>#include "connection-manager.h" #include "glib-helpers.h" #include "protocol.h" G_DEFINE_TYPE(SteamConnectionManager, steam_connection_manager, TP_TYPE_BASE_CONNECTION_MANAGER); static void stema_connection_manager_constructed (GObject * object) { GLIB_CALL_PARENT(steam_connection_manager_parent_class, constructed, object); tp_base_connection_manager_add_protocol(TP_BASE_CONNECTION_MANAGER(object), steam_protocol_new()); } static void steam_connection_manager_finalize (GObject * object) { GLIB_CALL_PARENT(steam_connection_manager_parent_class, finalize, object); } void steam_connection_manager_class_init(SteamConnectionManagerClass * klass) { GObjectClass *object_class = G_OBJECT_CLASS(klass); object_class->constructed = stema_connection_manager_constructed; object_class->finalize = steam_connection_manager_finalize; klass->parent_class.cm_dbus_name = "steam"; } void steam_connection_manager_init(SteamConnectionManager * scm) { } <commit_msg>connection-manager: added empty finalize method<commit_after>#include "connection-manager.h" #include "glib-helpers.h" #include "protocol.h" G_DEFINE_TYPE(SteamConnectionManager, steam_connection_manager, TP_TYPE_BASE_CONNECTION_MANAGER); static void stema_connection_manager_constructed (GObject * object) { GLIB_CALL_PARENT(steam_connection_manager_parent_class, constructed, object); tp_base_connection_manager_add_protocol(TP_BASE_CONNECTION_MANAGER(object), steam_protocol_new()); } void steam_connection_manager_class_init(SteamConnectionManagerClass * klass) { GObjectClass *object_class = G_OBJECT_CLASS(klass); object_class->constructed = stema_connection_manager_constructed; klass->parent_class.cm_dbus_name = "steam"; } void steam_connection_manager_init(SteamConnectionManager * scm) { } <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fastos/fastos.h> #include <vespa/vespalib/geo/zcurve.h> #include <vespa/vespalib/util/priority_queue.h> #include <vespa/vespalib/util/fiddle.h> #include <vespa/log/log.h> LOG_SETUP(".vespalib.geo.zcurve"); namespace vespalib { namespace geo { namespace { class ZAreaQueue { private: struct MaxAreaErrorCmp { bool operator()(const ZCurve::Area &a, const ZCurve::Area &b) const { return (a.error() > b.error()); } }; typedef ZCurve::Area Area; typedef ZCurve::Range Range; typedef ZCurve::RangeVector RangeVector; typedef PriorityQueue<Area, MaxAreaErrorCmp, LeftArrayHeap> Queue; Queue _queue; int64_t _total_estimate; public: ZAreaQueue() : _queue(), _total_estimate(0) {} int64_t total_estimate() const { return _total_estimate; } void put(Area area) { _total_estimate += area.estimate(); _queue.push(std::move(area)); } Area get() { assert(!_queue.empty()); Area area(_queue.front()); _queue.pop_front(); _total_estimate -= area.estimate(); return area; } size_t size() const { return _queue.size(); } RangeVector extract_ranges() { RangeVector ranges; ranges.reserve(_queue.size()); while (!_queue.empty()) { const Area &area = _queue.any(); ranges.push_back(Range(area.min.z, area.max.z)); _queue.pop_any(); } return ranges; } }; class ZAreaSplitter { private: typedef ZCurve::Area Area; typedef ZCurve::RangeVector RangeVector; ZAreaQueue _queue; public: ZAreaSplitter(int min_x, int min_y, int max_x, int max_y) : _queue() { assert(min_x <= max_x); assert(min_y <= max_y); bool cross_x = (min_x < 0) != (max_x < 0); bool cross_y = (min_y < 0) != (max_y < 0); if (cross_x) { if (cross_y) { _queue.put(Area(min_x, min_y, -1, -1)); _queue.put(Area( 0, min_y, max_x, -1)); _queue.put(Area(min_x, 0, -1, max_y)); _queue.put(Area( 0, 0, max_x, max_y)); } else { _queue.put(Area(min_x, min_y, -1, max_y)); _queue.put(Area( 0, min_y, max_x, max_y)); } } else { if (cross_y) { _queue.put(Area(min_x, min_y, max_x, -1)); _queue.put(Area(min_x, 0, max_x, max_y)); } else { _queue.put(Area(min_x, min_y, max_x, max_y)); } } } size_t num_ranges() const { return _queue.size(); } int64_t total_estimate() const { return _queue.total_estimate(); } void split_worst() { Area area = _queue.get(); uint32_t x_first_max, x_last_min; uint32_t y_first_max, y_last_min; uint32_t x_bits = bits::split_range(area.min.x, area.max.x, x_first_max, x_last_min); uint32_t y_bits = bits::split_range(area.min.y, area.max.y, y_first_max, y_last_min); if (x_bits > y_bits) { _queue.put(Area(area.min.x, area.min.y, x_first_max, area.max.y)); _queue.put(Area(x_last_min, area.min.y, area.max.x, area.max.y)); } else { assert(y_bits > 0); _queue.put(Area(area.min.x, area.min.y, area.max.x, y_first_max)); _queue.put(Area(area.min.x, y_last_min, area.max.x, area.max.y)); } } RangeVector extract_ranges() { return _queue.extract_ranges(); } }; } // namespace vespalib::geo::<unnamed> ZCurve::BoundingBox::BoundingBox(int32_t minx, int32_t maxx, int32_t miny, int32_t maxy) : _zMinx(ZCurve::encode(minx, 0)), _zMaxx(ZCurve::encode(maxx, 0)), _zMiny(ZCurve::encode(0, miny)), _zMaxy(ZCurve::encode(0, maxy)) { } ZCurve::RangeVector ZCurve::find_ranges(int min_x, int min_y, int max_x, int max_y) { int64_t total_size = ((max_x - min_x + 1L) * (max_y - min_y + 1L)); int64_t estimate_target = (total_size * 4); ZAreaSplitter splitter(min_x, min_y, max_x, max_y); while (splitter.total_estimate() > estimate_target && splitter.num_ranges() < 42) { splitter.split_worst(); } RangeVector ranges = splitter.extract_ranges(); std::sort(ranges.begin(), ranges.end()); LOG(debug, "split bounding box into %zu z-ranges", ranges.size()); return ranges; } int64_t ZCurve::encodeSlow(int32_t x, int32_t y) { uint64_t res = 0; uint32_t ibit = 1; uint64_t obit = 1; for (; ibit != 0; ibit <<= 1, obit <<= 2) { if (static_cast<uint32_t>(x) & ibit) res |= obit; if (static_cast<uint32_t>(y) & ibit) res |= (obit << 1); } return static_cast<int64_t>(res); } void ZCurve::decodeSlow(int64_t enc, int32_t *xp, int32_t *yp) { uint32_t x = 0; uint32_t y = 0; uint64_t ibit = 1; uint32_t obit = 1; for (; ibit != 0; ibit <<= 2, obit <<= 1) { if ((static_cast<uint64_t>(enc) & ibit) != 0) x |= obit; if ((static_cast<uint64_t>(enc) & (ibit << 1)) != 0) y |= obit; } *xp = static_cast<int32_t>(x); *yp = static_cast<int32_t>(y); } } } <commit_msg>Only include what is needed.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/geo/zcurve.h> #include <vespa/vespalib/util/priority_queue.h> #include <vespa/vespalib/util/fiddle.h> namespace vespalib { namespace geo { namespace { class ZAreaQueue { private: struct MaxAreaErrorCmp { bool operator()(const ZCurve::Area &a, const ZCurve::Area &b) const { return (a.error() > b.error()); } }; typedef ZCurve::Area Area; typedef ZCurve::Range Range; typedef ZCurve::RangeVector RangeVector; typedef PriorityQueue<Area, MaxAreaErrorCmp, LeftArrayHeap> Queue; Queue _queue; int64_t _total_estimate; public: ZAreaQueue() : _queue(), _total_estimate(0) {} int64_t total_estimate() const { return _total_estimate; } void put(Area area) { _total_estimate += area.estimate(); _queue.push(std::move(area)); } Area get() { assert(!_queue.empty()); Area area(_queue.front()); _queue.pop_front(); _total_estimate -= area.estimate(); return area; } size_t size() const { return _queue.size(); } RangeVector extract_ranges() { RangeVector ranges; ranges.reserve(_queue.size()); while (!_queue.empty()) { const Area &area = _queue.any(); ranges.push_back(Range(area.min.z, area.max.z)); _queue.pop_any(); } return ranges; } }; class ZAreaSplitter { private: typedef ZCurve::Area Area; typedef ZCurve::RangeVector RangeVector; ZAreaQueue _queue; public: ZAreaSplitter(int min_x, int min_y, int max_x, int max_y) : _queue() { assert(min_x <= max_x); assert(min_y <= max_y); bool cross_x = (min_x < 0) != (max_x < 0); bool cross_y = (min_y < 0) != (max_y < 0); if (cross_x) { if (cross_y) { _queue.put(Area(min_x, min_y, -1, -1)); _queue.put(Area( 0, min_y, max_x, -1)); _queue.put(Area(min_x, 0, -1, max_y)); _queue.put(Area( 0, 0, max_x, max_y)); } else { _queue.put(Area(min_x, min_y, -1, max_y)); _queue.put(Area( 0, min_y, max_x, max_y)); } } else { if (cross_y) { _queue.put(Area(min_x, min_y, max_x, -1)); _queue.put(Area(min_x, 0, max_x, max_y)); } else { _queue.put(Area(min_x, min_y, max_x, max_y)); } } } size_t num_ranges() const { return _queue.size(); } int64_t total_estimate() const { return _queue.total_estimate(); } void split_worst() { Area area = _queue.get(); uint32_t x_first_max, x_last_min; uint32_t y_first_max, y_last_min; uint32_t x_bits = bits::split_range(area.min.x, area.max.x, x_first_max, x_last_min); uint32_t y_bits = bits::split_range(area.min.y, area.max.y, y_first_max, y_last_min); if (x_bits > y_bits) { _queue.put(Area(area.min.x, area.min.y, x_first_max, area.max.y)); _queue.put(Area(x_last_min, area.min.y, area.max.x, area.max.y)); } else { assert(y_bits > 0); _queue.put(Area(area.min.x, area.min.y, area.max.x, y_first_max)); _queue.put(Area(area.min.x, y_last_min, area.max.x, area.max.y)); } } RangeVector extract_ranges() { return _queue.extract_ranges(); } }; } // namespace vespalib::geo::<unnamed> ZCurve::BoundingBox::BoundingBox(int32_t minx, int32_t maxx, int32_t miny, int32_t maxy) : _zMinx(ZCurve::encode(minx, 0)), _zMaxx(ZCurve::encode(maxx, 0)), _zMiny(ZCurve::encode(0, miny)), _zMaxy(ZCurve::encode(0, maxy)) { } ZCurve::RangeVector ZCurve::find_ranges(int min_x, int min_y, int max_x, int max_y) { int64_t total_size = ((max_x - min_x + 1L) * (max_y - min_y + 1L)); int64_t estimate_target = (total_size * 4); ZAreaSplitter splitter(min_x, min_y, max_x, max_y); while (splitter.total_estimate() > estimate_target && splitter.num_ranges() < 42) { splitter.split_worst(); } RangeVector ranges = splitter.extract_ranges(); std::sort(ranges.begin(), ranges.end()); return ranges; } int64_t ZCurve::encodeSlow(int32_t x, int32_t y) { uint64_t res = 0; uint32_t ibit = 1; uint64_t obit = 1; for (; ibit != 0; ibit <<= 1, obit <<= 2) { if (static_cast<uint32_t>(x) & ibit) res |= obit; if (static_cast<uint32_t>(y) & ibit) res |= (obit << 1); } return static_cast<int64_t>(res); } void ZCurve::decodeSlow(int64_t enc, int32_t *xp, int32_t *yp) { uint32_t x = 0; uint32_t y = 0; uint64_t ibit = 1; uint32_t obit = 1; for (; ibit != 0; ibit <<= 2, obit <<= 1) { if ((static_cast<uint64_t>(enc) & ibit) != 0) x |= obit; if ((static_cast<uint64_t>(enc) & (ibit << 1)) != 0) y |= obit; } *xp = static_cast<int32_t>(x); *yp = static_cast<int32_t>(y); } } } <|endoftext|>
<commit_before>/* poller.cpp * Copyright (C) 2005-2006 Tommi Maekitalo * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 "tnt/poller.h" #include "tnt/tntnet.h" #include "tnt/syserror.h" #include <cxxtools/log.h> #include <unistd.h> #include <fcntl.h> #ifdef WITH_EPOLL #include <sys/epoll.h> #include <errno.h> #endif log_define("tntnet.poller") namespace tnt { #ifdef WITH_EPOLL Poller::Poller(Jobqueue& q) : queue(q), pollFd(-1) { pollFd = ::epoll_create(256); if (pollFd < 0) throw SysError("epoll_create"); fcntl(notify_pipe.getReadFd(), F_SETFL, O_NONBLOCK); addFd(notify_pipe.getReadFd(), EPOLLIN); } void Poller::addFd(int fd, uint32_t event) { log_debug("addFd(" << fd << ')'); epoll_event e; e.events = event; e.data.fd = fd; int ret = ::epoll_ctl(pollFd, EPOLL_CTL_ADD, fd, &e); if (ret < 0) throw SysError("epoll_ctl(EPOLL_CTL_ADD)"); } void Poller::removeFd(int fd) { log_debug("removeFd(" << fd << ')'); epoll_event e; e.data.fd = fd; int ret = ::epoll_ctl(pollFd, EPOLL_CTL_DEL, fd, &e); if (ret < 0) { if (errno == EBADF) log_warn("fd " << fd << " couldn't be removed"); else throw SysError("epoll_ctl(EPOLL_CTL_DEL)"); } } void Poller::doStop() { log_debug("notify stop"); notify_pipe.write('A'); } void Poller::addIdleJob(Jobqueue::JobPtr job) { log_debug("addIdleJob " << job->getFd()); { cxxtools::MutexLock lock(mutex); new_jobs.insert(job); if (new_jobs.size() <= 1) notify_pipe.write('A'); } log_debug("addIdleJob ready"); } void Poller::append_new_jobs() { cxxtools::MutexLock lock(mutex); if (!new_jobs.empty()) { // append new jobs to current log_debug("add " << new_jobs.size() << " new jobs to poll-list"); time_t currentTime; time(&currentTime); for (new_jobs_type::iterator it = new_jobs.begin(); it != new_jobs.end(); ++it) { addFd((*it)->getFd(), EPOLLIN); jobs[(*it)->getFd()] = *it; int msec; if (poll_timeout < 0) poll_timeout = (*it)->msecToTimeout(currentTime); else if ((msec = (*it)->msecToTimeout(currentTime)) < poll_timeout) poll_timeout = msec; } new_jobs.clear(); } } void Poller::run() { epoll_event events[16]; time_t pollTime; time(&pollTime); while (!Tntnet::shouldStop()) { usleep(100); append_new_jobs(); if (jobs.size() == 0) poll_timeout = -1; log_debug("epoll_wait with timeout " << poll_timeout << " ms"); int ret = ::epoll_wait(pollFd, events, 16, poll_timeout); if (ret < 0) { if (errno != EINTR) throw SysError("epoll_wait"); } else if (ret == 0) { // timeout reached - check for timed out requests and get next timeout log_debug("timeout reached"); poll_timeout = -1; time_t currentTime; time(&currentTime); for (jobs_type::iterator it = jobs.begin(); it != jobs.end(); ) { int msec = it->second->msecToTimeout(currentTime); if (msec <= 0) { log_debug("keep-alive-timeout reached"); jobs_type::iterator it2 = it++; jobs.erase(it2); } else { if (poll_timeout < 0 || msec < poll_timeout) poll_timeout = msec; ++it; } } } else { time_t currentTime; time(&currentTime); poll_timeout -= (currentTime - pollTime) * 1000; if (poll_timeout <= 0) poll_timeout = 100; pollTime = currentTime; // no timeout - process events log_debug(ret << " events occured"); for (int i = 0; i < ret; ++i) { if (events[i].data.fd == notify_pipe.getReadFd()) { if (Tntnet::shouldStop()) { log_info("stop poller"); break; } log_debug("read notify-pipe"); char buffer[64]; ssize_t n = notify_pipe.read(buffer, sizeof(buffer)); log_debug("read returns " << n); } else { jobs_type::iterator it = jobs.find(events[i].data.fd); if (it == jobs.end()) { log_fatal("internal error: job for fd " << events[i].data.fd << " not found in jobs-list"); removeFd(events[i].data.fd); ::close(events[i].data.fd); throw std::runtime_error("job not found in jobs-list"); } if ((events[i].events & (EPOLLERR | EPOLLHUP)) != 0) { log_debug("remove fd " << it->first << " from queue"); } else { log_debug("put fd " << it->first << " back in queue"); queue.put(it->second); } jobs.erase(events[i].data.fd); removeFd(events[i].data.fd); } } } } } #else Poller::Poller(Jobqueue& q) : queue(q), poll_timeout(-1) { fcntl(notify_pipe.getReadFd(), F_SETFL, O_NONBLOCK); pollfds.reserve(16); pollfds[0].fd = notify_pipe.getReadFd(); pollfds[0].events = POLLIN; pollfds[0].revents = 0; } void Poller::append_new_jobs() { cxxtools::MutexLock lock(mutex); if (!new_jobs.empty()) { // append new jobs to current log_debug("add " << new_jobs.size() << " new jobs to poll-list"); pollfds.reserve(current_jobs.size() + new_jobs.size() + 1); time_t currentTime; time(&currentTime); for (jobs_type::iterator it = new_jobs.begin(); it != new_jobs.end(); ++it) { append(*it); int msec; if (poll_timeout < 0) poll_timeout = (*it)->msecToTimeout(currentTime); else if ((msec = (*it)->msecToTimeout(currentTime)) < poll_timeout) poll_timeout = msec; } new_jobs.clear(); } } void Poller::append(Jobqueue::JobPtr& job) { current_jobs.push_back(job); pollfd& p = *(pollfds.data() + current_jobs.size()); p.fd = job->getFd(); p.events = POLLIN; } void Poller::run() { while (!Tntnet::shouldStop()) { usleep(100); append_new_jobs(); try { log_debug("poll timeout=" << poll_timeout); ::poll(pollfds.data(), current_jobs.size() + 1, poll_timeout); poll_timeout = -1; if (pollfds[0].revents != 0) { if (Tntnet::shouldStop()) { log_info("stop poller"); break; } log_debug("read notify-pipe"); char buffer[64]; ssize_t n = notify_pipe.read(&buffer, sizeof(buffer)); log_debug("read returns " << n); pollfds[0].revents = 0; } if (current_jobs.size() > 0) dispatch(); } catch (const std::exception& e) { log_error("error in poll-loop: " << e.what()); } } } void Poller::doStop() { log_debug("notify stop"); notify_pipe.write('A'); } void Poller::dispatch() { log_debug("dispatch " << current_jobs.size() << " jobs"); time_t currentTime; time(&currentTime); for (unsigned i = 0; i < current_jobs.size(); ) { if (pollfds[i + 1].revents & POLLIN) { log_debug("job found " << pollfds[i + 1].fd); // put job into work-queue queue.put(current_jobs[i]); remove(i); } else if (pollfds[i + 1].revents != 0) { log_debug("pollevent " << std::hex << pollfds[i + 1].revents << " on fd " << pollfds[i + 1].fd); remove(i); } else { // check timeout int msec = current_jobs[i]->msecToTimeout(currentTime); if (msec <= 0) { log_debug("keep-alive-timeout reached"); remove(i); } else if (poll_timeout < 0 || msec < poll_timeout) poll_timeout = msec; ++i; } } } void Poller::remove(jobs_type::size_type n) { // replace job with last job in poller-list jobs_type::size_type last = current_jobs.size() - 1; if (n != last) { pollfds[n + 1] = pollfds[last + 1]; current_jobs[n] = current_jobs[last]; } current_jobs.pop_back(); } void Poller::addIdleJob(Jobqueue::JobPtr job) { log_debug("addIdleJob " << job->getFd()); { cxxtools::MutexLock lock(mutex); new_jobs.push_back(job); } log_debug("notify " << job->getFd()); notify_pipe.write('A'); log_debug("addIdleJob ready"); } #endif // #else HAVE_EPOLL } <commit_msg>notify each idle-job - not just the first<commit_after>/* poller.cpp * Copyright (C) 2005-2006 Tommi Maekitalo * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 "tnt/poller.h" #include "tnt/tntnet.h" #include "tnt/syserror.h" #include <cxxtools/log.h> #include <unistd.h> #include <fcntl.h> #ifdef WITH_EPOLL #include <sys/epoll.h> #include <errno.h> #endif log_define("tntnet.poller") namespace tnt { #ifdef WITH_EPOLL Poller::Poller(Jobqueue& q) : queue(q), pollFd(-1) { pollFd = ::epoll_create(256); if (pollFd < 0) throw SysError("epoll_create"); fcntl(notify_pipe.getReadFd(), F_SETFL, O_NONBLOCK); addFd(notify_pipe.getReadFd(), EPOLLIN); } void Poller::addFd(int fd, uint32_t event) { log_debug("addFd(" << fd << ')'); epoll_event e; e.events = event; e.data.fd = fd; int ret = ::epoll_ctl(pollFd, EPOLL_CTL_ADD, fd, &e); if (ret < 0) throw SysError("epoll_ctl(EPOLL_CTL_ADD)"); } void Poller::removeFd(int fd) { log_debug("removeFd(" << fd << ')'); epoll_event e; e.data.fd = fd; int ret = ::epoll_ctl(pollFd, EPOLL_CTL_DEL, fd, &e); if (ret < 0) { if (errno == EBADF) log_warn("fd " << fd << " couldn't be removed"); else throw SysError("epoll_ctl(EPOLL_CTL_DEL)"); } } void Poller::doStop() { log_debug("notify stop"); notify_pipe.write('A'); } void Poller::addIdleJob(Jobqueue::JobPtr job) { log_debug("addIdleJob " << job->getFd()); { cxxtools::MutexLock lock(mutex); new_jobs.insert(job); notify_pipe.write('A'); } log_debug("addIdleJob ready"); } void Poller::append_new_jobs() { cxxtools::MutexLock lock(mutex); if (!new_jobs.empty()) { // append new jobs to current log_debug("add " << new_jobs.size() << " new jobs to poll-list"); time_t currentTime; time(&currentTime); for (new_jobs_type::iterator it = new_jobs.begin(); it != new_jobs.end(); ++it) { addFd((*it)->getFd(), EPOLLIN); jobs[(*it)->getFd()] = *it; int msec; if (poll_timeout < 0) poll_timeout = (*it)->msecToTimeout(currentTime); else if ((msec = (*it)->msecToTimeout(currentTime)) < poll_timeout) poll_timeout = msec; } new_jobs.clear(); } } void Poller::run() { epoll_event events[16]; time_t pollTime; time(&pollTime); while (!Tntnet::shouldStop()) { usleep(100); append_new_jobs(); if (jobs.size() == 0) poll_timeout = -1; log_debug("epoll_wait with timeout " << poll_timeout << " ms"); int ret = ::epoll_wait(pollFd, events, 16, poll_timeout); if (ret < 0) { if (errno != EINTR) throw SysError("epoll_wait"); } else if (ret == 0) { // timeout reached - check for timed out requests and get next timeout log_debug("timeout reached"); poll_timeout = -1; time_t currentTime; time(&currentTime); for (jobs_type::iterator it = jobs.begin(); it != jobs.end(); ) { int msec = it->second->msecToTimeout(currentTime); if (msec <= 0) { log_debug("keep-alive-timeout reached"); jobs_type::iterator it2 = it++; jobs.erase(it2); } else { if (poll_timeout < 0 || msec < poll_timeout) poll_timeout = msec; ++it; } } } else { time_t currentTime; time(&currentTime); poll_timeout -= (currentTime - pollTime) * 1000; if (poll_timeout <= 0) poll_timeout = 100; pollTime = currentTime; // no timeout - process events log_debug(ret << " events occured"); for (int i = 0; i < ret; ++i) { if (events[i].data.fd == notify_pipe.getReadFd()) { if (Tntnet::shouldStop()) { log_info("stop poller"); break; } log_debug("read notify-pipe"); char buffer[64]; ssize_t n = notify_pipe.read(buffer, sizeof(buffer)); log_debug("read returns " << n); } else { jobs_type::iterator it = jobs.find(events[i].data.fd); if (it == jobs.end()) { log_fatal("internal error: job for fd " << events[i].data.fd << " not found in jobs-list"); removeFd(events[i].data.fd); ::close(events[i].data.fd); throw std::runtime_error("job not found in jobs-list"); } if ((events[i].events & (EPOLLERR | EPOLLHUP)) != 0) { log_debug("remove fd " << it->first << " from queue"); } else { log_debug("put fd " << it->first << " back in queue"); queue.put(it->second); } jobs.erase(events[i].data.fd); removeFd(events[i].data.fd); } } } } } #else Poller::Poller(Jobqueue& q) : queue(q), poll_timeout(-1) { fcntl(notify_pipe.getReadFd(), F_SETFL, O_NONBLOCK); pollfds.reserve(16); pollfds[0].fd = notify_pipe.getReadFd(); pollfds[0].events = POLLIN; pollfds[0].revents = 0; } void Poller::append_new_jobs() { cxxtools::MutexLock lock(mutex); if (!new_jobs.empty()) { // append new jobs to current log_debug("add " << new_jobs.size() << " new jobs to poll-list"); pollfds.reserve(current_jobs.size() + new_jobs.size() + 1); time_t currentTime; time(&currentTime); for (jobs_type::iterator it = new_jobs.begin(); it != new_jobs.end(); ++it) { append(*it); int msec; if (poll_timeout < 0) poll_timeout = (*it)->msecToTimeout(currentTime); else if ((msec = (*it)->msecToTimeout(currentTime)) < poll_timeout) poll_timeout = msec; } new_jobs.clear(); } } void Poller::append(Jobqueue::JobPtr& job) { current_jobs.push_back(job); pollfd& p = *(pollfds.data() + current_jobs.size()); p.fd = job->getFd(); p.events = POLLIN; } void Poller::run() { while (!Tntnet::shouldStop()) { usleep(100); append_new_jobs(); try { log_debug("poll timeout=" << poll_timeout); ::poll(pollfds.data(), current_jobs.size() + 1, poll_timeout); poll_timeout = -1; if (pollfds[0].revents != 0) { if (Tntnet::shouldStop()) { log_info("stop poller"); break; } log_debug("read notify-pipe"); char buffer[64]; ssize_t n = notify_pipe.read(&buffer, sizeof(buffer)); log_debug("read returns " << n); pollfds[0].revents = 0; } if (current_jobs.size() > 0) dispatch(); } catch (const std::exception& e) { log_error("error in poll-loop: " << e.what()); } } } void Poller::doStop() { log_debug("notify stop"); notify_pipe.write('A'); } void Poller::dispatch() { log_debug("dispatch " << current_jobs.size() << " jobs"); time_t currentTime; time(&currentTime); for (unsigned i = 0; i < current_jobs.size(); ) { if (pollfds[i + 1].revents & POLLIN) { log_debug("job found " << pollfds[i + 1].fd); // put job into work-queue queue.put(current_jobs[i]); remove(i); } else if (pollfds[i + 1].revents != 0) { log_debug("pollevent " << std::hex << pollfds[i + 1].revents << " on fd " << pollfds[i + 1].fd); remove(i); } else { // check timeout int msec = current_jobs[i]->msecToTimeout(currentTime); if (msec <= 0) { log_debug("keep-alive-timeout reached"); remove(i); } else if (poll_timeout < 0 || msec < poll_timeout) poll_timeout = msec; ++i; } } } void Poller::remove(jobs_type::size_type n) { // replace job with last job in poller-list jobs_type::size_type last = current_jobs.size() - 1; if (n != last) { pollfds[n + 1] = pollfds[last + 1]; current_jobs[n] = current_jobs[last]; } current_jobs.pop_back(); } void Poller::addIdleJob(Jobqueue::JobPtr job) { log_debug("addIdleJob " << job->getFd()); { cxxtools::MutexLock lock(mutex); new_jobs.push_back(job); } log_debug("notify " << job->getFd()); notify_pipe.write('A'); log_debug("addIdleJob ready"); } #endif // #else HAVE_EPOLL } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <stdlib.h> #include <pcl/point_types.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <ros/publisher.h> #include <tf/tf.h> #include <tf/transform_listener.h> #include <sensor_msgs/point_cloud_conversion.h> #include <pcl/filters/voxel_grid.h> #include <pcl/io/pcd_io.h> sensor_msgs::PointCloud2 cloud; ros::Publisher _pointcloud_pub; tf::TransformListener *tf_listener; void nodeCallback(const sensor_msgs::PointCloud2::ConstPtr &msg) { try { sensor_msgs::PointCloud transformed; sensor_msgs::convertPointCloud2ToPointCloud(*msg, transformed); transformed.header.stamp = ros::Time(0); tf_listener->transformPointCloud("/map",transformed,transformed); sensor_msgs::PointCloud2 transformed2; sensor_msgs::convertPointCloudToPointCloud2(transformed, transformed2); sensor_msgs::PointCloud2 output; pcl::concatenatePointCloud(transformed2, cloud, output); cloud = output; _pointcloud_pub.publish(cloud); } catch (int e) { ROS_ERROR_STREAM("caught error " << e); } } int main(int argc, char** argv) { ros::init(argc, argv, "mapper"); ros::NodeHandle nh; tf_listener = new tf::TransformListener(); std::string topics; std::string delimiter = " "; std::list<ros::Subscriber> subs; ros::NodeHandle pNh("~"); if(!pNh.hasParam("topics")) ROS_ERROR_STREAM("no param"); pNh.getParam("topics", topics); int pos; while((pos = topics.find(delimiter)) != std::string::npos) { std::string token = topics.substr(0, pos); ROS_ERROR_STREAM(token); topics.erase(0,pos+delimiter.length()); subs.push_back(nh.subscribe(token, 1, nodeCallback)); } ROS_ERROR_STREAM(topics); subs.push_back(nh.subscribe(topics, 1, nodeCallback)); cloud.header.frame_id = "/map"; _pointcloud_pub = nh.advertise<sensor_msgs::PointCloud2>("/pointcloud/map", 1); tf_listener->waitForTransform("/map", "/lidar", ros::Time(0), ros::Duration(5)); ros::spin(); } <commit_msg>Added comment<commit_after>#include <ros/ros.h> #include <stdlib.h> #include <pcl/point_types.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <ros/publisher.h> #include <tf/tf.h> #include <tf/transform_listener.h> #include <sensor_msgs/point_cloud_conversion.h> #include <pcl/filters/voxel_grid.h> #include <pcl/io/pcd_io.h> sensor_msgs::PointCloud2 cloud; ros::Publisher _pointcloud_pub; tf::TransformListener *tf_listener; void nodeCallback(const sensor_msgs::PointCloud2::ConstPtr &msg) { try { sensor_msgs::PointCloud transformed; sensor_msgs::convertPointCloud2ToPointCloud(*msg, transformed); transformed.header.stamp = ros::Time(0); tf_listener->transformPointCloud("/map",transformed,transformed); sensor_msgs::PointCloud2 transformed2; sensor_msgs::convertPointCloudToPointCloud2(transformed, transformed2); sensor_msgs::PointCloud2 output; pcl::concatenatePointCloud(transformed2, cloud, output); cloud = output; _pointcloud_pub.publish(cloud); } catch (int e) { ROS_ERROR_STREAM("caught error " << e); } } int main(int argc, char** argv) { ros::init(argc, argv, "mapper"); ros::NodeHandle nh; tf_listener = new tf::TransformListener(); std::string topics; std::string delimiter = " "; std::list<ros::Subscriber> subs; ros::NodeHandle pNh("~"); if(!pNh.hasParam("topics")) ROS_ERROR_STREAM("no param"); pNh.getParam("topics", topics); int pos; while((pos = topics.find(delimiter)) != std::string::npos) { std::string token = topics.substr(0, pos); ROS_ERROR_STREAM(token); topics.erase(0,pos+delimiter.length()); subs.push_back(nh.subscribe(token, 1, nodeCallback)); } ROS_ERROR_STREAM(topics); subs.push_back(nh.subscribe(topics, 1, nodeCallback)); cloud.header.frame_id = "/map"; _pointcloud_pub = nh.advertise<sensor_msgs::PointCloud2>("/pointcloud/map", 1); tf_listener->waitForTransform("/map", "/lidar", ros::Time(0), ros::Duration(5)); //Probably want to wait for other transforms that mapper will need like camera, camera_left, camera_right ros::spin(); } <|endoftext|>
<commit_before>#include "mitkBoundingObjectCutter.h" #include "mitkImageToItkMultiplexer.h" #include "mitkImage.h" #include "mitkBoundingObject.h" #include "mitkGeometry3D.h" #include <mitkStatusBar.h> #include <vtkTransform.h> mitk::BoundingObjectCutter::BoundingObjectCutter() : m_UseInsideValue(false), m_OutsideValue(0), m_InsideValue(1), m_BoundingObject(NULL), m_UseRegionGrower(true), m_SegmentationFilter(NULL), m_OutsidePixelCount(0), m_InsidePixelCount(0), m_ResampleFactor(1.0) { } mitk::BoundingObjectCutter::~BoundingObjectCutter() { } /** * \todo check if this is no conflict to the ITK filter writing rules -> ITK SoftwareGuide p.512 */ void mitk::BoundingObjectCutter::GenerateOutputInformation() { itkDebugMacro(<<"GenerateOutputInformation()"); //if(input.IsNull()) return; } void mitk::BoundingObjectCutter::GenerateData() { mitk::Image::Pointer outputImage = this->GetOutput(); // Check if there is an input bounding object if(m_BoundingObject.IsNull()) { outputImage = NULL; return; // return empty image/source image? } ImageToImageFilter::InputImageConstPointer inputImageMitkPointer = this->GetInput(); if(inputImageMitkPointer.IsNull()) { outputImage = NULL; return; // Eigentlich: eigenes Spacing/dimensions festlegen und neues Binrbild erzeugen } // convert input mitk image to itk image mitk::Image::Pointer inputImageMitk = const_cast<mitk::Image*>(inputImageMitkPointer.GetPointer()); // const away cast, because FixedInput...Multiplexer Macro needs non const Pointer ItkImageType::Pointer itkImage = ItkImageType::New(); FixedInputDimensionMitkToItkFunctionMultiplexer(itkImage, ItkImageType , inputImageMitk, 3, MakeCastImageFilter); // check if image conversion failed if (itkImage.IsNull()) { mitk::StatusBar::DisplayErrorText ("An internal error occurred. Can't convert Image. Please report to bugs@mitk.org"); std::cout << " image is NULL...returning" << std::endl; outputImage = NULL; return; // return and do nothing in case of failure } //std::cout << "itk Spacing: " << itkImage->GetSpacing()[0] << ", " << itkImage->GetSpacing()[1] << ", " << itkImage->GetSpacing()[2] << ".\n"; //std::cout << "mitk Spacing: " << inputImageMitk->GetSlicedGeometry()->GetSpacing()[0] << ", " << inputImageMitk->GetSlicedGeometry()->GetSpacing()[1] << ", " << inputImageMitk->GetSlicedGeometry()->GetSpacing()[2] << ".\n"; // calculate region of interest m_BoundingObject->UpdateOutputInformation(); mitk::BoundingBox::Pointer boundingBox = const_cast<mitk::BoundingBox*>(m_BoundingObject->GetGeometry()->GetBoundingBox()); /* get BoundingBox min max and center in world coordinates */ mitk::BoundingBox::PointType minPoint = boundingBox->GetMinimum(); mitk::ScalarType min[3]; min[0] = minPoint[0]; min[1] = minPoint[1]; min[2] = minPoint[2]; m_BoundingObject->GetGeometry()->GetVtkTransform()->TransformPoint(min, min); mitk::ITKPoint3D globalMinPoint; mitk::ITKPoint3D globalMaxPoint; globalMinPoint[0] = min[0]; globalMinPoint[1] = min[1]; globalMinPoint[2] = min[2]; globalMaxPoint[0] = min[0]; globalMaxPoint[1] = min[1]; globalMaxPoint[2] = min[2]; /* create all 8 points of the bounding box */ mitk::BoundingBox::PointsContainerPointer points = mitk::BoundingBox::PointsContainer::New(); mitk::ITKPoint3D p; p = boundingBox->GetMinimum(); points->InsertElement(0, p); p[0] = -p[0]; points->InsertElement(1, p); p = boundingBox->GetMinimum(); p[1] = -p[1]; points->InsertElement(2, p); p = boundingBox->GetMinimum(); p[2] = -p[2]; points->InsertElement(3, p); p = boundingBox->GetMaximum(); points->InsertElement(4, p); p[0] = -p[0]; points->InsertElement(5, p); p = boundingBox->GetMaximum(); p[1] = -p[1]; points->InsertElement(6, p); p = boundingBox->GetMaximum(); p[2] = -p[2]; points->InsertElement(7, p); mitk::BoundingBox::PointsContainerConstIterator pointsIterator = points->Begin(); mitk::BoundingBox::PointsContainerConstIterator pointsIteratorEnd = points->End(); while (pointsIterator != pointsIteratorEnd) // for each vertex of the bounding box { minPoint = pointsIterator->Value(); min[0] = minPoint[0]; min[1] = minPoint[1]; min[2] = minPoint[2]; m_BoundingObject->GetGeometry()->GetVtkTransform()->TransformPoint(min, min); // transform vertex point to world coordinates globalMinPoint[0] = (min[0] < globalMinPoint[0]) ? min[0] : globalMinPoint[0]; // check if world point globalMinPoint[1] = (min[1] < globalMinPoint[1]) ? min[1] : globalMinPoint[1]; // has a lower or a globalMinPoint[2] = (min[2] < globalMinPoint[2]) ? min[2] : globalMinPoint[2]; // higher value as globalMaxPoint[0] = (min[0] > globalMaxPoint[0]) ? min[0] : globalMaxPoint[0]; // the last known highest globalMaxPoint[1] = (min[1] > globalMaxPoint[1]) ? min[1] : globalMaxPoint[1]; // value globalMaxPoint[2] = (min[2] > globalMaxPoint[2]) ? min[2] : globalMaxPoint[2]; // in each axis pointsIterator++; } /* calculate regon of interest in pixel values */ ItkImageType::IndexType start; itkImage->TransformPhysicalPointToIndex(globalMinPoint, start); ItkImageType::SizeType size; size[0] = static_cast<ItkImageType::SizeType::SizeValueType>((globalMaxPoint[0] - globalMinPoint[0])/ itkImage->GetSpacing()[0]); // number of pixels along X axis size[1] = static_cast<ItkImageType::SizeType::SizeValueType>((globalMaxPoint[1] - globalMinPoint[1])/ itkImage->GetSpacing()[1]); // number of pixels along Y axis size[2] = static_cast<ItkImageType::SizeType::SizeValueType>((globalMaxPoint[2] - globalMinPoint[2])/ itkImage->GetSpacing()[2]); // number of pixels along Z axis ItkRegionType regionOfInterest; regionOfInterest.SetSize(size); regionOfInterest.SetIndex(start); ItkRegionOfInterestFilterType::Pointer regionOfInterestFilter = ItkRegionOfInterestFilterType::New(); regionOfInterestFilter->SetRegionOfInterest(regionOfInterest); regionOfInterestFilter->SetInput(itkImage); ItkImageType::Pointer itkImageCut = regionOfInterestFilter->GetOutput(); try { itkImageCut->Update(); // Cut the region of interest out of the source image } catch (itk::ExceptionObject & error) { std::cout << "Cutting not possible, bounding box is outside of the source image.\n"; std::cout << error; (mitk::StatusBar::GetInstance())->DisplayText("Cutting not possible, bounding box is outside of the source image.\n", 5000); outputImage = NULL; return; } ItkImageIteratorType imageIterator(itkImageCut, itkImageCut->GetRequestedRegion()); // mitk::ITKPoint3D p; bool inside = false; m_OutsidePixelCount = 0; m_InsidePixelCount = 0; //m_UseInsideValue = true; // just for testing //m_InsideValue = 30000; // just for testing //m_OutsideValue = -30000; // just for testing if (GetUseInsideValue()) // use a fixed value for each inside pixel(create a binary mask of the bounding object) for (imageIterator.GoToBegin(); !imageIterator.IsAtEnd(); ++imageIterator) { itkImageCut->TransformIndexToPhysicalPoint(imageIterator.GetIndex(), p); // transform index of current pixel to world coordinate point if(m_BoundingObject->IsInside(p)) { imageIterator.Value() = m_InsideValue; m_InsidePixelCount++; } else { imageIterator.Value() = m_OutsideValue; m_OutsidePixelCount++; } } else // no fixed value for inside, but the pixel value of the original image (normal cutting) for ( imageIterator.GoToBegin(); !imageIterator.IsAtEnd(); ++imageIterator) { // transform to world coordinates and check if p is inside the bounding object itkImageCut->TransformIndexToPhysicalPoint(imageIterator.GetIndex(), p); if(m_BoundingObject->IsInside(p)) { m_InsidePixelCount++; } else { imageIterator.Value() = m_OutsideValue; m_OutsidePixelCount++; } } // convert the itk image back to an mitk image and set it as output for this filter outputImage->InitializeByItk(itkImageCut.GetPointer()); outputImage->SetVolume(itkImageCut->GetBufferPointer()); } <commit_msg>- Cutting is now possible if the bounding object is partially outside of the input image - The output image is placed correctly, so that it matches with the corresponding region of the input image<commit_after>#include "mitkBoundingObjectCutter.h" #include "mitkImageToItkMultiplexer.h" #include "mitkImage.h" #include "mitkBoundingObject.h" #include "mitkGeometry3D.h" #include <mitkStatusBar.h> #include <vtkTransform.h> mitk::BoundingObjectCutter::BoundingObjectCutter() : m_UseInsideValue(false), m_OutsideValue(0), m_InsideValue(1), m_BoundingObject(NULL), m_UseRegionGrower(true), m_SegmentationFilter(NULL), m_OutsidePixelCount(0), m_InsidePixelCount(0), m_ResampleFactor(1.0) { } mitk::BoundingObjectCutter::~BoundingObjectCutter() { } /** * \todo check if this is no conflict to the ITK filter writing rules -> ITK SoftwareGuide p.512 */ void mitk::BoundingObjectCutter::GenerateOutputInformation() { itkDebugMacro(<<"GenerateOutputInformation()"); //if(input.IsNull()) return; } void mitk::BoundingObjectCutter::GenerateData() { mitk::Image::Pointer outputImage = this->GetOutput(); // Check if there is an input bounding object if(m_BoundingObject.IsNull()) { outputImage = NULL; return; // return empty image/source image? } ImageToImageFilter::InputImageConstPointer inputImageMitkPointer = this->GetInput(); if(inputImageMitkPointer.IsNull()) { outputImage = NULL; return; // Eigentlich: eigenes Spacing/dimensions festlegen und neues Binrbild erzeugen } // convert input mitk image to itk image mitk::Image::Pointer inputImageMitk = const_cast<mitk::Image*>(inputImageMitkPointer.GetPointer()); // const away cast, because FixedInput...Multiplexer Macro needs non const Pointer ItkImageType::Pointer itkImage = ItkImageType::New(); FixedInputDimensionMitkToItkFunctionMultiplexer(itkImage, ItkImageType , inputImageMitk, 3, MakeCastImageFilter); // check if image conversion failed if (itkImage.IsNull()) { mitk::StatusBar::DisplayErrorText ("An internal error occurred. Can't convert Image. Please report to bugs@mitk.org"); std::cout << " image is NULL...returning" << std::endl; outputImage = NULL; return; // return and do nothing in case of failure } // calculate region of interest m_BoundingObject->UpdateOutputInformation(); mitk::BoundingBox::Pointer boundingBox = const_cast<mitk::BoundingBox*>(m_BoundingObject->GetGeometry()->GetBoundingBox()); /* get BoundingBox min max and center in world coordinates */ mitk::BoundingBox::PointType minPoint = boundingBox->GetMinimum(); mitk::ScalarType min[3]; min[0] = minPoint[0]; min[1] = minPoint[1]; min[2] = minPoint[2]; m_BoundingObject->GetGeometry()->GetVtkTransform()->TransformPoint(min, min); mitk::ITKPoint3D globalMinPoint; mitk::ITKPoint3D globalMaxPoint; globalMinPoint[0] = min[0]; globalMinPoint[1] = min[1]; globalMinPoint[2] = min[2]; globalMaxPoint[0] = min[0]; globalMaxPoint[1] = min[1]; globalMaxPoint[2] = min[2]; /* create all 8 points of the bounding box */ mitk::BoundingBox::PointsContainerPointer points = mitk::BoundingBox::PointsContainer::New(); mitk::ITKPoint3D p; p = boundingBox->GetMinimum(); points->InsertElement(0, p); p[0] = -p[0]; points->InsertElement(1, p); p = boundingBox->GetMinimum(); p[1] = -p[1]; points->InsertElement(2, p); p = boundingBox->GetMinimum(); p[2] = -p[2]; points->InsertElement(3, p); p = boundingBox->GetMaximum(); points->InsertElement(4, p); p[0] = -p[0]; points->InsertElement(5, p); p = boundingBox->GetMaximum(); p[1] = -p[1]; points->InsertElement(6, p); p = boundingBox->GetMaximum(); p[2] = -p[2]; points->InsertElement(7, p); mitk::BoundingBox::PointsContainerConstIterator pointsIterator = points->Begin(); mitk::BoundingBox::PointsContainerConstIterator pointsIteratorEnd = points->End(); while (pointsIterator != pointsIteratorEnd) // for each vertex of the bounding box { minPoint = pointsIterator->Value(); min[0] = minPoint[0]; min[1] = minPoint[1]; min[2] = minPoint[2]; m_BoundingObject->GetGeometry()->GetVtkTransform()->TransformPoint(min, min); // transform vertex point to world coordinates globalMinPoint[0] = (min[0] < globalMinPoint[0]) ? min[0] : globalMinPoint[0]; // check if world point globalMinPoint[1] = (min[1] < globalMinPoint[1]) ? min[1] : globalMinPoint[1]; // has a lower or a globalMinPoint[2] = (min[2] < globalMinPoint[2]) ? min[2] : globalMinPoint[2]; // higher value as globalMaxPoint[0] = (min[0] > globalMaxPoint[0]) ? min[0] : globalMaxPoint[0]; // the last known highest globalMaxPoint[1] = (min[1] > globalMaxPoint[1]) ? min[1] : globalMaxPoint[1]; // value globalMaxPoint[2] = (min[2] > globalMaxPoint[2]) ? min[2] : globalMaxPoint[2]; // in each axis pointsIterator++; } mitk::BoundingBox::Pointer inputImageBoundingBox = const_cast<mitk::BoundingBox*>(inputImageMitk->GetGeometry()->GetBoundingBox()); mitk::BoundingBox::PointType imageMinPoint = inputImageBoundingBox->GetMinimum(); mitk::BoundingBox::PointType imageMaxPoint = inputImageBoundingBox->GetMaximum(); /* crop global bounding box to the source image bounding box */ globalMinPoint[0] = (globalMinPoint[0] < imageMinPoint[0]) ? imageMinPoint[0] : globalMinPoint[0]; globalMinPoint[1] = (globalMinPoint[1] < imageMinPoint[1]) ? imageMinPoint[1] : globalMinPoint[1]; globalMinPoint[2] = (globalMinPoint[2] < imageMinPoint[2]) ? imageMinPoint[2] : globalMinPoint[2]; globalMaxPoint[0] = (globalMaxPoint[0] > imageMaxPoint[0]) ? imageMaxPoint[0] : globalMaxPoint[0]; globalMaxPoint[1] = (globalMaxPoint[1] > imageMaxPoint[1]) ? imageMaxPoint[1] : globalMaxPoint[1]; globalMaxPoint[2] = (globalMaxPoint[2] > imageMaxPoint[2]) ? imageMaxPoint[2] : globalMaxPoint[2]; /* calculate regon of interest in pixel values */ ItkImageType::IndexType start; itkImage->TransformPhysicalPointToIndex(globalMinPoint, start); ItkImageType::SizeType size; size[0] = static_cast<ItkImageType::SizeType::SizeValueType>((globalMaxPoint[0] - globalMinPoint[0])/ itkImage->GetSpacing()[0]); // number of pixels along X axis size[1] = static_cast<ItkImageType::SizeType::SizeValueType>((globalMaxPoint[1] - globalMinPoint[1])/ itkImage->GetSpacing()[1]); // number of pixels along Y axis size[2] = static_cast<ItkImageType::SizeType::SizeValueType>((globalMaxPoint[2] - globalMinPoint[2])/ itkImage->GetSpacing()[2]); // number of pixels along Z axis ItkRegionType regionOfInterest; regionOfInterest.SetSize(size); regionOfInterest.SetIndex(start); /* fit region into source image */ regionOfInterest.Crop(itkImage->GetLargestPossibleRegion()); ItkRegionOfInterestFilterType::Pointer regionOfInterestFilter = ItkRegionOfInterestFilterType::New(); regionOfInterestFilter->SetRegionOfInterest(regionOfInterest); regionOfInterestFilter->SetInput(itkImage); ItkImageType::Pointer itkImageCut = regionOfInterestFilter->GetOutput(); try { itkImageCut->Update(); // Cut the region of interest out of the source image } catch (itk::ExceptionObject & error) { std::cout << "Cutting not possible, bounding box is outside of the source image.\n"; std::cout << error; (mitk::StatusBar::GetInstance())->DisplayText("Cutting not possible, bounding box is outside of the source image.\n", 5000); outputImage = NULL; return; } ItkImageIteratorType imageIterator(itkImageCut, itkImageCut->GetRequestedRegion()); bool inside = false; m_OutsidePixelCount = 0; m_InsidePixelCount = 0; if (GetUseInsideValue()) // use a fixed value for each inside pixel(create a binary mask of the bounding object) for (imageIterator.GoToBegin(); !imageIterator.IsAtEnd(); ++imageIterator) { itkImageCut->TransformIndexToPhysicalPoint(imageIterator.GetIndex(), p); // transform index of current pixel to world coordinate point if(m_BoundingObject->IsInside(p)) { imageIterator.Value() = m_InsideValue; m_InsidePixelCount++; } else { imageIterator.Value() = m_OutsideValue; m_OutsidePixelCount++; } } else // no fixed value for inside, but the pixel value of the original image (normal cutting) for ( imageIterator.GoToBegin(); !imageIterator.IsAtEnd(); ++imageIterator) { // transform to world coordinates and check if p is inside the bounding object itkImageCut->TransformIndexToPhysicalPoint(imageIterator.GetIndex(), p); if(m_BoundingObject->IsInside(p)) { m_InsidePixelCount++; } else { imageIterator.Value() = m_OutsideValue; m_OutsidePixelCount++; } } /* convert the itk image back to an mitk image and set it as output for this filter */ outputImage->InitializeByItk(itkImageCut.GetPointer()); outputImage->SetVolume(itkImageCut->GetBufferPointer()); /* Position the output Image to match the corresponding region of the input image */ mitkImageTransform->Translate(globalMinPoint[0], globalMinPoint[1], globalMinPoint[2]); } <|endoftext|>
<commit_before>#include "depthai-bootloader-shared/Bootloader.hpp" namespace dai { namespace bootloader { // Bootloader.hpp definitions // Requests decltype(request::UsbRomBoot::VERSION) constexpr request::UsbRomBoot::VERSION; decltype(request::UsbRomBoot::NAME) constexpr request::UsbRomBoot::NAME; decltype(request::BootApplication::VERSION) constexpr request::BootApplication::VERSION; decltype(request::BootApplication::NAME) constexpr request::BootApplication::NAME; decltype(request::UpdateFlash::VERSION) constexpr request::UpdateFlash::VERSION; decltype(request::UpdateFlash::NAME) constexpr request::UpdateFlash::NAME; decltype(request::GetBootloaderVersion::VERSION) constexpr request::GetBootloaderVersion::VERSION; decltype(request::GetBootloaderVersion::NAME) constexpr request::GetBootloaderVersion::NAME; decltype(request::BootMemory::VERSION) constexpr request::BootMemory::VERSION; decltype(request::BootMemory::NAME) constexpr request::BootMemory::NAME; decltype(request::UpdateFlashEx::VERSION) constexpr request::UpdateFlashEx::VERSION; decltype(request::UpdateFlashEx::NAME) constexpr request::UpdateFlashEx::NAME; decltype(request::UpdateFlashEx2::VERSION) constexpr request::UpdateFlashEx2::VERSION; decltype(request::UpdateFlashEx2::NAME) constexpr request::UpdateFlashEx2::NAME; decltype(request::GetBootloaderType::VERSION) constexpr request::GetBootloaderType::VERSION; decltype(request::GetBootloaderType::NAME) constexpr request::GetBootloaderType::NAME; decltype(request::SetBootloaderConfig::VERSION) constexpr request::SetBootloaderConfig::VERSION; decltype(request::SetBootloaderConfig::NAME) constexpr request::SetBootloaderConfig::NAME; decltype(request::GetBootloaderConfig::VERSION) constexpr request::GetBootloaderConfig::VERSION; decltype(request::GetBootloaderConfig::NAME) constexpr request::GetBootloaderConfig::NAME; decltype(request::BootloaderMemory::VERSION) constexpr request::BootloaderMemory::VERSION; decltype(request::BootloaderMemory::NAME) constexpr request::BootloaderMemory::NAME; // Responses decltype(response::FlashComplete::VERSION) constexpr response::FlashComplete::VERSION; decltype(response::FlashComplete::NAME) constexpr response::FlashComplete::NAME; decltype(response::FlashStatusUpdate::VERSION) constexpr response::FlashStatusUpdate::VERSION; decltype(response::FlashStatusUpdate::NAME) constexpr response::FlashStatusUpdate::NAME; decltype(response::BootloaderVersion::VERSION) constexpr response::BootloaderVersion::VERSION; decltype(response::BootloaderVersion::NAME) constexpr response::BootloaderVersion::NAME; decltype(response::BootloaderType::VERSION) constexpr response::BootloaderType::VERSION; decltype(response::BootloaderType::NAME) constexpr response::BootloaderType::NAME; decltype(response::GetBootloaderConfig::VERSION) constexpr response::GetBootloaderConfig::VERSION; decltype(response::GetBootloaderConfig::NAME) constexpr response::GetBootloaderConfig::NAME; decltype(response::BootloaderMemory::VERSION) constexpr response::BootloaderMemory::VERSION; decltype(response::BootloaderMemory::NAME) constexpr response::BootloaderMemory::NAME; decltype(response::BootApplication::VERSION) constexpr response::BootApplication::VERSION; decltype(response::BootApplication::NAME) constexpr response::BootApplication::NAME; } }<commit_msg>Updated formatting<commit_after>#include "depthai-bootloader-shared/Bootloader.hpp" namespace dai { namespace bootloader { // Bootloader.hpp definitions // Requests decltype(request::UsbRomBoot::VERSION) constexpr request::UsbRomBoot::VERSION; decltype(request::UsbRomBoot::NAME) constexpr request::UsbRomBoot::NAME; decltype(request::BootApplication::VERSION) constexpr request::BootApplication::VERSION; decltype(request::BootApplication::NAME) constexpr request::BootApplication::NAME; decltype(request::UpdateFlash::VERSION) constexpr request::UpdateFlash::VERSION; decltype(request::UpdateFlash::NAME) constexpr request::UpdateFlash::NAME; decltype(request::GetBootloaderVersion::VERSION) constexpr request::GetBootloaderVersion::VERSION; decltype(request::GetBootloaderVersion::NAME) constexpr request::GetBootloaderVersion::NAME; decltype(request::BootMemory::VERSION) constexpr request::BootMemory::VERSION; decltype(request::BootMemory::NAME) constexpr request::BootMemory::NAME; decltype(request::UpdateFlashEx::VERSION) constexpr request::UpdateFlashEx::VERSION; decltype(request::UpdateFlashEx::NAME) constexpr request::UpdateFlashEx::NAME; decltype(request::UpdateFlashEx2::VERSION) constexpr request::UpdateFlashEx2::VERSION; decltype(request::UpdateFlashEx2::NAME) constexpr request::UpdateFlashEx2::NAME; decltype(request::GetBootloaderType::VERSION) constexpr request::GetBootloaderType::VERSION; decltype(request::GetBootloaderType::NAME) constexpr request::GetBootloaderType::NAME; decltype(request::SetBootloaderConfig::VERSION) constexpr request::SetBootloaderConfig::VERSION; decltype(request::SetBootloaderConfig::NAME) constexpr request::SetBootloaderConfig::NAME; decltype(request::GetBootloaderConfig::VERSION) constexpr request::GetBootloaderConfig::VERSION; decltype(request::GetBootloaderConfig::NAME) constexpr request::GetBootloaderConfig::NAME; decltype(request::BootloaderMemory::VERSION) constexpr request::BootloaderMemory::VERSION; decltype(request::BootloaderMemory::NAME) constexpr request::BootloaderMemory::NAME; // Responses decltype(response::FlashComplete::VERSION) constexpr response::FlashComplete::VERSION; decltype(response::FlashComplete::NAME) constexpr response::FlashComplete::NAME; decltype(response::FlashStatusUpdate::VERSION) constexpr response::FlashStatusUpdate::VERSION; decltype(response::FlashStatusUpdate::NAME) constexpr response::FlashStatusUpdate::NAME; decltype(response::BootloaderVersion::VERSION) constexpr response::BootloaderVersion::VERSION; decltype(response::BootloaderVersion::NAME) constexpr response::BootloaderVersion::NAME; decltype(response::BootloaderType::VERSION) constexpr response::BootloaderType::VERSION; decltype(response::BootloaderType::NAME) constexpr response::BootloaderType::NAME; decltype(response::GetBootloaderConfig::VERSION) constexpr response::GetBootloaderConfig::VERSION; decltype(response::GetBootloaderConfig::NAME) constexpr response::GetBootloaderConfig::NAME; decltype(response::BootloaderMemory::VERSION) constexpr response::BootloaderMemory::VERSION; decltype(response::BootloaderMemory::NAME) constexpr response::BootloaderMemory::NAME; decltype(response::BootApplication::VERSION) constexpr response::BootApplication::VERSION; decltype(response::BootApplication::NAME) constexpr response::BootApplication::NAME; } // namespace bootloader } // namespace dai<|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2017 Ryo Suzuki // Copyright (c) 2016-2017 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Platform.hpp> # if defined(SIV3D_TARGET_WINDOWS) # include "CShader_D3D11.hpp" # include "../../EngineUtility.hpp" # include <Siv3D/IReader.hpp> # include <Siv3D/ByteArray.hpp> # include <Siv3D/BinaryReader.hpp> # include <Siv3D/Resource.hpp> # include <Siv3D/Logger.hpp> namespace s3d { CShader_D3D11::CShader_D3D11() { } CShader_D3D11::~CShader_D3D11() { m_standardVSs.clear(); m_standardPSs.clear(); m_vertexShaders.destroy(); m_pixelShaders.destroy(); if (m_d3dcompiler) { ::FreeLibrary(m_d3dcompiler); } } bool CShader_D3D11::init(ID3D11Device* const device, ID3D11DeviceContext* const context) { m_device = device; m_context = context; # if defined(SIV3D_TARGET_WINDOWS_DESKTOP_X64) m_d3dcompiler = ::LoadLibraryW(L"dll_x64/d3d/d3dcompiler_47.dll"); # elif defined(SIV3D_TARGET_WINDOWS_DESKTOP_X86) m_d3dcompiler = ::LoadLibraryW(L"dll_x86/d3d/d3dcompiler_47.dll"); # endif if (!m_d3dcompiler) { m_d3dcompiler = ::LoadLibraryW(L"d3dcompiler_47.dll"); } if (m_d3dcompiler) { p_D3DCompile2 = FunctionPointer(m_d3dcompiler, "D3DCompile2"); } { const auto nullVertexShader = std::make_shared<VertexShader_D3D11>(VertexShader_D3D11::Null{}); if (!nullVertexShader->isInitialized()) { return false; } m_vertexShaders.setNullData(nullVertexShader); } { const auto nullPixelShader = std::make_shared<PixelShader_D3D11>(PixelShader_D3D11::Null{}); if (!nullPixelShader->isInitialized()) { return false; } m_pixelShaders.setNullData(nullPixelShader); } ///* //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/sprite.vs", "VS", "vs_4_0"); //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/shape.ps", "PS_Shape", "ps_4_0"); //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/line_dot.ps", "PS_LineDot", "ps_4_0"); //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/line_round_dot.ps", "PS_LineRoundDot", "ps_4_0"); //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/sprite.ps", "PS_Sprite", "ps_4_0"); //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/sprite_sdf.ps", "PS_SDF", "ps_4_0"); //*/ # define RSC(path) Resource(path) //# define RSC(path) path m_standardVSs.push_back(VertexShader(RSC(U"engine/shader/sprite.vs"))); m_standardPSs.push_back(PixelShader(RSC(U"engine/shader/shape.ps"))); m_standardPSs.push_back(PixelShader(RSC(U"engine/shader/line_dot.ps"))); m_standardPSs.push_back(PixelShader(RSC(U"engine/shader/line_round_dot.ps"))); m_standardPSs.push_back(PixelShader(RSC(U"engine/shader/sprite.ps"))); m_standardPSs.push_back(PixelShader(RSC(U"engine/shader/sprite_sdf.ps"))); LOG_INFO(U"ℹ️ Shader initialized"); return true; } VertexShaderID CShader_D3D11::createVS(ByteArray&& binary) { const auto vertexShader = std::make_shared<VertexShader_D3D11>(std::move(binary), m_device); if (!vertexShader->isInitialized()) { return VertexShaderID::NullAsset(); } return m_vertexShaders.add(vertexShader); } VertexShaderID CShader_D3D11::createVSFromFile(const FilePath& path, const Array<BindingPoint>&) { BinaryReader reader(path); if (!reader.isOpened() || reader.size() == 0 || !reader.supportsLookahead()) { return VertexShaderID::NullAsset(); } static constexpr uint8 dxbc[4] = { 'D', 'X', 'B', 'C' }; uint8 fourcc[4]; if (!reader.lookahead(fourcc)) { return VertexShaderID::NullAsset(); } const bool isBinary = (::memcmp(dxbc, fourcc, 4) == 0); ByteArray memory; if (isBinary) { memory = reader.readAll(); } else if (!compileHLSL(reader, memory, reader.path().narrow().c_str(), "VS", "vs_4_0")) { return VertexShaderID::NullAsset(); } return createVS(std::move(memory)); } PixelShaderID CShader_D3D11::createPS(ByteArray&& binary) { const auto pixelShader = std::make_shared<PixelShader_D3D11>(std::move(binary), m_device); if (!pixelShader->isInitialized()) { return PixelShaderID::NullAsset(); } return m_pixelShaders.add(pixelShader); } PixelShaderID CShader_D3D11::createPSFromFile(const FilePath& path, const Array<BindingPoint>&) { BinaryReader reader(path); if (!reader.isOpened() || reader.size() == 0 || !reader.supportsLookahead()) { return PixelShaderID::NullAsset(); } static constexpr uint8 dxbc[4] = { 'D', 'X', 'B', 'C' }; uint8 fourcc[4]; if (!reader.lookahead(fourcc)) { return PixelShaderID::NullAsset(); } const bool isBinary = (::memcmp(dxbc, fourcc, 4) == 0); ByteArray memory; if (isBinary) { memory = reader.readAll(); } else if (!compileHLSL(reader, memory, reader.path().narrow().c_str(), "PS", "ps_4_0")) { return PixelShaderID::NullAsset(); } return createPS(std::move(memory)); } void CShader_D3D11::releaseVS(const VertexShaderID handleID) { m_vertexShaders.erase(handleID); } void CShader_D3D11::releasePS(const PixelShaderID handleID) { m_pixelShaders.erase(handleID); } ByteArrayView CShader_D3D11::getBinaryViewVS(const VertexShaderID handleID) { return m_vertexShaders[handleID]->getView(); } ByteArrayView CShader_D3D11::getBinaryViewPS(const PixelShaderID handleID) { return m_pixelShaders[handleID]->getView(); } const VertexShader& CShader_D3D11::getStandardVS(const size_t index) const { return m_standardVSs[index]; } const PixelShader& CShader_D3D11::getStandardPS(const size_t index) const { return m_standardPSs[index]; } void CShader_D3D11::setVS(const VertexShaderID handleID) { if (handleID == m_currentVS) { return; } m_context->VSSetShader(m_vertexShaders[handleID]->getShader(), nullptr, 0); m_currentVS = handleID; } void CShader_D3D11::setPS(const PixelShaderID handleID) { if (m_currentPS == handleID) { return; } m_context->PSSetShader(m_pixelShaders[handleID]->getShader(), nullptr, 0); m_currentPS = handleID; } bool CShader_D3D11::compileHLSL(IReader& reader, ByteArray& to, const char* filePath, const char* entryPoint, const char* target) { if (!p_D3DCompile2) { return false; } Array<Byte> data(static_cast<size_t>(reader.size())); reader.read(data.data(), data.size()); const bool preferFlow = false; const uint32 flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE_WARNINGS_ARE_ERRORS | (preferFlow ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0); ID3DBlob* pBlobOut = nullptr; ID3DBlob* pErrorBlob = nullptr; const HRESULT hr = p_D3DCompile2(data.data(), data.size(), filePath, nullptr, nullptr, entryPoint, target, flags, 0, 0, nullptr, 0, &pBlobOut, &pErrorBlob); if (pErrorBlob) { ::OutputDebugStringA((const char*)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } if (FAILED(hr)) { if (pBlobOut) { pBlobOut->Release(); } return false; } to.create(pBlobOut->GetBufferPointer(), pBlobOut->GetBufferSize()); pBlobOut->Release(); return true; } bool CShader_D3D11::compileHLSLToFile(const FilePath& hlsl, const FilePath& to, const char* entryPoint, const char* target) { BinaryReader reader(hlsl); ByteArray binary; if (!compileHLSL(reader, binary, hlsl.narrow().c_str(), entryPoint, target)) { return false; } return binary.save(to); } } # endif <commit_msg>update<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2017 Ryo Suzuki // Copyright (c) 2016-2017 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Platform.hpp> # if defined(SIV3D_TARGET_WINDOWS) # include "CShader_D3D11.hpp" # include "../../EngineUtility.hpp" # include <Siv3D/IReader.hpp> # include <Siv3D/ByteArray.hpp> # include <Siv3D/BinaryReader.hpp> # include <Siv3D/Resource.hpp> # include <Siv3D/Logger.hpp> namespace s3d { CShader_D3D11::CShader_D3D11() { } CShader_D3D11::~CShader_D3D11() { m_standardVSs.clear(); m_standardPSs.clear(); m_vertexShaders.destroy(); m_pixelShaders.destroy(); if (m_d3dcompiler) { ::FreeLibrary(m_d3dcompiler); } } bool CShader_D3D11::init(ID3D11Device* const device, ID3D11DeviceContext* const context) { m_device = device; m_context = context; # if defined(SIV3D_TARGET_WINDOWS_DESKTOP_X64) m_d3dcompiler = ::LoadLibraryW(L"dll_x64/d3d/d3dcompiler_47.dll"); # elif defined(SIV3D_TARGET_WINDOWS_DESKTOP_X86) m_d3dcompiler = ::LoadLibraryW(L"dll_x86/d3d/d3dcompiler_47.dll"); # endif if (!m_d3dcompiler) { m_d3dcompiler = ::LoadLibraryW(L"d3dcompiler_47.dll"); } if (m_d3dcompiler) { p_D3DCompile2 = FunctionPointer(m_d3dcompiler, "D3DCompile2"); } { const auto nullVertexShader = std::make_shared<VertexShader_D3D11>(VertexShader_D3D11::Null{}); if (!nullVertexShader->isInitialized()) { return false; } m_vertexShaders.setNullData(nullVertexShader); } { const auto nullPixelShader = std::make_shared<PixelShader_D3D11>(PixelShader_D3D11::Null{}); if (!nullPixelShader->isInitialized()) { return false; } m_pixelShaders.setNullData(nullPixelShader); } ///* //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/sprite.vs", "VS", "vs_4_0"); //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/shape.ps", "PS_Shape", "ps_4_0"); //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/line_dot.ps", "PS_LineDot", "ps_4_0"); //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/line_round_dot.ps", "PS_LineRoundDot", "ps_4_0"); //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/sprite.ps", "PS_Sprite", "ps_4_0"); //compileHLSLToFile(U"engine/shader/sprite.hlsl", U"engine/shader/sprite_sdf.ps", "PS_SDF", "ps_4_0"); //*/ # define RSC(path) Resource(path) //# define RSC(path) path m_standardVSs.push_back(VertexShader(RSC(U"engine/shader/sprite.vs"))); m_standardPSs.push_back(PixelShader(RSC(U"engine/shader/shape.ps"))); m_standardPSs.push_back(PixelShader(RSC(U"engine/shader/line_dot.ps"))); m_standardPSs.push_back(PixelShader(RSC(U"engine/shader/line_round_dot.ps"))); m_standardPSs.push_back(PixelShader(RSC(U"engine/shader/sprite.ps"))); m_standardPSs.push_back(PixelShader(RSC(U"engine/shader/sprite_sdf.ps"))); if (m_standardVSs.count_if(!Lambda::_) > 1) { LOG_FAIL(U"❌ CShader_GL: Failed to load standard vertex shaders"); return false; } if (m_standardPSs.count_if(!Lambda::_) > 1) { LOG_FAIL(U"❌ CShader_GL: Failed to load standard pixel shaders"); return false; } LOG_INFO(U"ℹ️ Shader initialized"); return true; } VertexShaderID CShader_D3D11::createVS(ByteArray&& binary) { const auto vertexShader = std::make_shared<VertexShader_D3D11>(std::move(binary), m_device); if (!vertexShader->isInitialized()) { return VertexShaderID::NullAsset(); } return m_vertexShaders.add(vertexShader); } VertexShaderID CShader_D3D11::createVSFromFile(const FilePath& path, const Array<BindingPoint>&) { BinaryReader reader(path); if (!reader.isOpened() || reader.size() == 0 || !reader.supportsLookahead()) { return VertexShaderID::NullAsset(); } static constexpr uint8 dxbc[4] = { 'D', 'X', 'B', 'C' }; uint8 fourcc[4]; if (!reader.lookahead(fourcc)) { return VertexShaderID::NullAsset(); } const bool isBinary = (::memcmp(dxbc, fourcc, 4) == 0); ByteArray memory; if (isBinary) { memory = reader.readAll(); } else if (!compileHLSL(reader, memory, reader.path().narrow().c_str(), "VS", "vs_4_0")) { return VertexShaderID::NullAsset(); } return createVS(std::move(memory)); } PixelShaderID CShader_D3D11::createPS(ByteArray&& binary) { const auto pixelShader = std::make_shared<PixelShader_D3D11>(std::move(binary), m_device); if (!pixelShader->isInitialized()) { return PixelShaderID::NullAsset(); } return m_pixelShaders.add(pixelShader); } PixelShaderID CShader_D3D11::createPSFromFile(const FilePath& path, const Array<BindingPoint>&) { BinaryReader reader(path); if (!reader.isOpened() || reader.size() == 0 || !reader.supportsLookahead()) { return PixelShaderID::NullAsset(); } static constexpr uint8 dxbc[4] = { 'D', 'X', 'B', 'C' }; uint8 fourcc[4]; if (!reader.lookahead(fourcc)) { return PixelShaderID::NullAsset(); } const bool isBinary = (::memcmp(dxbc, fourcc, 4) == 0); ByteArray memory; if (isBinary) { memory = reader.readAll(); } else if (!compileHLSL(reader, memory, reader.path().narrow().c_str(), "PS", "ps_4_0")) { return PixelShaderID::NullAsset(); } return createPS(std::move(memory)); } void CShader_D3D11::releaseVS(const VertexShaderID handleID) { m_vertexShaders.erase(handleID); } void CShader_D3D11::releasePS(const PixelShaderID handleID) { m_pixelShaders.erase(handleID); } ByteArrayView CShader_D3D11::getBinaryViewVS(const VertexShaderID handleID) { return m_vertexShaders[handleID]->getView(); } ByteArrayView CShader_D3D11::getBinaryViewPS(const PixelShaderID handleID) { return m_pixelShaders[handleID]->getView(); } const VertexShader& CShader_D3D11::getStandardVS(const size_t index) const { return m_standardVSs[index]; } const PixelShader& CShader_D3D11::getStandardPS(const size_t index) const { return m_standardPSs[index]; } void CShader_D3D11::setVS(const VertexShaderID handleID) { if (handleID == m_currentVS) { return; } m_context->VSSetShader(m_vertexShaders[handleID]->getShader(), nullptr, 0); m_currentVS = handleID; } void CShader_D3D11::setPS(const PixelShaderID handleID) { if (m_currentPS == handleID) { return; } m_context->PSSetShader(m_pixelShaders[handleID]->getShader(), nullptr, 0); m_currentPS = handleID; } bool CShader_D3D11::compileHLSL(IReader& reader, ByteArray& to, const char* filePath, const char* entryPoint, const char* target) { if (!p_D3DCompile2) { return false; } Array<Byte> data(static_cast<size_t>(reader.size())); reader.read(data.data(), data.size()); const bool preferFlow = false; const uint32 flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE_WARNINGS_ARE_ERRORS | (preferFlow ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0); ID3DBlob* pBlobOut = nullptr; ID3DBlob* pErrorBlob = nullptr; const HRESULT hr = p_D3DCompile2(data.data(), data.size(), filePath, nullptr, nullptr, entryPoint, target, flags, 0, 0, nullptr, 0, &pBlobOut, &pErrorBlob); if (pErrorBlob) { ::OutputDebugStringA((const char*)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } if (FAILED(hr)) { if (pBlobOut) { pBlobOut->Release(); } return false; } to.create(pBlobOut->GetBufferPointer(), pBlobOut->GetBufferSize()); pBlobOut->Release(); return true; } bool CShader_D3D11::compileHLSLToFile(const FilePath& hlsl, const FilePath& to, const char* entryPoint, const char* target) { BinaryReader reader(hlsl); ByteArray binary; if (!compileHLSL(reader, binary, hlsl.narrow().c_str(), entryPoint, target)) { return false; } return binary.save(to); } } # endif <|endoftext|>
<commit_before>#include "ButtonItem.h" ButtonItem::ButtonItem(QQuickItem *parent): QQuickItem(parent), m_active(false), m_modifier(false), m_col(0), m_row(0), m_colSpan(1), m_rowSpan(1), m_currentSymbolIndex(-1) { connect(this, SIGNAL(symbolsChanged(const QStringList &)), SLOT(onSymbolsChanged())); connect(this, SIGNAL(triggered()), SLOT(onTriggered())); } ButtonItem::~ButtonItem() { } void ButtonItem::setActive(bool active) { if (m_active == active) { return; } m_active = active; emit activeChanged(active); } void ButtonItem::setCurrentSymbolIndex(int currentSymbolIndex) { if (m_symbols.length() == 0) { currentSymbolIndex = -1; } if (currentSymbolIndex == -1 && m_symbols.length() > 0) { currentSymbolIndex = 0; } if (currentSymbolIndex == m_currentSymbolIndex) { return; } m_currentSymbolIndex = currentSymbolIndex; emit currentSymbolIndexChanged(currentSymbolIndex); } void ButtonItem::onSymbolsChanged() { if (m_symbols.length() == 0) { setCurrentSymbolIndex(-1); } else { if (m_currentSymbolIndex < 0 || m_currentSymbolIndex >= m_symbols.length()) { setCurrentSymbolIndex(0); } } } void ButtonItem::onTriggered() { if (m_currentSymbolIndex < 0 || m_currentSymbolIndex >= m_symbols.length()) { return; } emit symbolTriggered(m_symbols[m_currentSymbolIndex]); } <commit_msg>Set current symbol to 0 on active change.<commit_after>#include "ButtonItem.h" ButtonItem::ButtonItem(QQuickItem *parent): QQuickItem(parent), m_active(false), m_modifier(false), m_col(0), m_row(0), m_colSpan(1), m_rowSpan(1), m_currentSymbolIndex(-1) { connect(this, SIGNAL(symbolsChanged(const QStringList &)), SLOT(onSymbolsChanged())); connect(this, SIGNAL(triggered()), SLOT(onTriggered())); } ButtonItem::~ButtonItem() { } void ButtonItem::setActive(bool active) { if (m_active == active) { return; } m_active = active; emit activeChanged(active); setCurrentSymbolIndex(0); } void ButtonItem::setCurrentSymbolIndex(int currentSymbolIndex) { if (m_symbols.length() == 0) { currentSymbolIndex = -1; } if (currentSymbolIndex == -1 && m_symbols.length() > 0) { currentSymbolIndex = 0; } if (currentSymbolIndex == m_currentSymbolIndex) { return; } m_currentSymbolIndex = currentSymbolIndex; emit currentSymbolIndexChanged(currentSymbolIndex); } void ButtonItem::onSymbolsChanged() { if (m_symbols.length() == 0) { setCurrentSymbolIndex(-1); } else { if (m_currentSymbolIndex < 0 || m_currentSymbolIndex >= m_symbols.length()) { setCurrentSymbolIndex(0); } } } void ButtonItem::onTriggered() { if (m_currentSymbolIndex < 0 || m_currentSymbolIndex >= m_symbols.length()) { return; } emit symbolTriggered(m_symbols[m_currentSymbolIndex]); } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "StateMask.h" #include <functional> namespace sofa { namespace helper { #ifdef SOFA_USE_MASK void StateMask::resize( size_t size ) { mask.resize( size ); /*assign( size, true );*/ } void StateMask::assign( size_t size, bool value ) { assert(size <= mask.size()); mask.assign( size, value ); } void StateMask::activate( bool a ) { activated = a; } size_t StateMask::nbActiveDofs() const { size_t t = 0; for( size_t i = 0 ; i<size() ; ++i ) if( getEntry(i) ) t++; return t; } size_t StateMask::getHash() const { return std::hash<std::vector<bool> >()(mask); } #endif } // namespace helper } // namespace sofa <commit_msg>[core] fixed bogus assert (my bad)<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "StateMask.h" #include <functional> namespace sofa { namespace helper { #ifdef SOFA_USE_MASK void StateMask::resize( size_t size ) { mask.resize( size ); /*assign( size, true );*/ } void StateMask::assign( size_t size, bool value ) { // assert(size <= mask.size()); mask.assign( size, value ); } void StateMask::activate( bool a ) { activated = a; } size_t StateMask::nbActiveDofs() const { size_t t = 0; for( size_t i = 0 ; i<size() ; ++i ) if( getEntry(i) ) t++; return t; } size_t StateMask::getHash() const { return std::hash<std::vector<bool> >()(mask); } #endif } // namespace helper } // namespace sofa <|endoftext|>
<commit_before> #include "cocoa/CCSet.h" #include "basics/CAApplication.h" #include "dispatcher/CAKeypadDispatcher.h" #include "dispatcher/CATouch.h" #include "dispatcher/CATouchDispatcher.h" #include <android/log.h> #include <jni.h> #include "platform/android/CCEGLView.h" using namespace CrossApp; extern "C" { JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesBegin(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) { CrossApp::CAEvent* theEvent = new CrossApp::CAEvent(); theEvent->setEventType(CrossApp::EventType::androidEvent); intptr_t ids[5] = {0}; ids[0] = id; float x_s[5] = {0}; x_s[0] = x; float* y_s[5] = {0}; y_s[0] = y; CAApplication::getApplication()->getOpenGLView()->handleTouchesBegin(1, ids, x_s, y_s, theEvent); theEvent->release(); } JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesEnd(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) { CrossApp::CAEvent* theEvent = new CrossApp::CAEvent(); theEvent->setEventType(CrossApp::EventType::androidEvent); intptr_t ids[5] = {0}; ids[0] = id; float x_s[5] = {0}; x_s[0] = x; float* y_s[5] = {0}; y_s[0] = y; CAApplication::getApplication()->getOpenGLView()->handleTouchesEnd(1, ids, x_s, y_s, theEvent); theEvent->release(); } JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesMove(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) { int size = env->GetArrayLength(ids); jint id[size]; jfloat x[size]; jfloat y[size]; env->GetIntArrayRegion(ids, 0, size, id); env->GetFloatArrayRegion(xs, 0, size, x); env->GetFloatArrayRegion(ys, 0, size, y); intptr_t ids[size] = {0}; float x_s[size] = {0}; float* y_s[size] = {0}; for (int i=0; i<size; i++) { ids[i] = id[i]; x_s[i] = [i]; y_s[i] = y[i]; } CrossApp::CAEvent* theEvent = new CrossApp::CAEvent(); theEvent->setEventType(CrossApp::EventType::androidEvent); CAApplication::getApplication()->getOpenGLView()->handleTouchesMove(size, ids, x_s, y_s, theEvent); theEvent->release(); } JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesCancel(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) { int size = env->GetArrayLength(ids); jint id[size]; jfloat x[size]; jfloat y[size]; env->GetIntArrayRegion(ids, 0, size, id); env->GetFloatArrayRegion(xs, 0, size, x); env->GetFloatArrayRegion(ys, 0, size, y); intptr_t ids[size] = {0}; float x_s[size] = {0}; float* y_s[size] = {0}; for (int i=0; i<size; i++) { ids[i] = id[i]; x_s[i] = [i]; y_s[i] = y[i]; } CrossApp::CAEvent* theEvent = new CrossApp::CAEvent(); theEvent->setEventType(CrossApp::EventType::androidEvent); CAApplication::getApplication()->getOpenGLView()->handleTouchesCancel(size, ids, x_s, y_s, theEvent); theEvent->release(); } #define KEYCODE_BACK 0x04 #define KEYCODE_MENU 0x52 JNIEXPORT jboolean JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeKeyDown(JNIEnv * env, jobject thiz, jint keyCode) { CAApplication* application = CAApplication::getApplication(); switch (keyCode) { case KEYCODE_BACK: if (application->getKeypadDispatcher()->dispatchKeypadMSG(CAKeypadDispatcher::KeypadMSGType::BackClicked)) return JNI_TRUE; break; case KEYCODE_MENU: if (application->getKeypadDispatcher()->dispatchKeypadMSG(CAKeypadDispatcher::KeypadMSGType::MenuClicked)) return JNI_TRUE; break; default: return JNI_FALSE; } return JNI_FALSE; } } <commit_msg>no message<commit_after> #include "cocoa/CCSet.h" #include "basics/CAApplication.h" #include "dispatcher/CAKeypadDispatcher.h" #include "dispatcher/CATouch.h" #include "dispatcher/CATouchDispatcher.h" #include <android/log.h> #include <jni.h> #include "platform/android/CCEGLView.h" using namespace CrossApp; extern "C" { JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesBegin(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) { CrossApp::CAEvent* theEvent = new CrossApp::CAEvent(); theEvent->setEventType(CrossApp::EventType::androidEvent); intptr_t ids[5] = {0}; ids[0] = id; float x_s[5] = {0}; x_s[0] = x; float* y_s[5] = {0}; y_s[0] = y; CAApplication::getApplication()->getOpenGLView()->handleTouchesBegin(1, ids, x_s, y_s, theEvent); theEvent->release(); } JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesEnd(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) { CrossApp::CAEvent* theEvent = new CrossApp::CAEvent(); theEvent->setEventType(CrossApp::EventType::androidEvent); intptr_t ids[5] = {0}; ids[0] = id; float x_s[5] = {0}; x_s[0] = x; float* y_s[5] = {0}; y_s[0] = y; CAApplication::getApplication()->getOpenGLView()->handleTouchesEnd(1, ids, x_s, y_s, theEvent); theEvent->release(); } JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesMove(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) { int size = env->GetArrayLength(ids); jint id[size]; jfloat x[size]; jfloat y[size]; env->GetIntArrayRegion(ids, 0, size, id); env->GetFloatArrayRegion(xs, 0, size, x); env->GetFloatArrayRegion(ys, 0, size, y); intptr_t ids[size] = {0}; float x_s[size] = {0}; float* y_s[size] = {0}; for (int i=0; i<size; i++) { ids[i] = id[i]; x_s[i] = x[i]; y_s[i] = y[i]; } CrossApp::CAEvent* theEvent = new CrossApp::CAEvent(); theEvent->setEventType(CrossApp::EventType::androidEvent); CAApplication::getApplication()->getOpenGLView()->handleTouchesMove(size, ids, x_s, y_s, theEvent); theEvent->release(); } JNIEXPORT void JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeTouchesCancel(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) { int size = env->GetArrayLength(ids); jint id[size]; jfloat x[size]; jfloat y[size]; env->GetIntArrayRegion(ids, 0, size, id); env->GetFloatArrayRegion(xs, 0, size, x); env->GetFloatArrayRegion(ys, 0, size, y); intptr_t ids[size] = {0}; float x_s[size] = {0}; float* y_s[size] = {0}; for (int i=0; i<size; i++) { ids[i] = id[i]; x_s[i] = x[i]; y_s[i] = y[i]; } CrossApp::CAEvent* theEvent = new CrossApp::CAEvent(); theEvent->setEventType(CrossApp::EventType::androidEvent); CAApplication::getApplication()->getOpenGLView()->handleTouchesCancel(size, ids, x_s, y_s, theEvent); theEvent->release(); } #define KEYCODE_BACK 0x04 #define KEYCODE_MENU 0x52 JNIEXPORT jboolean JNICALL Java_org_CrossApp_lib_CrossAppRenderer_nativeKeyDown(JNIEnv * env, jobject thiz, jint keyCode) { CAApplication* application = CAApplication::getApplication(); switch (keyCode) { case KEYCODE_BACK: if (application->getKeypadDispatcher()->dispatchKeypadMSG(CAKeypadDispatcher::KeypadMSGType::BackClicked)) return JNI_TRUE; break; case KEYCODE_MENU: if (application->getKeypadDispatcher()->dispatchKeypadMSG(CAKeypadDispatcher::KeypadMSGType::MenuClicked)) return JNI_TRUE; break; default: return JNI_FALSE; } return JNI_FALSE; } } <|endoftext|>
<commit_before>// Copyright 2010 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 <string> #include <sstream> #include <list> #include <typeinfo> #include <utils.hpp> #ifndef ARGUMENT_LIST_HPP #define ARGUMENT_LIST_HPP namespace isa { namespace utils { // Exception: no items in the command line class EmptyCommandLine : public std::exception {}; // Exception: requested switch not present class SwitchNotFound : public std::exception { public: SwitchNotFound(std:::string option); ~SwitchNotFound() throw (); const char *what() const throw (); private: std::string option; }; // ArgumentList class class ArgumentList { public: ArgumentList(int argc, char * argv[]); ~ArgumentList(); string getName(); template< typename T > T getFirst() throw(EmptyCommandLine); bool getSwitch(const string opt) throw(EmptyCommandLine); template< typename T > T getSwitchArgument(const std::string & option) throw(EmptyCommandLine, SwitchNotFound); private: std::list< std::string > args; std::string name; }; // Implementations SwitchNotFound::SwitchNotFound(std::string option) : option(option) {} const char * SwitchNotFound::what() throw() { return ("Switch \"" + option + "\" not found.").c_str(); } ArgumentList::ArgumentList(int argc, char * argv[]) { name = std::string(argv[0]); for ( unsigned int i = 1; i < argc; i++ ) { args.push_back(std::string(argv[1])); } } std::string ArgumentList::getName() { return name; } template< typename T > T ArgumentList::getFirst() throw(EmptyCommandLine) { if ( args.empty() ) { throw EmptyCommandLine(); } std::string temp = args.front(); args.pop_front(); return castToType< std::string, T >(temp); } bool ArgumentList::getSwitch(const std::string opt) throw(EmptyCommandLine) { if ( args.empty() ) { return false; } for ( std::list< std::string >::iterator s = args.begin(); s != args.end(); ++s ) { if ( opt.compare(*s) == 0 ) { args.erase(s); return true; } } return false; } template< class T > T ArgumentList::getSwitchArgument(const std::string opt) throw(EmptyCommandLine, SwitchNotFound) { if ( args.empty() ) { throw EmptyCommandLine(); } for ( std::list< std::string >::iterator s = args.begin(); s != args.end(); ++s ) { if ( opt.compare(*s) == 0 ) { std::string temp = *(++s); T retVal = castToType< std::string, T >(temp); args.erase(s); args.erase(--s); return retVal; } } throw SwitchNotFound(opt); } } // utils } // isa #endif // ARGUMENT_LIST_HPP <commit_msg>Fixing a few typos.<commit_after>// Copyright 2010 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 <string> #include <sstream> #include <list> #include <typeinfo> #include <utils.hpp> #ifndef ARGUMENT_LIST_HPP #define ARGUMENT_LIST_HPP namespace isa { namespace utils { // Exception: no items in the command line class EmptyCommandLine : public std::exception {}; // Exception: requested switch not present class SwitchNotFound : public std::exception { public: SwitchNotFound(std::string option); ~SwitchNotFound() throw (); const char *what() const throw (); private: std::string option; }; // ArgumentList class class ArgumentList { public: ArgumentList(int argc, char * argv[]); ~ArgumentList(); std::string getName(); template< typename T > T getFirst() throw(EmptyCommandLine); bool getSwitch(const std::string opt) throw(EmptyCommandLine); template< typename T > T getSwitchArgument(const std::string & option) throw(EmptyCommandLine, SwitchNotFound); private: std::list< std::string > args; std::string name; }; // Implementations SwitchNotFound::SwitchNotFound(std::string option) : option(option) {} const char * SwitchNotFound::what() throw() { return ("Switch \"" + option + "\" not found.").c_str(); } ArgumentList::ArgumentList(int argc, char * argv[]) { name = std::string(argv[0]); for ( unsigned int i = 1; i < argc; i++ ) { args.push_back(std::string(argv[1])); } } std::string ArgumentList::getName() { return name; } template< typename T > T ArgumentList::getFirst() throw(EmptyCommandLine) { if ( args.empty() ) { throw EmptyCommandLine(); } std::string temp = args.front(); args.pop_front(); return castToType< std::string, T >(temp); } bool ArgumentList::getSwitch(const std::string opt) throw(EmptyCommandLine) { if ( args.empty() ) { return false; } for ( std::list< std::string >::iterator s = args.begin(); s != args.end(); ++s ) { if ( opt.compare(*s) == 0 ) { args.erase(s); return true; } } return false; } template< class T > T ArgumentList::getSwitchArgument(const std::string opt) throw(EmptyCommandLine, SwitchNotFound) { if ( args.empty() ) { throw EmptyCommandLine(); } for ( std::list< std::string >::iterator s = args.begin(); s != args.end(); ++s ) { if ( opt.compare(*s) == 0 ) { std::string temp = *(++s); T retVal = castToType< std::string, T >(temp); args.erase(s); args.erase(--s); return retVal; } } throw SwitchNotFound(opt); } } // utils } // isa #endif // ARGUMENT_LIST_HPP <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef VISITOR_UTILS_H #define VISITOR_UTILS_H #include <boost/variant/apply_visitor.hpp> #include <boost/variant/variant.hpp> #include <boost/optional/optional.hpp> #include <boost/utility/enable_if.hpp> #define ASSIGN(Type, Value)\ result_type operator()(Type & ){\ return Value;\ } #define ASSIGN_INSIDE(Visitor, Type, Value)\ result_type Visitor::operator()(Type & ){\ return Value;\ } namespace eddic { /* non-const-non-const version */ template<typename Visitor, typename Visitable> inline typename boost::disable_if<boost::is_void<typename Visitor::result_type>, typename Visitor::result_type>::type visit(Visitor& visitor, Visitable& visitable){ return boost::apply_visitor(visitor, visitable); } template<typename Visitor, typename Visitable> inline void visit(Visitor& visitor, Visitable& visitable){ boost::apply_visitor(visitor, visitable); } /* const-const version */ template<typename Visitor, typename Visitable> inline typename boost::disable_if<boost::is_void<typename Visitor::result_type>, typename Visitor::result_type>::type visit(const Visitor& visitor, const Visitable& visitable){ return boost::apply_visitor(visitor, visitable); } template<typename Visitor, typename Visitable> inline void visit(const Visitor& visitor, const Visitable& visitable){ boost::apply_visitor(visitor, visitable); } /* non const non variant version */ template<typename Visitor, typename Visitable> inline typename boost::disable_if<boost::is_void<typename Visitor::result_type>, typename Visitor::result_type>::type visit_non_variant(Visitor& visitor, Visitable& visitable){ return visitor(visitable); } template<typename Visitor, typename Visitable> inline void visit_non_variant(Visitor& visitor, Visitable& visitable){ visitor(visitable); } /* const non variant version */ template<typename Visitor, typename Visitable> inline typename boost::disable_if<boost::is_void<typename Visitor::result_type>, typename Visitor::result_type>::type visit_non_variant(const Visitor& visitor, const Visitable& visitable){ return visitor(visitable); } template<typename Visitor, typename Visitable> inline void visit_non_variant(const Visitor& visitor, const Visitable& visitable){ visitor(visitable); } /* optional versions : no return */ template<typename Visitor, typename Visitable> inline void visit_optional(Visitor& visitor, boost::optional<Visitable>& optional){ if(optional){ boost::apply_visitor(visitor, *optional); } } template<typename Visitor, typename Visitable> inline void visit_optional_non_variant(Visitor& visitor, boost::optional<Visitable>& optional){ if(optional){ visit_non_variant(visitor, *optional); } } /* Visit a set : only void version */ template<typename Visitor, typename Visitable> inline void visit_each(Visitor& visitor, std::vector<Visitable>& elements){ for_each(elements.begin(), elements.end(), [&](Visitable& visitable){ visit(visitor, visitable); }); } template<typename Visitor, typename Visitable> inline void visit_each_non_variant(Visitor& visitor, std::vector<Visitable>& elements){ for_each(elements.begin(), elements.end(), [&](Visitable& visitable){ visit_non_variant(visitor, visitable); }); } } //end of eddic #endif <commit_msg>Improve VisitorUtils to handle pass-by-value visitors<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef VISITOR_UTILS_H #define VISITOR_UTILS_H #include <boost/variant/apply_visitor.hpp> #include <boost/variant/variant.hpp> #include <boost/optional/optional.hpp> #include <boost/utility/enable_if.hpp> #define ASSIGN(Type, Value)\ result_type operator()(Type & ){\ return Value;\ } #define ASSIGN_INSIDE(Visitor, Type, Value)\ result_type Visitor::operator()(Type & ){\ return Value;\ } namespace eddic { /* Use with a variant */ template<typename Visitor, typename Visitable> inline typename boost::disable_if<boost::is_void<typename Visitor::result_type>, typename Visitor::result_type>::type visit(Visitor&& visitor, Visitable& visitable){ return boost::apply_visitor(visitor, visitable); } template<typename Visitor, typename Visitable> inline typename boost::enable_if<boost::is_void<typename Visitor::result_type>, typename Visitor::result_type>::type visit(Visitor&& visitor, Visitable& visitable){ boost::apply_visitor(visitor, visitable); } template<typename Visitor, typename Visitable> inline typename boost::disable_if<boost::is_void<typename Visitor::result_type>, typename Visitor::result_type>::type visit(Visitor& visitor, Visitable& visitable){ return boost::apply_visitor(visitor, visitable); } template<typename Visitor, typename Visitable> inline typename boost::enable_if<boost::is_void<typename Visitor::result_type>, typename Visitor::result_type>::type visit(Visitor& visitor, Visitable& visitable){ boost::apply_visitor(visitor, visitable); } /* Use with non-variant */ template<typename Visitor, typename Visitable> inline typename boost::disable_if<boost::is_void<typename Visitor::result_type>, typename Visitor::result_type>::type visit_non_variant(Visitor& visitor, Visitable& visitable){ return visitor(visitable); } template<typename Visitor, typename Visitable> inline void visit_non_variant(Visitor& visitor, Visitable& visitable){ visitor(visitable); } /* const non variant version */ template<typename Visitor, typename Visitable> inline typename boost::disable_if<boost::is_void<typename Visitor::result_type>, typename Visitor::result_type>::type visit_non_variant(const Visitor& visitor, const Visitable& visitable){ return visitor(visitable); } template<typename Visitor, typename Visitable> inline void visit_non_variant(const Visitor& visitor, const Visitable& visitable){ visitor(visitable); } /* optional versions : no return */ template<typename Visitor, typename Visitable> inline void visit_optional(Visitor& visitor, boost::optional<Visitable>& optional){ if(optional){ boost::apply_visitor(visitor, *optional); } } template<typename Visitor, typename Visitable> inline void visit_optional_non_variant(Visitor& visitor, boost::optional<Visitable>& optional){ if(optional){ visit_non_variant(visitor, *optional); } } /* Visit a set : only void version */ template<typename Visitor, typename Visitable> inline void visit_each(Visitor& visitor, std::vector<Visitable>& elements){ for_each(elements.begin(), elements.end(), [&](Visitable& visitable){ visit(visitor, visitable); }); } template<typename Visitor, typename Visitable> inline void visit_each_non_variant(Visitor& visitor, std::vector<Visitable>& elements){ for_each(elements.begin(), elements.end(), [&](Visitable& visitable){ visit_non_variant(visitor, visitable); }); } } //end of eddic #endif <|endoftext|>
<commit_before>//======================================================================= // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef WORD_SPOTTER_CONFIG_THIRD_HPP #define WORD_SPOTTER_CONFIG_THIRD_HPP namespace third { //#define THIRD_RBM_1 //One layer of RBM //#define THIRD_RBM_2 //Two layers of RBM //#define THIRD_RBM_3 //Three layers of RBM //#define THIRD_CRBM_PMP_1 //One layer of CRBM with Probabilistic Max Pooling (C1) //#define THIRD_CRBM_PMP_2 //Two layers of CRBM with Probabilistic Max Pooling (C1/C2) //#define THIRD_CRBM_PMP_3 //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3) //#define THIRD_CRBM_MP_1 //One layers of CRBM with Max Pooling after each layer (C1) #define THIRD_CRBM_MP_2 //Two layers of CRBM with Max Pooling after each layer (C1/C2) //#define THIRD_CRBM_MP_3 //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3) //#define THIRD_PATCH_CRBM_MP_2 //Patches -> Two layers of CRBM with Max Pooling after each layer (C1/C2) //#define THIRD_COMPLEX_2 //Architecture to play around LCN //#define THIRD_MODERN //Architecture to play around constexpr const std::size_t patch_height = 40; //Should not be changed constexpr const std::size_t patch_width = 20; // Data augmentation constexpr const std::size_t elastic_augment = 1; //not ready constexpr const std::size_t epochs = 10; constexpr const std::size_t train_stride = 1; constexpr const std::size_t test_stride = 1; constexpr const std::size_t NF1 = 9; // 9 for GW constexpr const std::size_t K1 = 12; // 8 for GW constexpr const std::size_t C1 = 2; // 2 for GW constexpr const std::size_t B1 = 256; // 128 for GW constexpr const dll::unit_type HT1 = dll::unit_type::RELU1; // BINARY for GW constexpr const dll::decay_type DT1 = dll::decay_type::L2; // L2 for GW constexpr const dll::sparsity_method SM1 = dll::sparsity_method::NONE; // LEE for GW constexpr const bool shuffle_1 = false; // false for GW constexpr const bool clipping_1 = true; // false for GW constexpr const std::size_t NF2 = 3; // 3 for GW constexpr const std::size_t K2 = 12; // 8 for GW constexpr const std::size_t C2 = 2; // 2 for GW constexpr const std::size_t B2 = 256; // 128 for GW constexpr const dll::unit_type HT2 = dll::unit_type::RELU6; // BINARY for GW constexpr const dll::decay_type DT2 = dll::decay_type::L2; // L2 for GW constexpr const dll::sparsity_method SM2 = dll::sparsity_method::NONE; // LEE for GW constexpr const bool shuffle_2 = false; // false for GW constexpr const bool clipping_2 = true; // false for GW constexpr const std::size_t NF3 = 3; constexpr const std::size_t K3 = 48; constexpr const std::size_t C3 = 2; constexpr const std::size_t B3 = 64; constexpr const dll::unit_type HT3 = dll::unit_type::BINARY; constexpr const dll::decay_type DT3 = dll::decay_type::L2; constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE; constexpr const bool shuffle_3 = true; constexpr const bool clipping_3 = false; const auto rate_0 = [](weight& value) { value = 1e-4; }; //0.1 * value for GW const auto rate_1 = [](weight& value) { value = 1e-6; }; //0.1 * value for GW const auto rate_2 = [](weight& value) { value = 1.0 * value; }; const auto momentum_0 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; }; const auto momentum_1 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; }; const auto momentum_2 = [](weight& ini, weight& fin) { ini = 1.0 * ini; fin = 1.0 * fin; }; const auto wd_l1_0 = [](weight& value) { value = 1.0 * value; }; const auto wd_l1_1 = [](weight& value) { value = 1.0 * value; }; const auto wd_l1_2 = [](weight& value) { value = 1.0 * value; }; const auto wd_l2_0 = [](weight& value) { value = 1.0 * value; }; const auto wd_l2_1 = [](weight& value) { value = 1.0 * value; }; const auto wd_l2_2 = [](weight& value) { value = 1.0 * value; }; const auto pbias_0 = [](weight& value) { value = 1.0 * value; }; const auto pbias_1 = [](weight& value) { value = 1.0 * value; }; const auto pbias_2 = [](weight& value) { value = 1.0 * value; }; #if defined(THIRD_CRBM_MP_2) || defined(THIRD_PATCH_CRBM_MP_2) const auto pbias_lambda_0 = [](weight& value) { value = 10.0 * value; }; const auto pbias_lambda_1 = [](weight& value) { value = 10.0 * value; }; const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; }; #else const auto pbias_lambda_0 = [](weight& value) { value = 1.0 * value; }; const auto pbias_lambda_1 = [](weight& value) { value = 1.0 * value; }; const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; }; #endif const auto sparsity_target_0 = [](weight& value) { value = 10.0 * value; }; const auto sparsity_target_1 = [](weight& value) { value = 10.0 * value; }; const auto sparsity_target_2 = [](weight& value) { value = 1.0 * value; }; const auto clip_norm_1 = [](weight& t) { t = 5.0; }; const auto clip_norm_2 = [](weight& t) { t = 5.0; }; const auto clip_norm_3 = [](weight& t) { t = 5.0; }; } // end of namespace third #endif <commit_msg>Updates<commit_after>//======================================================================= // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef WORD_SPOTTER_CONFIG_THIRD_HPP #define WORD_SPOTTER_CONFIG_THIRD_HPP namespace third { //#define THIRD_RBM_1 //One layer of RBM //#define THIRD_RBM_2 //Two layers of RBM //#define THIRD_RBM_3 //Three layers of RBM //#define THIRD_CRBM_PMP_1 //One layer of CRBM with Probabilistic Max Pooling (C1) //#define THIRD_CRBM_PMP_2 //Two layers of CRBM with Probabilistic Max Pooling (C1/C2) //#define THIRD_CRBM_PMP_3 //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3) //#define THIRD_CRBM_MP_1 //One layers of CRBM with Max Pooling after each layer (C1) #define THIRD_CRBM_MP_2 //Two layers of CRBM with Max Pooling after each layer (C1/C2) //#define THIRD_CRBM_MP_3 //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3) //#define THIRD_PATCH_CRBM_MP_2 //Patches -> Two layers of CRBM with Max Pooling after each layer (C1/C2) //#define THIRD_COMPLEX_2 //Architecture to play around LCN //#define THIRD_MODERN //Architecture to play around constexpr const std::size_t patch_height = 40; //Should not be changed constexpr const std::size_t patch_width = 20; // Data augmentation constexpr const std::size_t elastic_augment = 1; //not ready constexpr const std::size_t epochs = 10; constexpr const std::size_t train_stride = 1; constexpr const std::size_t test_stride = 1; constexpr const std::size_t NF1 = 9; // 9 for ALL constexpr const std::size_t K1 = 7; // 7 for GW, 12 for PAR/IAM constexpr const std::size_t C1 = 2; // 2 for ALL constexpr const std::size_t B1 = 128; // 128 for GW, 256 for PAR/IAM constexpr const dll::unit_type HT1 = dll::unit_type::RELU1; // RELU1 for ALL constexpr const dll::decay_type DT1 = dll::decay_type::L2; // L2 for ALL constexpr const dll::sparsity_method SM1 = dll::sparsity_method::NONE; // NONE for ALL constexpr const bool shuffle_1 = false; // false for ALL constexpr const bool clipping_1 = true; // true for ALL constexpr const std::size_t NF2 = 3; // 3 for ALL constexpr const std::size_t K2 = 7; // 7 for GW, 12 for PAR/IAM constexpr const std::size_t C2 = 2; // 2 for ALL constexpr const std::size_t B2 = 128; // 128 for GW, 256 for PAR/IAM constexpr const dll::unit_type HT2 = dll::unit_type::RELU6; // RELU6 for ALL constexpr const dll::decay_type DT2 = dll::decay_type::L2; // L2 for ALL constexpr const dll::sparsity_method SM2 = dll::sparsity_method::NONE; // NONE for ALL constexpr const bool shuffle_2 = false; // false for ALL constexpr const bool clipping_2 = true; // true for ALL constexpr const std::size_t NF3 = 3; constexpr const std::size_t K3 = 48; constexpr const std::size_t C3 = 2; constexpr const std::size_t B3 = 64; constexpr const dll::unit_type HT3 = dll::unit_type::BINARY; constexpr const dll::decay_type DT3 = dll::decay_type::L2; constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE; constexpr const bool shuffle_3 = true; constexpr const bool clipping_3 = false; const auto rate_0 = [](weight& value) { value = 1e-4; }; //0.1 * value for GW const auto rate_1 = [](weight& value) { value = 1e-6; }; //0.1 * value for GW const auto rate_2 = [](weight& value) { value = 1.0 * value; }; const auto momentum_0 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; }; const auto momentum_1 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; }; const auto momentum_2 = [](weight& ini, weight& fin) { ini = 1.0 * ini; fin = 1.0 * fin; }; const auto wd_l1_0 = [](weight& value) { value = 1.0 * value; }; const auto wd_l1_1 = [](weight& value) { value = 1.0 * value; }; const auto wd_l1_2 = [](weight& value) { value = 1.0 * value; }; const auto wd_l2_0 = [](weight& value) { value = 1.0 * value; }; const auto wd_l2_1 = [](weight& value) { value = 1.0 * value; }; const auto wd_l2_2 = [](weight& value) { value = 1.0 * value; }; const auto pbias_0 = [](weight& value) { value = 1.0 * value; }; const auto pbias_1 = [](weight& value) { value = 1.0 * value; }; const auto pbias_2 = [](weight& value) { value = 1.0 * value; }; #if defined(THIRD_CRBM_MP_2) || defined(THIRD_PATCH_CRBM_MP_2) const auto pbias_lambda_0 = [](weight& value) { value = 10.0 * value; }; const auto pbias_lambda_1 = [](weight& value) { value = 10.0 * value; }; const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; }; #else const auto pbias_lambda_0 = [](weight& value) { value = 1.0 * value; }; const auto pbias_lambda_1 = [](weight& value) { value = 1.0 * value; }; const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; }; #endif const auto sparsity_target_0 = [](weight& value) { value = 10.0 * value; }; const auto sparsity_target_1 = [](weight& value) { value = 10.0 * value; }; const auto sparsity_target_2 = [](weight& value) { value = 1.0 * value; }; const auto clip_norm_1 = [](weight& t) { t = 5.0; }; const auto clip_norm_2 = [](weight& t) { t = 5.0; }; const auto clip_norm_3 = [](weight& t) { t = 5.0; }; } // end of namespace third #endif <|endoftext|>
<commit_before>/** * @file meta.hpp * * Meta-programming facilities. */ #ifndef CPPSTDX_META__ #define CPPSTDX_META__ #include <cppstdx/config.hpp> #include <type_traits> namespace cppstdx { namespace meta { using ::std::size_t; using ::std::integral_constant; //=============================================== // // types // //=============================================== template<typename T> struct type_ { using type = T; }; template<typename A> using get_type = typename A::type; struct nil_{}; template<bool V> using bool_ = integral_constant<bool, V>; using true_ = bool_<true>; using false_ = bool_<false>; template<char V> using char_ = integral_constant<char, V>; template<int V> using int_ = integral_constant<int, V>; template<long V> using long_ = integral_constant<long, V>; template<short V> using short_ = integral_constant<short, V>; template<unsigned char V> using uchar_ = integral_constant<unsigned char, V>; template<unsigned int V> using uint_ = integral_constant<unsigned int, V>; template<unsigned long V> using ulong_ = integral_constant<unsigned long, V>; template<unsigned short V> using ushort_ = integral_constant<unsigned short, V>; template<size_t V> using size_ = integral_constant<size_t, V>; template<class A> using value_type_of = typename A::value_type; // pair template<typename T1, typename T2> struct pair_ { using first_type = T1; using second_type = T2; }; template<class A> struct first; template<class A> struct second; template<class A> using first_t = typename first<A>::type; template<class A> using second_t = typename second<A>::type; template<typename T1, typename T2> struct first<pair_<T1, T2>> { using type = T1; }; template<typename T1, typename T2> struct second<pair_<T1, T2>> { using type = T2; }; //=============================================== // // basic functions // //=============================================== template<typename A> using id = A; template<typename A> using identity = A; // arithmetic functions template<typename A> using negate = integral_constant<value_type_of<A>, -A::value>; template<typename A> using complement = integral_constant<value_type_of<A>, ~A::value>; template<typename A> using next = integral_constant<value_type_of<A>, A::value+1>; template<typename A> using prev = integral_constant<value_type_of<A>, A::value-1>; template<typename A, typename B> using plus = integral_constant<value_type_of<A>, A::value + B::value>; template<typename A, typename B> using minus = integral_constant<value_type_of<A>, A::value - B::value>; template<typename A, typename B> using mul = integral_constant<value_type_of<A>, A::value * B::value>; template<typename A, typename B> using div = integral_constant<value_type_of<A>, A::value / B::value>; template<typename A, typename B> using mod = integral_constant<value_type_of<A>, A::value % B::value>; template<typename A, typename B> using multiplies = mul<A, B>; template<typename A, typename B> using divides = div<A, B>; template<typename A, typename B> using modulo = mod<A, B>; // comparison functions template<typename A, typename B> using eq = bool_<(A::value == B::value)>; template<typename A, typename B> using ne = bool_<(A::value != B::value)>; template<typename A, typename B> using gt = bool_<(A::value > B::value)>; template<typename A, typename B> using ge = bool_<(A::value >= B::value)>; template<typename A, typename B> using lt = bool_<(A::value < B::value)>; template<typename A, typename B> using le = bool_<(A::value <= B::value)>; template<typename A, typename B> using equal_to = eq<A, B>; template<typename A, typename B> using not_equal_to = ne<A, B>; template<typename A, typename B> using greater = gt<A, B>; template<typename A, typename B> using greater_equal = ge<A, B>; template<typename A, typename B> using less = lt<A, B>; template<typename A, typename B> using less_equal = le<A, B>; // logical functions template<typename A> using not_ = bool_<!A::value>; template<typename A, typename B> using xor_ = bool_<A::value != B::value>; namespace details { template<typename B, bool Av> struct and_helper : public bool_<B::value> {}; template<typename B> struct and_helper<B, false> : public bool_<false> {}; template<typename B, bool Av> struct or_helper : public bool_<true> {}; template<typename B> struct or_helper<B, false> : public bool_<B::value> {}; } template<typename A, typename B> using and_ = details::and_helper<B, A::value>; template<typename A, typename B> using or_ = details::or_helper<B, A::value>; //=============================================== // // variadic reduction // //=============================================== namespace details { // sum template<typename A, typename... Rest> struct sum_impl : public plus<A, sum_impl<Rest...>> {}; template<typename A> struct sum_impl<A> : public id<A> {}; // prod template<typename A, typename... Rest> struct prod_impl : public mul<A, prod_impl<Rest...>> {}; template<typename A> struct prod_impl<A> : public id<A> {}; // max template<typename A, typename B> using _max = integral_constant< value_type_of<A>, (A::value > B::value ? A::value : B::value)>; template<typename A, typename... Rest> struct max_impl : public _max<A, max_impl<Rest...>> {}; template<typename A> struct max_impl<A> : public id<A> {}; // min template<typename A, typename B> using _min = integral_constant< value_type_of<A>, (A::value < B::value ? A::value : B::value)>; template<typename A, typename... Rest> struct min_impl : public _min<A, min_impl<Rest...>> {}; template<typename A> struct min_impl<A> : public id<A> {}; // all template<bool a, typename... Rest> struct all_helper; template<typename... Rest> struct all_helper<false, Rest...> : public bool_<false> {}; template<typename A, typename... Rest> struct all_helper<true, A, Rest...> : public all_helper<A::value, Rest...> {}; template<typename A> struct all_helper<true, A> : public bool_<A::value> {}; template<> struct all_helper<true> : public std::true_type {}; template<typename... Args> struct all_impl; template<typename A, typename... Rest> struct all_impl<A, Rest...> : public all_helper<A::value, Rest...> {}; template<> struct all_impl<> : public bool_<true> {}; // any template<bool a, typename... Rest> struct any_helper; template<typename... Rest> struct any_helper<true, Rest...> : public bool_<true> {}; template<typename A, typename... Rest> struct any_helper<false, A, Rest...> : public any_helper<A::value, Rest...> {}; template<typename A> struct any_helper<false, A> : public bool_<A::value> {}; template<> struct any_helper<false> : public bool_<false> {}; template<typename... Args> struct any_impl; template<typename A, typename... Rest> struct any_impl<A, Rest...> : public any_helper<A::value, Rest...> {}; template<> struct any_impl<> : public bool_<false> {}; // count_true template<typename... Args> struct count_true_impl; template<typename A, typename... Rest> struct count_true_impl<A, Rest...> : public plus< count_true_impl<A>, count_true_impl<Rest...>> {}; template<typename A> struct count_true_impl<A> : public size_<(A::value ? 1 : 0)> {}; template<> struct count_true_impl<> : public size_<0> {}; // count_false template<typename... Args> struct count_false_impl; template<typename A, typename... Rest> struct count_false_impl<A, Rest...> : public plus< count_false_impl<A>, count_false_impl<Rest...>> {}; template<typename A> struct count_false_impl<A> : public size_<(A::value ? 0 : 1)> {}; template<> struct count_false_impl<> : public size_<0> {}; } // end namespace details template<typename... Args> using sum = details::sum_impl<Args...>; template<typename... Args> using prod = details::prod_impl<Args...>; template<typename... Args> using max = details::max_impl<Args...>; template<typename... Args> using min = details::min_impl<Args...>; template<typename... Args> using count_true = details::count_true_impl<Args...>; template<typename... Args> using count_false = details::count_false_impl<Args...>; template<typename... Args> using all = details::all_impl<Args...>; template<typename... Args> using any = details::any_impl<Args...>; } // end namespace meta } // end namespace cppstdx #endif <commit_msg>refactor the implementation of or, and, and count<commit_after>/** * @file meta.hpp * * Meta-programming facilities. */ #ifndef CPPSTDX_META__ #define CPPSTDX_META__ #include <cppstdx/config.hpp> #include <type_traits> namespace cppstdx { namespace meta { using ::std::size_t; using ::std::integral_constant; //=============================================== // // types // //=============================================== template<typename T> struct type_ { using type = T; }; template<typename A> using get_type = typename A::type; struct nil_{}; template<bool V> using bool_ = integral_constant<bool, V>; using true_ = bool_<true>; using false_ = bool_<false>; template<char V> using char_ = integral_constant<char, V>; template<int V> using int_ = integral_constant<int, V>; template<long V> using long_ = integral_constant<long, V>; template<short V> using short_ = integral_constant<short, V>; template<unsigned char V> using uchar_ = integral_constant<unsigned char, V>; template<unsigned int V> using uint_ = integral_constant<unsigned int, V>; template<unsigned long V> using ulong_ = integral_constant<unsigned long, V>; template<unsigned short V> using ushort_ = integral_constant<unsigned short, V>; template<size_t V> using size_ = integral_constant<size_t, V>; template<class A> using value_type_of = typename A::value_type; // pair template<typename T1, typename T2> struct pair_ { using first_type = T1; using second_type = T2; }; template<class A> struct first; template<class A> struct second; template<class A> using first_t = typename first<A>::type; template<class A> using second_t = typename second<A>::type; template<typename T1, typename T2> struct first<pair_<T1, T2>> { using type = T1; }; template<typename T1, typename T2> struct second<pair_<T1, T2>> { using type = T2; }; //=============================================== // // basic functions // //=============================================== template<typename A> using id = A; template<typename A> using identity = A; // arithmetic functions template<typename A> using negate = integral_constant<value_type_of<A>, -A::value>; template<typename A> using complement = integral_constant<value_type_of<A>, ~A::value>; template<typename A> using next = integral_constant<value_type_of<A>, A::value+1>; template<typename A> using prev = integral_constant<value_type_of<A>, A::value-1>; template<typename A, typename B> using plus = integral_constant<value_type_of<A>, A::value + B::value>; template<typename A, typename B> using minus = integral_constant<value_type_of<A>, A::value - B::value>; template<typename A, typename B> using mul = integral_constant<value_type_of<A>, A::value * B::value>; template<typename A, typename B> using div = integral_constant<value_type_of<A>, A::value / B::value>; template<typename A, typename B> using mod = integral_constant<value_type_of<A>, A::value % B::value>; template<typename A, typename B> using multiplies = mul<A, B>; template<typename A, typename B> using divides = div<A, B>; template<typename A, typename B> using modulo = mod<A, B>; // comparison functions template<typename A, typename B> using eq = bool_<(A::value == B::value)>; template<typename A, typename B> using ne = bool_<(A::value != B::value)>; template<typename A, typename B> using gt = bool_<(A::value > B::value)>; template<typename A, typename B> using ge = bool_<(A::value >= B::value)>; template<typename A, typename B> using lt = bool_<(A::value < B::value)>; template<typename A, typename B> using le = bool_<(A::value <= B::value)>; template<typename A, typename B> using equal_to = eq<A, B>; template<typename A, typename B> using not_equal_to = ne<A, B>; template<typename A, typename B> using greater = gt<A, B>; template<typename A, typename B> using greater_equal = ge<A, B>; template<typename A, typename B> using less = lt<A, B>; template<typename A, typename B> using less_equal = le<A, B>; // logical functions template<typename A> using not_ = bool_<!A::value>; template<typename A, typename B> using xor_ = bool_<A::value != B::value>; namespace details { template<bool Av, typename B> struct and_helper : public bool_<B::value> {}; template<typename B> struct and_helper<false, B> : public bool_<false> {}; template<bool Av, typename B> struct or_helper : public bool_<true> {}; template<typename B> struct or_helper<false, B> : public bool_<B::value> {}; } template<typename A, typename B> using and_ = details::and_helper<A::value, B>; template<typename A, typename B> using or_ = details::or_helper<A::value, B>; //=============================================== // // variadic reduction // //=============================================== namespace details { // sum template<typename A, typename... Rest> struct sum_impl : public plus<A, sum_impl<Rest...>> {}; template<typename A> struct sum_impl<A> : public id<A> {}; // prod template<typename A, typename... Rest> struct prod_impl : public mul<A, prod_impl<Rest...>> {}; template<typename A> struct prod_impl<A> : public id<A> {}; // max template<typename A, typename B> using _max = integral_constant< value_type_of<A>, (A::value > B::value ? A::value : B::value)>; template<typename A, typename... Rest> struct max_impl : public _max<A, max_impl<Rest...>> {}; template<typename A> struct max_impl<A> : public id<A> {}; // min template<typename A, typename B> using _min = integral_constant< value_type_of<A>, (A::value < B::value ? A::value : B::value)>; template<typename A, typename... Rest> struct min_impl : public _min<A, min_impl<Rest...>> {}; template<typename A> struct min_impl<A> : public id<A> {}; // all template<bool a, typename... Rest> struct all_helper; template<typename... Rest> struct all_helper<false, Rest...> : public bool_<false> {}; template<typename A, typename... Rest> struct all_helper<true, A, Rest...> : public all_helper<A::value, Rest...> {}; template<typename A> struct all_helper<true, A> : public bool_<A::value> {}; template<> struct all_helper<true> : public std::true_type {}; template<typename... Args> struct all_impl; template<typename A, typename... Rest> struct all_impl<A, Rest...> : public all_helper<A::value, Rest...> {}; template<> struct all_impl<> : public bool_<true> {}; // any template<bool a, typename... Rest> struct any_helper; template<typename... Rest> struct any_helper<true, Rest...> : public bool_<true> {}; template<typename A, typename... Rest> struct any_helper<false, A, Rest...> : public any_helper<A::value, Rest...> {}; template<typename A> struct any_helper<false, A> : public bool_<A::value> {}; template<> struct any_helper<false> : public bool_<false> {}; template<typename... Args> struct any_impl; template<typename A, typename... Rest> struct any_impl<A, Rest...> : public any_helper<A::value, Rest...> {}; template<> struct any_impl<> : public bool_<false> {}; // generic count_if template<template<typename> class Pred, typename... Args> struct count_if_impl; template<template<typename> class Pred, typename X, typename... Rest> struct count_if_impl<Pred, X, Rest...> : public size_< (Pred<X>::value ? 1 : 0) + count_if_impl<Pred, Rest...>::value> {}; template<template<typename> class Pred, typename X> struct count_if_impl<Pred, X> : public size_<Pred<X>::value ? 1 : 0> {}; template<template<typename> class Pred> struct count_if_impl<Pred> : public size_<0> {}; } // end namespace details template<typename... Args> using sum = details::sum_impl<Args...>; template<typename... Args> using prod = details::prod_impl<Args...>; template<typename... Args> using max = details::max_impl<Args...>; template<typename... Args> using min = details::min_impl<Args...>; template<typename... Args> using count_true = details::count_if_impl<id, Args...>; template<typename... Args> using count_false = details::count_if_impl<not_, Args...>; template<typename... Args> using all = details::all_impl<Args...>; template<typename... Args> using any = details::any_impl<Args...>; } // end namespace meta } // end namespace cppstdx #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ namespace libport { namespace netdetail { #if defined LIBPORT_ENABLE_SSL struct LIBPORT_API SSLSettings { boost::asio::ssl::context_base::method context; boost::asio::ssl::context::options options; std::string privateKeyFile; std::string certChainFile; std::string tmpDHFile; std::string cipherList; }; LIBPORT_API BaseSocket* makeSSLLayer(SSLSettings settings, boost::asio::ip::tcp::socket* s); #endif template<class Stream> class SocketImpl; class LIBPORT_API SocketImplBase : public BaseSocket , protected libport::Lockable { public: SocketImplBase() : current_(-1) , pending_(false) {} /// Return ammount of data in write buffer size_t getWriteBufferContentSize(); protected: /// Write double-buffer. boost::asio::streambuf buffers_[2]; /// Read buffer. boost::asio::streambuf readBuffer_; /// Buffer id currently engaged in an async write, -1 for none int current_; /// Second buffer has data to write. bool pending_; friend class libport::Socket; template<class Stream> friend class SocketImpl; }; template<typename T> SocketImplBase* create(T* s) { return SocketImpl<T>::create(s); } inline size_t SocketImplBase::getWriteBufferContentSize() { if (!pending_) return 0; else return buffers_[1-current_].size(); } } template<class Sock> inline void Socket::setFD(native_handle_type fd, typename Sock::protocol_type proto) { if (base_ && base_->isConnected()) { base_->close(); base_->destroy(); base_ = 0; } Sock* s = new Sock(get_io_service()); s->assign(proto, fd); netdetail::SocketImplBase* b = (netdetail::SocketImplBase*)netdetail::create(s); // (netdetail::SocketImplBase*)netdetail::SocketImpl<Sock>::create(s); setBase(b); b->startReader(); } inline void Socket::syncWrite(const std::string& s) { syncWrite(s.c_str(), s.length()); } inline void Socket::syncWrite(const void* data, size_t length) { const char* cdata = static_cast<const char*>(data); size_t pos = 0; #ifdef WIN32 BOOL ok; DWORD written; while (length-pos && (ok=WriteFile((HANDLE)getFD(), cdata+pos, length-pos, &written, NULL))) pos += written; if (!ok) throw std::runtime_error(std::string("WriteFile: ") + libport::strerror(0)); #else ssize_t written; while (length-pos && (written = ::write(getFD(), cdata+pos, length-pos))) { if (written == -1) throw std::runtime_error(std::string("write: ") + libport::strerror(errno)); pos += written; } #endif } } <commit_msg>asio: add missing const.<commit_after>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ namespace libport { namespace netdetail { #if defined LIBPORT_ENABLE_SSL struct LIBPORT_API SSLSettings { boost::asio::ssl::context_base::method context; boost::asio::ssl::context::options options; std::string privateKeyFile; std::string certChainFile; std::string tmpDHFile; std::string cipherList; }; LIBPORT_API BaseSocket* makeSSLLayer(SSLSettings settings, boost::asio::ip::tcp::socket* s); #endif template<class Stream> class SocketImpl; class LIBPORT_API SocketImplBase : public BaseSocket , protected libport::Lockable { public: SocketImplBase() : current_(-1) , pending_(false) {} /// Return ammount of data in write buffer size_t getWriteBufferContentSize() const; protected: /// Write double-buffer. boost::asio::streambuf buffers_[2]; /// Read buffer. boost::asio::streambuf readBuffer_; /// Buffer id currently engaged in an async write, -1 for none int current_; /// Second buffer has data to write. bool pending_; friend class libport::Socket; template<class Stream> friend class SocketImpl; }; template<typename T> SocketImplBase* create(T* s) { return SocketImpl<T>::create(s); } inline size_t SocketImplBase::getWriteBufferContentSize() const { return pending_ ? buffers_[1-current_].size() : 0; } } template<class Sock> inline void Socket::setFD(native_handle_type fd, typename Sock::protocol_type proto) { if (base_ && base_->isConnected()) { base_->close(); base_->destroy(); base_ = 0; } Sock* s = new Sock(get_io_service()); s->assign(proto, fd); netdetail::SocketImplBase* b = (netdetail::SocketImplBase*)netdetail::create(s); // (netdetail::SocketImplBase*)netdetail::SocketImpl<Sock>::create(s); setBase(b); b->startReader(); } inline void Socket::syncWrite(const std::string& s) { syncWrite(s.c_str(), s.length()); } inline void Socket::syncWrite(const void* data, size_t length) { const char* cdata = static_cast<const char*>(data); size_t pos = 0; #ifdef WIN32 BOOL ok; DWORD written; while (length-pos && (ok=WriteFile((HANDLE)getFD(), cdata+pos, length-pos, &written, NULL))) pos += written; if (!ok) throw std::runtime_error(std::string("WriteFile: ") + libport::strerror(0)); #else ssize_t written; while (length-pos && (written = ::write(getFD(), cdata+pos, length-pos))) { if (written == -1) throw std::runtime_error(std::string("write: ") + libport::strerror(errno)); pos += written; } #endif } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: style.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef STYLE_HPP #define STYLE_HPP // mapnik #include <mapnik/color.hpp> #include <mapnik/symbolizer.hpp> // boost #include <boost/shared_ptr.hpp> // stl #include <vector> #include <algorithm> #include <functional> namespace mapnik { } #endif //STYLE_HPP <commit_msg>remove unused header<commit_after><|endoftext|>
<commit_before>#pragma once #include <vector> #include <initializer_list> #include <string> #include <atomic> #include <memory> #include <chrono> #include <mos/gfx/vertex.hpp> namespace mos { namespace gfx { class Mesh; using SharedMesh = std::shared_ptr<Mesh>; /** * Describes the geometric data to be rendered. Contains vertices * and indices, for vertex order. */ class Mesh { public: using Positions = std::vector<glm::vec3>; using TimePoint = std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>; /** * @brief Vertices container. */ using Vertices = std::vector<Vertex>; /** * @brief Elements/indices container. */ using Indices = std::vector<int>; template<class Tv, class Te> /** * @brief Mesh constructor. * @param vertices_begin Iterator to first vertex. * @param vertices_end Iterator to last vertex. * @param elements_begin Iterator to first element. * @param elements_end Iterator to last element. * * Mesh constructor that takes Vertices and elements (vertex order for *rendering). */ Mesh(const Tv vertices_begin, const Tv vertices_end, Te elements_begin, Te elements_end) : vertices(vertices_begin, vertices_end), indices(elements_begin, elements_end), id_(current_id_++) { invalidate(); } /** * @brief Mesh constructor * @param vertices * @param elements */ Mesh(const std::initializer_list<Vertex> &vertices, const std::initializer_list<int> &elements); /** * @brief Mesh constructor from file. * @param path */ Mesh(const std::string &path); /** * @brief Mesh */ Mesh(); /** * @brief Mesh copy constructor. * @param mesh */ Mesh(const Mesh &mesh); /** * @brief ~Mesh destructor. */ ~Mesh(); static SharedMesh load(const std::string &path); /** * @return A unique identifier. */ unsigned int id() const; /** * @return Time when modified. */ TimePoint modified() const; /** * @brief invalidates the mesh, hence the data is updated. * */ //TODO: Automatic when moodified void invalidate(); /** * @brief Clear the whole mesh. */ void clear(); /** * @brief Get a copy of positions. * @return */ Positions positions() const; /** * @brief mix * @param mesh1 * @param mesh2 * @param amount */ void mix(const Mesh &mesh1, const Mesh &mesh2, const float amount); void apply_transform(const glm::mat4 &transform); void calculate_normals(); void calculate_flat_normals(); void calculate_tangents(); Vertices vertices; Indices indices; private: TimePoint modified_; void calculate_tangents(Vertex &v0, Vertex &v1, Vertex &v2); static std::atomic_uint current_id_; unsigned int id_; }; } } <commit_msg>Document mesh<commit_after>#pragma once #include <vector> #include <initializer_list> #include <string> #include <atomic> #include <memory> #include <chrono> #include <mos/gfx/vertex.hpp> namespace mos { namespace gfx { class Mesh; using SharedMesh = std::shared_ptr<Mesh>; /** Geometric data description. Vertices and optional indices for rendering. */ class Mesh { public: using Vertices = std::vector<Vertex>; using Positions = std::vector<glm::vec3>; using TimePoint = std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>; using Indices = std::vector<int>; template<class Tv, class Te> Mesh(const Tv vertices_begin, const Tv vertices_end, Te elements_begin, Te elements_end) : vertices(vertices_begin, vertices_end), indices(elements_begin, elements_end), id_(current_id_++) { invalidate(); } Mesh(const std::initializer_list<Vertex> &vertices, const std::initializer_list<int> &elements); /** Load from *.mesh file. @param path Full path*/ Mesh(const std::string &path); Mesh(); Mesh(const Mesh &mesh); ~Mesh(); static SharedMesh load(const std::string &path); /** @return Unique identifier. */ unsigned int id() const; /** @return Time point when modified. */ TimePoint modified() const; /** Invalidates the mesh, hence the data is updated. */ //TODO: Automatic when modified void invalidate(); /** Erease all vertices and indices. */ void clear(); /** Get only positions from vertices */ Positions positions() const; void mix(const Mesh &mesh1, const Mesh &mesh2, const float amount); void apply_transform(const glm::mat4 &transform); void calculate_normals(); void calculate_flat_normals(); void calculate_tangents(); Vertices vertices; Indices indices; private: TimePoint modified_; void calculate_tangents(Vertex &v0, Vertex &v1, Vertex &v2); static std::atomic_uint current_id_; unsigned int id_; }; } } <|endoftext|>
<commit_before>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #ifndef NOMLIB_STDINT_TYPES_HPP #define NOMLIB_STDINT_TYPES_HPP #include "platforms.hpp" /* TODO: This should be replaced by an actual CMake script -- think: compile-time check for the necessary feature support for C++11 style headers support. Look into why GCC doesn't like the inclusion of <cstdint> -- otherwise known as stdint.h. MSVCPP2013 & llvm-clang are fine with it). */ #ifndef NOM_PLATFORM_LINUX // To be replace with NOM_COMPILER_FEATURE_NULLPTR // (see above TODO note). #include <cstdint> #else #include <sys/types.h> #endif // Borrowed from /usr/include/MacTypes.h && /usr/include/objc/objc.h: #ifndef NULL #if defined( NOM_COMPILER_FEATURE_NULLPTR ) #define NULL nullptr #else #define NULL __DARWIN_NULL #endif #endif // ! NULL #ifndef nil #if defined( NOM_COMPILER_FEATURE_NULLPTR ) #define nil nullptr #else #define nil __DARWIN_NULL #endif #endif // ! nil // Portable fixed-size data types derive from stdint.h namespace nom { // 8-bit integer types typedef int8_t int8; typedef uint8_t uint8; // 16-bit integer types typedef int16_t int16; typedef uint16_t uint16; // 32-bit integer types typedef int32_t int32; typedef uint32_t uint32; /// \brief 64-bit integer types /// \note As per **/usr/include/MacTypes.h**: /// /// "The MS Visual C/C++ compiler uses __int64 instead of long long". #if defined( NOM_COMPILER_MSVCPP ) && defined( NOM_PLATFORM_ARCH_X86 ) typedef signed __int64 int64; typedef unsigned __int64 uint64; #else // Blindly assume a 64-bit architecture typedef int64_t int64; //typedef signed long long int int64; typedef uint64_t uint64; //typedef unsigned long long int uint64; #endif // Additional integer type definitions #if defined (NOM_PLATFORM_ARCH_X86_64) typedef unsigned long ulong; #else // Blindly assume 32-bit arch typedef long long ulong; #endif typedef unsigned char uchar; typedef signed int sint; typedef unsigned int uint; typedef std::size_t size; typedef int boolean; typedef sint* sint_ptr; typedef uint* uint_ptr; typedef int32_t* int32_ptr; typedef uint32_t* uint32_ptr; typedef void* void_ptr; } // namespace nom /// Ensure our data types have the right sizes using C++11 compile-time asserts. static_assert ( sizeof ( nom::uint8 ) == 1, "nom::uint8" ); static_assert ( sizeof ( nom::int8 ) == 1, "nom::int8" ); static_assert ( sizeof ( nom::uint16 ) == 2, "nom::uint16" ); static_assert ( sizeof ( nom::int16 ) == 2, "nom::int16" ); static_assert ( sizeof ( nom::uint32 ) == 4, "nom::uint32" ); static_assert ( sizeof ( nom::int32 ) == 4, "nom::int32" ); static_assert ( sizeof ( nom::uint64 ) == 8, "nom::uint64" ); static_assert ( sizeof ( nom::int64 ) == 8, "nom::int64" ); static_assert ( sizeof ( nom::ulong ) == 8, "nom::ulong" ); static_assert ( sizeof ( nom::uchar ) == 1, "nom::uchar" ); #if defined(NOM_PLATFORM_ARCH_X86_64) static_assert ( sizeof ( nom::size ) == ( sizeof(nom::uint64) ), "nom::size" ); static_assert ( sizeof ( nom::int32_ptr ) == ( sizeof(long) ), "nom::int32_ptr" ); static_assert ( sizeof ( nom::uint32_ptr ) == ( sizeof(nom::ulong) ), "nom::uint32_ptr" ); #elif defined(NOM_PLATFORM_ARCH_X86) static_assert ( sizeof ( nom::size ) == ( sizeof(nom::uint32) ), "nom::size" ); #else #pragma message ( "types.hpp: Unknown architecture; defined data types may be wrong." ) #endif static_assert ( sizeof ( nom::boolean ) == ( sizeof(int) ), "nom::boolean" ); /// Additional type definitions const nom::sint NOM_EXIT_FAILURE = 1; // EXIT_FAILURE from cstdlib headers const nom::sint NOM_EXIT_SUCCESS = 0; // EXIT_SUCCESS from cstdlib headers //#if defined(HAVE_SDL2) const nom::sint SDL_SUCCESS = 0; // Non-error return value for SDL2 API //#endif #endif // include guard defined <commit_msg>types: Introduce NOM_PTR_CAST macro<commit_after>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #ifndef NOMLIB_STDINT_TYPES_HPP #define NOMLIB_STDINT_TYPES_HPP #include "platforms.hpp" #define NOM_PTR_CAST(type, expression) \ ( std::dynamic_pointer_cast<type>(expression) ) //#define NOM_STATIC_CAST(type, expression) static_cast<type>(expression) //#define NOM_CONST_CAST(type, expression) const_cast<type>(expression) /* TODO: This should be replaced by an actual CMake script -- think: compile-time check for the necessary feature support for C++11 style headers support. Look into why GCC doesn't like the inclusion of <cstdint> -- otherwise known as stdint.h. MSVCPP2013 & llvm-clang are fine with it). */ #ifndef NOM_PLATFORM_LINUX // To be replace with NOM_COMPILER_FEATURE_NULLPTR // (see above TODO note). #include <cstdint> #else #include <sys/types.h> #endif // Borrowed from /usr/include/MacTypes.h && /usr/include/objc/objc.h: #ifndef NULL #if defined( NOM_COMPILER_FEATURE_NULLPTR ) #define NULL nullptr #else #define NULL __DARWIN_NULL #endif #endif // ! NULL #ifndef nil #if defined( NOM_COMPILER_FEATURE_NULLPTR ) #define nil nullptr #else #define nil __DARWIN_NULL #endif #endif // ! nil // Portable fixed-size data types derive from stdint.h namespace nom { // 8-bit integer types typedef int8_t int8; typedef uint8_t uint8; // 16-bit integer types typedef int16_t int16; typedef uint16_t uint16; // 32-bit integer types typedef int32_t int32; typedef uint32_t uint32; /// \brief 64-bit integer types /// \note As per **/usr/include/MacTypes.h**: /// /// "The MS Visual C/C++ compiler uses __int64 instead of long long". #if defined( NOM_COMPILER_MSVCPP ) && defined( NOM_PLATFORM_ARCH_X86 ) typedef signed __int64 int64; typedef unsigned __int64 uint64; #else // Blindly assume a 64-bit architecture typedef int64_t int64; //typedef signed long long int int64; typedef uint64_t uint64; //typedef unsigned long long int uint64; #endif // Additional integer type definitions #if defined (NOM_PLATFORM_ARCH_X86_64) typedef unsigned long ulong; #else // Blindly assume 32-bit arch typedef long long ulong; #endif typedef unsigned char uchar; typedef signed int sint; typedef unsigned int uint; typedef std::size_t size; typedef int boolean; typedef sint* sint_ptr; typedef uint* uint_ptr; typedef int32_t* int32_ptr; typedef uint32_t* uint32_ptr; typedef void* void_ptr; } // namespace nom /// Ensure our data types have the right sizes using C++11 compile-time asserts. static_assert ( sizeof ( nom::uint8 ) == 1, "nom::uint8" ); static_assert ( sizeof ( nom::int8 ) == 1, "nom::int8" ); static_assert ( sizeof ( nom::uint16 ) == 2, "nom::uint16" ); static_assert ( sizeof ( nom::int16 ) == 2, "nom::int16" ); static_assert ( sizeof ( nom::uint32 ) == 4, "nom::uint32" ); static_assert ( sizeof ( nom::int32 ) == 4, "nom::int32" ); static_assert ( sizeof ( nom::uint64 ) == 8, "nom::uint64" ); static_assert ( sizeof ( nom::int64 ) == 8, "nom::int64" ); static_assert ( sizeof ( nom::ulong ) == 8, "nom::ulong" ); static_assert ( sizeof ( nom::uchar ) == 1, "nom::uchar" ); #if defined(NOM_PLATFORM_ARCH_X86_64) static_assert ( sizeof ( nom::size ) == ( sizeof(nom::uint64) ), "nom::size" ); static_assert ( sizeof ( nom::int32_ptr ) == ( sizeof(long) ), "nom::int32_ptr" ); static_assert ( sizeof ( nom::uint32_ptr ) == ( sizeof(nom::ulong) ), "nom::uint32_ptr" ); #elif defined(NOM_PLATFORM_ARCH_X86) static_assert ( sizeof ( nom::size ) == ( sizeof(nom::uint32) ), "nom::size" ); #else #pragma message ( "types.hpp: Unknown architecture; defined data types may be wrong." ) #endif static_assert ( sizeof ( nom::boolean ) == ( sizeof(int) ), "nom::boolean" ); /// Additional type definitions const nom::sint NOM_EXIT_FAILURE = 1; // EXIT_FAILURE from cstdlib headers const nom::sint NOM_EXIT_SUCCESS = 0; // EXIT_SUCCESS from cstdlib headers //#if defined(HAVE_SDL2) const nom::sint SDL_SUCCESS = 0; // Non-error return value for SDL2 API //#endif #endif // include guard defined <|endoftext|>
<commit_before>#pragma once #include "indexer/cell_id.hpp" #include "geometry/rect2d.hpp" #include "base/buffer_vector.hpp" #include <array> #include <cstdint> #include <queue> #include <utility> #include <vector> // TODO: Move neccessary functions to geometry/covering_utils.hpp and delete this file. constexpr int SPLIT_RECT_CELLS_COUNT = 512; template <typename Bounds, typename CellId> inline size_t SplitRectCell(CellId const & id, m2::RectD const & rect, std::array<std::pair<CellId, m2::RectD>, 4> & result) { size_t index = 0; for (int8_t i = 0; i < 4; ++i) { auto const child = id.Child(i); double minCellX, minCellY, maxCellX, maxCellY; CellIdConverter<Bounds, CellId>::GetCellBounds(child, minCellX, minCellY, maxCellX, maxCellY); m2::RectD const childRect(minCellX, minCellY, maxCellX, maxCellY); if (rect.IsIntersect(childRect)) result[index++] = {child, childRect}; } return index; } // Covers |rect| with at most |cellsCount| cells that have levels equal to or less than |maxLevel|. template <typename Bounds, typename CellId> inline void CoverRect(m2::RectD rect, size_t cellsCount, int maxLevel, std::vector<CellId> & result) { ASSERT(result.empty(), ()); { // Cut rect with world bound coordinates. if (!rect.Intersect(Bounds::FullRect())) return; ASSERT(rect.IsValid(), ()); } auto const commonCell = CellIdConverter<Bounds, CellId>::Cover2PointsWithCell( rect.minX(), rect.minY(), rect.maxX(), rect.maxY()); std::priority_queue<CellId, buffer_vector<CellId, SPLIT_RECT_CELLS_COUNT>, typename CellId::GreaterLevelOrder> cellQueue; cellQueue.push(commonCell); while (!cellQueue.empty() && cellQueue.size() + result.size() < cellsCount) { auto id = cellQueue.top(); cellQueue.pop(); while (id.Level() > maxLevel) id = id.Parent(); if (id.Level() == maxLevel) { result.push_back(id); break; } std::array<std::pair<CellId, m2::RectD>, 4> arr; size_t const count = SplitRectCell<Bounds>(id, rect, arr); if (cellQueue.size() + result.size() + count <= cellsCount) { for (size_t i = 0; i < count; ++i) { if (rect.IsRectInside(arr[i].second)) result.push_back(arr[i].first); else cellQueue.push(arr[i].first); } } else { result.push_back(id); } } for (; !cellQueue.empty(); cellQueue.pop()) { auto id = cellQueue.top(); while (id.Level() < maxLevel) { std::array<std::pair<CellId, m2::RectD>, 4> arr; size_t const count = SplitRectCell<Bounds>(id, rect, arr); ASSERT_GREATER(count, 0, ()); if (count > 1) break; id = arr[0].first; } result.push_back(id); } } // Covers |rect| with cells using spiral order starting from the rect center cell of |maxLevel|. template <typename Bounds, typename CellId> void CoverSpiral(m2::RectD rect, int maxLevel, std::vector<CellId> & result) { using Converter = CellIdConverter<Bounds, CellId>; enum class Direction : uint8_t { Right = 0, Down = 1, Left = 2, Up = 3 }; CHECK(result.empty(), ()); // Cut rect with world bound coordinates. if (!rect.Intersect(Bounds::FullRect())) return; CHECK(rect.IsValid(), ()); auto centralCell = Converter::ToCellId(rect.Center().x, rect.Center().y); while (maxLevel < centralCell.Level() && centralCell.Level() > 0) centralCell = centralCell.Parent(); if (maxLevel < centralCell.Level()) return; result.push_back(centralCell); // Area around CentralCell will be covered with surrounding cells. // // * -> * -> * -> * // ^ | // | V // * C -> * * // ^ | | // | V V // * <- * <- * * // // To get the best ranking quality we should use the smallest cell size but it's not // efficient because it generates too many index requests. To get good quality-performance // tradeoff we cover area with |maxCount| small cells, then increase cell size and cover // area with |maxCount| bigger cells. We increase cell size until |rect| is covered. // We start covering from the center each time and it's ok for ranking because each object // appears in result at most once. // |maxCount| may be adjusted after testing to ensure better quality-performance tradeoff. uint32_t constexpr maxCount = 64; auto const nextDirection = [](Direction direction) { return static_cast<Direction>((static_cast<uint8_t>(direction) + 1) % 4); }; auto const nextCoords = [](std::pair<int32_t, int32_t> const & xy, Direction direction, uint32_t step) { auto res = xy; switch (direction) { case Direction::Right: res.first += step; break; case Direction::Down: res.second -= step; break; case Direction::Left: res.first -= step; break; case Direction::Up: res.second += step; break; } return res; }; auto const coordsAreValid = [](std::pair<int32_t, int32_t> const & xy) { return xy.first >= 0 && xy.second >= 0 && static_cast<decltype(CellId::MAX_COORD)>(xy.first) <= CellId::MAX_COORD && static_cast<decltype(CellId::MAX_COORD)>(xy.second) <= CellId::MAX_COORD; }; m2::RectD coveredRect; static_assert(CellId::MAX_COORD == static_cast<int32_t>(CellId::MAX_COORD), ""); while (centralCell.Level() > 0 && !coveredRect.IsRectInside(rect)) { uint32_t count = 0; auto const centerXY = centralCell.XY(); // We support negative coordinates while covering and check coordinates validity before pushing // cell to |result|. std::pair<int32_t, int32_t> xy{centerXY.first, centerXY.second}; auto direction = Direction::Right; int sideLength = 1; // Indicates whether it is the first pass with current |sideLength|. We use spiral cells order and // must increment |sideLength| every second side pass. |sideLength| and |direction| will behave like: // 1 right, 1 down, 2 left, 2 up, 3 right, 3 down, etc. bool evenPass = true; while (count <= maxCount && !coveredRect.IsRectInside(rect)) { for (int i = 0; i < sideLength; ++i) { xy = nextCoords(xy, direction, centralCell.Radius() * 2); if (coordsAreValid(xy)) { auto const cell = CellId::FromXY(xy.first, xy.second, centralCell.Level()); double minCellX, minCellY, maxCellX, maxCellY; Converter::GetCellBounds(cell, minCellX, minCellY, maxCellX, maxCellY); auto const cellRect = m2::RectD(minCellX, minCellY, maxCellX, maxCellY); coveredRect.Add(cellRect); if (rect.IsIntersect(cellRect)) result.push_back(cell); } ++count; } if (!evenPass) ++sideLength; direction = nextDirection(direction); evenPass = !evenPass; } centralCell = centralCell.Parent(); } } <commit_msg>[indexer] Fix for review<commit_after>#pragma once #include "indexer/cell_id.hpp" #include "geometry/rect2d.hpp" #include "base/buffer_vector.hpp" #include <array> #include <cstdint> #include <queue> #include <utility> #include <vector> // TODO: Move neccessary functions to geometry/covering_utils.hpp and delete this file. constexpr int SPLIT_RECT_CELLS_COUNT = 512; template <typename Bounds, typename CellId> inline size_t SplitRectCell(CellId const & id, m2::RectD const & rect, std::array<std::pair<CellId, m2::RectD>, 4> & result) { size_t index = 0; for (int8_t i = 0; i < 4; ++i) { auto const child = id.Child(i); double minCellX, minCellY, maxCellX, maxCellY; CellIdConverter<Bounds, CellId>::GetCellBounds(child, minCellX, minCellY, maxCellX, maxCellY); m2::RectD const childRect(minCellX, minCellY, maxCellX, maxCellY); if (rect.IsIntersect(childRect)) result[index++] = {child, childRect}; } return index; } // Covers |rect| with at most |cellsCount| cells that have levels equal to or less than |maxLevel|. template <typename Bounds, typename CellId> inline void CoverRect(m2::RectD rect, size_t cellsCount, int maxLevel, std::vector<CellId> & result) { ASSERT(result.empty(), ()); { // Cut rect with world bound coordinates. if (!rect.Intersect(Bounds::FullRect())) return; ASSERT(rect.IsValid(), ()); } auto const commonCell = CellIdConverter<Bounds, CellId>::Cover2PointsWithCell( rect.minX(), rect.minY(), rect.maxX(), rect.maxY()); std::priority_queue<CellId, buffer_vector<CellId, SPLIT_RECT_CELLS_COUNT>, typename CellId::GreaterLevelOrder> cellQueue; cellQueue.push(commonCell); while (!cellQueue.empty() && cellQueue.size() + result.size() < cellsCount) { auto id = cellQueue.top(); cellQueue.pop(); while (id.Level() > maxLevel) id = id.Parent(); if (id.Level() == maxLevel) { result.push_back(id); break; } std::array<std::pair<CellId, m2::RectD>, 4> arr; size_t const count = SplitRectCell<Bounds>(id, rect, arr); if (cellQueue.size() + result.size() + count <= cellsCount) { for (size_t i = 0; i < count; ++i) { if (rect.IsRectInside(arr[i].second)) result.push_back(arr[i].first); else cellQueue.push(arr[i].first); } } else { result.push_back(id); } } for (; !cellQueue.empty(); cellQueue.pop()) { auto id = cellQueue.top(); while (id.Level() < maxLevel) { std::array<std::pair<CellId, m2::RectD>, 4> arr; size_t const count = SplitRectCell<Bounds>(id, rect, arr); ASSERT_GREATER(count, 0, ()); if (count > 1) break; id = arr[0].first; } result.push_back(id); } } // Covers |rect| with cells using spiral order starting from the rect center cell of |maxLevel|. template <typename Bounds, typename CellId> void CoverSpiral(m2::RectD rect, int maxLevel, std::vector<CellId> & result) { using Converter = CellIdConverter<Bounds, CellId>; enum class Direction : uint8_t { Right = 0, Down = 1, Left = 2, Up = 3 }; CHECK(result.empty(), ()); // Cut rect with world bound coordinates. if (!rect.Intersect(Bounds::FullRect())) return; CHECK(rect.IsValid(), ()); auto centralCell = Converter::ToCellId(rect.Center().x, rect.Center().y); while (maxLevel < centralCell.Level() && centralCell.Level() > 0) centralCell = centralCell.Parent(); result.push_back(centralCell); // Area around CentralCell will be covered with surrounding cells. // // * -> * -> * -> * // ^ | // | V // * C -> * * // ^ | | // | V V // * <- * <- * * // // To get the best ranking quality we should use the smallest cell size but it's not // efficient because it generates too many index requests. To get good quality-performance // tradeoff we cover area with |maxCount| small cells, then increase cell size and cover // area with |maxCount| bigger cells. We increase cell size until |rect| is covered. // We start covering from the center each time and it's ok for ranking because each object // appears in result at most once. // |maxCount| may be adjusted after testing to ensure better quality-performance tradeoff. uint32_t constexpr maxCount = 64; auto const nextDirection = [](Direction direction) { return static_cast<Direction>((static_cast<uint8_t>(direction) + 1) % 4); }; auto const nextCoords = [](std::pair<int32_t, int32_t> const & xy, Direction direction, uint32_t step) { auto res = xy; switch (direction) { case Direction::Right: res.first += step; break; case Direction::Down: res.second -= step; break; case Direction::Left: res.first -= step; break; case Direction::Up: res.second += step; break; } return res; }; auto const coordsAreValid = [](std::pair<int32_t, int32_t> const & xy) { return xy.first >= 0 && xy.second >= 0 && static_cast<decltype(CellId::MAX_COORD)>(xy.first) <= CellId::MAX_COORD && static_cast<decltype(CellId::MAX_COORD)>(xy.second) <= CellId::MAX_COORD; }; m2::RectD coveredRect; static_assert(CellId::MAX_COORD == static_cast<int32_t>(CellId::MAX_COORD), ""); while (centralCell.Level() > 0 && !coveredRect.IsRectInside(rect)) { uint32_t count = 0; auto const centerXY = centralCell.XY(); // We support negative coordinates while covering and check coordinates validity before pushing // cell to |result|. std::pair<int32_t, int32_t> xy{centerXY.first, centerXY.second}; auto direction = Direction::Right; int sideLength = 1; // Indicates whether it is the first pass with current |sideLength|. We use spiral cells order and // must increment |sideLength| every second side pass. |sideLength| and |direction| will behave like: // 1 right, 1 down, 2 left, 2 up, 3 right, 3 down, etc. bool evenPass = true; while (count <= maxCount && !coveredRect.IsRectInside(rect)) { for (int i = 0; i < sideLength; ++i) { xy = nextCoords(xy, direction, centralCell.Radius() * 2); if (coordsAreValid(xy)) { auto const cell = CellId::FromXY(xy.first, xy.second, centralCell.Level()); double minCellX, minCellY, maxCellX, maxCellY; Converter::GetCellBounds(cell, minCellX, minCellY, maxCellX, maxCellY); auto const cellRect = m2::RectD(minCellX, minCellY, maxCellX, maxCellY); coveredRect.Add(cellRect); if (rect.IsIntersect(cellRect)) result.push_back(cell); } ++count; } if (!evenPass) ++sideLength; direction = nextDirection(direction); evenPass = !evenPass; } centralCell = centralCell.Parent(); } } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <string> #include "pegmatite.hh" // This is very bad style, but it's okay for a short example... using namespace std; using namespace pegmatite; /** * The AST namespace contains the abstract syntax tree for this grammar. */ namespace AST { /** * The base class for expressions in our language. */ class Expression : public ASTContainer { public: /** * Evaluate this expression. Returns a `double` representing the result of * the evaluation. */ virtual double eval() const = 0; /** * Print the node, at the specified indent depth. */ virtual void print(int depth = 0) const = 0; PEGMATITE_RTTI(Expression, ASTContainer); }; /** * AST node representing a number. */ class Number : public Expression { public: /** * Construct the numerical value from the text in the input range. */ virtual void construct(const pegmatite::InputRange &r, pegmatite::ASTStack &st) { stringstream stream; for(char c : r) { stream << c; } stream >> value; } virtual double eval() const { return value; } virtual void print(int depth) const { cout << string(depth, '\t') << value << endl; } private: double value; }; /** * Superclass for all of the binary expressions. Contains pointers to the left * and right children. Subclasses encode the operation type. */ class BinaryExpression : public Expression { protected: /** * The pointers to the left and right nodes. The `ASTPtr` class will * automatically fill these in when this node is constructed, popping the * two top values from the AST stack. */ ASTPtr<Expression> left, right; public: virtual void print(int depth) const { left->print(depth); right->print(depth); } }; /** * Add expression node. */ class AddExpression : public BinaryExpression { public: virtual double eval() const { return left->eval() + right->eval(); } virtual void print(int depth) const { cout << string(depth, '\t') << "+" << endl; BinaryExpression::print(depth+1); } }; /** * Subtract expression node. */ class SubtractExpression : public BinaryExpression { public: virtual double eval() const { return left->eval() - right->eval(); } virtual void print(int depth) const { cout << string(depth, '\t') << "-" << endl; BinaryExpression::print(depth+1); } }; /** * Multiply expression node. */ class MultiplyExpression : public BinaryExpression { public: virtual double eval() const { return left->eval() * right->eval(); } virtual void print(int depth) const { cout << string(depth, '\t') << "*" << endl; BinaryExpression::print(depth+1); } }; /** * Divide expression node. */ class DivideExpression : public BinaryExpression { public: virtual double eval() const { double ret = 0; double rval = right->eval(); if (rval != 0) { ret = left->eval() / rval; } return ret; } virtual void print(int depth) const { cout << string(depth, '\t') << "/" << endl; BinaryExpression::print(depth+1); } }; } namespace Parser { /** * The (singleton) calculator grammar. */ struct CalculatorGrammar { /** * Only spaces are recognised as whitespace in this toy example. */ Rule ws = " \t\n"_E; /** * Digits are things in the range 0-9. */ Rule digit = '0'_E - '9'; /** * Numbers are one or more digits, optionally followed by a decimal point, * and one or more digits, optionally followed by an exponent (which may * also be negative. */ Rule num = +digit >> -('.'_E >> +digit >> -("eE"_S >> -("+-"_S) >> +digit)); /** * Values are either numbers or expressions in brackets (highest precedence). */ Rule val = num | '(' >> expr >> ')'; /** * Multiply operations are values or multiply, or divide operations, * followed by a multiply symbol, followed by a value. The sides can never * be add or subtract operations, because they have lower precedence and so * can only be parents of multiply or divide operations (or children via * parenthetical expressions), not direct children. */ Rule mul_op = mul >> '*' >> val; /** * Divide operations follow the same syntax as multiply. */ Rule div_op = mul >> '/' >> val; /** * Multiply-precedence operations are either multiply or divide operations, * or simple values (numbers of parenthetical expressions). */ Rule mul = mul_op | div_op | val; /** * Add operations can have any expression on the left (including other add * expressions), but only higher-precedence operations on the right. */ Rule add_op = expr >> '+' >> mul; /** * Subtract operations follow the same structure as add. */ Rule sub_op = expr >> '-' >> mul; /** * Expressions can be any of the other types. */ Rule expr = add_op | sub_op | mul; /** * Returns a singleton instance of this grammar. */ static const CalculatorGrammar& get() { static CalculatorGrammar g; return g; } private: /** * Private constructor. This class is immutable, and so only the `get()` * method should be used to return the singleton instance. */ CalculatorGrammar() {}; }; /** * CalculatorParser, constructs an AST from an input string. */ class CalculatorParser : public ASTParserDelegate { BindAST<AST::Number> num = CalculatorGrammar::get().num; BindAST<AST::AddExpression> add = CalculatorGrammar::get().add_op; BindAST<AST::SubtractExpression> sub = CalculatorGrammar::get().sub_op; BindAST<AST::MultiplyExpression> mul = CalculatorGrammar::get().mul_op; BindAST<AST::DivideExpression> div = CalculatorGrammar::get().div_op; public: const CalculatorGrammar &g = CalculatorGrammar::get(); }; } int main() { Parser::CalculatorParser p; for(;;) { string s; cout << "enter a math expression (+ - * /, floats, parentheses) or enter to exit:\n"; getline(cin, s); if (s.empty()) break; //convert the string to input StringInput i(s); //parse ErrorList el; unique_ptr<AST::Expression> root = 0; p.parse(i, p.g.expr, p.g.ws, el, root); //on success if (root) { double v = root->eval(); cout << "success\n"; cout << "result = " << v << endl; cout << "parse tree:\n"; root->print(0); } //on error else { cout << "errors: \n"; for(auto &err : el) { cout << "line " << err.start.line << ", col " << err.finish.col << ": "; wcout << "syntax error" << endl; } } //next input cout << endl; } return 0; } <commit_msg>Whitespace cleanups.<commit_after>#include <iostream> #include <sstream> #include <string> #include "pegmatite.hh" // This is very bad style, but it's okay for a short example... using namespace std; using namespace pegmatite; /** * The AST namespace contains the abstract syntax tree for this grammar. */ namespace AST { /** * The base class for expressions in our language. */ class Expression : public ASTContainer { public: /** * Evaluate this expression. Returns a `double` representing the result of * the evaluation. */ virtual double eval() const = 0; /** * Print the node, at the specified indent depth. */ virtual void print(int depth = 0) const = 0; PEGMATITE_RTTI(Expression, ASTContainer); }; /** * AST node representing a number. */ class Number : public Expression { public: /** * Construct the numerical value from the text in the input range. */ virtual void construct(const pegmatite::InputRange &r, pegmatite::ASTStack &st) { stringstream stream; for (char c : r) { stream << c; } stream >> value; } virtual double eval() const { return value; } virtual void print(int depth) const { cout << string(depth, '\t') << value << endl; } private: double value; }; /** * Superclass for all of the binary expressions. Contains pointers to the left * and right children. Subclasses encode the operation type. */ class BinaryExpression : public Expression { protected: /** * The pointers to the left and right nodes. The `ASTPtr` class will * automatically fill these in when this node is constructed, popping the * two top values from the AST stack. */ ASTPtr<Expression> left, right; public: virtual void print(int depth) const { left->print(depth); right->print(depth); } }; /** * Add expression node. */ class AddExpression : public BinaryExpression { public: virtual double eval() const { return left->eval() + right->eval(); } virtual void print(int depth) const { cout << string(depth, '\t') << "+" << endl; BinaryExpression::print(depth+1); } }; /** * Subtract expression node. */ class SubtractExpression : public BinaryExpression { public: virtual double eval() const { return left->eval() - right->eval(); } virtual void print(int depth) const { cout << string(depth, '\t') << "-" << endl; BinaryExpression::print(depth+1); } }; /** * Multiply expression node. */ class MultiplyExpression : public BinaryExpression { public: virtual double eval() const { return left->eval() * right->eval(); } virtual void print(int depth) const { cout << string(depth, '\t') << "*" << endl; BinaryExpression::print(depth+1); } }; /** * Divide expression node. */ class DivideExpression : public BinaryExpression { public: virtual double eval() const { double ret = 0; double rval = right->eval(); if (rval != 0) { ret = left->eval() / rval; } return ret; } virtual void print(int depth) const { cout << string(depth, '\t') << "/" << endl; BinaryExpression::print(depth+1); } }; } namespace Parser { /** * The (singleton) calculator grammar. */ struct CalculatorGrammar { /** * Only spaces are recognised as whitespace in this toy example. */ Rule ws = " \t\n"_E; /** * Digits are things in the range 0-9. */ Rule digit = '0'_E - '9'; /** * Numbers are one or more digits, optionally followed by a decimal point, * and one or more digits, optionally followed by an exponent (which may * also be negative. */ Rule num = +digit >> -('.'_E >> +digit >> -("eE"_S >> -("+-"_S) >> +digit)); /** * Values are either numbers or expressions in brackets (highest precedence). */ Rule val = num | '(' >> expr >> ')'; /** * Multiply operations are values or multiply, or divide operations, * followed by a multiply symbol, followed by a value. The sides can never * be add or subtract operations, because they have lower precedence and so * can only be parents of multiply or divide operations (or children via * parenthetical expressions), not direct children. */ Rule mul_op = mul >> '*' >> val; /** * Divide operations follow the same syntax as multiply. */ Rule div_op = mul >> '/' >> val; /** * Multiply-precedence operations are either multiply or divide operations, * or simple values (numbers of parenthetical expressions). */ Rule mul = mul_op | div_op | val; /** * Add operations can have any expression on the left (including other add * expressions), but only higher-precedence operations on the right. */ Rule add_op = expr >> '+' >> mul; /** * Subtract operations follow the same structure as add. */ Rule sub_op = expr >> '-' >> mul; /** * Expressions can be any of the other types. */ Rule expr = add_op | sub_op | mul; /** * Returns a singleton instance of this grammar. */ static const CalculatorGrammar& get() { static CalculatorGrammar g; return g; } private: /** * Private constructor. This class is immutable, and so only the `get()` * method should be used to return the singleton instance. */ CalculatorGrammar() {}; }; /** * CalculatorParser, constructs an AST from an input string. */ class CalculatorParser : public ASTParserDelegate { BindAST<AST::Number> num = CalculatorGrammar::get().num; BindAST<AST::AddExpression> add = CalculatorGrammar::get().add_op; BindAST<AST::SubtractExpression> sub = CalculatorGrammar::get().sub_op; BindAST<AST::MultiplyExpression> mul = CalculatorGrammar::get().mul_op; BindAST<AST::DivideExpression> div = CalculatorGrammar::get().div_op; public: const CalculatorGrammar &g = CalculatorGrammar::get(); }; } int main() { Parser::CalculatorParser p; for (;;) { string s; cout << "enter a math expression (+ - * /, floats, parentheses) or enter to exit:\n"; getline(cin, s); if (s.empty()) break; //convert the string to input StringInput i(s); //parse ErrorList el; unique_ptr<AST::Expression> root = 0; p.parse(i, p.g.expr, p.g.ws, el, root); //on success if (root) { double v = root->eval(); cout << "success\n"; cout << "result = " << v << endl; cout << "parse tree:\n"; root->print(0); } //on error else { cout << "errors: \n"; for (auto &err : el) { cout << "line " << err.start.line << ", col " << err.finish.col << ": "; wcout << "syntax error" << endl; } } //next input cout << endl; } return 0; } <|endoftext|>
<commit_before>/** * @file TODO * @brief MegaCMD: TODO * * (c) 2013-2016 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include <stdio.h> #include <iostream> #include <errno.h> #include <string> #include <vector> #include <memory.h> #include <limits.h> #include <sys/types.h> #ifdef _WIN32 #include <WinSock2.h> #include <Shlwapi.h> //PathAppend #else #include <sys/socket.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/un.h> #endif #define MEGACMDINITIALPORTNUMBER 12300 #ifdef _WIN32 #include <windows.h> #define ERRNO WSAGetLastError() #else #define ERRNO errno #endif #ifndef SOCKET_ERROR #define SOCKET_ERROR -1 #endif #ifdef __MACH__ #define MSG_NOSIGNAL 0 #elif _WIN32 #define MSG_NOSIGNAL 0 #endif bool socketValid(int socket) { #ifdef _WIN32 return socket != INVALID_SOCKET; #else return socket >= 0; #endif } #ifndef INVALID_SOCKET #define INVALID_SOCKET -1 #endif void closeSocket(int socket){ #ifdef _WIN32 closesocket(socket); #else close(socket); #endif } using namespace std; #ifdef _WIN32 // convert UTF-8 to Windows Unicode void path2local(string* path, string* local) { // make space for the worst case local->resize((path->size() + 1) * sizeof(wchar_t)); int len = MultiByteToWideChar(CP_UTF8, 0, path->c_str(), -1, (wchar_t*)local->data(), local->size() / sizeof(wchar_t) + 1); if (len) { // resize to actual result local->resize(sizeof(wchar_t) * (len - 1)); } else { local->clear(); } } // convert to Windows Unicode Utf8 void local2path(string* local, string* path) { path->resize((local->size() + 1) * 4 / sizeof(wchar_t)); path->resize(WideCharToMultiByte(CP_UTF8, 0, (wchar_t*)local->data(), local->size() / sizeof(wchar_t), (char*)path->data(), path->size() + 1, NULL, NULL)); //normalize(path); } #endif string getAbsPath(string relativePath) { if (!relativePath.size()) { return relativePath; } #ifdef _WIN32 string utf8absolutepath; string localpath; path2local(&relativePath, &localpath); string absolutelocalpath; localpath.append("", 1); if (!PathIsRelativeW((LPCWSTR)localpath.data())) { utf8absolutepath = relativePath; if (utf8absolutepath.find("\\\\?\\") != 0) { utf8absolutepath.insert(0, "\\\\?\\", sizeof("\\\\?\\")-1); } return utf8absolutepath; } int len = GetFullPathNameW((LPCWSTR)localpath.data(), 0, NULL, NULL); if (len <= 0) { return relativePath; } absolutelocalpath.resize(len * sizeof(wchar_t)); int newlen = GetFullPathNameW((LPCWSTR)localpath.data(), len, (LPWSTR)absolutelocalpath.data(), NULL); if (newlen <= 0 || newlen >= len) { cerr << " failed to get CWD" << endl; return relativePath; } local2path(&absolutelocalpath, &utf8absolutepath); if (utf8absolutepath.find("\\\\?\\") != 0) { utf8absolutepath.insert(0, "\\\\?\\", sizeof("\\\\?\\")-1); } return utf8absolutepath; #else if (relativePath.size() && relativePath.at(0) == '/') { return relativePath; } else { char cCurrentPath[PATH_MAX]; if (!getcwd(cCurrentPath, sizeof(cCurrentPath))) { cerr << " failed to get CWD" << endl; return relativePath; } string absolutepath = cCurrentPath; absolutepath.append("/"); absolutepath.append(relativePath); return absolutepath; } return relativePath; #endif } string parseArgs(int argc, char* argv[]) { vector<string> absolutedargs; int itochange = -1; int totalRealArgs = 0; if (argc>1) { absolutedargs.push_back(argv[1]); if (!strcmp(argv[1],"sync")) { for (int i = 2; i < argc; i++) { if (strlen(argv[i]) && argv[i][0] !='-' ) { totalRealArgs++; itochange = i; } } for (int i = 2; i < argc; i++) { if (i==itochange && totalRealArgs>=2) { absolutedargs.push_back(getAbsPath(argv[i])); } else { absolutedargs.push_back(argv[i]); } } } else if (!strcmp(argv[1],"lcd")) //localpath args { for (int i = 2; i < argc; i++) { if (strlen(argv[i]) && argv[i][0] !='-' ) { absolutedargs.push_back(getAbsPath(argv[i])); } else { absolutedargs.push_back(argv[i]); } } } else if (!strcmp(argv[1],"get") || !strcmp(argv[1],"preview") || !strcmp(argv[1],"thumbnail")) { for (int i = 2; i < argc; i++) { if (strlen(argv[i]) && argv[i][0] != '-' ) { totalRealArgs++; if (totalRealArgs>1) { absolutedargs.push_back(getAbsPath(argv[i])); } else { absolutedargs.push_back(argv[i]); } } else { absolutedargs.push_back(argv[i]); } } } else if (!strcmp(argv[1],"put")) { int lastRealArg = 0; for (int i = 2; i < argc; i++) { if (strlen(argv[i]) && argv[i][0] !='-' ) { lastRealArg = i; } } bool firstRealArg = true; for (int i = 2; i < argc; i++) { if (strlen(argv[i]) && argv[i][0] !='-') { if (firstRealArg || i <lastRealArg) { absolutedargs.push_back(getAbsPath(argv[i])); } else { absolutedargs.push_back(argv[i]); } } else { absolutedargs.push_back(argv[i]); } } } else { for (int i = 2; i < argc; i++) { absolutedargs.push_back(argv[i]); } } } string toret=""; for (u_int i=0; i < absolutedargs.size(); i++) { if (absolutedargs.at(i).find(" ") != string::npos || !absolutedargs.at(i).size()) { toret += "\""; } toret+=absolutedargs.at(i); if (absolutedargs.at(i).find(" ") != string::npos || !absolutedargs.at(i).size()) { toret += "\""; } if (i != (absolutedargs.size()-1)) { toret += " "; } } return toret; } #ifdef _WIN32 int createSocket(int number = 0, bool net = true) #else int createSocket(int number = 0, bool net = false) #endif { if (net) { int thesock = socket(AF_INET, SOCK_STREAM, 0); if (!socketValid(thesock)) { cerr << "ERROR opening socket: " << ERRNO << endl; return INVALID_SOCKET; } int portno=MEGACMDINITIALPORTNUMBER+number; struct sockaddr_in addr; memset(&addr, 0, sizeof( addr )); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); addr.sin_port = htons(portno); if (::connect(thesock, (struct sockaddr*)&addr, sizeof( addr )) == SOCKET_ERROR) { cerr << "ERROR connecting to initial socket: " << ERRNO << endl; cerr << "Unable to connect to service" << endl; cerr << "Please ensure MegaCMD is running" << endl; return INVALID_SOCKET; } return thesock; } #ifndef _WIN32 else { int thesock = socket(AF_UNIX, SOCK_STREAM, 0); char socket_path[60]; if (!socketValid(thesock)) { cerr << "ERROR opening socket: " << ERRNO << endl; return INVALID_SOCKET; } bzero(socket_path, sizeof( socket_path ) * sizeof( *socket_path )); if (number) { sprintf(socket_path, "/tmp/megaCMD_%d/srv_%d", getuid(), number); } else { sprintf(socket_path, "/tmp/megaCMD_%d/srv", getuid() ); } struct sockaddr_un addr; memset(&addr, 0, sizeof( addr )); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, socket_path, sizeof( addr.sun_path ) - 1); if (::connect(thesock, (struct sockaddr*)&addr, sizeof( addr )) == SOCKET_ERROR) { cerr << "ERROR connecting to initial socket: " << ERRNO << endl; cerr << "Unable to connect to service" << endl; cerr << "Please ensure MegaCMD is running" << endl; return INVALID_SOCKET; } return thesock; } return INVALID_SOCKET; #endif } int main(int argc, char* argv[]) { if (argc < 2) { cerr << "Too few arguments" << endl; return -1; } #if _WIN32 WORD wVersionRequested; WSADATA wsaData; int err; /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */ wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { cerr << "ERROR initializing WSA" << endl; } #endif string parsedArgs = parseArgs(argc,argv); int thesock = createSocket(); if (thesock == INVALID_SOCKET) { return INVALID_SOCKET; } int n = send(thesock,parsedArgs.data(),parsedArgs.size(), MSG_NOSIGNAL); if (n == SOCKET_ERROR) { cerr << "ERROR writing output Code to socket: " << ERRNO << endl; return -1;; } int receiveSocket = SOCKET_ERROR ; n = recv(thesock, (char *)&receiveSocket, sizeof(receiveSocket), MSG_NOSIGNAL); if (n == SOCKET_ERROR) { cerr << "ERROR reading output socket" << endl; return -1;; } int newsockfd =createSocket(receiveSocket); if (newsockfd == INVALID_SOCKET) return INVALID_SOCKET; int outcode = -1; n = recv(newsockfd, (char *)&outcode, sizeof(outcode), MSG_NOSIGNAL); if (n == SOCKET_ERROR) { cerr << "ERROR reading output code: " << ERRNO << endl; return -1;; } int BUFFERSIZE = 1024; char buffer[1025]; do{ n = recv(newsockfd, buffer, BUFFERSIZE, MSG_NOSIGNAL); if (n) { buffer[n]='\0'; cout << buffer; } } while(n == BUFFERSIZE && n !=SOCKET_ERROR); if (n == SOCKET_ERROR) { cerr << "ERROR reading output: " << ERRNO << endl; return -1;; } closeSocket(thesock); closeSocket(newsockfd); #if _WIN32 WSACleanup(); #endif return outcode; } <commit_msg>client passes $PWD in get/preview/thumbnail if no destination specified<commit_after>/** * @file TODO * @brief MegaCMD: TODO * * (c) 2013-2016 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include <stdio.h> #include <iostream> #include <errno.h> #include <string> #include <vector> #include <memory.h> #include <limits.h> #include <sys/types.h> #ifdef _WIN32 #include <WinSock2.h> #include <Shlwapi.h> //PathAppend #else #include <sys/socket.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/un.h> #endif #define MEGACMDINITIALPORTNUMBER 12300 #ifdef _WIN32 #include <windows.h> #define ERRNO WSAGetLastError() #else #define ERRNO errno #endif #ifndef SOCKET_ERROR #define SOCKET_ERROR -1 #endif #ifdef __MACH__ #define MSG_NOSIGNAL 0 #elif _WIN32 #define MSG_NOSIGNAL 0 #endif bool socketValid(int socket) { #ifdef _WIN32 return socket != INVALID_SOCKET; #else return socket >= 0; #endif } #ifndef INVALID_SOCKET #define INVALID_SOCKET -1 #endif void closeSocket(int socket){ #ifdef _WIN32 closesocket(socket); #else close(socket); #endif } using namespace std; #ifdef _WIN32 // convert UTF-8 to Windows Unicode void path2local(string* path, string* local) { // make space for the worst case local->resize((path->size() + 1) * sizeof(wchar_t)); int len = MultiByteToWideChar(CP_UTF8, 0, path->c_str(), -1, (wchar_t*)local->data(), local->size() / sizeof(wchar_t) + 1); if (len) { // resize to actual result local->resize(sizeof(wchar_t) * (len - 1)); } else { local->clear(); } } // convert to Windows Unicode Utf8 void local2path(string* local, string* path) { path->resize((local->size() + 1) * 4 / sizeof(wchar_t)); path->resize(WideCharToMultiByte(CP_UTF8, 0, (wchar_t*)local->data(), local->size() / sizeof(wchar_t), (char*)path->data(), path->size() + 1, NULL, NULL)); //normalize(path); } #endif string getAbsPath(string relativePath) { if (!relativePath.size()) { return relativePath; } #ifdef _WIN32 string utf8absolutepath; string localpath; path2local(&relativePath, &localpath); string absolutelocalpath; localpath.append("", 1); if (!PathIsRelativeW((LPCWSTR)localpath.data())) { utf8absolutepath = relativePath; if (utf8absolutepath.find("\\\\?\\") != 0) { utf8absolutepath.insert(0, "\\\\?\\", sizeof("\\\\?\\")-1); } return utf8absolutepath; } int len = GetFullPathNameW((LPCWSTR)localpath.data(), 0, NULL, NULL); if (len <= 0) { return relativePath; } absolutelocalpath.resize(len * sizeof(wchar_t)); int newlen = GetFullPathNameW((LPCWSTR)localpath.data(), len, (LPWSTR)absolutelocalpath.data(), NULL); if (newlen <= 0 || newlen >= len) { cerr << " failed to get CWD" << endl; return relativePath; } local2path(&absolutelocalpath, &utf8absolutepath); if (utf8absolutepath.find("\\\\?\\") != 0) { utf8absolutepath.insert(0, "\\\\?\\", sizeof("\\\\?\\")-1); } return utf8absolutepath; #else if (relativePath.size() && relativePath.at(0) == '/') { return relativePath; } else { char cCurrentPath[PATH_MAX]; if (!getcwd(cCurrentPath, sizeof(cCurrentPath))) { cerr << " failed to get CWD" << endl; return relativePath; } string absolutepath = cCurrentPath; absolutepath.append("/"); absolutepath.append(relativePath); return absolutepath; } return relativePath; #endif } string parseArgs(int argc, char* argv[]) { vector<string> absolutedargs; int itochange = -1; int totalRealArgs = 0; if (argc>1) { absolutedargs.push_back(argv[1]); if (!strcmp(argv[1],"sync")) { for (int i = 2; i < argc; i++) { if (strlen(argv[i]) && argv[i][0] !='-' ) { totalRealArgs++; itochange = i; } } for (int i = 2; i < argc; i++) { if (i==itochange && totalRealArgs>=2) { absolutedargs.push_back(getAbsPath(argv[i])); } else { absolutedargs.push_back(argv[i]); } } } else if (!strcmp(argv[1],"lcd")) //localpath args { for (int i = 2; i < argc; i++) { if (strlen(argv[i]) && argv[i][0] !='-' ) { absolutedargs.push_back(getAbsPath(argv[i])); } else { absolutedargs.push_back(argv[i]); } } } else if (!strcmp(argv[1],"get") || !strcmp(argv[1],"preview") || !strcmp(argv[1],"thumbnail")) { for (int i = 2; i < argc; i++) { if (strlen(argv[i]) && argv[i][0] != '-' ) { totalRealArgs++; if (totalRealArgs>1) { absolutedargs.push_back(getAbsPath(argv[i])); } else { absolutedargs.push_back(argv[i]); } } else { absolutedargs.push_back(argv[i]); } } if (totalRealArgs == 1) { absolutedargs.push_back(getAbsPath(".")); } } else if (!strcmp(argv[1],"put")) { int lastRealArg = 0; for (int i = 2; i < argc; i++) { if (strlen(argv[i]) && argv[i][0] !='-' ) { lastRealArg = i; } } bool firstRealArg = true; for (int i = 2; i < argc; i++) { if (strlen(argv[i]) && argv[i][0] !='-') { if (firstRealArg || i <lastRealArg) { absolutedargs.push_back(getAbsPath(argv[i])); } else { absolutedargs.push_back(argv[i]); } } else { absolutedargs.push_back(argv[i]); } } } else { for (int i = 2; i < argc; i++) { absolutedargs.push_back(argv[i]); } } } string toret=""; for (u_int i=0; i < absolutedargs.size(); i++) { if (absolutedargs.at(i).find(" ") != string::npos || !absolutedargs.at(i).size()) { toret += "\""; } toret+=absolutedargs.at(i); if (absolutedargs.at(i).find(" ") != string::npos || !absolutedargs.at(i).size()) { toret += "\""; } if (i != (absolutedargs.size()-1)) { toret += " "; } } return toret; } #ifdef _WIN32 int createSocket(int number = 0, bool net = true) #else int createSocket(int number = 0, bool net = false) #endif { if (net) { int thesock = socket(AF_INET, SOCK_STREAM, 0); if (!socketValid(thesock)) { cerr << "ERROR opening socket: " << ERRNO << endl; return INVALID_SOCKET; } int portno=MEGACMDINITIALPORTNUMBER+number; struct sockaddr_in addr; memset(&addr, 0, sizeof( addr )); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); addr.sin_port = htons(portno); if (::connect(thesock, (struct sockaddr*)&addr, sizeof( addr )) == SOCKET_ERROR) { cerr << "ERROR connecting to initial socket: " << ERRNO << endl; cerr << "Unable to connect to service" << endl; cerr << "Please ensure MegaCMD is running" << endl; return INVALID_SOCKET; } return thesock; } #ifndef _WIN32 else { int thesock = socket(AF_UNIX, SOCK_STREAM, 0); char socket_path[60]; if (!socketValid(thesock)) { cerr << "ERROR opening socket: " << ERRNO << endl; return INVALID_SOCKET; } bzero(socket_path, sizeof( socket_path ) * sizeof( *socket_path )); if (number) { sprintf(socket_path, "/tmp/megaCMD_%d/srv_%d", getuid(), number); } else { sprintf(socket_path, "/tmp/megaCMD_%d/srv", getuid() ); } struct sockaddr_un addr; memset(&addr, 0, sizeof( addr )); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, socket_path, sizeof( addr.sun_path ) - 1); if (::connect(thesock, (struct sockaddr*)&addr, sizeof( addr )) == SOCKET_ERROR) { cerr << "ERROR connecting to initial socket: " << ERRNO << endl; cerr << "Unable to connect to service" << endl; cerr << "Please ensure MegaCMD is running" << endl; return INVALID_SOCKET; } return thesock; } return INVALID_SOCKET; #endif } int main(int argc, char* argv[]) { if (argc < 2) { cerr << "Too few arguments" << endl; return -1; } #if _WIN32 WORD wVersionRequested; WSADATA wsaData; int err; /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */ wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { cerr << "ERROR initializing WSA" << endl; } #endif string parsedArgs = parseArgs(argc,argv); int thesock = createSocket(); if (thesock == INVALID_SOCKET) { return INVALID_SOCKET; } int n = send(thesock,parsedArgs.data(),parsedArgs.size(), MSG_NOSIGNAL); if (n == SOCKET_ERROR) { cerr << "ERROR writing output Code to socket: " << ERRNO << endl; return -1;; } int receiveSocket = SOCKET_ERROR ; n = recv(thesock, (char *)&receiveSocket, sizeof(receiveSocket), MSG_NOSIGNAL); if (n == SOCKET_ERROR) { cerr << "ERROR reading output socket" << endl; return -1;; } int newsockfd =createSocket(receiveSocket); if (newsockfd == INVALID_SOCKET) return INVALID_SOCKET; int outcode = -1; n = recv(newsockfd, (char *)&outcode, sizeof(outcode), MSG_NOSIGNAL); if (n == SOCKET_ERROR) { cerr << "ERROR reading output code: " << ERRNO << endl; return -1;; } int BUFFERSIZE = 1024; char buffer[1025]; do{ n = recv(newsockfd, buffer, BUFFERSIZE, MSG_NOSIGNAL); if (n) { buffer[n]='\0'; cout << buffer; } } while(n == BUFFERSIZE && n !=SOCKET_ERROR); if (n == SOCKET_ERROR) { cerr << "ERROR reading output: " << ERRNO << endl; return -1;; } closeSocket(thesock); closeSocket(newsockfd); #if _WIN32 WSACleanup(); #endif return outcode; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ // Class header file. #include "XercesParserLiaison.hpp" #include <algorithm> #if defined(XALAN_OLD_STREAM_HEADERS) #include <iostream.h> #else #include <iostream> #endif #include <framework/URLInputSource.hpp> #include <parsers/DOMParser.hpp> #include <parsers/SAXParser.hpp> #include <sax/SAXParseException.hpp> #include <Include/XalanAutoPtr.hpp> #include <PlatformSupport/ExecutionContext.hpp> #include <PlatformSupport/STLHelper.hpp> #include <PlatformSupport/XalanUnicode.hpp> #include <DOMSupport/DOMSupport.hpp> #include "XercesDOMSupport.hpp" #include "XercesDocumentBridge.hpp" static const XalanDOMChar theDefaultSpecialCharacters[] = { XalanUnicode::charLessThanSign, XalanUnicode::charGreaterThanSign, XalanUnicode::charAmpersand, XalanUnicode::charApostrophe, XalanUnicode::charQuoteMark, XalanUnicode::charCR, XalanUnicode::charLF, 0 }; XercesParserLiaison::XercesParserLiaison(XercesDOMSupport& theSupport) : m_DOMSupport(theSupport), m_specialCharacters(theDefaultSpecialCharacters), m_indent(-1), m_shouldExpandEntityRefs(true), m_useValidation(false), m_includeIgnorableWhitespace(true), m_doNamespaces(true), m_exitOnFirstFatalError(true), m_entityResolver(0), m_errorHandler(this), m_documentMap(), m_buildBridge(true), m_threadSafe(false), m_executionContext(0) { } XercesParserLiaison::~XercesParserLiaison() { reset(); } void XercesParserLiaison::reset() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Delete any live documents. for_each(m_documentMap.begin(), m_documentMap.end(), makeMapValueDeleteFunctor(m_documentMap)); m_documentMap.clear(); m_DOMSupport.reset(); m_executionContext = 0; } ExecutionContext* XercesParserLiaison::getExecutionContext() const { return m_executionContext; } void XercesParserLiaison::setExecutionContext(ExecutionContext& theContext) { m_executionContext = &theContext; } bool XercesParserLiaison::supportsSAX() const { return true; } void XercesParserLiaison::parseXMLStream( const InputSource& urlInputSource, DocumentHandler& handler, const XalanDOMString& /* identifier */) { XalanAutoPtr<SAXParser> theParser(CreateSAXParser()); theParser->setDocumentHandler(&handler); theParser->parse(urlInputSource); } XalanDocument* XercesParserLiaison::parseXMLStream( const InputSource& reader, const XalanDOMString& /* identifier */) { XalanAutoPtr<DOMParser> theParser(CreateDOMParser()); theParser->parse(reader); const DOM_Document theXercesDocument = theParser->getDocument(); XercesDocumentBridge* theNewDocument = 0; if (theXercesDocument.isNull() == false) { theNewDocument = createDocument(theXercesDocument, m_threadSafe, m_buildBridge); m_documentMap[theNewDocument] = theNewDocument; } return theNewDocument; } XalanDocument* XercesParserLiaison::createDocument() { const DOM_Document theXercesDocument = DOM_Document::createDocument(); return createDocument(theXercesDocument, false, false); } XalanDocument* XercesParserLiaison::createDOMFactory() { return createDocument(); } void XercesParserLiaison::destroyDocument(XalanDocument* theDocument) { if (mapDocument(theDocument) != 0) { m_documentMap.erase(theDocument); delete theDocument; } } void XercesParserLiaison::setSpecialCharacters(const XalanDOMString& str) { m_specialCharacters = str; } const XalanDOMString& XercesParserLiaison::getSpecialCharacters() const { return m_specialCharacters; } int XercesParserLiaison::getIndent() const { return m_indent; } void XercesParserLiaison::setIndent(int i) { m_indent = i; } bool XercesParserLiaison::getShouldExpandEntityRefs() const { return m_shouldExpandEntityRefs; } void XercesParserLiaison::SetShouldExpandEntityRefs(bool b) { m_shouldExpandEntityRefs = b; } bool XercesParserLiaison::getUseValidation() const { return m_useValidation; } void XercesParserLiaison::setUseValidation(bool b) { m_useValidation = b; } const XalanDOMString XercesParserLiaison::getParserDescription() const { return XALAN_STATIC_UCODE_STRING("Xerces"); } bool XercesParserLiaison::getIncludeIgnorableWhitespace() const { return m_includeIgnorableWhitespace; } void XercesParserLiaison::setIncludeIgnorableWhitespace(bool include) { m_includeIgnorableWhitespace = include; } ErrorHandler* XercesParserLiaison::getErrorHandler() { return m_errorHandler; } const ErrorHandler* XercesParserLiaison::getErrorHandler() const { return m_errorHandler; } void XercesParserLiaison::setErrorHandler(ErrorHandler* handler) { assert(handler != 0); m_errorHandler = handler; } bool XercesParserLiaison::getDoNamespaces() const { return m_doNamespaces; } void XercesParserLiaison::setDoNamespaces(bool newState) { m_doNamespaces = newState; } bool XercesParserLiaison::getExitOnFirstFatalError() const { return m_exitOnFirstFatalError; } void XercesParserLiaison::setExitOnFirstFatalError(bool newState) { m_exitOnFirstFatalError = newState; } EntityResolver* XercesParserLiaison::getEntityResolver() { return m_entityResolver; } const EntityResolver* XercesParserLiaison::getEntityResolver() const { return m_entityResolver; } void XercesParserLiaison::setEntityResolver(EntityResolver* resolver) { m_entityResolver = resolver; } XalanDocument* XercesParserLiaison::createDocument(const DOM_Document& theXercesDocument) { return createDocument(theXercesDocument, false, false); } XercesDocumentBridge* XercesParserLiaison::mapDocument(const XalanDocument* theDocument) const { const DocumentMapType::const_iterator i = m_documentMap.find(theDocument); return i != m_documentMap.end() ? (*i).second : 0; } DOM_Document XercesParserLiaison::mapXercesDocument(const XalanDocument* theDocument) const { const DocumentMapType::const_iterator i = m_documentMap.find(theDocument); return i != m_documentMap.end() ? (*i).second->getXercesDocument() : DOM_Document(); } void XercesParserLiaison::fatalError(const SAXParseException& e) { XalanDOMString theMessage("Fatal Error"); formatErrorMessage(e, theMessage); if (m_executionContext != 0) { // We call warning() because we don't want the execution // context to potentially throw an exception. m_executionContext->warn(theMessage); } else { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; #endif cerr << endl << theMessage << endl; } throw e; } void XercesParserLiaison::error(const SAXParseException& e) { XalanDOMString theMessage("Error "); formatErrorMessage(e, theMessage); if (m_executionContext != 0) { // We call warn() because we don't want the execution // context to potentially throw an exception. m_executionContext->warn(theMessage); } else { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; #endif cerr << endl << theMessage << endl; } } void XercesParserLiaison::warning(const SAXParseException& e) { XalanDOMString theMessage("Warning "); formatErrorMessage(e, theMessage); if (m_executionContext != 0) { m_executionContext->warn(theMessage); } else { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; #endif cerr << endl << theMessage << endl; } } void XercesParserLiaison::formatErrorMessage(const SAXParseException& e, XalanDOMString& theMessage) { append(theMessage, " at (file "); append(theMessage, e.getSystemId()); append(theMessage, ", line "); append(theMessage, LongToDOMString(long(e.getLineNumber()))); append(theMessage, ", column "); append(theMessage, LongToDOMString(long(e.getColumnNumber()))); append(theMessage, "): "); append(theMessage, e.getMessage()); } void XercesParserLiaison::resetErrors() { } DOMParser* XercesParserLiaison::CreateDOMParser() { DOMParser* const theParser = new DOMParser; theParser->setExpandEntityReferences(m_shouldExpandEntityRefs); theParser->setDoValidation(m_useValidation); theParser->setIncludeIgnorableWhitespace(m_includeIgnorableWhitespace); theParser->setDoNamespaces(m_doNamespaces); theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError); if (m_entityResolver != 0) { theParser->setEntityResolver(m_entityResolver); } theParser->setErrorHandler(m_errorHandler); return theParser; } SAXParser* XercesParserLiaison::CreateSAXParser() { SAXParser* const theParser = new SAXParser; theParser->setDoValidation(m_useValidation); // $$$ ToDo: For the time being, we cannot process namespaces // with SAX due to the age of Xerces' SAX interfaces. // theParser->setDoNamespaces(m_doNamespaces); theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError); if (m_entityResolver != 0) { theParser->setEntityResolver(m_entityResolver); } theParser->setErrorHandler(m_errorHandler); return theParser; } XercesDocumentBridge* XercesParserLiaison::createDocument( const DOM_Document& theXercesDocument, bool threadSafe, bool buildBridge) { XercesDocumentBridge* const theNewDocument = new XercesDocumentBridge(theXercesDocument, threadSafe, buildBridge); m_documentMap[theNewDocument] = theNewDocument; return theNewDocument; } <commit_msg>Turn off xml decl nodes.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ // Class header file. #include "XercesParserLiaison.hpp" #include <algorithm> #if defined(XALAN_OLD_STREAM_HEADERS) #include <iostream.h> #else #include <iostream> #endif #include <framework/URLInputSource.hpp> #include <parsers/DOMParser.hpp> #include <parsers/SAXParser.hpp> #include <sax/SAXParseException.hpp> #include <Include/XalanAutoPtr.hpp> #include <PlatformSupport/ExecutionContext.hpp> #include <PlatformSupport/STLHelper.hpp> #include <PlatformSupport/XalanUnicode.hpp> #include <DOMSupport/DOMSupport.hpp> #include "XercesDOMSupport.hpp" #include "XercesDocumentBridge.hpp" static const XalanDOMChar theDefaultSpecialCharacters[] = { XalanUnicode::charLessThanSign, XalanUnicode::charGreaterThanSign, XalanUnicode::charAmpersand, XalanUnicode::charApostrophe, XalanUnicode::charQuoteMark, XalanUnicode::charCR, XalanUnicode::charLF, 0 }; XercesParserLiaison::XercesParserLiaison(XercesDOMSupport& theSupport) : m_DOMSupport(theSupport), m_specialCharacters(theDefaultSpecialCharacters), m_indent(-1), m_shouldExpandEntityRefs(true), m_useValidation(false), m_includeIgnorableWhitespace(true), m_doNamespaces(true), m_exitOnFirstFatalError(true), m_entityResolver(0), m_errorHandler(this), m_documentMap(), m_buildBridge(true), m_threadSafe(false), m_executionContext(0) { } XercesParserLiaison::~XercesParserLiaison() { reset(); } void XercesParserLiaison::reset() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Delete any live documents. for_each(m_documentMap.begin(), m_documentMap.end(), makeMapValueDeleteFunctor(m_documentMap)); m_documentMap.clear(); m_DOMSupport.reset(); m_executionContext = 0; } ExecutionContext* XercesParserLiaison::getExecutionContext() const { return m_executionContext; } void XercesParserLiaison::setExecutionContext(ExecutionContext& theContext) { m_executionContext = &theContext; } bool XercesParserLiaison::supportsSAX() const { return true; } void XercesParserLiaison::parseXMLStream( const InputSource& urlInputSource, DocumentHandler& handler, const XalanDOMString& /* identifier */) { XalanAutoPtr<SAXParser> theParser(CreateSAXParser()); theParser->setDocumentHandler(&handler); theParser->parse(urlInputSource); } XalanDocument* XercesParserLiaison::parseXMLStream( const InputSource& reader, const XalanDOMString& /* identifier */) { XalanAutoPtr<DOMParser> theParser(CreateDOMParser()); theParser->parse(reader); const DOM_Document theXercesDocument = theParser->getDocument(); XercesDocumentBridge* theNewDocument = 0; if (theXercesDocument.isNull() == false) { theNewDocument = createDocument(theXercesDocument, m_threadSafe, m_buildBridge); m_documentMap[theNewDocument] = theNewDocument; } return theNewDocument; } XalanDocument* XercesParserLiaison::createDocument() { const DOM_Document theXercesDocument = DOM_Document::createDocument(); return createDocument(theXercesDocument, false, false); } XalanDocument* XercesParserLiaison::createDOMFactory() { return createDocument(); } void XercesParserLiaison::destroyDocument(XalanDocument* theDocument) { if (mapDocument(theDocument) != 0) { m_documentMap.erase(theDocument); delete theDocument; } } void XercesParserLiaison::setSpecialCharacters(const XalanDOMString& str) { m_specialCharacters = str; } const XalanDOMString& XercesParserLiaison::getSpecialCharacters() const { return m_specialCharacters; } int XercesParserLiaison::getIndent() const { return m_indent; } void XercesParserLiaison::setIndent(int i) { m_indent = i; } bool XercesParserLiaison::getShouldExpandEntityRefs() const { return m_shouldExpandEntityRefs; } void XercesParserLiaison::SetShouldExpandEntityRefs(bool b) { m_shouldExpandEntityRefs = b; } bool XercesParserLiaison::getUseValidation() const { return m_useValidation; } void XercesParserLiaison::setUseValidation(bool b) { m_useValidation = b; } const XalanDOMString XercesParserLiaison::getParserDescription() const { return XALAN_STATIC_UCODE_STRING("Xerces"); } bool XercesParserLiaison::getIncludeIgnorableWhitespace() const { return m_includeIgnorableWhitespace; } void XercesParserLiaison::setIncludeIgnorableWhitespace(bool include) { m_includeIgnorableWhitespace = include; } ErrorHandler* XercesParserLiaison::getErrorHandler() { return m_errorHandler; } const ErrorHandler* XercesParserLiaison::getErrorHandler() const { return m_errorHandler; } void XercesParserLiaison::setErrorHandler(ErrorHandler* handler) { assert(handler != 0); m_errorHandler = handler; } bool XercesParserLiaison::getDoNamespaces() const { return m_doNamespaces; } void XercesParserLiaison::setDoNamespaces(bool newState) { m_doNamespaces = newState; } bool XercesParserLiaison::getExitOnFirstFatalError() const { return m_exitOnFirstFatalError; } void XercesParserLiaison::setExitOnFirstFatalError(bool newState) { m_exitOnFirstFatalError = newState; } EntityResolver* XercesParserLiaison::getEntityResolver() { return m_entityResolver; } const EntityResolver* XercesParserLiaison::getEntityResolver() const { return m_entityResolver; } void XercesParserLiaison::setEntityResolver(EntityResolver* resolver) { m_entityResolver = resolver; } XalanDocument* XercesParserLiaison::createDocument(const DOM_Document& theXercesDocument) { return createDocument(theXercesDocument, false, false); } XercesDocumentBridge* XercesParserLiaison::mapDocument(const XalanDocument* theDocument) const { const DocumentMapType::const_iterator i = m_documentMap.find(theDocument); return i != m_documentMap.end() ? (*i).second : 0; } DOM_Document XercesParserLiaison::mapXercesDocument(const XalanDocument* theDocument) const { const DocumentMapType::const_iterator i = m_documentMap.find(theDocument); return i != m_documentMap.end() ? (*i).second->getXercesDocument() : DOM_Document(); } void XercesParserLiaison::fatalError(const SAXParseException& e) { XalanDOMString theMessage("Fatal Error"); formatErrorMessage(e, theMessage); if (m_executionContext != 0) { // We call warning() because we don't want the execution // context to potentially throw an exception. m_executionContext->warn(theMessage); } else { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; #endif cerr << endl << theMessage << endl; } throw e; } void XercesParserLiaison::error(const SAXParseException& e) { XalanDOMString theMessage("Error "); formatErrorMessage(e, theMessage); if (m_executionContext != 0) { // We call warn() because we don't want the execution // context to potentially throw an exception. m_executionContext->warn(theMessage); } else { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; #endif cerr << endl << theMessage << endl; } } void XercesParserLiaison::warning(const SAXParseException& e) { XalanDOMString theMessage("Warning "); formatErrorMessage(e, theMessage); if (m_executionContext != 0) { m_executionContext->warn(theMessage); } else { #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::endl; #endif cerr << endl << theMessage << endl; } } void XercesParserLiaison::formatErrorMessage(const SAXParseException& e, XalanDOMString& theMessage) { append(theMessage, " at (file "); append(theMessage, e.getSystemId()); append(theMessage, ", line "); append(theMessage, LongToDOMString(long(e.getLineNumber()))); append(theMessage, ", column "); append(theMessage, LongToDOMString(long(e.getColumnNumber()))); append(theMessage, "): "); append(theMessage, e.getMessage()); } void XercesParserLiaison::resetErrors() { } DOMParser* XercesParserLiaison::CreateDOMParser() { DOMParser* const theParser = new DOMParser; theParser->setExpandEntityReferences(m_shouldExpandEntityRefs); theParser->setDoValidation(m_useValidation); theParser->setIncludeIgnorableWhitespace(m_includeIgnorableWhitespace); theParser->setDoNamespaces(m_doNamespaces); theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError); if (m_entityResolver != 0) { theParser->setEntityResolver(m_entityResolver); } theParser->setErrorHandler(m_errorHandler); // Xerces has a non-standard node type to represent the XML decl. // Why did they ever do this? theParser->setToCreateXMLDeclTypeNode(false); return theParser; } SAXParser* XercesParserLiaison::CreateSAXParser() { SAXParser* const theParser = new SAXParser; theParser->setDoValidation(m_useValidation); // $$$ ToDo: For the time being, we cannot process namespaces // with SAX due to the age of Xerces' SAX interfaces. // theParser->setDoNamespaces(m_doNamespaces); theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError); if (m_entityResolver != 0) { theParser->setEntityResolver(m_entityResolver); } theParser->setErrorHandler(m_errorHandler); return theParser; } XercesDocumentBridge* XercesParserLiaison::createDocument( const DOM_Document& theXercesDocument, bool threadSafe, bool buildBridge) { XercesDocumentBridge* const theNewDocument = new XercesDocumentBridge(theXercesDocument, threadSafe, buildBridge); m_documentMap[theNewDocument] = theNewDocument; return theNewDocument; } <|endoftext|>
<commit_before>/* This file is part of the Palabos library. * * Copyright (C) 2011-2015 FlowKit Sarl * Route d'Oron 2 * 1010 Lausanne, Switzerland * E-mail contact: contact@flowkit.com * * The most recent release of Palabos can be downloaded at * <http://www.palabos.org/> * * The library Palabos 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. * * The 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 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/>. */ /** \file * Flow in a lid-driven 3D cavity. The cavity is square and has no-slip walls, * except for the top wall which is diagonally driven with a constant * velocity. The benchmark is challenging because of the velocity * discontinuities on corner nodes. **/ #include "palabos3D.h" #include "palabos3D.hh" #include <vector> #include <cmath> #include <iostream> #include <fstream> using namespace plb; using namespace std; typedef double T; #define DESCRIPTOR descriptors::D3Q19Descriptor void cavitySetup( MultiBlockLattice3D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition3D<T,DESCRIPTOR>& boundaryCondition ) { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); const plint nz = parameters.getNz(); Box3D topLid = Box3D(0, nx-1, ny-1, ny-1, 0, nz-1); Box3D everythingButTopLid = Box3D(0, nx-1, 0, ny-2, 0, nz-1); // All walls implement a Dirichlet velocity condition. boundaryCondition.setVelocityConditionOnBlockBoundaries(lattice); T u = std::sqrt((T)2)/(T)2 * parameters.getLatticeU(); initializeAtEquilibrium(lattice, everythingButTopLid, (T)1., Array<T,3>((T)0.,(T)0.,(T)0.) ); initializeAtEquilibrium(lattice, topLid, (T)1., Array<T,3>(u,(T)0.,u) ); setBoundaryVelocity(lattice, topLid, Array<T,3>(u,(T)0.,u) ); lattice.initialize(); } template<class BlockLatticeT> void writeGifs(BlockLatticeT& lattice, IncomprFlowParam<T> const& parameters, plint iter) { const plint imSize = 600; const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); const plint nz = parameters.getNz(); const plint zComponent = 2; Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2); ImageWriter<T> imageWriter("leeloo"); imageWriter.writeScaledGif( createFileName("uz", iter, 6), *computeVelocityComponent (lattice, slice, zComponent), imSize, imSize ); imageWriter.writeScaledGif( createFileName("uNorm", iter, 6), *computeVelocityNorm (lattice, slice), imSize, imSize ); imageWriter.writeScaledGif( createFileName("omega", iter, 6), *computeNorm(*computeVorticity ( *computeVelocity(lattice) ), slice ), imSize, imSize ); } template<class BlockLatticeT> void writeVTK(BlockLatticeT& lattice, IncomprFlowParam<T> const& parameters, plint iter) { T dx = parameters.getDeltaX(); T dt = parameters.getDeltaT(); VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), dx); vtkOut.writeData<float>(*computeVelocityNorm(lattice), "velocityNorm", dx/dt); vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", dx/dt); vtkOut.writeData<3,float>(*computeVorticity(*computeVelocity(lattice)), "vorticity", 1./dt); } SparseBlockStructure3D createRegularDistribution3D ( std::vector<plint> const& xVal, std::vector<plint> const& yVal, std::vector<plint> const& zVal ) { PLB_ASSERT(xVal.size()>=2); PLB_ASSERT(yVal.size()>=2); PLB_ASSERT(zVal.size()>=2); SparseBlockStructure3D dataGeometry ( Box3D(xVal[0], xVal.back()-1, yVal[0], yVal.back()-1, zVal[0], zVal.back()-1) ); for (plint iX=0; iX<(plint)xVal.size()-1; ++iX) { for (plint iY=0; iY<(plint)yVal.size()-1; ++iY) { for (plint iZ=0; iZ<(plint)zVal.size()-1; ++iZ) { plint nextID = dataGeometry.nextIncrementalId(); Box3D domain( xVal[iX], xVal[iX+1]-1, yVal[iY], yVal[iY+1]-1, zVal[iZ], zVal[iZ+1]-1 ); dataGeometry.addBlock(domain, nextID); pcout << "Adding block with ID=" << nextID << ": [" << domain.x0 << "," << domain.x1 << " | " << domain.y0 << "," << domain.y1 << " | " << domain.z0 << "," << domain.z1 << "]" << std::endl; } } } return dataGeometry; } SparseBlockStructure3D createCavityDistribution3D(plint nx, plint ny, plint nz) { static const plint numval=4; plint x[numval] = {0, nx/4, 3*nx/4, nx}; plint y[numval] = {0, ny/4, 3*ny/4, ny}; plint z[numval] = {0, nz/4, 3*nz/4, nz}; std::vector<plint> xVal(x, x+numval); std::vector<plint> yVal(y, y+numval); std::vector<plint> zVal(z, z+numval); return createRegularDistribution3D(xVal, yVal, zVal); } void saveAtomicBlock(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint blockId) { BlockLattice3D<T,DESCRIPTOR>& atomicBlock = lattice.getComponent(blockId); plb_ofstream ofile("block13.dat"); ofile << atomicBlock; } int main(int argc, char* argv[]) { plbInit(&argc, &argv); global::directories().setOutputDir("./tmp/"); IncomprFlowParam<T> parameters( (T) 1e-4, // uMax (T) 10., // Re 30, // N 1., // lx 1., // ly 1. // lz ); const T logT = (T)1/(T)1000; const T imSave = (T)1/(T)40; const T vtkSave = (T)1; const T maxT = (T)10.1; pcout << "omega= " << parameters.getOmega() << std::endl; writeLogFile(parameters, "3D diagonal cavity"); // @Tomasz: STEP 1 // Instead of simply creating a MultiBlockLattice3D as usual, the internal // structure and parallelization of the block are created manually. The block // is covered by 5x5x5 sub-domains. Each of these 125 sub-domains, if it // contains no boundary area (i.e. only pure BGK), will then be off-loaded to // the co-processor. pcout << "Taille du domaine: " << parameters.getNx() << " x " << parameters.getNy() << " x " << parameters.getNz() << std::endl; // Here the 5x5x5 cover-up is instantiated. plint numBlocksX = 3; plint numBlocksY = 3; plint numBlocksZ = 3; plint numBlocks = numBlocksX*numBlocksY*numBlocksZ; plint envelopeWidth = 1; SparseBlockStructure3D blockStructure ( createCavityDistribution3D ( parameters.getNx(), parameters.getNy(), parameters.getNz() ) ); // In case of MPI parallelism, the blocks are explicitly assigned to processors, // with equal load. ExplicitThreadAttribution* threadAttribution = new ExplicitThreadAttribution; std::vector<std::pair<plint,plint> > ranges; plint numRanges = std::min(numBlocks, (plint)global::mpi().getSize()); util::linearRepartition(0, numBlocks-1, numRanges, ranges); for (pluint iProc=0; iProc<ranges.size(); ++iProc) { for (plint blockId=ranges[iProc].first; blockId<=ranges[iProc].second; ++blockId) { threadAttribution -> addBlock(blockId, iProc); } } // Create a lattice with the above specified internal structure. MultiBlockLattice3D<T, DESCRIPTOR> lattice ( MultiBlockManagement3D ( blockStructure, threadAttribution, envelopeWidth ), defaultMultiBlockPolicy3D().getBlockCommunicator(), defaultMultiBlockPolicy3D().getCombinedStatistics(), defaultMultiBlockPolicy3D().getMultiCellAccess<T,DESCRIPTOR>(), new BGKdynamics<T,DESCRIPTOR>(parameters.getOmega()) ); saveAtomicBlock(lattice, 13); OnLatticeBoundaryCondition3D<T,DESCRIPTOR>* boundaryCondition = createInterpBoundaryCondition3D<T,DESCRIPTOR>(); cavitySetup(lattice, parameters, *boundaryCondition); // @Tomasz: STEP 2 // Here the co-processor is informed about the domains for which it will need to do computations. bool printInfo=true; initiateCoProcessors(lattice, BGKdynamics<T,DESCRIPTOR>(parameters.getOmega()).getId(), printInfo); T previousIterationTime = T(); // Loop over main time iteration. for (plint iT=0; iT<parameters.nStep(maxT); ++iT) { global::timer("mainLoop").restart(); if (iT%parameters.nStep(imSave)==0) { pcout << "Writing Gif ..." << endl; writeGifs(lattice, parameters, iT); } if (iT%parameters.nStep(vtkSave)==0 && iT>0) { pcout << "Saving VTK file ..." << endl; writeVTK(lattice, parameters, iT); } if (iT%parameters.nStep(logT)==0) { pcout << "step " << iT << "; t=" << iT*parameters.getDeltaT(); } // @Tomasz: STEP 3 // For now, all the data assigned to co-processors is transferred from CPU memory // to co-processor memory before the collision-streaming step, and back to CPU // memory after the collision-streaming step. This is not efficient at all: we // will replace this by communicating outer boundary layers only. It is however // simpler for now, for our first proof of concept. // Execute a time iteration. transferToCoProcessors(lattice); lattice.collideAndStream(); transferFromCoProcessors(lattice); // After transferring back from co-processor to CPU memory, data in the envelopes // of the CPU blocks must be synchronized. lattice.duplicateOverlaps(modif::staticVariables); // Access averages from internal statistics ( their value is defined // only after the call to lattice.collideAndStream() ) if (iT%parameters.nStep(logT)==0) { pcout << "; av energy=" << setprecision(10) << computeAverageEnergy<T>(lattice) << "; av rho=" << setprecision(10) << computeAverageDensity<T>(lattice) << endl; pcout << "Time spent during previous iteration: " << previousIterationTime << endl; } previousIterationTime = global::timer("mainLoop").stop(); } delete boundaryCondition; } <commit_msg>autre simplification<commit_after>/* This file is part of the Palabos library. * * Copyright (C) 2011-2015 FlowKit Sarl * Route d'Oron 2 * 1010 Lausanne, Switzerland * E-mail contact: contact@flowkit.com * * The most recent release of Palabos can be downloaded at * <http://www.palabos.org/> * * The library Palabos 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. * * The 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 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/>. */ /** \file * Flow in a lid-driven 3D cavity. The cavity is square and has no-slip walls, * except for the top wall which is diagonally driven with a constant * velocity. The benchmark is challenging because of the velocity * discontinuities on corner nodes. **/ #include "palabos3D.h" #include "palabos3D.hh" #include <vector> #include <cmath> #include <iostream> #include <fstream> using namespace plb; using namespace std; typedef double T; #define DESCRIPTOR descriptors::D3Q19Descriptor void cavitySetup( MultiBlockLattice3D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition3D<T,DESCRIPTOR>& boundaryCondition ) { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); const plint nz = parameters.getNz(); Box3D topLid = Box3D(0, nx-1, ny-1, ny-1, 0, nz-1); Box3D everythingButTopLid = Box3D(0, nx-1, 0, ny-2, 0, nz-1); // All walls implement a Dirichlet velocity condition. boundaryCondition.setVelocityConditionOnBlockBoundaries(lattice); T u = std::sqrt((T)2)/(T)2 * parameters.getLatticeU(); initializeAtEquilibrium(lattice, everythingButTopLid, (T)1., Array<T,3>((T)0.,(T)0.,(T)0.) ); initializeAtEquilibrium(lattice, topLid, (T)1., Array<T,3>(u,(T)0.,u) ); setBoundaryVelocity(lattice, topLid, Array<T,3>(u,(T)0.,u) ); lattice.initialize(); } template<class BlockLatticeT> void writeGifs(BlockLatticeT& lattice, IncomprFlowParam<T> const& parameters, plint iter) { const plint imSize = 600; const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); const plint nz = parameters.getNz(); const plint zComponent = 2; Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2); ImageWriter<T> imageWriter("leeloo"); //imageWriter.writeScaledGif( createFileName("uz", iter, 6), // *computeVelocityComponent (lattice, slice, zComponent), // imSize, imSize ); imageWriter.writeScaledGif( createFileName("uNorm", iter, 6), *computeVelocityNorm (lattice, slice), imSize, imSize ); //imageWriter.writeScaledGif( createFileName("omega", iter, 6), // *computeNorm(*computeVorticity ( // *computeVelocity(lattice) ), slice ), // imSize, imSize ); } template<class BlockLatticeT> void writeVTK(BlockLatticeT& lattice, IncomprFlowParam<T> const& parameters, plint iter) { T dx = parameters.getDeltaX(); T dt = parameters.getDeltaT(); VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), dx); vtkOut.writeData<float>(*computeVelocityNorm(lattice), "velocityNorm", dx/dt); vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", dx/dt); vtkOut.writeData<3,float>(*computeVorticity(*computeVelocity(lattice)), "vorticity", 1./dt); } SparseBlockStructure3D createRegularDistribution3D ( std::vector<plint> const& xVal, std::vector<plint> const& yVal, std::vector<plint> const& zVal ) { PLB_ASSERT(xVal.size()>=2); PLB_ASSERT(yVal.size()>=2); PLB_ASSERT(zVal.size()>=2); SparseBlockStructure3D dataGeometry ( Box3D(xVal[0], xVal.back()-1, yVal[0], yVal.back()-1, zVal[0], zVal.back()-1) ); for (plint iX=0; iX<(plint)xVal.size()-1; ++iX) { for (plint iY=0; iY<(plint)yVal.size()-1; ++iY) { for (plint iZ=0; iZ<(plint)zVal.size()-1; ++iZ) { plint nextID = dataGeometry.nextIncrementalId(); Box3D domain( xVal[iX], xVal[iX+1]-1, yVal[iY], yVal[iY+1]-1, zVal[iZ], zVal[iZ+1]-1 ); dataGeometry.addBlock(domain, nextID); pcout << "Adding block with ID=" << nextID << ": [" << domain.x0 << "," << domain.x1 << " | " << domain.y0 << "," << domain.y1 << " | " << domain.z0 << "," << domain.z1 << "]" << std::endl; } } } return dataGeometry; } SparseBlockStructure3D createCavityDistribution3D(plint nx, plint ny, plint nz) { static const plint numval=4; plint x[numval] = {0, nx/4, 3*nx/4, nx}; plint y[numval] = {0, ny/4, 3*ny/4, ny}; plint z[numval] = {0, nz/4, 3*nz/4, nz}; std::vector<plint> xVal(x, x+numval); std::vector<plint> yVal(y, y+numval); std::vector<plint> zVal(z, z+numval); return createRegularDistribution3D(xVal, yVal, zVal); } void saveAtomicBlock(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint blockId) { BlockLattice3D<T,DESCRIPTOR>& atomicBlock = lattice.getComponent(blockId); plb_ofstream ofile("block13.dat"); ofile << atomicBlock; } int main(int argc, char* argv[]) { plbInit(&argc, &argv); global::directories().setOutputDir("./tmp/"); IncomprFlowParam<T> parameters( (T) 1e-4, // uMax (T) 10., // Re 30, // N 1., // lx 1., // ly 1. // lz ); const T logT = (T)1/(T)1000; const T imSave = (T)1/(T)40; const T vtkSave = (T)1; const T maxT = (T)10.1; pcout << "omega= " << parameters.getOmega() << std::endl; writeLogFile(parameters, "3D diagonal cavity"); // @Tomasz: STEP 1 // Instead of simply creating a MultiBlockLattice3D as usual, the internal // structure and parallelization of the block are created manually. The block // is covered by 5x5x5 sub-domains. Each of these 125 sub-domains, if it // contains no boundary area (i.e. only pure BGK), will then be off-loaded to // the co-processor. pcout << "Taille du domaine: " << parameters.getNx() << " x " << parameters.getNy() << " x " << parameters.getNz() << std::endl; // Here the 5x5x5 cover-up is instantiated. plint numBlocksX = 3; plint numBlocksY = 3; plint numBlocksZ = 3; plint numBlocks = numBlocksX*numBlocksY*numBlocksZ; plint envelopeWidth = 1; SparseBlockStructure3D blockStructure ( createCavityDistribution3D ( parameters.getNx(), parameters.getNy(), parameters.getNz() ) ); // In case of MPI parallelism, the blocks are explicitly assigned to processors, // with equal load. ExplicitThreadAttribution* threadAttribution = new ExplicitThreadAttribution; std::vector<std::pair<plint,plint> > ranges; plint numRanges = std::min(numBlocks, (plint)global::mpi().getSize()); util::linearRepartition(0, numBlocks-1, numRanges, ranges); for (pluint iProc=0; iProc<ranges.size(); ++iProc) { for (plint blockId=ranges[iProc].first; blockId<=ranges[iProc].second; ++blockId) { threadAttribution -> addBlock(blockId, iProc); } } // Create a lattice with the above specified internal structure. MultiBlockLattice3D<T, DESCRIPTOR> lattice ( MultiBlockManagement3D ( blockStructure, threadAttribution, envelopeWidth ), defaultMultiBlockPolicy3D().getBlockCommunicator(), defaultMultiBlockPolicy3D().getCombinedStatistics(), defaultMultiBlockPolicy3D().getMultiCellAccess<T,DESCRIPTOR>(), new BGKdynamics<T,DESCRIPTOR>(parameters.getOmega()) ); saveAtomicBlock(lattice, 13); OnLatticeBoundaryCondition3D<T,DESCRIPTOR>* boundaryCondition = createInterpBoundaryCondition3D<T,DESCRIPTOR>(); cavitySetup(lattice, parameters, *boundaryCondition); // @Tomasz: STEP 2 // Here the co-processor is informed about the domains for which it will need to do computations. bool printInfo=true; initiateCoProcessors(lattice, BGKdynamics<T,DESCRIPTOR>(parameters.getOmega()).getId(), printInfo); T previousIterationTime = T(); // Loop over main time iteration. for (plint iT=0; iT<parameters.nStep(maxT); ++iT) { global::timer("mainLoop").restart(); if (iT%parameters.nStep(imSave)==0) { pcout << "Writing Gif ..." << endl; writeGifs(lattice, parameters, iT); } if (iT%parameters.nStep(vtkSave)==0 && iT>0) { pcout << "Saving VTK file ..." << endl; writeVTK(lattice, parameters, iT); } if (iT%parameters.nStep(logT)==0) { pcout << "step " << iT << "; t=" << iT*parameters.getDeltaT(); } // @Tomasz: STEP 3 // For now, all the data assigned to co-processors is transferred from CPU memory // to co-processor memory before the collision-streaming step, and back to CPU // memory after the collision-streaming step. This is not efficient at all: we // will replace this by communicating outer boundary layers only. It is however // simpler for now, for our first proof of concept. // Execute a time iteration. transferToCoProcessors(lattice); lattice.collideAndStream(); transferFromCoProcessors(lattice); // After transferring back from co-processor to CPU memory, data in the envelopes // of the CPU blocks must be synchronized. lattice.duplicateOverlaps(modif::staticVariables); // Access averages from internal statistics ( their value is defined // only after the call to lattice.collideAndStream() ) if (iT%parameters.nStep(logT)==0) { pcout << "; av energy=" << setprecision(10) << computeAverageEnergy<T>(lattice) << "; av rho=" << setprecision(10) << computeAverageDensity<T>(lattice) << endl; pcout << "Time spent during previous iteration: " << previousIterationTime << endl; } previousIterationTime = global::timer("mainLoop").stop(); } delete boundaryCondition; } <|endoftext|>
<commit_before>#include<cstdio> void num2str(int n) { char buffer[50]; int i = 0; bool isNeg = n<0; unsigned int n1 = isNeg ? -n : n; while(n1!=0) { buffer[i++] = n1%10+'0'; n1=n1/10; } if(isNeg) buffer[i++] = '-'; buffer[i] = '\0'; for(int t = 0; t < i/2; t++) { buffer[t] ^= buffer[i-t-1]; buffer[i-t-1] ^= buffer[t]; buffer[t] ^= buffer[i-t-1]; } if(n == 0) { buffer[0] = '0'; buffer[1] = '\0'; } printf("%s\n", buffer); } int main() { // your code goes here num2str(-1); num2str(-0); num2str(100); num2str(-100); return 0; } <commit_msg>format<commit_after>#include <cstdio> void num2str(int n, char *buffer) { int i = 0; bool isNeg = n < 0; unsigned int n1 = isNeg ? -n : n; while (n1 != 0) { buffer[i++] = n1 % 10 + '0'; n1 = n1 / 10; } if (isNeg) buffer[i++] = '-'; buffer[i] = '\0'; // reverse the string for (int t = 0; t < i / 2; t++) { buffer[t] ^= buffer[i - t - 1]; buffer[i - t - 1] ^= buffer[t]; buffer[t] ^= buffer[i - t - 1]; } if (n == 0) { buffer[0] = '0'; buffer[1] = '\0'; } printf("%s\n", buffer); } int main() { char buf[50]; num2str(-1, buf); num2str(-0, buf); num2str(100, buf); num2str(-100, buf); return 0; } <|endoftext|>
<commit_before>/** * @file main.cpp * * @author <a href="mailto:xu@informatik.hu-berlin.de">Xu Yuan</a> * */ #include <glib.h> #include <glib-object.h> #include <SimSpark/SimSparkController.h> #include "Cognition.h" #include "Motion.h" using namespace std; // allows for changing the platform name during the compilation #ifndef PLATFORM_NAME #define PLATFORM_NAME SimSpark #endif #define MAKE_STRING(name) #name #define MAKE_NAME(name) MAKE_STRING(name) int main(int argc, char** argv) { g_type_init(); string teamName = "NaoTH"; gchar* optTeamName = NULL; unsigned int num = 0; // zero means get a number from server string server = "localhost"; gchar* optServer = NULL; unsigned int port = 3100; bool sync = false; GOptionEntry entries[] = { {"num",'n', 0, G_OPTION_ARG_INT, &num, "player number", "0"}, {"team", 't', 0, G_OPTION_ARG_STRING, &optTeamName, "team name", "NaoTH"}, {"server", 's', 0, G_OPTION_ARG_STRING, &optServer, "server host", "localhost"}, {"port", 'p', 0, G_OPTION_ARG_INT, &port, "server port", "3100"}, {"sync", 0, 0, G_OPTION_ARG_NONE, &sync, "sync mode", NULL}, {NULL} // This NULL is very important!!! }; GError *error = NULL; GOptionContext *context = g_option_context_new("\n-------------------------------\n http://www.naoth.de"); g_option_context_add_main_entries (context, entries, "NaoTH Simspark controller"); if (!g_option_context_parse (context, &argc, &argv, &error)) { g_print ("option parsing failed: %s\n", error->message); return EXIT_FAILURE; } if ( optTeamName != NULL ) { teamName = optTeamName; g_free(optTeamName); } if ( optServer != NULL ) { server = optServer; g_free(optServer); } g_option_context_free(context); SimSparkController theController(MAKE_NAME(PLATFORM_NAME)); if (!theController.init(teamName, num, server, port, sync)) { cerr << "NaoTH SimSpark initialization failed!" << endl; return EXIT_FAILURE; } Cognition theCognition; Motion theMotion; theController.registerCallbacks(&theMotion, &theCognition); theController.main(); return 0; }//end main <commit_msg>just extended output comment<commit_after>/** * @file main.cpp * * @author <a href="mailto:xu@informatik.hu-berlin.de">Xu Yuan</a> * */ #include <glib.h> #include <glib-object.h> #include <SimSpark/SimSparkController.h> #include "Cognition.h" #include "Motion.h" using namespace std; // allows for changing the platform name during the compilation #ifndef PLATFORM_NAME #define PLATFORM_NAME SimSpark #endif #define MAKE_STRING(name) #name #define MAKE_NAME(name) MAKE_STRING(name) int main(int argc, char** argv) { g_type_init(); string teamName = "NaoTH"; gchar* optTeamName = NULL; unsigned int num = 0; // zero means get a number from server string server = "localhost"; gchar* optServer = NULL; unsigned int port = 3100; bool sync = false; GOptionEntry entries[] = { {"num",'n', 0, G_OPTION_ARG_INT, &num, "player number", "0"}, {"team", 't', 0, G_OPTION_ARG_STRING, &optTeamName, "team name", "NaoTH"}, {"server", 's', 0, G_OPTION_ARG_STRING, &optServer, "server host", "localhost"}, {"port", 'p', 0, G_OPTION_ARG_INT, &port, "server port", "3100"}, {"sync", 0, 0, G_OPTION_ARG_NONE, &sync, "sync mode", NULL}, {NULL} // This NULL is very important!!! }; GError *error = NULL; GOptionContext *context = g_option_context_new("\n-------------------------------\n http://www.naoth.de"); g_option_context_add_main_entries (context, entries, "NaoTH Simspark (SPL) controller"); if (!g_option_context_parse (context, &argc, &argv, &error)) { g_print ("option parsing failed: %s\n", error->message); return EXIT_FAILURE; } if ( optTeamName != NULL ) { teamName = optTeamName; g_free(optTeamName); } if ( optServer != NULL ) { server = optServer; g_free(optServer); } g_option_context_free(context); SimSparkController theController(MAKE_NAME(PLATFORM_NAME)); if (!theController.init(teamName, num, server, port, sync)) { cerr << "NaoTH SimSpark (SPL) initialization failed!" << endl; return EXIT_FAILURE; } Cognition theCognition; Motion theMotion; theController.registerCallbacks(&theMotion, &theCognition); theController.main(); return 0; }//end main <|endoftext|>
<commit_before>/* Copyright (c) by respective owners including Yahoo!, Microsoft, and individual contributors. All rights reserved. Released under a BSD (revised) license as described in the file LICENSE. */ #include <fstream> #include <iostream> using namespace std; #ifndef _WIN32 #include <unistd.h> #endif #include <stdlib.h> #include <stdint.h> #include <math.h> #include <algorithm> #include "parse_regressor.h" #include "loss_functions.h" #include "global_data.h" #include "io_buf.h" #include "rand48.h" /* Define the last version where files are backward compatible. */ #define LAST_COMPATIBLE_VERSION "6.1.3" #define VERSION_FILE_WITH_CUBIC "6.1.3" void initialize_regressor(vw& all) { size_t length = ((size_t)1) << all.num_bits; all.reg.weight_mask = (all.reg.stride * length) - 1; all.reg.weight_vector = (weight *)calloc(all.reg.stride*length, sizeof(weight)); if (all.reg.weight_vector == NULL) { cerr << all.program_name << ": Failed to allocate weight array with " << all.num_bits << " bits: try decreasing -b <bits>" << endl; throw exception(); } if (all.random_weights) { for (size_t j = 0; j < length; j++) all.reg.weight_vector[j*all.reg.stride] = (float)(frand48() - 0.5); } if (all.initial_weight != 0.) for (size_t j = 0; j < all.reg.stride*length; j+=all.reg.stride) all.reg.weight_vector[j] = all.initial_weight; } const size_t buf_size = 512; void save_load_header(vw& all, io_buf& model_file, bool read, bool text) { char buff[buf_size]; char buff2[buf_size]; uint32_t text_len; if (model_file.files.size() > 0) { uint32_t v_length = (uint32_t)version.to_string().length()+1; text_len = sprintf(buff, "Version %s\n", version.to_string().c_str()); memcpy(buff2,version.to_string().c_str(),v_length); if (read) v_length = buf_size; bin_text_read_write(model_file, buff2, v_length, "", read, buff, text_len, text); version_struct v_tmp(buff2); if (v_tmp < LAST_COMPATIBLE_VERSION) { cout << "Model has possibly incompatible version! " << v_tmp.to_string() << endl; throw exception(); } char model = 'm'; bin_text_read_write_fixed(model_file,&model,1, "file is not a model file", read, "", 0, text); text_len = sprintf(buff, "Min label:%f\n", all.sd->min_label); bin_text_read_write_fixed(model_file,(char*)&all.sd->min_label, sizeof(all.sd->min_label), "", read, buff, text_len, text); text_len = sprintf(buff, "Max label:%f\n", all.sd->max_label); bin_text_read_write_fixed(model_file,(char*)&all.sd->max_label, sizeof(all.sd->max_label), "", read, buff, text_len, text); text_len = sprintf(buff, "bits:%d\n", (int)all.num_bits); uint32_t local_num_bits = all.num_bits; bin_text_read_write_fixed(model_file,(char *)&local_num_bits, sizeof(local_num_bits), "", read, buff, text_len, text); if (all.default_bits != true && all.num_bits != local_num_bits) { cout << "Wrong number of bits for source!" << endl; throw exception(); } all.default_bits = false; all.num_bits = local_num_bits; uint32_t pair_len = (uint32_t)all.pairs.size(); text_len = sprintf(buff, "%d pairs: ", (int)pair_len); bin_text_read_write_fixed(model_file,(char *)&pair_len, sizeof(pair_len), "", read, buff, text_len, text); for (size_t i = 0; i < pair_len; i++) { char pair[2]; if (!read) { memcpy(pair,all.pairs[i].c_str(),2); text_len = sprintf(buff, "%s ", all.pairs[i].c_str()); } bin_text_read_write_fixed(model_file, pair,2, "", read, buff, text_len, text); if (read) { string temp(pair, 2); if (count(all.pairs.begin(), all.pairs.end(), temp) == 0) all.pairs.push_back(temp); } } bin_text_read_write_fixed(model_file,buff,0, "", read, "\n",1,text); uint32_t triple_len = (uint32_t)all.triples.size(); text_len = sprintf(buff, "%d triples: ", (int)triple_len); bin_text_read_write_fixed(model_file,(char *)&triple_len, sizeof(triple_len), "", read, buff,text_len, text); for (size_t i = 0; i < triple_len; i++) { char triple[3]; if (!read) { text_len = sprintf(buff, "%s ", all.triples[i].c_str()); memcpy(triple, all.triples[i].c_str(), 3); } bin_text_read_write_fixed(model_file,triple,3, "", read, buff,text_len,text); if (read) { string temp(triple,3); all.triples.push_back(temp); } } bin_text_read_write_fixed(model_file,buff,0, "", read, "\n",1, text); text_len = sprintf(buff, "rank:%d\n", (int)all.rank); bin_text_read_write_fixed(model_file,(char*)&all.rank, sizeof(all.rank), "", read, buff,text_len, text); text_len = sprintf(buff, "lda:%d\n", (int)all.lda); bin_text_read_write_fixed(model_file,(char*)&all.lda, sizeof(all.lda), "", read, buff, text_len,text); uint32_t ngram_len = (uint32_t)all.ngram_strings.size(); text_len = sprintf(buff, "%d ngram: ", (int)ngram_len); bin_text_read_write_fixed(model_file,(char *)&ngram_len, sizeof(ngram_len), "", read, buff,text_len, text); for (size_t i = 0; i < ngram_len; i++) { char ngram[3]; if (!read) { text_len = sprintf(buff, "%s ", all.ngram_strings[i].c_str()); memcpy(ngram, all.ngram_strings[i].c_str(), min(3, all.ngram_strings[i].size())); } bin_text_read_write_fixed(model_file,ngram,3, "", read, buff,text_len,text); if (read) { string temp(ngram,3); all.ngram_strings.push_back(temp); } } if(read) compile_gram(all.ngram_strings, all.ngram, (char*)"grams", all.quiet); bin_text_read_write_fixed(model_file,buff,0, "", read, "\n",1, text); uint32_t skip_len = (uint32_t)all.skip_strings.size(); text_len = sprintf(buff, "%d skip: ", (int)skip_len); bin_text_read_write_fixed(model_file,(char *)&skip_len, sizeof(skip_len), "", read, buff,text_len, text); for (size_t i = 0; i < skip_len; i++) { char skip[3]; if (!read) { text_len = sprintf(buff, "%s ", all.skip_strings[i].c_str()); memcpy(skip, all.skip_strings[i].c_str(), min(3, all.skip_strings[i].size())); } bin_text_read_write_fixed(model_file,skip,3, "", read, buff,text_len,text); if (read) { string temp(skip,3); all.skip_strings.push_back(temp); } } if(read) compile_gram(all.skip_strings, all.skips, (char*)"skips", all.quiet); bin_text_read_write_fixed(model_file,buff,0, "", read, "\n",1, text); text_len = sprintf(buff, "options:%s\n", all.options_from_file.c_str()); uint32_t len = (uint32_t)all.options_from_file.length()+1; memcpy(buff2, all.options_from_file.c_str(),len); if (read) len = buf_size; bin_text_read_write(model_file,buff2, len, "", read, buff, text_len, text); if (read) all.options_from_file.assign(buff2); } } void dump_regressor(vw& all, string reg_name, bool as_text) { if (reg_name == string("")) return; string start_name = reg_name+string(".writing"); io_buf io_temp; io_temp.open_file(start_name.c_str(), all.stdin_off, io_buf::WRITE); save_load_header(all, io_temp, false, as_text); all.l.save_load(io_temp, false, as_text); io_temp.flush(); // close_file() should do this for me ... io_temp.close_file(); remove(reg_name.c_str()); rename(start_name.c_str(),reg_name.c_str()); } void save_predictor(vw& all, string reg_name, size_t current_pass) { char* filename = new char[reg_name.length()+4]; if (all.save_per_pass) sprintf(filename,"%s.%lu",reg_name.c_str(),(long unsigned)current_pass); else sprintf(filename,"%s",reg_name.c_str()); dump_regressor(all, string(filename), false); delete[] filename; } void finalize_regressor(vw& all, string reg_name) { if (all.per_feature_regularizer_output.length() > 0) dump_regressor(all, all.per_feature_regularizer_output, false); else dump_regressor(all, reg_name, false); if (all.per_feature_regularizer_text.length() > 0) dump_regressor(all, all.per_feature_regularizer_text, true); else{ dump_regressor(all, all.text_regressor_name, true); all.print_invert = true; dump_regressor(all, all.inv_hash_regressor_name, true); all.print_invert = false; } } void parse_regressor_args(vw& all, po::variables_map& vm, io_buf& io_temp) { if (vm.count("final_regressor")) { all.final_regressor_name = vm["final_regressor"].as<string>(); if (!all.quiet) cerr << "final_regressor = " << vm["final_regressor"].as<string>() << endl; } else all.final_regressor_name = ""; vector<string> regs; if (vm.count("initial_regressor") || vm.count("i")) regs = vm["initial_regressor"].as< vector<string> >(); if (regs.size() > 0) io_temp.open_file(regs[0].c_str(), all.stdin_off, io_buf::READ); save_load_header(all, io_temp, true, false); } void parse_mask_regressor_args(vw& all, po::variables_map& vm){ if (vm.count("feature_mask")) { size_t length = ((size_t)1) << all.num_bits; string mask_filename = vm["feature_mask"].as<string>(); if (vm.count("initial_regressor")){ vector<string> init_filename = vm["initial_regressor"].as< vector<string> >(); if(mask_filename == init_filename[0]){//-i and -mask are from same file, just generate mask for (size_t j = 0; j < length; j++){ if(all.reg.weight_vector[j*all.reg.stride] != 0.) all.reg.weight_vector[j*all.reg.stride + all.feature_mask_idx] = 1.; } return; } } //all other cases, including from different file, or -i does not exist, need to read in the mask file io_buf io_temp_mask; io_temp_mask.open_file(mask_filename.c_str(), false, io_buf::READ); save_load_header(all, io_temp_mask, true, false); all.l.save_load(io_temp_mask, true, false); io_temp_mask.close_file(); for (size_t j = 0; j < length; j++){ if(all.reg.weight_vector[j*all.reg.stride] != 0.) all.reg.weight_vector[j*all.reg.stride + all.feature_mask_idx] = 1.; } } } <commit_msg>Zero the ngram and skip arrays before use<commit_after>/* Copyright (c) by respective owners including Yahoo!, Microsoft, and individual contributors. All rights reserved. Released under a BSD (revised) license as described in the file LICENSE. */ #include <fstream> #include <iostream> using namespace std; #ifndef _WIN32 #include <unistd.h> #endif #include <stdlib.h> #include <stdint.h> #include <math.h> #include <algorithm> #include "parse_regressor.h" #include "loss_functions.h" #include "global_data.h" #include "io_buf.h" #include "rand48.h" /* Define the last version where files are backward compatible. */ #define LAST_COMPATIBLE_VERSION "6.1.3" #define VERSION_FILE_WITH_CUBIC "6.1.3" void initialize_regressor(vw& all) { size_t length = ((size_t)1) << all.num_bits; all.reg.weight_mask = (all.reg.stride * length) - 1; all.reg.weight_vector = (weight *)calloc(all.reg.stride*length, sizeof(weight)); if (all.reg.weight_vector == NULL) { cerr << all.program_name << ": Failed to allocate weight array with " << all.num_bits << " bits: try decreasing -b <bits>" << endl; throw exception(); } if (all.random_weights) { for (size_t j = 0; j < length; j++) all.reg.weight_vector[j*all.reg.stride] = (float)(frand48() - 0.5); } if (all.initial_weight != 0.) for (size_t j = 0; j < all.reg.stride*length; j+=all.reg.stride) all.reg.weight_vector[j] = all.initial_weight; } const size_t buf_size = 512; void save_load_header(vw& all, io_buf& model_file, bool read, bool text) { char buff[buf_size]; char buff2[buf_size]; uint32_t text_len; if (model_file.files.size() > 0) { uint32_t v_length = (uint32_t)version.to_string().length()+1; text_len = sprintf(buff, "Version %s\n", version.to_string().c_str()); memcpy(buff2,version.to_string().c_str(),v_length); if (read) v_length = buf_size; bin_text_read_write(model_file, buff2, v_length, "", read, buff, text_len, text); version_struct v_tmp(buff2); if (v_tmp < LAST_COMPATIBLE_VERSION) { cout << "Model has possibly incompatible version! " << v_tmp.to_string() << endl; throw exception(); } char model = 'm'; bin_text_read_write_fixed(model_file,&model,1, "file is not a model file", read, "", 0, text); text_len = sprintf(buff, "Min label:%f\n", all.sd->min_label); bin_text_read_write_fixed(model_file,(char*)&all.sd->min_label, sizeof(all.sd->min_label), "", read, buff, text_len, text); text_len = sprintf(buff, "Max label:%f\n", all.sd->max_label); bin_text_read_write_fixed(model_file,(char*)&all.sd->max_label, sizeof(all.sd->max_label), "", read, buff, text_len, text); text_len = sprintf(buff, "bits:%d\n", (int)all.num_bits); uint32_t local_num_bits = all.num_bits; bin_text_read_write_fixed(model_file,(char *)&local_num_bits, sizeof(local_num_bits), "", read, buff, text_len, text); if (all.default_bits != true && all.num_bits != local_num_bits) { cout << "Wrong number of bits for source!" << endl; throw exception(); } all.default_bits = false; all.num_bits = local_num_bits; uint32_t pair_len = (uint32_t)all.pairs.size(); text_len = sprintf(buff, "%d pairs: ", (int)pair_len); bin_text_read_write_fixed(model_file,(char *)&pair_len, sizeof(pair_len), "", read, buff, text_len, text); for (size_t i = 0; i < pair_len; i++) { char pair[2]; if (!read) { memcpy(pair,all.pairs[i].c_str(),2); text_len = sprintf(buff, "%s ", all.pairs[i].c_str()); } bin_text_read_write_fixed(model_file, pair,2, "", read, buff, text_len, text); if (read) { string temp(pair, 2); if (count(all.pairs.begin(), all.pairs.end(), temp) == 0) all.pairs.push_back(temp); } } bin_text_read_write_fixed(model_file,buff,0, "", read, "\n",1,text); uint32_t triple_len = (uint32_t)all.triples.size(); text_len = sprintf(buff, "%d triples: ", (int)triple_len); bin_text_read_write_fixed(model_file,(char *)&triple_len, sizeof(triple_len), "", read, buff,text_len, text); for (size_t i = 0; i < triple_len; i++) { char triple[3]; if (!read) { text_len = sprintf(buff, "%s ", all.triples[i].c_str()); memcpy(triple, all.triples[i].c_str(), 3); } bin_text_read_write_fixed(model_file,triple,3, "", read, buff,text_len,text); if (read) { string temp(triple,3); all.triples.push_back(temp); } } bin_text_read_write_fixed(model_file,buff,0, "", read, "\n",1, text); text_len = sprintf(buff, "rank:%d\n", (int)all.rank); bin_text_read_write_fixed(model_file,(char*)&all.rank, sizeof(all.rank), "", read, buff,text_len, text); text_len = sprintf(buff, "lda:%d\n", (int)all.lda); bin_text_read_write_fixed(model_file,(char*)&all.lda, sizeof(all.lda), "", read, buff, text_len,text); uint32_t ngram_len = (uint32_t)all.ngram_strings.size(); text_len = sprintf(buff, "%d ngram: ", (int)ngram_len); bin_text_read_write_fixed(model_file,(char *)&ngram_len, sizeof(ngram_len), "", read, buff,text_len, text); for (size_t i = 0; i < ngram_len; i++) { char ngram[3] = {0,0,0}; if (!read) { text_len = sprintf(buff, "%s ", all.ngram_strings[i].c_str()); memcpy(ngram, all.ngram_strings[i].c_str(), min(3, all.ngram_strings[i].size())); } bin_text_read_write_fixed(model_file,ngram,3, "", read, buff,text_len,text); if (read) { string temp(ngram,3); all.ngram_strings.push_back(temp); } } if(read) compile_gram(all.ngram_strings, all.ngram, (char*)"grams", all.quiet); bin_text_read_write_fixed(model_file,buff,0, "", read, "\n",1, text); uint32_t skip_len = (uint32_t)all.skip_strings.size(); text_len = sprintf(buff, "%d skip: ", (int)skip_len); bin_text_read_write_fixed(model_file,(char *)&skip_len, sizeof(skip_len), "", read, buff,text_len, text); for (size_t i = 0; i < skip_len; i++) { char skip[3] = {0,0,0}; if (!read) { text_len = sprintf(buff, "%s ", all.skip_strings[i].c_str()); memcpy(skip, all.skip_strings[i].c_str(), min(3, all.skip_strings[i].size())); } bin_text_read_write_fixed(model_file,skip,3, "", read, buff,text_len,text); if (read) { string temp(skip,3); all.skip_strings.push_back(temp); } } if(read) compile_gram(all.skip_strings, all.skips, (char*)"skips", all.quiet); bin_text_read_write_fixed(model_file,buff,0, "", read, "\n",1, text); text_len = sprintf(buff, "options:%s\n", all.options_from_file.c_str()); uint32_t len = (uint32_t)all.options_from_file.length()+1; memcpy(buff2, all.options_from_file.c_str(),len); if (read) len = buf_size; bin_text_read_write(model_file,buff2, len, "", read, buff, text_len, text); if (read) all.options_from_file.assign(buff2); } } void dump_regressor(vw& all, string reg_name, bool as_text) { if (reg_name == string("")) return; string start_name = reg_name+string(".writing"); io_buf io_temp; io_temp.open_file(start_name.c_str(), all.stdin_off, io_buf::WRITE); save_load_header(all, io_temp, false, as_text); all.l.save_load(io_temp, false, as_text); io_temp.flush(); // close_file() should do this for me ... io_temp.close_file(); remove(reg_name.c_str()); rename(start_name.c_str(),reg_name.c_str()); } void save_predictor(vw& all, string reg_name, size_t current_pass) { char* filename = new char[reg_name.length()+4]; if (all.save_per_pass) sprintf(filename,"%s.%lu",reg_name.c_str(),(long unsigned)current_pass); else sprintf(filename,"%s",reg_name.c_str()); dump_regressor(all, string(filename), false); delete[] filename; } void finalize_regressor(vw& all, string reg_name) { if (all.per_feature_regularizer_output.length() > 0) dump_regressor(all, all.per_feature_regularizer_output, false); else dump_regressor(all, reg_name, false); if (all.per_feature_regularizer_text.length() > 0) dump_regressor(all, all.per_feature_regularizer_text, true); else{ dump_regressor(all, all.text_regressor_name, true); all.print_invert = true; dump_regressor(all, all.inv_hash_regressor_name, true); all.print_invert = false; } } void parse_regressor_args(vw& all, po::variables_map& vm, io_buf& io_temp) { if (vm.count("final_regressor")) { all.final_regressor_name = vm["final_regressor"].as<string>(); if (!all.quiet) cerr << "final_regressor = " << vm["final_regressor"].as<string>() << endl; } else all.final_regressor_name = ""; vector<string> regs; if (vm.count("initial_regressor") || vm.count("i")) regs = vm["initial_regressor"].as< vector<string> >(); if (regs.size() > 0) io_temp.open_file(regs[0].c_str(), all.stdin_off, io_buf::READ); save_load_header(all, io_temp, true, false); } void parse_mask_regressor_args(vw& all, po::variables_map& vm){ if (vm.count("feature_mask")) { size_t length = ((size_t)1) << all.num_bits; string mask_filename = vm["feature_mask"].as<string>(); if (vm.count("initial_regressor")){ vector<string> init_filename = vm["initial_regressor"].as< vector<string> >(); if(mask_filename == init_filename[0]){//-i and -mask are from same file, just generate mask for (size_t j = 0; j < length; j++){ if(all.reg.weight_vector[j*all.reg.stride] != 0.) all.reg.weight_vector[j*all.reg.stride + all.feature_mask_idx] = 1.; } return; } } //all other cases, including from different file, or -i does not exist, need to read in the mask file io_buf io_temp_mask; io_temp_mask.open_file(mask_filename.c_str(), false, io_buf::READ); save_load_header(all, io_temp_mask, true, false); all.l.save_load(io_temp_mask, true, false); io_temp_mask.close_file(); for (size_t j = 0; j < length; j++){ if(all.reg.weight_vector[j*all.reg.stride] != 0.) all.reg.weight_vector[j*all.reg.stride + all.feature_mask_idx] = 1.; } } } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Song Gao <song@gao.io> 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 flags.cc 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. */ /* GitHub: https://github.com/songgao/flags.hh */ #ifndef FLAGS_HH #define FLAGS_HH #include <getopt.h> #include <string> #include <functional> #include <iostream> #include <map> #include <set> #include <vector> #include <sstream> class Flags { public: Flags() : autoId(256) { } template <typename T> void Var(T & var, char shortFlag, std::string longFlag, T defaultValue, std::string description, std::string descriptionGroup = ""); void Bool(bool & var, char shortFlag, std::string longFlag, std::string description, std::string descriptionGroup = ""); bool Parse(int argc, char ** argv); void PrintHelp(char * argv0, std::ostream & to = std::cout); private: int autoId; std::map<int, std::function< void(std::string optarg) > > setters; // flag id -> setters std::set<std::string> longFlags; std::map<std::string, std::vector<std::string> > help; // group -> help itmes std::vector<struct option> options; std::string optionStr; template <typename T> void set(T & var, std::string optarg); template <typename T> void entry(struct option & op, char shortFlag, std::string longFlag, T & defaultValue, std::string description, std::string descriptionGroup); }; template <typename T> void Flags::entry(struct option & op, char shortFlag, std::string longFlag, T & defaultValue, std::string description, std::string descriptionGroup) { if (!shortFlag && !longFlag.size()) { throw std::string("no flag specified"); } if (shortFlag) { if (this->setters.find((int)(shortFlag)) != this->setters.end()) { throw std::string("short flag exists: ") + shortFlag; } this->optionStr += shortFlag; op.val = shortFlag; } else { op.val = this->autoId++; } if (longFlag.size()) { if (this->longFlags.find(longFlag) != this->longFlags.end()) { throw std::string("long flag exists: ") + longFlag; } op.name = this->longFlags.insert(longFlag).first->c_str(); } op.flag = NULL; // generate help item std::stringstream ss; ss << " "; if (shortFlag) { ss << "-" << shortFlag << " "; } if (longFlag.size()) { ss << "--" << longFlag << " "; } ss << "[default: " << defaultValue << "]"; ss << std::endl; constexpr size_t step = 80 - 6; for (size_t i = 0; i < description.size(); i += step) { ss << " "; if (i + step < description.size()) { ss << description.substr(i, step) << std::endl; } else { ss << description.substr(i); } } this->help[descriptionGroup].push_back(ss.str()); } template <typename T> void Flags::Var(T & var, char shortFlag, std::string longFlag, T defaultValue, std::string description, std::string descriptionGroup) { struct option op; this->entry(op, shortFlag, longFlag, defaultValue, description, descriptionGroup); this->optionStr += ":"; op.has_arg = required_argument; var = defaultValue; this->setters[op.val] = std::bind(&Flags::set<T>, this, std::ref(var), std::placeholders::_1); this->options.push_back(op); } void Flags::Bool(bool & var, char shortFlag, std::string longFlag, std::string description, std::string descriptionGroup) { struct option op; this->entry(op, shortFlag, longFlag, "(unset)", description, descriptionGroup); op.has_arg = no_argument; var = false; this->setters[op.val] = [&var](std::string) { var = true; }; this->options.push_back(op); } bool Flags::Parse(int argc, char ** argv) { this->options.push_back({NULL, 0, NULL, 0}); int ch; while ((ch = getopt_long(argc, argv, this->optionStr.c_str(), &this->options[0], NULL)) != -1) { auto it = this->setters.find(ch); if (it != this->setters.end()) { if (optarg) { it->second(optarg); } else { it->second(""); } } else { return false; } } return true; } void Flags::PrintHelp(char * argv0, std::ostream & to) { to << "Usage: " << argv0 << " [options]" << std::endl <<std::endl; for (auto& it : this->help) { if (it.first.size()) { to << it.first << ":" << std::endl; } for (auto& h : it.second) { to << h << std::endl; } to << std::endl; } } template <typename T> void Flags::set(T & var, std::string optarg) { std::stringstream ss(optarg); ss >> var; } #endif <commit_msg>inline member functions to avoid duplicate symbols<commit_after>/* Copyright (c) 2015, Song Gao <song@gao.io> 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 flags.cc 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. */ /* GitHub: https://github.com/songgao/flags.hh */ #ifndef FLAGS_HH #define FLAGS_HH #include <getopt.h> #include <string> #include <functional> #include <iostream> #include <map> #include <set> #include <vector> #include <sstream> class Flags { public: Flags() : autoId(256) { } template <typename T> void Var(T & var, char shortFlag, std::string longFlag, T defaultValue, std::string description, std::string descriptionGroup = ""); void Bool(bool & var, char shortFlag, std::string longFlag, std::string description, std::string descriptionGroup = ""); bool Parse(int argc, char ** argv); void PrintHelp(char * argv0, std::ostream & to = std::cout); private: int autoId; std::map<int, std::function< void(std::string optarg) > > setters; // flag id -> setters std::set<std::string> longFlags; std::map<std::string, std::vector<std::string> > help; // group -> help itmes std::vector<struct option> options; std::string optionStr; template <typename T> void set(T & var, std::string optarg); template <typename T> void entry(struct option & op, char shortFlag, std::string longFlag, T & defaultValue, std::string description, std::string descriptionGroup); }; template <typename T> inline void Flags::entry(struct option & op, char shortFlag, std::string longFlag, T & defaultValue, std::string description, std::string descriptionGroup) { if (!shortFlag && !longFlag.size()) { throw std::string("no flag specified"); } if (shortFlag) { if (this->setters.find((int)(shortFlag)) != this->setters.end()) { throw std::string("short flag exists: ") + shortFlag; } this->optionStr += shortFlag; op.val = shortFlag; } else { op.val = this->autoId++; } if (longFlag.size()) { if (this->longFlags.find(longFlag) != this->longFlags.end()) { throw std::string("long flag exists: ") + longFlag; } op.name = this->longFlags.insert(longFlag).first->c_str(); } op.flag = NULL; // generate help item std::stringstream ss; ss << " "; if (shortFlag) { ss << "-" << shortFlag << " "; } if (longFlag.size()) { ss << "--" << longFlag << " "; } ss << "[default: " << defaultValue << "]"; ss << std::endl; constexpr size_t step = 80 - 6; for (size_t i = 0; i < description.size(); i += step) { ss << " "; if (i + step < description.size()) { ss << description.substr(i, step) << std::endl; } else { ss << description.substr(i); } } this->help[descriptionGroup].push_back(ss.str()); } template <typename T> inline void Flags::Var(T & var, char shortFlag, std::string longFlag, T defaultValue, std::string description, std::string descriptionGroup) { struct option op; this->entry(op, shortFlag, longFlag, defaultValue, description, descriptionGroup); this->optionStr += ":"; op.has_arg = required_argument; var = defaultValue; this->setters[op.val] = std::bind(&Flags::set<T>, this, std::ref(var), std::placeholders::_1); this->options.push_back(op); } inline void Flags::Bool(bool & var, char shortFlag, std::string longFlag, std::string description, std::string descriptionGroup) { struct option op; this->entry(op, shortFlag, longFlag, "(unset)", description, descriptionGroup); op.has_arg = no_argument; var = false; this->setters[op.val] = [&var](std::string) { var = true; }; this->options.push_back(op); } inline bool Flags::Parse(int argc, char ** argv) { this->options.push_back({NULL, 0, NULL, 0}); int ch; while ((ch = getopt_long(argc, argv, this->optionStr.c_str(), &this->options[0], NULL)) != -1) { auto it = this->setters.find(ch); if (it != this->setters.end()) { if (optarg) { it->second(optarg); } else { it->second(""); } } else { return false; } } return true; } inline void Flags::PrintHelp(char * argv0, std::ostream & to) { to << "Usage: " << argv0 << " [options]" << std::endl <<std::endl; for (auto& it : this->help) { if (it.first.size()) { to << it.first << ":" << std::endl; } for (auto& h : it.second) { to << h << std::endl; } to << std::endl; } } template <typename T> inline void Flags::set(T & var, std::string optarg) { std::stringstream ss(optarg); ss >> var; } #endif <|endoftext|>
<commit_before>#include "Font.h" int hm::Font::fontsOpen = 0; namespace hm { Font::Font() : file(""), font(NULL), rm(SOLID) { if(TTF_WasInit() == 0) std::cout << "WARNING: SDL_ttf is not initialized!" << std::endl; } Font::Font(std::string file, int ptsize) : file(file), font(NULL), rm(SOLID) { if(TTF_WasInit() == 0) std::cout << "WARNING: SDL_ttf is not initialized!" << std::endl; loadFont(file, ptsize); } Font::~Font() { closeFont(); } int Font::getFontsOpen() { return fontsOpen; } void Font::loadFont(std::string file, int ptsize) { // Set our new font file string. this->file = file; // Unload a previous font. closeFont(); // Open the font. font = TTF_OpenFont(file.c_str(), ptsize); // Check it. if(font == NULL) std::cout << "Could not load " << file << std::endl; else fontsOpen++; // Add to the amount of fonts open. return; } TTF_Font* Font::getFont() { if(font == NULL) std::cout << "WARNING: Font is NULL." << std::endl; return font; } void Font::closeFont() { if(font != NULL) { TTF_CloseFont(font); font = NULL; fontsOpen--; } return; } void Font::setSize(int size) { loadFont(file, size); return; } void Font::setRenderMode(RenderMode rm) { this->rm = rm; return; } RenderMode Font::getRenderMode() { return rm; } } <commit_msg>Clean up Font code.<commit_after>#include "Font.h" int hm::Font::fontsOpen = 0; namespace hm { Font::Font() : file(""), font(NULL), rm(SOLID) { if(TTF_WasInit() == 0) std::cout << "WARNING: SDL_ttf is not initialized!" << std::endl; } Font::Font(std::string file, int ptsize) : file(file), font(NULL), rm(SOLID) { if(TTF_WasInit() == 0) std::cout << "WARNING: SDL_ttf is not initialized!" << std::endl; loadFont(file, ptsize); } Font::~Font() { closeFont(); } int Font::getFontsOpen() { return fontsOpen; } void Font::loadFont(std::string file, int ptsize) { this->file = file; closeFont(); font = TTF_OpenFont(file.c_str(), ptsize); if(font == NULL) std::cout << "Could not load " << file << std::endl; else fontsOpen++; return; } TTF_Font* Font::getFont() { if(font == NULL) std::cout << "WARNING: Font is NULL." << std::endl; return font; } void Font::closeFont() { if(font != NULL) { TTF_CloseFont(font); font = NULL; fontsOpen--; } return; } void Font::setSize(int size) { loadFont(file, size); return; } void Font::setRenderMode(RenderMode rm) { this->rm = rm; return; } RenderMode Font::getRenderMode() { return rm; } } <|endoftext|>
<commit_before>#include "../Entity/ZoneEntity.hpp" #include "../Event/ContactEventData.h" #include "../Task/CameraMoveTask.hpp" #include "../System/GraphicsManager.hpp" #include "../System/SceneManager.hpp" std::list<Task*> ZoneEntity::_taskList; ZoneEntity::ZoneEntity() : BaseClass(), _zoneBody(this), _containsBall(false) { } ZoneEntity::~ZoneEntity() { } void ZoneEntity::Initialize( const TiXmlElement *propertyElement /*= NULL */ ) { BaseClass::Initialize(propertyElement); { b2BodyDef bodyDefinition; bodyDefinition.userData = (IPhysics*)this; bodyDefinition.position = b2Vec2(GetPosition().x, GetPosition().y); bodyDefinition.angle = 0.0f; bodyDefinition.fixedRotation = true; bodyDefinition.type = b2_staticBody; _zoneBody.CreateBody( bodyDefinition ); b2PolygonShape boxShape; boxShape.SetAsBox( 0.5f * SCREENWIDTH * UNRATIO, 0.5f * SCREENHEIGHT * UNRATIO ); b2FixtureDef fixtureDef; fixtureDef.isSensor = true; fixtureDef.shape = &boxShape; _zoneBody.CreateFixture( fixtureDef, "Zone" ); _zoneBody.ResetTransform(); } } void ZoneEntity::PostLoad() { ITransform* moonTransform = SceneManager::GetInstance()->FindTransform("Player"); Vec2D moonPos = moonTransform->GetPosition(); if(_zoneBody.LookUpFixture("Zone")->TestPoint(moonPos)) { for(unsigned int i = 0; i < GraphicsManager::GetInstance()->GetRenderLayerStackSize(); i++ ) { GraphicsManager::GetInstance()->GetRenderLayer(i)->GetCamera().SetPosition(GetPosition()); } } } bool ZoneEntity::HandleEvent( const EventData& theevent ) { switch (theevent.GetEventType()) { case Event_BeginContact: { const ContactEventData& contactData = static_cast<const ContactEventData&>(theevent); const b2Contact* contactInfo = contactData.GetContact(); const b2Fixture* target = nullptr; if(_zoneBody.IsContactRelated(contactInfo,target)) { IPhysics *targetInterface = GetPhysicsInterface(target); if(targetInterface->GetEntity()->GetEntityType() == 'BALL') { _containsBall = true; for(std::list<Task*>::iterator iter = _taskList.begin(); iter != _taskList.end(); iter++ ) { Task* moveTask = (*iter); moveTask->RemoveTask(); delete moveTask; } _taskList.clear(); for(unsigned int i = 0; i < GraphicsManager::GetInstance()->GetRenderLayerStackSize(); i++ ) { CameraMoveTask* cameraTask = nullptr; if(i==0) { cameraTask = new CameraMoveTask(GetPosition(),i,0.5f); } else { cameraTask = new CameraMoveTask(GetPosition(),i,1.0f); } cameraTask->AddTask(); _taskList.push_back(cameraTask); } } } break; } case Event_EndContact: { const ContactEventData& contactData = static_cast<const ContactEventData&>(theevent); const b2Contact* contactInfo = contactData.GetContact(); const b2Fixture* target = nullptr; if(_zoneBody.IsContactRelated(contactInfo,target)) { IPhysics *targetInterface = GetPhysicsInterface(target); if(targetInterface->GetEntity()->GetEntityType() == 'BALL') { _containsBall = false; } } break; } } return false; } <commit_msg>ZoneEntity gets released when the ball exits.<commit_after>#include "../Entity/ZoneEntity.hpp" #include "../Event/ContactEventData.h" #include "../Task/CameraMoveTask.hpp" #include "../System/GraphicsManager.hpp" #include "../System/SceneManager.hpp" std::list<Task*> ZoneEntity::_taskList; ZoneEntity::ZoneEntity() : BaseClass(), _zoneBody(this), _containsBall(false) { } ZoneEntity::~ZoneEntity() { } void ZoneEntity::Initialize( const TiXmlElement *propertyElement /*= NULL */ ) { BaseClass::Initialize(propertyElement); { b2BodyDef bodyDefinition; bodyDefinition.userData = (IPhysics*)this; bodyDefinition.position = b2Vec2(GetPosition().x, GetPosition().y); bodyDefinition.angle = 0.0f; bodyDefinition.fixedRotation = true; bodyDefinition.type = b2_staticBody; _zoneBody.CreateBody( bodyDefinition ); b2PolygonShape boxShape; boxShape.SetAsBox( 0.5f * SCREENWIDTH * UNRATIO, 0.5f * SCREENHEIGHT * UNRATIO ); b2FixtureDef fixtureDef; fixtureDef.isSensor = true; fixtureDef.shape = &boxShape; _zoneBody.CreateFixture( fixtureDef, "Zone" ); _zoneBody.ResetTransform(); } } void ZoneEntity::PostLoad() { ITransform* moonTransform = SceneManager::GetInstance()->FindTransform("Player"); Vec2D moonPos = moonTransform->GetPosition(); if(_zoneBody.LookUpFixture("Zone")->TestPoint(moonPos)) { for(unsigned int i = 0; i < GraphicsManager::GetInstance()->GetRenderLayerStackSize(); i++ ) { GraphicsManager::GetInstance()->GetRenderLayer(i)->GetCamera().SetPosition(GetPosition()); } } } bool ZoneEntity::HandleEvent( const EventData& theevent ) { switch (theevent.GetEventType()) { case Event_BeginContact: { const ContactEventData& contactData = static_cast<const ContactEventData&>(theevent); const b2Contact* contactInfo = contactData.GetContact(); const b2Fixture* target = nullptr; if(_zoneBody.IsContactRelated(contactInfo,target)) { IPhysics *targetInterface = GetPhysicsInterface(target); if(targetInterface->GetEntity()->GetEntityType() == 'BALL') { _containsBall = true; for(std::list<Task*>::iterator iter = _taskList.begin(); iter != _taskList.end(); iter++ ) { Task* moveTask = (*iter); moveTask->RemoveTask(); delete moveTask; } _taskList.clear(); for(unsigned int i = 0; i < GraphicsManager::GetInstance()->GetRenderLayerStackSize(); i++ ) { CameraMoveTask* cameraTask = nullptr; if(i==0) { cameraTask = new CameraMoveTask(GetPosition(),i,0.5f); } else { cameraTask = new CameraMoveTask(GetPosition(),i,1.0f); } cameraTask->AddTask(); _taskList.push_back(cameraTask); } } } break; } case Event_EndContact: { const ContactEventData& contactData = static_cast<const ContactEventData&>(theevent); const b2Contact* contactInfo = contactData.GetContact(); const b2Fixture* target = nullptr; if(_zoneBody.IsContactRelated(contactInfo,target)) { IPhysics *targetInterface = GetPhysicsInterface(target); if(targetInterface->GetEntity()->GetEntityType() == 'BALL') { _containsBall = false; Release(); } } break; } } return false; } <|endoftext|>
<commit_before>#ifndef __INCLUDED_TS_PROCESSOR_TS_PAYLOAD_BUILDER_HPP__ #define __INCLUDED_TS_PROCESSOR_TS_PAYLOAD_BUILDER_HPP__ #include <ts_processor/ts/packet.hpp> #include <bitfield/container/vector.hpp> namespace ts_processor { namespace ts { struct payload_builder { bitfield::container::vector container; public: void push(const ts::packet & packet); const ts::payload * payload() const; void clear(); }; }} #endif // __INCLUDED_TS_PROCESSOR_TS_PAYLOAD_BUILDER_HPP__ <commit_msg>Fix typo.<commit_after>#ifndef __INCLUDED_TS_PROCESSOR_TS_PAYLOAD_BUILDER_HPP__ #define __INCLUDED_TS_PROCESSOR_TS_PAYLOAD_BUILDER_HPP__ #include <ts_processor/ts/packet.hpp> #include <bitfield/container/vector.hpp> namespace ts_processor { namespace ts { class payload_builder { bitfield::container::vector container; public: void push(const ts::packet & packet); const ts::payload * payload() const; void clear(); }; }} #endif // __INCLUDED_TS_PROCESSOR_TS_PAYLOAD_BUILDER_HPP__ <|endoftext|>
<commit_before>// Halide tutorial lesson 16: RGB images and memory layouts part 1 // This lesson demonstrates how to feed Halide RGB images in // interleaved or planar format, and how to write code optimized for // each case. // On linux or os x, you can compile and run it like so: // g++ lesson_16_rgb_generate.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_16_generate // export LD_LIBRARY_PATH=../bin # For linux // export DYLD_LIBRARY_PATH=../bin # For OS X // ./lesson_16_generate -o . -f brighten_planar target=host layout=planar // ./lesson_16_generate -o . -f brighten_interleaved target=host layout=interleaved // ./lesson_16_generate -o . -f brighten_either target=host layout=either // ./lesson_16_generate -o . -f brighten_specialized target=host layout=specialized // g++ lesson_16_rgb_run.cpp brighten_*.o -ldl -lpthread -o lesson_16_run // ./lesson_16_run // If you have the entire Halide source tree, you can also build it by // running: // make tutorial_lesson_16_rgb_run // in a shell with the current directory at the top of the halide // source tree. #include "Halide.h" #include <stdio.h> using namespace Halide; // We will define a generator that brightens an RGB image. class Brighten : public Halide::Generator<Brighten> { public: // We declare a three-dimensional input image. The first two // dimensions will be x, and y, and the third dimension will be // the color channel. ImageParam input{UInt(8), 3, "input"}; // We will compile this generator in several ways to accept // several different memory layouts for the input and output. This // is a good use of a GeneratorParam (see lesson 15). enum class Layout { Planar, Interleaved, Either, Specialized }; GeneratorParam<Layout> layout{"layout", // default value Layout::Planar, // map from names to values {{ "planar", Layout::Planar }, { "interleaved", Layout::Interleaved }, { "either", Layout::Either }, { "specialized", Layout::Specialized }}}; // We also declare a scalar parameter to control the amount of // brightening. Param<uint8_t> offset{"offset"}; // Declare our Vars Var x, y, c; Func build() { // Define the Func. Func brighter("brighter"); brighter(x, y, c) = input(x, y, c) + offset; // Schedule it. brighter.vectorize(x, 16); // We will compile this pipeline to handle memory layouts in // several different ways, depending on the 'layout' generator // param. if (layout == Layout::Planar) { // This pipeline as written will only work with images in // which each scanline is densely-packed single color // channel. In terms of the strides described in lesson // 10, Halide assumes and asserts that the stride in x is // one. // This constraint permits planar images, where the red, // green, and blue channels are laid out in memory like // this: // RRRRRRRR // RRRRRRRR // RRRRRRRR // RRRRRRRR // GGGGGGGG // GGGGGGGG // GGGGGGGG // GGGGGGGG // BBBBBBBB // BBBBBBBB // BBBBBBBB // BBBBBBBB // It also works with the less-commonly used line-by-line // layout, in which scanlines of red, green, and blue // alternate. // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB } else if (layout == Layout::Interleaved) { // Another common format is 'interleaved', in which the // red, green, and blue values for each pixel occur next // to each other in memory: // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // In this case the stride in x is three, the stride in y // is three times the width of the image, and the stride // in c is one. We can tell Halide to assume (and assert) // that this is the case for the input and output like so: input .dim(0).set_stride(3) // stride in dimension 0 (x) is three .dim(2).set_stride(1); // stride in dimension 2 (c) is one brighter.output_buffer() .dim(0).set_stride(3) .dim(2).set_stride(1); // For interleaved layout, you may want to use a different // schedule. We'll tell Halide to additionally assume and // assert that there are three color channels, then // exploit this fact to make the loop over 'c' innermost // and unrolled. input.dim(2).set_bounds(0, 3); // Dimension 2 (c) starts at 0 and has extent 3. brighter.output_buffer().dim(2).set_bounds(0, 3); // Move the loop over color channels innermost and unroll // it. brighter.reorder(c, x, y).unroll(c); // Note that if we were dealing with an image with an // alpha channel (RGBA), then the stride in x and the // bounds of the channels dimension would both be four // instead of three. } else if (layout == Layout::Either) { // We can also remove all constraints and compile a // pipeline that will work with any memory layout. It will // probably be slow, because all vector loads become // gathers, and all vector stores become scatters. input.dim(0).set_stride(Expr()); // Use a default-constructed // undefined Expr to mean // there is no constraint. brighter.output_buffer().dim(0).set_stride(Expr()); } else if (layout == Layout::Specialized) { // We can accept any memory layout with good performance // by telling Halide to inspect the memory layout at // runtime, and branch to different code depending on the // strides it find. First we relax the default constraint // that dim(0).stride() == 1: input.dim(0).set_stride(Expr()); // Use an undefined Expr to // mean there is no // constraint. brighter.output_buffer().dim(0).set_stride(Expr()); // The we construct boolean Exprs that detect at runtime // whether we're planar or interleaved. The conditions // should check for all the facts we want to exploit in // each case. Expr input_is_planar = (input.dim(0).stride() == 1); Expr input_is_interleaved = (input.dim(0).stride() == 3 && input.dim(2).stride() == 1 && input.dim(2).extent() == 3); Expr output_is_planar = (brighter.output_buffer().dim(0).stride() == 1); Expr output_is_interleaved = (brighter.output_buffer().dim(0).stride() == 3 && brighter.output_buffer().dim(2).stride() == 1 && brighter.output_buffer().dim(2).extent() == 3); // We can then use Func::specialize to write a schedule // that switches at runtime to specialized code based on a // boolean Expr. That code will exploit the fact that the // Expr is known to be true. brighter.specialize(input_is_planar && output_is_planar); // We've already vectorized and parallelized brighter, and // our two specializations will inherit those scheduling // directives. We can also add additional scheduling // directives that apply to a single specialization // only. We'll tell Halide to make a specialized version // of the code for interleaved layouts, and to reorder and // unroll that specialized code. brighter.specialize(input_is_interleaved && output_is_interleaved) .reorder(c, x, y).unroll(c); // We could also add specializations for if the input is // interleaved and the output is planar, and vice versa, // but two specializations is enough to demonstrate the // feature. A later tutorial will explore more creative // uses of Func::specialize. // Adding specializations can improve performance // substantially for the cases they apply to, but it also // increases the amount of code to compile and ship. If // binary sizes are a concern and the input and output // memory layouts are known, you probably want to use // set_stride and set_extent instead. } return brighter; } }; // As in lesson 15, we register our generator and then compile this // file along with tools/GenGen.cpp. HALIDE_REGISTER_GENERATOR(Brighten, brighten) // After compiling this file, see how to use it in // lesson_16_rgb_run.cpp <commit_msg>Param->Input in lesson_16<commit_after>// Halide tutorial lesson 16: RGB images and memory layouts part 1 // This lesson demonstrates how to feed Halide RGB images in // interleaved or planar format, and how to write code optimized for // each case. // On linux or os x, you can compile and run it like so: // g++ lesson_16_rgb_generate.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_16_generate // export LD_LIBRARY_PATH=../bin # For linux // export DYLD_LIBRARY_PATH=../bin # For OS X // ./lesson_16_generate -o . -f brighten_planar target=host layout=planar // ./lesson_16_generate -o . -f brighten_interleaved target=host layout=interleaved // ./lesson_16_generate -o . -f brighten_either target=host layout=either // ./lesson_16_generate -o . -f brighten_specialized target=host layout=specialized // g++ lesson_16_rgb_run.cpp brighten_*.o -ldl -lpthread -o lesson_16_run // ./lesson_16_run // If you have the entire Halide source tree, you can also build it by // running: // make tutorial_lesson_16_rgb_run // in a shell with the current directory at the top of the halide // source tree. #include "Halide.h" #include <stdio.h> using namespace Halide; // We will define a generator that brightens an RGB image. class Brighten : public Halide::Generator<Brighten> { public: // We declare a three-dimensional input image. The first two // dimensions will be x, and y, and the third dimension will be // the color channel. Input<Buffer<uint8_t>> input{"input", 3}; // We will compile this generator in several ways to accept // several different memory layouts for the input and output. This // is a good use of a GeneratorParam (see lesson 15). enum class Layout { Planar, Interleaved, Either, Specialized }; GeneratorParam<Layout> layout{"layout", // default value Layout::Planar, // map from names to values {{ "planar", Layout::Planar }, { "interleaved", Layout::Interleaved }, { "either", Layout::Either }, { "specialized", Layout::Specialized }}}; // We also declare a scalar input to control the amount of // brightening. Input<uint8_t> offset{"offset"}; // Declare our Vars Var x, y, c; Func build() { // Define the Func. Func brighter("brighter"); brighter(x, y, c) = input(x, y, c) + offset; // Schedule it. brighter.vectorize(x, 16); // We will compile this pipeline to handle memory layouts in // several different ways, depending on the 'layout' generator // param. if (layout == Layout::Planar) { // This pipeline as written will only work with images in // which each scanline is densely-packed single color // channel. In terms of the strides described in lesson // 10, Halide assumes and asserts that the stride in x is // one. // This constraint permits planar images, where the red, // green, and blue channels are laid out in memory like // this: // RRRRRRRR // RRRRRRRR // RRRRRRRR // RRRRRRRR // GGGGGGGG // GGGGGGGG // GGGGGGGG // GGGGGGGG // BBBBBBBB // BBBBBBBB // BBBBBBBB // BBBBBBBB // It also works with the less-commonly used line-by-line // layout, in which scanlines of red, green, and blue // alternate. // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB // RRRRRRRR // GGGGGGGG // BBBBBBBB } else if (layout == Layout::Interleaved) { // Another common format is 'interleaved', in which the // red, green, and blue values for each pixel occur next // to each other in memory: // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // RGBRGBRGBRGBRGBRGBRGBRGB // In this case the stride in x is three, the stride in y // is three times the width of the image, and the stride // in c is one. We can tell Halide to assume (and assert) // that this is the case for the input and output like so: input .dim(0).set_stride(3) // stride in dimension 0 (x) is three .dim(2).set_stride(1); // stride in dimension 2 (c) is one brighter.output_buffer() .dim(0).set_stride(3) .dim(2).set_stride(1); // For interleaved layout, you may want to use a different // schedule. We'll tell Halide to additionally assume and // assert that there are three color channels, then // exploit this fact to make the loop over 'c' innermost // and unrolled. input.dim(2).set_bounds(0, 3); // Dimension 2 (c) starts at 0 and has extent 3. brighter.output_buffer().dim(2).set_bounds(0, 3); // Move the loop over color channels innermost and unroll // it. brighter.reorder(c, x, y).unroll(c); // Note that if we were dealing with an image with an // alpha channel (RGBA), then the stride in x and the // bounds of the channels dimension would both be four // instead of three. } else if (layout == Layout::Either) { // We can also remove all constraints and compile a // pipeline that will work with any memory layout. It will // probably be slow, because all vector loads become // gathers, and all vector stores become scatters. input.dim(0).set_stride(Expr()); // Use a default-constructed // undefined Expr to mean // there is no constraint. brighter.output_buffer().dim(0).set_stride(Expr()); } else if (layout == Layout::Specialized) { // We can accept any memory layout with good performance // by telling Halide to inspect the memory layout at // runtime, and branch to different code depending on the // strides it find. First we relax the default constraint // that dim(0).stride() == 1: input.dim(0).set_stride(Expr()); // Use an undefined Expr to // mean there is no // constraint. brighter.output_buffer().dim(0).set_stride(Expr()); // The we construct boolean Exprs that detect at runtime // whether we're planar or interleaved. The conditions // should check for all the facts we want to exploit in // each case. Expr input_is_planar = (input.dim(0).stride() == 1); Expr input_is_interleaved = (input.dim(0).stride() == 3 && input.dim(2).stride() == 1 && input.dim(2).extent() == 3); Expr output_is_planar = (brighter.output_buffer().dim(0).stride() == 1); Expr output_is_interleaved = (brighter.output_buffer().dim(0).stride() == 3 && brighter.output_buffer().dim(2).stride() == 1 && brighter.output_buffer().dim(2).extent() == 3); // We can then use Func::specialize to write a schedule // that switches at runtime to specialized code based on a // boolean Expr. That code will exploit the fact that the // Expr is known to be true. brighter.specialize(input_is_planar && output_is_planar); // We've already vectorized and parallelized brighter, and // our two specializations will inherit those scheduling // directives. We can also add additional scheduling // directives that apply to a single specialization // only. We'll tell Halide to make a specialized version // of the code for interleaved layouts, and to reorder and // unroll that specialized code. brighter.specialize(input_is_interleaved && output_is_interleaved) .reorder(c, x, y).unroll(c); // We could also add specializations for if the input is // interleaved and the output is planar, and vice versa, // but two specializations is enough to demonstrate the // feature. A later tutorial will explore more creative // uses of Func::specialize. // Adding specializations can improve performance // substantially for the cases they apply to, but it also // increases the amount of code to compile and ship. If // binary sizes are a concern and the input and output // memory layouts are known, you probably want to use // set_stride and set_extent instead. } return brighter; } }; // As in lesson 15, we register our generator and then compile this // file along with tools/GenGen.cpp. HALIDE_REGISTER_GENERATOR(Brighten, brighten) // After compiling this file, see how to use it in // lesson_16_rgb_run.cpp <|endoftext|>
<commit_before>/// @brief provides CORDIC for ln function /// @ref see C. Baumann, "A simple and fast look-up table method to compute the /// exp(x) and ln(x) functions", 2004 #include "./../../fixed_point_lib/src/CORDIC/lut/lut.hpp" #include <boost/foreach.hpp> #include <boost/range/irange.hpp> namespace std { template<typename T, size_t n, size_t f, class op, class up> core::fixed_point<T, n, f, op, up> log(core::fixed_point<T, n, f, op, up> const& val) { typedef core::fixed_point<T, n, f, op, up> fp; typedef core::cordic::lut<f, fp> lut_type; assert(("log2: argument must be positive", val >= fp(0))); if (val < fp(0)) { throw std::exception("log2: argument must be positive"); } // reduces argument to interval [1.0, 2.0] int power(0); fp arg(val); while (arg >= fp(2.0)) { as_native(arg) >>= 1u; power++; } while (arg < fp(1.0)) { as_native(arg) <<= 1u; power--; } // one can consider 0 < y = log(2, x) < 1 as x = 2^y // so CORDIC rotation is just a multiplication by 2^{1/2^i}: // 2^y = 2^{a1/2} * 2^{a2/4} * ... * 2^{ai/2^i}, where ai is from // {0, 1} static lut_type const inv_roots_from2_lut = lut_type::build_inv_2roots_lut(); fp result(0); BOOST_FOREACH(size_t i, boost::irange<size_t>(0, f, 1)) { if (fp(arg * inv_roots_from2_lut[i]) >= fp(1.0)) { arg = fp(arg * inv_roots_from2_lut[i]); as_native(result) += T(1u) << (f - i - 1u); } } result += fp(power); return result; } } <commit_msg>log.inl: refactoring + approximation from Taylor series in case of small argument<commit_after>/// @brief provides CORDIC for ln function /// @ref see C. Baumann, "A simple and fast look-up table method to compute the /// exp(x) and ln(x) functions", 2004 #include "./../../fixed_point_lib/src/CORDIC/lut/lut.hpp" #include <boost/foreach.hpp> #include <boost/range/irange.hpp> namespace std { template<typename T, size_t n, size_t f, class op, class up> core::fixed_point<T, n, f, op, up> log(core::fixed_point<T, n, f, op, up> const& val) { typedef core::fixed_point<T, n, f, op, up> fp; typedef core::cordic::lut<f, fp> lut; assert(("log2: argument must be positive", val >= fp(0))); if (val < fp(0)) { throw std::exception("log2: argument must be positive"); } // reduces argument to interval [1.0, 2.0] int power(0); fp arg(val); while (arg >= fp(2.0)) { as_native(arg) >>= 1u; power++; } while (arg < fp(1.0)) { as_native(arg) <<= 1u; power--; } // approximation in case argument approaches 1.0 if (arg - fp(1.0) <= fp(0.01)) { return fp((fp(power) / fp::CONST_LOG2E) + (arg - fp(1.0))); } // one can consider 0 < y = log(2, x) < 1 as x = 2^y // so CORDIC rotation is just a multiplication by 2^{1/2^i}: // 2^y = 2^{a1/2} * 2^{a2/4} * ... * 2^{ai/2^i}, where ai is from // {0, 1} static lut const inv_pow2_lut = lut::inv_pow2(); fp result(0); BOOST_FOREACH(size_t i, boost::irange<size_t>(0, f, 1)) { if (fp(arg * inv_pow2_lut[i]) >= fp(1.0)) { arg = fp(arg * inv_pow2_lut[i]); as_native(result) += T(1u) << (f - i - 1u); } } result += fp(power); return fp(result / fp::CONST_LOG2E); } } <|endoftext|>
<commit_before>/* ** Copyright 2009-2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <QtSql> #include <map> #include "com/centreon/broker/bam/configuration/db.hh" #include "com/centreon/broker/bam/configuration/state.hh" #include "com/centreon/broker/bam/configuration/reader.hh" #include "com/centreon/broker/bam/configuration/reader_exception.hh" using namespace com::centreon::broker::bam::configuration; /** * @class create_map * @brief A clever piece of code found on the net to * automate the loading of a map from a literal expression * .... why write it yourself? ... This sort of code needs a seperate namespace.. */ template <typename T, typename U> class create_map { public: /** * Constructor * */ create_map(const T& key, const U& val) { m_map[key] = val; } /** * Operator ( key, value ) * * @brief This operator takes the same parameters as constructor * so that the row for the constructor and all preceding rows are identical. * This allows for a clean layout of table rows. */ create_map<T, U>& operator()(const T& key, const U& val) { m_map[key] = val; return (*this); } /** * Operator map * * @return Returns the internal map loaded with all the values of the literal table. */ operator std::map<T, U>() { return (m_map); } private: std::map<T,U> m_map; }; /** * @function map_2_QT * * @brief maps the logical name for a RDBMS to the Qlib name * @param[in] The logical name for the database * @return The QT lib name for the database system */ QString map_2_QT(const std::string& dbtype){ using namespace std; // lower case the string QString qt_db_type(dbtype.c_str()); qt_db_type = qt_db_type.toLower(); // load map only ONCE.. at first execution // avantage : logN, typesafe, thread-safe ( AFTER init) // disavantage : race on initialisation... typedef map<QString, QString> string_2_string; static string_2_string name_2_qname= create_map<QString,QString> ("db2", "QDB2") ("ibase", "QIBASE") ("interbase", "QIBASE") ("mysql", "QMYSQL") ("oci", "QOCI") ("oracle", "QOCI") ("odbc", "QODBC") ("psql", "QPSQL") ("postgres", "QPSQL") ("postgresql", "QPSQL") ("sqlite", "QSQLITE") ("tds", "QTDS") ("sybase", "QTDS"); // find the database in table string_2_string::iterator found = name_2_qname.find(qt_db_type); return (found != name_2_qname.end() ? found->first : qt_db_type); } /** * Constructor. * * @param[in] mydb Information for accessing database. */ reader::reader(configuration::db const& mydb) : _db(), _dbinfo(mydb){ QString id; id.setNum((qulonglong)this, 16); _db = QSqlDatabase::addDatabase(map_2_QT(mydb.get_type()), id); _ensure_open(); } /** * Destructor. */ reader::~reader() { _db.close(); } /** * Reader * * @param[out] st All the configuration state for the BA subsystem * recuperated from the specified database */ void reader::read(state& st) { try { _ensure_open(); _db.transaction(); // A single explicit transaction is more efficient _load( st.get_bas()); _load( st.get_kpis()); _load( st.get_boolexps()); _db.commit(); } catch (std::exception& e) { //apparently, no need to rollback transaction.. achieved in the db destructor st.clear(); throw; } } /** * Copy constructor * * @Brief Hidden implementation */ reader::reader(reader const& other) : _dbinfo(other._dbinfo){ } /** * assignment operator * * @Brief Hidden implementation * */ reader& reader::operator=(reader const& other){ (void)other; return (*this); } /** * open * * @brief Enforce that the database be open as a postcondition */ void reader::_ensure_open(){ if(!_db.isOpen()){ _db.setHostName(_dbinfo.get_host().c_str() ); _db.setDatabaseName(_dbinfo.get_name().c_str() ); _db.setUserName(_dbinfo.get_user().c_str() ); _db.setPassword(_dbinfo.get_password().c_str() ); // we must have a valid database connexion at this point if( !_db.open() ){ throw (reader_exception() << "BAM: Database access failure" << ", Reason: "<< _db.lastError().text() << ", Type: " << _dbinfo.get_type() << ", Host: " << _dbinfo.get_host() << ", Name: " << _dbinfo.get_name()); } } } /** * Load * * @param[out] list of kpis in database */ void reader::_load(state::kpis& kpis){ kpis.clear(); QSqlQuery query = _db.exec("SELECT k.kpi_id, " " k.state_type, " " k.host_id, " " k.service_id, " " k.id_ba, " " k.current_status, " " k.last_level, " " k.downtime, " " k.acknowledged, " " k.ignore_downtime, " " k.ignore_acknowledged, " " coalesce(k.drop_warning,ww.impact), " " coalesce(k.drop_critical,cc.impact), " " coalesce(k.drop_unknown,uu.impact) " "FROM mod_bam_kpi AS k " "LEFT JOIN mod_bam_impacts AS ww ON k.drop_warning_impact_id = ww.id_impact " "LEFT JOIN mod_bam_impacts AS cc ON k.drop_critical_impact_id = cc.id_impact " "LEFT JOIN mod_bam_impacts AS uu ON k.drop_unknown_impact_id = uu.id_impact;"); _assert_query(query); while (query.next()) { kpis.push_back( kpi( query.value(0).toInt(), //unsigned int id = 0, query.value(1).toInt(), //short state_type = 0, query.value(2).toInt(), //unsigned int hostid = 0, query.value(3).toInt(),//unsigned int serviceid = 0 query.value(4).toInt(),//unsigned int ba = 0, query.value(5).toInt(),//short status = 0, query.value(6).toInt(),//short lasthardstate = 0, query.value(7).toFloat(),//bool downtimed = false, query.value(8).toFloat(),//bool acknowledged = false, query.value(9).toBool(),//bool ignoredowntime = false, query.value(10).toBool(),//bool ignoreacknowledgement = false, query.value(11).toDouble(),//double warning = 0, query.value(12).toDouble(),//double critical = 0, query.value(13).toDouble()//double unknown = 0); )); } } /** * Load * * @param[out] list of bas in database */ void reader::_load(state::bas& bas){ QSqlQuery query = _db.exec("SELECT ba_id, " " name, " " current_level, " " level_w, " " level_c, " "FROM mod_bam"); _assert_query(query); while (query.next()) { bas.push_back( ba(query.value(0).toInt(), //unsigned int id = 0, query.value(1).toString().toStdString() ,//std::string const& name = "", query.value(2).toFloat(), //double level = 0.0, query.value(3).toFloat(), //double warning_level = 0.0 query.value(4).toFloat() //double critical_level = 0.0); )); } } /** * Load * * @param[out] list of bool expression in database */ void reader::_load(state::bool_exps& bool_exps){ QSqlQuery query = _db.exec("SELECT be.boolean_id, " " COALESCE(be.impact,imp.impact)" " be.expression," " be.bool_state," " be.current_state" "FROM mod_bam_boolean as be" "LEFT JOIN mod_bam_impacts as imp ON be.impact_id = imp.id_impact " ); _assert_query(query); while (query.next()) { bool_exps.push_back( bool_expression( query.value(0).toInt(), //unsigned int id = 0, query.value(1).toFloat(),//double impact = 0.0, query.value(2).toString().toStdString(),//std::string const& expression = "", query.value(3).toBool(),//bool impact_if = false, query.value(4).toBool()//bool state = false )); } } /** * Assert query * * @param[in] assert that the query succeeded */ void reader::_assert_query(QSqlQuery& query){ if(!query.isActive()){ throw reader_exception() << "Database Select Error: " << query.lastError().text() << ", Type: " << _dbinfo.get_type() << ", Host:" << _db.hostName() << ", Name:" << _db.databaseName() ; } } <commit_msg>BAM:conformance<commit_after>/* ** Copyright 2009-2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <QtSql> #include <map> #include "com/centreon/broker/bam/configuration/db.hh" #include "com/centreon/broker/bam/configuration/state.hh" #include "com/centreon/broker/bam/configuration/reader.hh" #include "com/centreon/broker/bam/configuration/reader_exception.hh" using namespace com::centreon::broker::bam::configuration; /** * @class create_map * @brief A clever piece of code found on the net to * automate the loading of a map from a literal expression * .... why write it yourself? ... This sort of code needs a seperate namespace.. */ template <typename T, typename U> class create_map { public: /** * Constructor * */ create_map(T const& key,U const& val) { m_map[key] = val; } /** * Operator ( key, value ) * * @brief This operator takes the same parameters as constructor * so that the row for the constructor and all preceding rows are identical. * This allows for a clean layout of table rows. */ create_map<T,U>& operator()(T const& key, U const& val) { m_map[key] = val; return (*this); } /** * Operator map * * @return Returns the internal map loaded with all the values of the literal table. */ operator std::map<T, U>() { return (m_map); } private: std::map<T,U> m_map; }; /** * @function map_2_QT * * @brief maps the logical name for a RDBMS to the Qlib name * @param[in] The logical name for the database * @return The QT lib name for the database system */ QString map_2_QT(std::string const& dbtype) { using namespace std; // lower case the string QString qt_db_type(dbtype.c_str()); qt_db_type = qt_db_type.toLower(); // load map only ONCE.. at first execution // avantage : logN, typesafe, thread-safe ( AFTER init) // disavantage : race on initialisation... typedef map<QString, QString> string_2_string; static string_2_string name_2_qname= create_map<QString,QString> ("db2", "QDB2") ("ibase", "QIBASE") ("interbase", "QIBASE") ("mysql", "QMYSQL") ("oci", "QOCI") ("oracle", "QOCI") ("odbc", "QODBC") ("psql", "QPSQL") ("postgres", "QPSQL") ("postgresql", "QPSQL") ("sqlite", "QSQLITE") ("tds", "QTDS") ("sybase", "QTDS"); // find the database in table string_2_string::iterator found = name_2_qname.find(qt_db_type); return (found != name_2_qname.end() ? found->first : qt_db_type); } /** * Constructor. * * @param[in] mydb Information for accessing database. */ reader::reader(configuration::db const& mydb) : _db(), _dbinfo(mydb){ QString id; id.setNum((qulonglong)this, 16); _db = QSqlDatabase::addDatabase(map_2_QT(mydb.get_type()), id); _ensure_open(); } /** * Destructor. */ reader::~reader() { _db.close(); } /** * Reader * * @param[out] st All the configuration state for the BA subsystem * recuperated from the specified database */ void reader::read(state& st) { try { _ensure_open(); _db.transaction(); // A single explicit transaction is more efficient _load( st.get_bas()); _load( st.get_kpis()); _load( st.get_boolexps()); _db.commit(); } catch (std::exception& e) { //apparently, no need to rollback transaction.. achieved in the db destructor st.clear(); throw; } } /** * Copy constructor * * @Brief Hidden implementation */ reader::reader(reader const& other) : _dbinfo(other._dbinfo){ } /** * assignment operator * * @Brief Hidden implementation * */ reader& reader::operator=(reader const& other) { (void)other; return (*this); } /** * open * * @brief Enforce that the database be open as a postcondition */ void reader::_ensure_open() { if(!_db.isOpen()){ _db.setHostName(_dbinfo.get_host().c_str() ); _db.setDatabaseName(_dbinfo.get_name().c_str() ); _db.setUserName(_dbinfo.get_user().c_str() ); _db.setPassword(_dbinfo.get_password().c_str() ); // we must have a valid database connexion at this point if( !_db.open() ){ throw (reader_exception() << "BAM: Database access failure" << ", Reason: "<< _db.lastError().text() << ", Type: " << _dbinfo.get_type() << ", Host: " << _dbinfo.get_host() << ", Name: " << _dbinfo.get_name()); } } } /** * Load * * @param[out] list of kpis in database */ void reader::_load(state::kpis& kpis) { kpis.clear(); QSqlQuery query = _db.exec("SELECT k.kpi_id, " " k.state_type, " " k.host_id, " " k.service_id, " " k.id_ba, " " k.current_status, " " k.last_level, " " k.downtime, " " k.acknowledged, " " k.ignore_downtime, " " k.ignore_acknowledged, " " coalesce(k.drop_warning,ww.impact), " " coalesce(k.drop_critical,cc.impact), " " coalesce(k.drop_unknown,uu.impact) " "FROM mod_bam_kpi AS k " "LEFT JOIN mod_bam_impacts AS ww ON k.drop_warning_impact_id = ww.id_impact " "LEFT JOIN mod_bam_impacts AS cc ON k.drop_critical_impact_id = cc.id_impact " "LEFT JOIN mod_bam_impacts AS uu ON k.drop_unknown_impact_id = uu.id_impact;"); _assert_query(query); while (query.next()) { kpis.push_back( kpi( query.value(0).toInt(), //unsigned int id = 0, query.value(1).toInt(), //short state_type = 0, query.value(2).toInt(), //unsigned int hostid = 0, query.value(3).toInt(),//unsigned int serviceid = 0 query.value(4).toInt(),//unsigned int ba = 0, query.value(5).toInt(),//short status = 0, query.value(6).toInt(),//short lasthardstate = 0, query.value(7).toFloat(),//bool downtimed = false, query.value(8).toFloat(),//bool acknowledged = false, query.value(9).toBool(),//bool ignoredowntime = false, query.value(10).toBool(),//bool ignoreacknowledgement = false, query.value(11).toDouble(),//double warning = 0, query.value(12).toDouble(),//double critical = 0, query.value(13).toDouble()//double unknown = 0); )); } } /** * Load * * @param[out] list of bas in database */ void reader::_load(state::bas& bas) { QSqlQuery query = _db.exec("SELECT ba_id, " " name, " " current_level, " " level_w, " " level_c, " "FROM mod_bam"); _assert_query(query); while (query.next()) { bas.push_back( ba(query.value(0).toInt(), //unsigned int id = 0, query.value(1).toString().toStdString() ,//std::string const& name = "", query.value(2).toFloat(), //double level = 0.0, query.value(3).toFloat(), //double warning_level = 0.0 query.value(4).toFloat() //double critical_level = 0.0); )); } } /** * Load * * @param[out] list of bool expression in database */ void reader::_load(state::bool_exps& bool_exps) { QSqlQuery query = _db.exec("SELECT be.boolean_id, " " COALESCE(be.impact,imp.impact)" " be.expression," " be.bool_state," " be.current_state" "FROM mod_bam_boolean as be" "LEFT JOIN mod_bam_impacts as imp ON be.impact_id = imp.id_impact " ); _assert_query(query); while (query.next()) { bool_exps.push_back( bool_expression( query.value(0).toInt(), //unsigned int id = 0, query.value(1).toFloat(),//double impact = 0.0, query.value(2).toString().toStdString(),//std::string const& expression = "", query.value(3).toBool(),//bool impact_if = false, query.value(4).toBool()//bool state = false )); } } /** * Assert query * * @param[in] assert that the query succeeded */ void reader::_assert_query(QSqlQuery& query) { if(!query.isActive()){ throw reader_exception() << "Database Select Error: " << query.lastError().text() << ", Type: " << _dbinfo.get_type() << ", Host:" << _db.hostName() << ", Name:" << _db.databaseName() ; } } <|endoftext|>
<commit_before><commit_msg>drawing a vertical/horizontal line does not really damage 0 width/height areas<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <lcm/lcm-cpp.hpp> #include "drake/common/drake_assert.h" #include "drake/common/drake_path.h" #include "drake/common/polynomial.h" #include "drake/systems/plants/IKoptions.h" #include "drake/systems/plants/RigidBodyIK.h" #include "drake/systems/plants/RigidBodyTree.h" #include "drake/systems/plants/constraint/RigidBodyConstraint.h" #include "drake/systems/trajectories/PiecewisePolynomial.h" #include "drake/systems/vector.h" #include "lcmtypes/drake/lcmt_iiwa_command.hpp" #include "lcmtypes/drake/lcmt_iiwa_status.hpp" #include "iiwa_status.h" using Eigen::MatrixXd; using Eigen::VectorXd; using Eigen::VectorXi; using drake::Vector1d; using Eigen::Vector2d; using Eigen::Vector3d; namespace drake { namespace examples { namespace kuka_iiwa_arm { namespace { const char* kLcmCommandChannel = "IIWA_COMMAND"; /// This is a really simple demo class to run a trajectory which is /// the output of an IK plan. It lacks a lot of useful things, like a /// controller which does a remotely good job of mapping the /// trajectory onto the robot. The paramaters @p nT and @p t are /// identical to their usage for inverseKinPointwise (@p nT is number /// of time samples and @p t is an array of times in seconds). class TrajectoryRunner { public: TrajectoryRunner(std::shared_ptr<lcm::LCM> lcm, int nT, const double* t, const Eigen::MatrixXd& traj) : lcm_(lcm), nT_(nT), t_(t), traj_(traj) { lcm_->subscribe(IiwaStatus<double>::channel(), &TrajectoryRunner::HandleStatus, this); DRAKE_ASSERT(traj_.cols() == nT); } void Run() { typedef PiecewisePolynomial<double> PPType; typedef PPType::PolynomialType PPPoly; typedef PPType::PolynomialMatrix PPMatrix; std::vector<PPMatrix> polys; std::vector<double> times; // For each timestep, create a PolynomialMatrix for each joint // position. Each column of traj_ represents a particular time, // and the rows of that column contain values for each joint // coordinate. for (int i = 0; i < nT_; i++) { PPMatrix poly_matrix(traj_.rows(), 1); const auto traj_now = traj_.col(i); // Produce interpolating polynomials for each joint coordinate. for (int row = 0; row < traj_.rows(); row++) { Eigen::Vector2d coeffs(0, 0); coeffs[0] = traj_now(row); if (i != nT_ - 1) { // Set the coefficient such that it will reach the value of // the next timestep at the time when we advance to the next // piece. In the event that we're at the end of the // trajectory, this will be left 0. coeffs[1] = (traj_(row, i + 1) - coeffs[0]) / (t_[i + 1] - t_[i]); } poly_matrix(row) = PPPoly(coeffs); } polys.push_back(poly_matrix); times.push_back(t_[i]); } PPType pp_traj(polys, times); bool time_initialized = false; int64_t start_time_ms = -1; int64_t cur_time_ms = -1; const int64_t end_time_offset_ms = (t_[nT_ - 1] * 1e3); DRAKE_ASSERT(end_time_offset_ms > 0); lcmt_iiwa_command iiwa_command; iiwa_command.num_joints = kNumJoints; iiwa_command.joint_position.resize(kNumJoints, 0.); iiwa_command.num_torques = 0; iiwa_command.joint_torque.resize(kNumJoints, 0.); while (!time_initialized || cur_time_ms < (start_time_ms + end_time_offset_ms)) { // The argument to handleTimeout is in msec, and should be // safely bigger than e.g. a 200Hz input rate. int handled = lcm_->handleTimeout(10); if (handled <= 0) { std::cerr << "Failed to receive LCM status." << std::endl; return; } if (!time_initialized) { start_time_ms = iiwa_status_.timestamp; time_initialized = true; } cur_time_ms = iiwa_status_.timestamp; const double cur_traj_time_s = static_cast<double>(cur_time_ms - start_time_ms) / 1e3; const auto desired_next = pp_traj.value(cur_traj_time_s); iiwa_command.timestamp = iiwa_status_.timestamp; // This is totally arbitrary. There's no good reason to // implement this as a maximum delta to submit per tick. What // we actually need is something like a proper // planner/interpolater which spreads the motion out over the // entire duration from current_t to next_t, and commands the // next position taking into account the velocity of the joints // and the distance remaining. const double max_joint_delta = 0.1; for (int joint = 0; joint < kNumJoints; joint++) { double joint_delta = desired_next(joint) - iiwa_status_.joint_position_measured[joint]; joint_delta = std::max(-max_joint_delta, std::min(max_joint_delta, joint_delta)); iiwa_command.joint_position[joint] = iiwa_status_.joint_position_measured[joint] + joint_delta; } lcm_->publish(kLcmCommandChannel, &iiwa_command); } } private: void HandleStatus(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const lcmt_iiwa_status* status) { iiwa_status_ = *status; } static const int kNumJoints = 7; std::shared_ptr<lcm::LCM> lcm_; const int nT_; const double* t_; const Eigen::MatrixXd& traj_; lcmt_iiwa_status iiwa_status_; }; int do_main(int argc, const char* argv[]) { std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>(); RigidBodyTree tree( drake::GetDrakePath() + "/examples/kuka_iiwa_arm/urdf/iiwa14.urdf", DrakeJoint::FIXED); // Create a basic pointwise IK trajectory for moving the iiwa arm. // We start in the zero configuration (straight up). // TODO(sam.creasey) We should start planning with the robot's // current position rather than assuming vertical. VectorXd zero_conf = tree.getZeroConfiguration(); VectorXd joint_lb = zero_conf - VectorXd::Constant(7, 0.01); VectorXd joint_ub = zero_conf + VectorXd::Constant(7, 0.01); PostureConstraint pc1(&tree, Vector2d(0, 0.5)); VectorXi joint_idx(7); joint_idx << 0, 1, 2, 3, 4, 5, 6; pc1.setJointLimits(joint_idx, joint_lb, joint_ub); // Define an end effector constraint and make it active for the // timespan from 1 to 3 seconds. Vector3d pos_end; pos_end << 0.6, 0, 0.325; Vector3d pos_lb = pos_end - Vector3d::Constant(0.005); Vector3d pos_ub = pos_end + Vector3d::Constant(0.005); WorldPositionConstraint wpc(&tree, tree.FindBodyIndex("iiwa_link_ee"), Vector3d::Zero(), pos_lb, pos_ub, Vector2d(1, 3)); // After the end effector constraint is released, apply the straight // up configuration again. PostureConstraint pc2(&tree, Vector2d(4, 5.9)); pc2.setJointLimits(joint_idx, joint_lb, joint_ub); // Bring back the end effector constraint through second 9 of the // demo. WorldPositionConstraint wpc2(&tree, tree.FindBodyIndex("iiwa_link_ee"), Vector3d::Zero(), pos_lb, pos_ub, Vector2d(6, 9)); // For part of the remaining time, constrain the second joint while // preserving the end effector constraint. // // Variable `joint_position_start_idx` below is a collection of offsets into // the state vector referring to the positions of the joints to be // constrained. Eigen::VectorXi joint_position_start_idx(1); joint_position_start_idx(0) = tree.FindChildBodyOfJoint("iiwa_joint_2")-> get_position_start_index(); PostureConstraint pc3(&tree, Vector2d(6, 8)); pc3.setJointLimits(joint_position_start_idx, Vector1d(0.7), Vector1d(0.8)); const int kNumTimesteps = 5; double t[kNumTimesteps] = { 0.0, 2.0, 5.0, 7.0, 9.0 }; MatrixXd q0(tree.number_of_positions(), kNumTimesteps); for (int i = 0; i < kNumTimesteps; i++) { q0.col(i) = zero_conf; } std::vector<RigidBodyConstraint*> constraint_array; constraint_array.push_back(&pc1); constraint_array.push_back(&wpc); constraint_array.push_back(&pc2); constraint_array.push_back(&pc3); constraint_array.push_back(&wpc2); IKoptions ikoptions(&tree); int info[kNumTimesteps]; MatrixXd q_sol(tree.number_of_positions(), kNumTimesteps); std::vector<std::string> infeasible_constraint; inverseKinPointwise(&tree, kNumTimesteps, t, q0, q0, constraint_array.size(), constraint_array.data(), ikoptions, &q_sol, info, &infeasible_constraint); bool info_good = true; for (int i = 0; i < kNumTimesteps; i++) { printf("INFO[%d] = %d ", i, info[i]); if (info[i] != 1) { info_good = false; } } printf("\n"); if (!info_good) { std::cerr << "Solution failed, not sending." << std::endl; return 1; } // Now run through the plan. TrajectoryRunner runner(lcm, kNumTimesteps, t, q_sol); runner.Run(); return 0; } } // namespace } // namespace kuka_iiwa_arm } // namespace examples } // namespace drake int main(int argc, const char* argv[]) { return drake::examples::kuka_iiwa_arm::do_main(argc, argv); } <commit_msg>Fixes #3298<commit_after>#include <iostream> #include <lcm/lcm-cpp.hpp> #include "drake/common/drake_assert.h" #include "drake/common/drake_path.h" #include "drake/common/polynomial.h" #include "drake/systems/plants/IKoptions.h" #include "drake/systems/plants/RigidBodyIK.h" #include "drake/systems/plants/RigidBodyTree.h" #include "drake/systems/plants/constraint/RigidBodyConstraint.h" #include "drake/systems/trajectories/PiecewisePolynomial.h" #include "drake/systems/vector.h" #include "lcmtypes/drake/lcmt_iiwa_command.hpp" #include "lcmtypes/drake/lcmt_iiwa_status.hpp" #include "iiwa_status.h" using Eigen::MatrixXd; using Eigen::VectorXd; using Eigen::VectorXi; using drake::Vector1d; using Eigen::Vector2d; using Eigen::Vector3d; namespace drake { namespace examples { namespace kuka_iiwa_arm { namespace { const char* kLcmCommandChannel = "IIWA_COMMAND"; /// This is a really simple demo class to run a trajectory which is /// the output of an IK plan. It lacks a lot of useful things, like a /// controller which does a remotely good job of mapping the /// trajectory onto the robot. The paramaters @p nT and @p t are /// identical to their usage for inverseKinPointwise (@p nT is number /// of time samples and @p t is an array of times in seconds). class TrajectoryRunner { public: TrajectoryRunner(std::shared_ptr<lcm::LCM> lcm, int nT, const double* t, const Eigen::MatrixXd& traj) : lcm_(lcm), nT_(nT), t_(t), traj_(traj) { lcm_->subscribe(IiwaStatus<double>::channel(), &TrajectoryRunner::HandleStatus, this); DRAKE_ASSERT(traj_.cols() == nT); } void Run() { typedef PiecewisePolynomial<double> PPType; typedef PPType::PolynomialType PPPoly; typedef PPType::PolynomialMatrix PPMatrix; std::vector<PPMatrix> polys; std::vector<double> times; // For each timestep, create a PolynomialMatrix for each joint // position. Each column of traj_ represents a particular time, // and the rows of that column contain values for each joint // coordinate. for (int i = 0; i < nT_; i++) { PPMatrix poly_matrix(traj_.rows(), 1); const auto traj_now = traj_.col(i); // Produce interpolating polynomials for each joint coordinate. if (i != nT_ - 1) { for (int row = 0; row < traj_.rows(); row++) { Eigen::Vector2d coeffs(0, 0); coeffs[0] = traj_now(row); // Sets the coefficients for a linear polynomial within the interval // of time t_[i] < t < t_[i+1] so that the entire piecewise polynomial // is continuous at the time instances t_[i]. // PiecewisePolynomial<T>::value(T t) clamps t to be between t_[0] and // t_[nT-1] so that for t > t_[nT-1] the piecewise polynomial always // evaluates to the last trajectory instance, traj_.col(nT_-1). coeffs[1] = (traj_(row, i + 1) - coeffs[0]) / (t_[i + 1] - t_[i]); poly_matrix(row) = PPPoly(coeffs); } polys.push_back(poly_matrix); } times.push_back(t_[i]); } PPType pp_traj(polys, times); bool time_initialized = false; int64_t start_time_ms = -1; int64_t cur_time_ms = -1; const int64_t end_time_offset_ms = (t_[nT_ - 1] * 1e3); DRAKE_ASSERT(end_time_offset_ms > 0); lcmt_iiwa_command iiwa_command; iiwa_command.num_joints = kNumJoints; iiwa_command.joint_position.resize(kNumJoints, 0.); iiwa_command.num_torques = 0; iiwa_command.joint_torque.resize(kNumJoints, 0.); while (!time_initialized || cur_time_ms < (start_time_ms + end_time_offset_ms)) { // The argument to handleTimeout is in msec, and should be // safely bigger than e.g. a 200Hz input rate. int handled = lcm_->handleTimeout(10); if (handled <= 0) { std::cerr << "Failed to receive LCM status." << std::endl; return; } if (!time_initialized) { start_time_ms = iiwa_status_.timestamp; time_initialized = true; } cur_time_ms = iiwa_status_.timestamp; const double cur_traj_time_s = static_cast<double>(cur_time_ms - start_time_ms) / 1e3; const auto desired_next = pp_traj.value(cur_traj_time_s); iiwa_command.timestamp = iiwa_status_.timestamp; // This is totally arbitrary. There's no good reason to // implement this as a maximum delta to submit per tick. What // we actually need is something like a proper // planner/interpolater which spreads the motion out over the // entire duration from current_t to next_t, and commands the // next position taking into account the velocity of the joints // and the distance remaining. const double max_joint_delta = 0.1; for (int joint = 0; joint < kNumJoints; joint++) { double joint_delta = desired_next(joint) - iiwa_status_.joint_position_measured[joint]; joint_delta = std::max(-max_joint_delta, std::min(max_joint_delta, joint_delta)); iiwa_command.joint_position[joint] = iiwa_status_.joint_position_measured[joint] + joint_delta; } lcm_->publish(kLcmCommandChannel, &iiwa_command); } } private: void HandleStatus(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const lcmt_iiwa_status* status) { iiwa_status_ = *status; } static const int kNumJoints = 7; std::shared_ptr<lcm::LCM> lcm_; const int nT_; const double* t_; const Eigen::MatrixXd& traj_; lcmt_iiwa_status iiwa_status_; }; int do_main(int argc, const char* argv[]) { std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>(); RigidBodyTree tree( drake::GetDrakePath() + "/examples/kuka_iiwa_arm/urdf/iiwa14.urdf", DrakeJoint::FIXED); // Create a basic pointwise IK trajectory for moving the iiwa arm. // We start in the zero configuration (straight up). // TODO(sam.creasey) We should start planning with the robot's // current position rather than assuming vertical. VectorXd zero_conf = tree.getZeroConfiguration(); VectorXd joint_lb = zero_conf - VectorXd::Constant(7, 0.01); VectorXd joint_ub = zero_conf + VectorXd::Constant(7, 0.01); PostureConstraint pc1(&tree, Vector2d(0, 0.5)); VectorXi joint_idx(7); joint_idx << 0, 1, 2, 3, 4, 5, 6; pc1.setJointLimits(joint_idx, joint_lb, joint_ub); // Define an end effector constraint and make it active for the // timespan from 1 to 3 seconds. Vector3d pos_end; pos_end << 0.6, 0, 0.325; Vector3d pos_lb = pos_end - Vector3d::Constant(0.005); Vector3d pos_ub = pos_end + Vector3d::Constant(0.005); WorldPositionConstraint wpc(&tree, tree.FindBodyIndex("iiwa_link_ee"), Vector3d::Zero(), pos_lb, pos_ub, Vector2d(1, 3)); // After the end effector constraint is released, apply the straight // up configuration again. PostureConstraint pc2(&tree, Vector2d(4, 5.9)); pc2.setJointLimits(joint_idx, joint_lb, joint_ub); // Bring back the end effector constraint through second 9 of the // demo. WorldPositionConstraint wpc2(&tree, tree.FindBodyIndex("iiwa_link_ee"), Vector3d::Zero(), pos_lb, pos_ub, Vector2d(6, 9)); // For part of the remaining time, constrain the second joint while // preserving the end effector constraint. // // Variable `joint_position_start_idx` below is a collection of offsets into // the state vector referring to the positions of the joints to be // constrained. Eigen::VectorXi joint_position_start_idx(1); joint_position_start_idx(0) = tree.FindChildBodyOfJoint("iiwa_joint_2")-> get_position_start_index(); PostureConstraint pc3(&tree, Vector2d(6, 8)); pc3.setJointLimits(joint_position_start_idx, Vector1d(0.7), Vector1d(0.8)); const int kNumTimesteps = 5; double t[kNumTimesteps] = { 0.0, 2.0, 5.0, 7.0, 9.0 }; MatrixXd q0(tree.number_of_positions(), kNumTimesteps); for (int i = 0; i < kNumTimesteps; i++) { q0.col(i) = zero_conf; } std::vector<RigidBodyConstraint*> constraint_array; constraint_array.push_back(&pc1); constraint_array.push_back(&wpc); constraint_array.push_back(&pc2); constraint_array.push_back(&pc3); constraint_array.push_back(&wpc2); IKoptions ikoptions(&tree); int info[kNumTimesteps]; MatrixXd q_sol(tree.number_of_positions(), kNumTimesteps); std::vector<std::string> infeasible_constraint; inverseKinPointwise(&tree, kNumTimesteps, t, q0, q0, constraint_array.size(), constraint_array.data(), ikoptions, &q_sol, info, &infeasible_constraint); bool info_good = true; for (int i = 0; i < kNumTimesteps; i++) { printf("INFO[%d] = %d ", i, info[i]); if (info[i] != 1) { info_good = false; } } printf("\n"); if (!info_good) { std::cerr << "Solution failed, not sending." << std::endl; return 1; } // Now run through the plan. TrajectoryRunner runner(lcm, kNumTimesteps, t, q_sol); runner.Run(); return 0; } } // namespace } // namespace kuka_iiwa_arm } // namespace examples } // namespace drake int main(int argc, const char* argv[]) { return drake::examples::kuka_iiwa_arm::do_main(argc, argv); } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <Interface/Modules/Render/ViewScene.h> #include <Dataflow/Network/ModuleStateInterface.h> #include <Core/Datatypes/Geometry.h> #include <QFileDialog> using namespace SCIRun::Gui; using namespace SCIRun::Dataflow::Networks; //------------------------------------------------------------------------------ ViewSceneDialog::ViewSceneDialog(const std::string& name, ModuleStateHandle state, QWidget* parent /* = 0 */) : ModuleDialogGeneric(state, parent) { setupUi(this); setWindowTitle(QString::fromStdString(name)); // Setup Qt OpenGL widget. QGLFormat fmt; fmt.setAlpha(true); fmt.setRgba(true); mGLWidget = new GLWidget(fmt); // Hook up the GLWidget glLayout->addWidget(mGLWidget); glLayout->update(); // Grab the context and pass that to the module (via the state). // (should no longer be used). std::weak_ptr<Spire::Context> ctx = std::weak_ptr<Spire::Context>( std::dynamic_pointer_cast<Spire::Context>(mGLWidget->getContext())); state->setTransientValue("glContext", ctx); // Set spire transient value (should no longer be used). mSpire = std::weak_ptr<Spire::SCIRun::SRInterface>(mGLWidget->getSpire()); state->setTransientValue("spire", mSpire); } //------------------------------------------------------------------------------ ViewSceneDialog::~ViewSceneDialog() { delete mGLWidget; } //------------------------------------------------------------------------------ void ViewSceneDialog::moduleExecuted() { // Grab the geomData transient value. boost::any geomDataTransient = state_->getTransientValue("geomData"); if (!geomDataTransient.empty()) { boost::shared_ptr<Core::Datatypes::GeometryObject> geomData; try { geomData = boost::any_cast<boost::shared_ptr<Core::Datatypes::GeometryObject>>(geomDataTransient); } catch (const boost::bad_any_cast& e) { //error("Unable to cast boost::any transient value to spire pointer."); return; } // Send buffers to spire... std::shared_ptr<Spire::SCIRun::SRInterface> spire = mSpire.lock(); spire->renderHACKSetCommonVBO(geomData->vboCommon, geomData->vboCommonSize); spire->renderHACKSetUCFace(geomData->iboFaces, geomData->iboFacesSize); spire->renderHACKSetUCFaceColor(Spire::V4(1.0f, 1.0f, 1.0f, 0.3f)); spire->renderHACKSetUCEdge(geomData->iboEdges, geomData->iboEdgesSize); spire->renderHACKSetUCEdgeColor(Spire::V4(1.0f, 1.0f, 1.0f, 1.0f)); } } <commit_msg>Increased face transparency a tad.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <Interface/Modules/Render/ViewScene.h> #include <Dataflow/Network/ModuleStateInterface.h> #include <Core/Datatypes/Geometry.h> #include <QFileDialog> using namespace SCIRun::Gui; using namespace SCIRun::Dataflow::Networks; //------------------------------------------------------------------------------ ViewSceneDialog::ViewSceneDialog(const std::string& name, ModuleStateHandle state, QWidget* parent /* = 0 */) : ModuleDialogGeneric(state, parent) { setupUi(this); setWindowTitle(QString::fromStdString(name)); // Setup Qt OpenGL widget. QGLFormat fmt; fmt.setAlpha(true); fmt.setRgba(true); mGLWidget = new GLWidget(fmt); // Hook up the GLWidget glLayout->addWidget(mGLWidget); glLayout->update(); // Grab the context and pass that to the module (via the state). // (should no longer be used). std::weak_ptr<Spire::Context> ctx = std::weak_ptr<Spire::Context>( std::dynamic_pointer_cast<Spire::Context>(mGLWidget->getContext())); state->setTransientValue("glContext", ctx); // Set spire transient value (should no longer be used). mSpire = std::weak_ptr<Spire::SCIRun::SRInterface>(mGLWidget->getSpire()); state->setTransientValue("spire", mSpire); } //------------------------------------------------------------------------------ ViewSceneDialog::~ViewSceneDialog() { delete mGLWidget; } //------------------------------------------------------------------------------ void ViewSceneDialog::moduleExecuted() { // Grab the geomData transient value. boost::any geomDataTransient = state_->getTransientValue("geomData"); if (!geomDataTransient.empty()) { boost::shared_ptr<Core::Datatypes::GeometryObject> geomData; try { geomData = boost::any_cast<boost::shared_ptr<Core::Datatypes::GeometryObject>>(geomDataTransient); } catch (const boost::bad_any_cast& e) { //error("Unable to cast boost::any transient value to spire pointer."); return; } // Send buffers to spire... std::shared_ptr<Spire::SCIRun::SRInterface> spire = mSpire.lock(); spire->renderHACKSetCommonVBO(geomData->vboCommon, geomData->vboCommonSize); spire->renderHACKSetUCFace(geomData->iboFaces, geomData->iboFacesSize); spire->renderHACKSetUCFaceColor(Spire::V4(1.0f, 1.0f, 1.0f, 0.4f)); spire->renderHACKSetUCEdge(geomData->iboEdges, geomData->iboEdgesSize); spire->renderHACKSetUCEdgeColor(Spire::V4(1.0f, 1.0f, 1.0f, 1.0f)); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkImageToListGeneratorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // The example tests the class itk::Statistics::ImageToListGenerator. // The class is capable of generating an itk::ListSample from an image // confined to a mask (if specified). This test exercises that. #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImageToListGenerator.h" #include "itkImageRegionIteratorWithIndex.h" typedef itk::Image< unsigned char, 2 > ImageType; typedef itk::Image< unsigned char, 2 > MaskImageType; //------------------------------------------------------------------------ // Creates a 10 x 10 image of unsigned chars with pixel at location // (x,y) being yx. ie Pixel at (6,4) = 46. // static ImageType::Pointer CreateImage() { ImageType::Pointer image = ImageType::New(); ImageType::IndexType start = {0,0}; ImageType::SizeType size = {10,10}; ImageType::RegionType region( start, size ); image->SetRegions( region ); image->Allocate(); typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType; IteratorType it( image, region ); it.GoToBegin(); while (!it.IsAtEnd()) { it.Set( it.GetIndex()[1] * 10 + it.GetIndex()[0]); ++it; } return image; } //------------------------------------------------------------------------ // Creates a 10 x 10 image of unsigned chars with pixel from (2,3) - (8,5) as // 255 and rest as 0 static MaskImageType::Pointer CreateMaskImage() { MaskImageType::Pointer image = ImageType::New(); MaskImageType::IndexType start = {0,0}; MaskImageType::SizeType size = {10, 10}; MaskImageType::RegionType region( start, size ); image->SetRegions( region ); image->Allocate(); image->FillBuffer(0); MaskImageType::IndexType startMask = {2,3}; MaskImageType::SizeType sizeMask = {7, 3}; MaskImageType::RegionType regionMask( startMask, sizeMask); typedef itk::ImageRegionIteratorWithIndex< MaskImageType > IteratorType; IteratorType it( image, regionMask ); it.GoToBegin(); while (!it.IsAtEnd()) { it.Set((unsigned char)255); ++it; } return image; } int itkImageToListGeneratorTest(int, char* [] ) { ImageType::Pointer image = CreateImage(); MaskImageType::Pointer maskImage = CreateMaskImage(); // Generate a list sampel from "image" confined to the mask, "maskImage". typedef itk::Statistics::ImageToListGenerator< ImageType, MaskImageType > ImageToListGeneratorType; ImageToListGeneratorType::Pointer listGenerator = ImageToListGeneratorType::New(); listGenerator->SetInput( image ); listGenerator->SetMaskImage( maskImage ); listGenerator->SetMaskValue( 255 ); listGenerator->Update(); typedef ImageToListGeneratorType::ListSampleType ListSampleType; ListSampleType * list = listGenerator->GetListSample(); // Check the sum of the pixels in the list sample. This should // be 945 ListSampleType::Iterator lit = list->Begin(); unsigned int sum = 0; while (lit != list->End()) { sum += lit.GetMeasurementVector()[0]; ++lit; } if (sum != 945) { std::cerr << "[FAILED]" << std::endl; std::cerr << " Sum of pixels in the list sample (masked) is : " << sum << " but should be 945."; return EXIT_FAILURE; } std::cerr << "[PASSED]" << std::endl; return EXIT_SUCCESS; } <commit_msg>COMP: Meaningless change to prevent VS6 from throwing an Internal Compiler Error.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkImageToListGeneratorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // The example tests the class itk::Statistics::ImageToListGenerator. // The class is capable of generating an itk::ListSample from an image // confined to a mask (if specified). This test exercises that. #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImageToListGenerator.h" #include "itkImageRegionIteratorWithIndex.h" typedef itk::Image< unsigned int , 2 > ImageType; typedef itk::Image< unsigned char, 2 > MaskImageType; //------------------------------------------------------------------------ // Creates a 10 x 10 image of unsigned chars with pixel at location // (x,y) being yx. ie Pixel at (6,4) = 46. // static ImageType::Pointer CreateImage() { ImageType::Pointer image = ImageType::New(); ImageType::IndexType start = {0,0}; ImageType::SizeType size = {10,10}; ImageType::RegionType region( start, size ); image->SetRegions( region ); image->Allocate(); typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType; IteratorType it( image, region ); it.GoToBegin(); while (!it.IsAtEnd()) { it.Set( it.GetIndex()[1] * 10 + it.GetIndex()[0]); ++it; } return image; } //------------------------------------------------------------------------ // Creates a 10 x 10 image of unsigned chars with pixel from (2,3) - (8,5) as // 255 and rest as 0 static MaskImageType::Pointer CreateMaskImage() { MaskImageType::Pointer image = MaskImageType::New(); MaskImageType::IndexType start = {0,0}; MaskImageType::SizeType size = {10, 10}; MaskImageType::RegionType region( start, size ); image->SetRegions( region ); image->Allocate(); image->FillBuffer(0); MaskImageType::IndexType startMask = {2,3}; MaskImageType::SizeType sizeMask = {7, 3}; MaskImageType::RegionType regionMask( startMask, sizeMask); typedef itk::ImageRegionIteratorWithIndex< MaskImageType > IteratorType; IteratorType it( image, regionMask ); it.GoToBegin(); while (!it.IsAtEnd()) { it.Set((unsigned char)255); ++it; } return image; } int itkImageToListGeneratorTest(int, char* [] ) { ImageType::Pointer image = CreateImage(); MaskImageType::Pointer maskImage = CreateMaskImage(); // Generate a list sampel from "image" confined to the mask, "maskImage". typedef itk::Statistics::ImageToListGenerator< ImageType, MaskImageType > ImageToListGeneratorType; ImageToListGeneratorType::Pointer listGenerator = ImageToListGeneratorType::New(); listGenerator->SetInput( image ); listGenerator->SetMaskImage( maskImage ); listGenerator->SetMaskValue( 255 ); listGenerator->Update(); typedef ImageToListGeneratorType::ListSampleType ListSampleType; ListSampleType * list = listGenerator->GetListSample(); // Check the sum of the pixels in the list sample. This should // be 945 ListSampleType::Iterator lit = list->Begin(); unsigned int sum = 0; while (lit != list->End()) { sum += lit.GetMeasurementVector()[0]; ++lit; } if (sum != 945) { std::cerr << "[FAILED]" << std::endl; std::cerr << " Sum of pixels in the list sample (masked) is : " << sum << " but should be 945."; return EXIT_FAILURE; } std::cerr << "[PASSED]" << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>Fix memory allocation fprintf statements to use C89 instead of C99<commit_after><|endoftext|>
<commit_before>//---------------------------------------------------------------------------- // // "Copyright Centre National d'Etudes Spatiales" // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id$ #include "ossimPluginProjectionFactory.h" #include <ossim/base/ossimKeywordNames.h> #include <ossim/base/ossimRefPtr.h> #include <ossim/projection/ossimProjection.h> #include "ossimRadarSatModel.h" #include "ossimEnvisatAsarModel.h" #include "ossimTerraSarModel.h" //#include <ossim/projection/ossimCosmoSkymedModel.h> #include "ossimRadarSat2Model.h" #include "ossimErsSarModel.h" #include "ossimAlosPalsarModel.h" namespace ossimplugins { ossimPluginProjectionFactory* ossimPluginProjectionFactory::instance() { static ossimPluginProjectionFactory* factoryInstance = new ossimPluginProjectionFactory(); return factoryInstance; } ossimProjection* ossimPluginProjectionFactory::createProjection( const ossimFilename& filename, ossim_uint32 /*entryIdx*/)const { ossimRefPtr<ossimProjection> result = 0; if ( !result ) { ossimRefPtr<ossimRadarSat2Model> model = new ossimRadarSat2Model(); if ( model->open(filename) ) { result = model.get(); } else { model = 0; } } if ( !result ) { ossimRefPtr<ossimTerraSarModel> model = new ossimTerraSarModel(); if ( model->open(filename) ) { result = model.get(); } else { model = 0; } } if ( !result ) { ossimRefPtr<ossimErsSarModel> model = new ossimErsSarModel(); if ( model->open(filename) ) { result = model.get(); } else { model = 0; } } if (!result) { ossimRefPtr<ossimEnvisatAsarModel> model = new ossimEnvisatAsarModel(); if (model->open(filename)) { result = model.get(); } else { model = 0; } } if (!result) { ossimRefPtr<ossimRadarSatModel> model = new ossimRadarSatModel(); if (model->open(filename)) { result = model.get(); } else { model = 0; } } if (!result) { ossimRefPtr<ossimAlosPalsarModel> model = new ossimAlosPalsarModel(); if (model->open(filename)) { result = model.get(); } else { model = 0; } } return result.release(); } ossimProjection* ossimPluginProjectionFactory::createProjection( const ossimString& name)const { // if (name == STATIC_TYPE_NAME(ossimRadarSatModel)) // { // return new ossimRadarSatModel; // } // else if (name == STATIC_TYPE_NAME(ossimEnvisatAsarModel)) // { // return new ossimEnvisatAsarModel; // } // else if (name == STATIC_TYPE_NAME(ossimTerraSarModel)) // { // return new ossimTerraSarModel; // } // else if (name == STATIC_TYPE_NAME(ossimCosmoSkymedModel)) // { // return new ossimCosmoSkymedModel; // } if (name == STATIC_TYPE_NAME(ossimRadarSat2Model)) { return new ossimRadarSat2Model(); } else if (name == STATIC_TYPE_NAME(ossimTerraSarModel)) { return new ossimTerraSarModel(); } else if (name == STATIC_TYPE_NAME(ossimErsSarModel)) { return new ossimErsSarModel; } else if (name == STATIC_TYPE_NAME(ossimEnvisatAsarModel)) { return new ossimEnvisatAsarModel; } else if (name == STATIC_TYPE_NAME(ossimRadarSatModel)) { return new ossimRadarSatModel; } else if (name == STATIC_TYPE_NAME(ossimAlosPalsarModel)) { return new ossimRadarSatModel; } return 0; } ossimProjection* ossimPluginProjectionFactory::createProjection( const ossimKeywordlist& kwl, const char* prefix)const { ossimRefPtr<ossimProjection> result = 0; const char* lookup = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if (lookup) { ossimString type = lookup; if (type == "ossimRadarSat2Model") { result = new ossimRadarSat2Model(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } else if (type == "ossimTerraSarModel") { result = new ossimTerraSarModel(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } else if (type == "ossimErsSarModel") { result = new ossimErsSarModel(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } else if (type == "ossimEnvisatAsarModel") { result = new ossimEnvisatAsarModel(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } else if (type == "ossimRadarSatModel") { result = new ossimRadarSatModel(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } else if (type == "ossimAlosPalsarModel") { result = new ossimAlosPalsarModel(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } } return result.release(); } ossimObject* ossimPluginProjectionFactory::createObject( const ossimString& typeName)const { return createProjection(typeName); } ossimObject* ossimPluginProjectionFactory::createObject( const ossimKeywordlist& kwl, const char* prefix)const { return createProjection(kwl, prefix); } void ossimPluginProjectionFactory::getTypeNameList(std::vector<ossimString>& typeList)const { typeList.push_back(STATIC_TYPE_NAME(ossimRadarSatModel)); typeList.push_back(STATIC_TYPE_NAME(ossimRadarSat2Model)); typeList.push_back(STATIC_TYPE_NAME(ossimTerraSarModel)); // result.push_back(STATIC_TYPE_NAME(ossimCosmoSkymedModel)); typeList.push_back(STATIC_TYPE_NAME(ossimEnvisatAsarModel)); typeList.push_back(STATIC_TYPE_NAME(ossimErsSarModel)); typeList.push_back(STATIC_TYPE_NAME(ossimAlosPalsarModel)); } } <commit_msg>STYLE: remove unused lines<commit_after>//---------------------------------------------------------------------------- // // "Copyright Centre National d'Etudes Spatiales" // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id$ #include "ossimPluginProjectionFactory.h" #include <ossim/base/ossimKeywordNames.h> #include <ossim/base/ossimRefPtr.h> #include <ossim/projection/ossimProjection.h> #include "ossimRadarSatModel.h" #include "ossimEnvisatAsarModel.h" #include "ossimTerraSarModel.h" //#include <ossim/projection/ossimCosmoSkymedModel.h> #include "ossimRadarSat2Model.h" #include "ossimErsSarModel.h" #include "ossimAlosPalsarModel.h" namespace ossimplugins { ossimPluginProjectionFactory* ossimPluginProjectionFactory::instance() { static ossimPluginProjectionFactory* factoryInstance = new ossimPluginProjectionFactory(); return factoryInstance; } ossimProjection* ossimPluginProjectionFactory::createProjection( const ossimFilename& filename, ossim_uint32 /*entryIdx*/)const { ossimRefPtr<ossimProjection> result = 0; if ( !result ) { ossimRefPtr<ossimRadarSat2Model> model = new ossimRadarSat2Model(); if ( model->open(filename) ) { result = model.get(); } else { model = 0; } } if ( !result ) { ossimRefPtr<ossimTerraSarModel> model = new ossimTerraSarModel(); if ( model->open(filename) ) { result = model.get(); } else { model = 0; } } if ( !result ) { ossimRefPtr<ossimErsSarModel> model = new ossimErsSarModel(); if ( model->open(filename) ) { result = model.get(); } else { model = 0; } } if (!result) { ossimRefPtr<ossimEnvisatAsarModel> model = new ossimEnvisatAsarModel(); if (model->open(filename)) { result = model.get(); } else { model = 0; } } if (!result) { ossimRefPtr<ossimRadarSatModel> model = new ossimRadarSatModel(); if (model->open(filename)) { result = model.get(); } else { model = 0; } } if (!result) { ossimRefPtr<ossimAlosPalsarModel> model = new ossimAlosPalsarModel(); if (model->open(filename)) { result = model.get(); } else { model = 0; } } return result.release(); } ossimProjection* ossimPluginProjectionFactory::createProjection( const ossimString& name)const { // else if (name == STATIC_TYPE_NAME(ossimCosmoSkymedModel)) // { // return new ossimCosmoSkymedModel; // } if (name == STATIC_TYPE_NAME(ossimRadarSat2Model)) { return new ossimRadarSat2Model(); } else if (name == STATIC_TYPE_NAME(ossimTerraSarModel)) { return new ossimTerraSarModel(); } else if (name == STATIC_TYPE_NAME(ossimErsSarModel)) { return new ossimErsSarModel; } else if (name == STATIC_TYPE_NAME(ossimEnvisatAsarModel)) { return new ossimEnvisatAsarModel; } else if (name == STATIC_TYPE_NAME(ossimRadarSatModel)) { return new ossimRadarSatModel; } else if (name == STATIC_TYPE_NAME(ossimAlosPalsarModel)) { return new ossimRadarSatModel; } return 0; } ossimProjection* ossimPluginProjectionFactory::createProjection( const ossimKeywordlist& kwl, const char* prefix)const { ossimRefPtr<ossimProjection> result = 0; const char* lookup = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if (lookup) { ossimString type = lookup; if (type == "ossimRadarSat2Model") { result = new ossimRadarSat2Model(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } else if (type == "ossimTerraSarModel") { result = new ossimTerraSarModel(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } else if (type == "ossimErsSarModel") { result = new ossimErsSarModel(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } else if (type == "ossimEnvisatAsarModel") { result = new ossimEnvisatAsarModel(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } else if (type == "ossimRadarSatModel") { result = new ossimRadarSatModel(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } else if (type == "ossimAlosPalsarModel") { result = new ossimAlosPalsarModel(); if ( !result->loadState(kwl, prefix) ) { result = 0; } } } return result.release(); } ossimObject* ossimPluginProjectionFactory::createObject( const ossimString& typeName)const { return createProjection(typeName); } ossimObject* ossimPluginProjectionFactory::createObject( const ossimKeywordlist& kwl, const char* prefix)const { return createProjection(kwl, prefix); } void ossimPluginProjectionFactory::getTypeNameList(std::vector<ossimString>& typeList)const { typeList.push_back(STATIC_TYPE_NAME(ossimRadarSatModel)); typeList.push_back(STATIC_TYPE_NAME(ossimRadarSat2Model)); typeList.push_back(STATIC_TYPE_NAME(ossimTerraSarModel)); // result.push_back(STATIC_TYPE_NAME(ossimCosmoSkymedModel)); typeList.push_back(STATIC_TYPE_NAME(ossimEnvisatAsarModel)); typeList.push_back(STATIC_TYPE_NAME(ossimErsSarModel)); typeList.push_back(STATIC_TYPE_NAME(ossimAlosPalsarModel)); } } <|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 "ui/base/models/simple_menu_model.h" #include "base/message_loop.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/l10n/l10n_util.h" namespace ui { const int kSeparatorId = -1; struct SimpleMenuModel::Item { int command_id; string16 label; SkBitmap icon; ItemType type; int group_id; MenuModel* submenu; ButtonMenuItemModel* button_model; }; //////////////////////////////////////////////////////////////////////////////// // SimpleMenuModel::Delegate, public: bool SimpleMenuModel::Delegate::IsCommandIdVisible(int command_id) const { return true; } bool SimpleMenuModel::Delegate::IsItemForCommandIdDynamic( int command_id) const { return false; } string16 SimpleMenuModel::Delegate::GetLabelForCommandId(int command_id) const { return string16(); } bool SimpleMenuModel::Delegate::GetIconForCommandId( int command_id, SkBitmap* bitmap) const { return false; } void SimpleMenuModel::Delegate::CommandIdHighlighted(int command_id) { } void SimpleMenuModel::Delegate::ExecuteCommand( int command_id, int event_flags) { ExecuteCommand(command_id); } void SimpleMenuModel::Delegate::MenuWillShow(SimpleMenuModel* /*source*/) { } void SimpleMenuModel::Delegate::MenuClosed(SimpleMenuModel* /*source*/) { } //////////////////////////////////////////////////////////////////////////////// // SimpleMenuModel, public: SimpleMenuModel::SimpleMenuModel(Delegate* delegate) : delegate_(delegate), menu_model_delegate_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) { } SimpleMenuModel::~SimpleMenuModel() { } void SimpleMenuModel::AddItem(int command_id, const string16& label) { Item item = { command_id, label, SkBitmap(), TYPE_COMMAND, -1, NULL, NULL }; AppendItem(item); } void SimpleMenuModel::AddItemWithStringId(int command_id, int string_id) { AddItem(command_id, l10n_util::GetStringUTF16(string_id)); } void SimpleMenuModel::AddSeparator() { Item item = { kSeparatorId, string16(), SkBitmap(), TYPE_SEPARATOR, -1, NULL, NULL }; AppendItem(item); } void SimpleMenuModel::AddCheckItem(int command_id, const string16& label) { Item item = { command_id, label, SkBitmap(), TYPE_CHECK, -1, NULL }; AppendItem(item); } void SimpleMenuModel::AddCheckItemWithStringId(int command_id, int string_id) { AddCheckItem(command_id, l10n_util::GetStringUTF16(string_id)); } void SimpleMenuModel::AddRadioItem(int command_id, const string16& label, int group_id) { Item item = { command_id, label, SkBitmap(), TYPE_RADIO, group_id, NULL, NULL }; AppendItem(item); } void SimpleMenuModel::AddRadioItemWithStringId(int command_id, int string_id, int group_id) { AddRadioItem(command_id, l10n_util::GetStringUTF16(string_id), group_id); } void SimpleMenuModel::AddButtonItem(int command_id, ButtonMenuItemModel* model) { Item item = { command_id, string16(), SkBitmap(), TYPE_BUTTON_ITEM, -1, NULL, model }; AppendItem(item); } void SimpleMenuModel::AddSubMenu(int command_id, const string16& label, MenuModel* model) { Item item = { command_id, label, SkBitmap(), TYPE_SUBMENU, -1, model, NULL }; AppendItem(item); } void SimpleMenuModel::AddSubMenuWithStringId(int command_id, int string_id, MenuModel* model) { AddSubMenu(command_id, l10n_util::GetStringUTF16(string_id), model); } void SimpleMenuModel::InsertItemAt( int index, int command_id, const string16& label) { Item item = { command_id, label, SkBitmap(), TYPE_COMMAND, -1, NULL, NULL }; InsertItemAtIndex(item, index); } void SimpleMenuModel::InsertItemWithStringIdAt( int index, int command_id, int string_id) { InsertItemAt(index, command_id, l10n_util::GetStringUTF16(string_id)); } void SimpleMenuModel::InsertSeparatorAt(int index) { Item item = { kSeparatorId, string16(), SkBitmap(), TYPE_SEPARATOR, -1, NULL, NULL }; InsertItemAtIndex(item, index); } void SimpleMenuModel::InsertCheckItemAt( int index, int command_id, const string16& label) { Item item = { command_id, label, SkBitmap(), TYPE_CHECK, -1, NULL, NULL }; InsertItemAtIndex(item, index); } void SimpleMenuModel::InsertCheckItemWithStringIdAt( int index, int command_id, int string_id) { InsertCheckItemAt( FlipIndex(index), command_id, l10n_util::GetStringUTF16(string_id)); } void SimpleMenuModel::InsertRadioItemAt( int index, int command_id, const string16& label, int group_id) { Item item = { command_id, label, SkBitmap(), TYPE_RADIO, group_id, NULL, NULL }; InsertItemAtIndex(item, index); } void SimpleMenuModel::InsertRadioItemWithStringIdAt( int index, int command_id, int string_id, int group_id) { InsertRadioItemAt( index, command_id, l10n_util::GetStringUTF16(string_id), group_id); } void SimpleMenuModel::InsertSubMenuAt( int index, int command_id, const string16& label, MenuModel* model) { Item item = { command_id, label, SkBitmap(), TYPE_SUBMENU, -1, model, NULL }; InsertItemAtIndex(item, index); } void SimpleMenuModel::InsertSubMenuWithStringIdAt( int index, int command_id, int string_id, MenuModel* model) { InsertSubMenuAt(index, command_id, l10n_util::GetStringUTF16(string_id), model); } void SimpleMenuModel::SetIcon(int index, const SkBitmap& icon) { items_[index].icon = icon; } void SimpleMenuModel::Clear() { items_.clear(); } int SimpleMenuModel::GetIndexOfCommandId(int command_id) { std::vector<Item>::iterator itr; for (itr = items_.begin(); itr != items_.end(); itr++) { if ((*itr).command_id == command_id) { return FlipIndex(static_cast<int>(std::distance(items_.begin(), itr))); } } return -1; } //////////////////////////////////////////////////////////////////////////////// // SimpleMenuModel, MenuModel implementation: bool SimpleMenuModel::HasIcons() const { for (std::vector<Item>::const_iterator iter = items_.begin(); iter != items_.end(); ++iter) { if (!iter->icon.isNull()) return true; } return false; } int SimpleMenuModel::GetItemCount() const { return static_cast<int>(items_.size()); } MenuModel::ItemType SimpleMenuModel::GetTypeAt(int index) const { return items_.at(FlipIndex(index)).type; } int SimpleMenuModel::GetCommandIdAt(int index) const { return items_.at(FlipIndex(index)).command_id; } string16 SimpleMenuModel::GetLabelAt(int index) const { if (IsItemDynamicAt(index)) return delegate_->GetLabelForCommandId(GetCommandIdAt(index)); return items_.at(FlipIndex(index)).label; } bool SimpleMenuModel::IsItemDynamicAt(int index) const { if (delegate_) return delegate_->IsItemForCommandIdDynamic(GetCommandIdAt(index)); return false; } bool SimpleMenuModel::GetAcceleratorAt(int index, ui::Accelerator* accelerator) const { if (delegate_) { return delegate_->GetAcceleratorForCommandId(GetCommandIdAt(index), accelerator); } return false; } bool SimpleMenuModel::IsItemCheckedAt(int index) const { if (!delegate_) return false; int item_index = FlipIndex(index); MenuModel::ItemType item_type = items_[item_index].type; return (item_type == TYPE_CHECK || item_type == TYPE_RADIO) ? delegate_->IsCommandIdChecked(GetCommandIdAt(index)) : false; } int SimpleMenuModel::GetGroupIdAt(int index) const { return items_.at(FlipIndex(index)).group_id; } bool SimpleMenuModel::GetIconAt(int index, SkBitmap* icon) { if (IsItemDynamicAt(index)) return delegate_->GetIconForCommandId(GetCommandIdAt(index), icon); if (items_[index].icon.isNull()) return false; *icon = items_[index].icon; return true; } ButtonMenuItemModel* SimpleMenuModel::GetButtonMenuItemAt(int index) const { return items_.at(FlipIndex(index)).button_model; } bool SimpleMenuModel::IsEnabledAt(int index) const { int command_id = GetCommandIdAt(index); if (!delegate_ || command_id == kSeparatorId || items_.at(FlipIndex(index)).button_model) return true; return delegate_->IsCommandIdEnabled(command_id); } bool SimpleMenuModel::IsVisibleAt(int index) const { int command_id = GetCommandIdAt(index); if (!delegate_ || command_id == kSeparatorId || items_.at(FlipIndex(index)).button_model) return true; return delegate_->IsCommandIdVisible(command_id); } void SimpleMenuModel::HighlightChangedTo(int index) { if (delegate_) delegate_->CommandIdHighlighted(GetCommandIdAt(index)); } void SimpleMenuModel::ActivatedAt(int index) { if (delegate_) delegate_->ExecuteCommand(GetCommandIdAt(index)); } void SimpleMenuModel::ActivatedAt(int index, int event_flags) { if (delegate_) delegate_->ExecuteCommand(GetCommandIdAt(index), event_flags); } MenuModel* SimpleMenuModel::GetSubmenuModelAt(int index) const { return items_.at(FlipIndex(index)).submenu; } void SimpleMenuModel::MenuWillShow() { if (delegate_) delegate_->MenuWillShow(this); } void SimpleMenuModel::MenuClosed() { // Due to how menus work on the different platforms, ActivatedAt will be // called after this. It's more convenient for the delegate to be called // afterwards though, so post a task. MessageLoop::current()->PostTask( FROM_HERE, method_factory_.NewRunnableMethod(&SimpleMenuModel::OnMenuClosed)); } void SimpleMenuModel::SetMenuModelDelegate( ui::MenuModelDelegate* menu_model_delegate) { menu_model_delegate_ = menu_model_delegate; } void SimpleMenuModel::OnMenuClosed() { if (delegate_) delegate_->MenuClosed(this); } int SimpleMenuModel::FlipIndex(int index) const { return index; } //////////////////////////////////////////////////////////////////////////////// // SimpleMenuModel, Private: void SimpleMenuModel::AppendItem(const Item& item) { ValidateItem(item); items_.push_back(item); } void SimpleMenuModel::InsertItemAtIndex(const Item& item, int index) { ValidateItem(item); items_.insert(items_.begin() + FlipIndex(index), item); } void SimpleMenuModel::ValidateItem(const Item& item) { #ifndef NDEBUG if (item.type == TYPE_SEPARATOR) { DCHECK_EQ(item.command_id, kSeparatorId); } else { DCHECK_GE(item.command_id, 0); } #endif // NDEBUG } } // namespace ui <commit_msg>Adds some debugging code for a crash. I'm curious to see if the items are valid at the time we enter the destructor.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/base/models/simple_menu_model.h" #include "base/message_loop.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/l10n/l10n_util.h" namespace ui { const int kSeparatorId = -1; // The instance is alive. static const uint32 kMagicIdAlive = 0xCa11ab1e; // The instance has been deleted. static const uint32 kMagicIdDead = 0xDECEA5ED; struct SimpleMenuModel::Item { // TODO(sky): Remove this when done investigating 95851. #if defined(COMPILER_MSVC) #pragma optimize("", off) MSVC_PUSH_DISABLE_WARNING(4748) #endif ~Item() { CHECK_EQ(magic_id, kMagicIdAlive); magic_id = kMagicIdDead; } #if defined(COMPILER_MSVC) #pragma optimize("", off) MSVC_PUSH_DISABLE_WARNING(4748) #endif int command_id; string16 label; SkBitmap icon; ItemType type; int group_id; MenuModel* submenu; ButtonMenuItemModel* button_model; uint32 magic_id; }; //////////////////////////////////////////////////////////////////////////////// // SimpleMenuModel::Delegate, public: bool SimpleMenuModel::Delegate::IsCommandIdVisible(int command_id) const { return true; } bool SimpleMenuModel::Delegate::IsItemForCommandIdDynamic( int command_id) const { return false; } string16 SimpleMenuModel::Delegate::GetLabelForCommandId(int command_id) const { return string16(); } bool SimpleMenuModel::Delegate::GetIconForCommandId( int command_id, SkBitmap* bitmap) const { return false; } void SimpleMenuModel::Delegate::CommandIdHighlighted(int command_id) { } void SimpleMenuModel::Delegate::ExecuteCommand( int command_id, int event_flags) { ExecuteCommand(command_id); } void SimpleMenuModel::Delegate::MenuWillShow(SimpleMenuModel* /*source*/) { } void SimpleMenuModel::Delegate::MenuClosed(SimpleMenuModel* /*source*/) { } //////////////////////////////////////////////////////////////////////////////// // SimpleMenuModel, public: SimpleMenuModel::SimpleMenuModel(Delegate* delegate) : delegate_(delegate), menu_model_delegate_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) { } SimpleMenuModel::~SimpleMenuModel() { for (size_t i = 0; i < items_.size(); ++i) CHECK_EQ(kMagicIdAlive, items_[i].magic_id) << i; } void SimpleMenuModel::AddItem(int command_id, const string16& label) { Item item = { command_id, label, SkBitmap(), TYPE_COMMAND, -1, NULL, NULL, kMagicIdAlive}; AppendItem(item); } void SimpleMenuModel::AddItemWithStringId(int command_id, int string_id) { AddItem(command_id, l10n_util::GetStringUTF16(string_id)); } void SimpleMenuModel::AddSeparator() { Item item = { kSeparatorId, string16(), SkBitmap(), TYPE_SEPARATOR, -1, NULL, NULL, kMagicIdAlive }; AppendItem(item); } void SimpleMenuModel::AddCheckItem(int command_id, const string16& label) { Item item = { command_id, label, SkBitmap(), TYPE_CHECK, -1, NULL, NULL, kMagicIdAlive }; AppendItem(item); } void SimpleMenuModel::AddCheckItemWithStringId(int command_id, int string_id) { AddCheckItem(command_id, l10n_util::GetStringUTF16(string_id)); } void SimpleMenuModel::AddRadioItem(int command_id, const string16& label, int group_id) { Item item = { command_id, label, SkBitmap(), TYPE_RADIO, group_id, NULL, NULL, kMagicIdAlive }; AppendItem(item); } void SimpleMenuModel::AddRadioItemWithStringId(int command_id, int string_id, int group_id) { AddRadioItem(command_id, l10n_util::GetStringUTF16(string_id), group_id); } void SimpleMenuModel::AddButtonItem(int command_id, ButtonMenuItemModel* model) { Item item = { command_id, string16(), SkBitmap(), TYPE_BUTTON_ITEM, -1, NULL, model, kMagicIdAlive }; AppendItem(item); } void SimpleMenuModel::AddSubMenu(int command_id, const string16& label, MenuModel* model) { Item item = { command_id, label, SkBitmap(), TYPE_SUBMENU, -1, model, NULL, kMagicIdAlive }; AppendItem(item); } void SimpleMenuModel::AddSubMenuWithStringId(int command_id, int string_id, MenuModel* model) { AddSubMenu(command_id, l10n_util::GetStringUTF16(string_id), model); } void SimpleMenuModel::InsertItemAt( int index, int command_id, const string16& label) { Item item = { command_id, label, SkBitmap(), TYPE_COMMAND, -1, NULL, NULL, kMagicIdAlive }; InsertItemAtIndex(item, index); } void SimpleMenuModel::InsertItemWithStringIdAt( int index, int command_id, int string_id) { InsertItemAt(index, command_id, l10n_util::GetStringUTF16(string_id)); } void SimpleMenuModel::InsertSeparatorAt(int index) { Item item = { kSeparatorId, string16(), SkBitmap(), TYPE_SEPARATOR, -1, NULL, NULL, kMagicIdAlive }; InsertItemAtIndex(item, index); } void SimpleMenuModel::InsertCheckItemAt( int index, int command_id, const string16& label) { Item item = { command_id, label, SkBitmap(), TYPE_CHECK, -1, NULL, NULL, kMagicIdAlive }; InsertItemAtIndex(item, index); } void SimpleMenuModel::InsertCheckItemWithStringIdAt( int index, int command_id, int string_id) { InsertCheckItemAt( FlipIndex(index), command_id, l10n_util::GetStringUTF16(string_id)); } void SimpleMenuModel::InsertRadioItemAt( int index, int command_id, const string16& label, int group_id) { Item item = { command_id, label, SkBitmap(), TYPE_RADIO, group_id, NULL, NULL, kMagicIdAlive }; InsertItemAtIndex(item, index); } void SimpleMenuModel::InsertRadioItemWithStringIdAt( int index, int command_id, int string_id, int group_id) { InsertRadioItemAt( index, command_id, l10n_util::GetStringUTF16(string_id), group_id); } void SimpleMenuModel::InsertSubMenuAt( int index, int command_id, const string16& label, MenuModel* model) { Item item = { command_id, label, SkBitmap(), TYPE_SUBMENU, -1, model, NULL, kMagicIdAlive }; InsertItemAtIndex(item, index); } void SimpleMenuModel::InsertSubMenuWithStringIdAt( int index, int command_id, int string_id, MenuModel* model) { InsertSubMenuAt(index, command_id, l10n_util::GetStringUTF16(string_id), model); } void SimpleMenuModel::SetIcon(int index, const SkBitmap& icon) { items_[index].icon = icon; } void SimpleMenuModel::Clear() { items_.clear(); } int SimpleMenuModel::GetIndexOfCommandId(int command_id) { std::vector<Item>::iterator itr; for (itr = items_.begin(); itr != items_.end(); itr++) { if ((*itr).command_id == command_id) { return FlipIndex(static_cast<int>(std::distance(items_.begin(), itr))); } } return -1; } //////////////////////////////////////////////////////////////////////////////// // SimpleMenuModel, MenuModel implementation: bool SimpleMenuModel::HasIcons() const { for (std::vector<Item>::const_iterator iter = items_.begin(); iter != items_.end(); ++iter) { if (!iter->icon.isNull()) return true; } return false; } int SimpleMenuModel::GetItemCount() const { return static_cast<int>(items_.size()); } MenuModel::ItemType SimpleMenuModel::GetTypeAt(int index) const { return items_.at(FlipIndex(index)).type; } int SimpleMenuModel::GetCommandIdAt(int index) const { return items_.at(FlipIndex(index)).command_id; } string16 SimpleMenuModel::GetLabelAt(int index) const { if (IsItemDynamicAt(index)) return delegate_->GetLabelForCommandId(GetCommandIdAt(index)); return items_.at(FlipIndex(index)).label; } bool SimpleMenuModel::IsItemDynamicAt(int index) const { if (delegate_) return delegate_->IsItemForCommandIdDynamic(GetCommandIdAt(index)); return false; } bool SimpleMenuModel::GetAcceleratorAt(int index, ui::Accelerator* accelerator) const { if (delegate_) { return delegate_->GetAcceleratorForCommandId(GetCommandIdAt(index), accelerator); } return false; } bool SimpleMenuModel::IsItemCheckedAt(int index) const { if (!delegate_) return false; int item_index = FlipIndex(index); MenuModel::ItemType item_type = items_[item_index].type; return (item_type == TYPE_CHECK || item_type == TYPE_RADIO) ? delegate_->IsCommandIdChecked(GetCommandIdAt(index)) : false; } int SimpleMenuModel::GetGroupIdAt(int index) const { return items_.at(FlipIndex(index)).group_id; } bool SimpleMenuModel::GetIconAt(int index, SkBitmap* icon) { if (IsItemDynamicAt(index)) return delegate_->GetIconForCommandId(GetCommandIdAt(index), icon); if (items_[index].icon.isNull()) return false; *icon = items_[index].icon; return true; } ButtonMenuItemModel* SimpleMenuModel::GetButtonMenuItemAt(int index) const { return items_.at(FlipIndex(index)).button_model; } bool SimpleMenuModel::IsEnabledAt(int index) const { int command_id = GetCommandIdAt(index); if (!delegate_ || command_id == kSeparatorId || items_.at(FlipIndex(index)).button_model) return true; return delegate_->IsCommandIdEnabled(command_id); } bool SimpleMenuModel::IsVisibleAt(int index) const { int command_id = GetCommandIdAt(index); if (!delegate_ || command_id == kSeparatorId || items_.at(FlipIndex(index)).button_model) return true; return delegate_->IsCommandIdVisible(command_id); } void SimpleMenuModel::HighlightChangedTo(int index) { if (delegate_) delegate_->CommandIdHighlighted(GetCommandIdAt(index)); } void SimpleMenuModel::ActivatedAt(int index) { if (delegate_) delegate_->ExecuteCommand(GetCommandIdAt(index)); } void SimpleMenuModel::ActivatedAt(int index, int event_flags) { if (delegate_) delegate_->ExecuteCommand(GetCommandIdAt(index), event_flags); } MenuModel* SimpleMenuModel::GetSubmenuModelAt(int index) const { return items_.at(FlipIndex(index)).submenu; } void SimpleMenuModel::MenuWillShow() { if (delegate_) delegate_->MenuWillShow(this); } void SimpleMenuModel::MenuClosed() { // Due to how menus work on the different platforms, ActivatedAt will be // called after this. It's more convenient for the delegate to be called // afterwards though, so post a task. MessageLoop::current()->PostTask( FROM_HERE, method_factory_.NewRunnableMethod(&SimpleMenuModel::OnMenuClosed)); } void SimpleMenuModel::SetMenuModelDelegate( ui::MenuModelDelegate* menu_model_delegate) { menu_model_delegate_ = menu_model_delegate; } void SimpleMenuModel::OnMenuClosed() { if (delegate_) delegate_->MenuClosed(this); } int SimpleMenuModel::FlipIndex(int index) const { return index; } //////////////////////////////////////////////////////////////////////////////// // SimpleMenuModel, Private: void SimpleMenuModel::AppendItem(const Item& item) { ValidateItem(item); items_.push_back(item); } void SimpleMenuModel::InsertItemAtIndex(const Item& item, int index) { ValidateItem(item); items_.insert(items_.begin() + FlipIndex(index), item); } void SimpleMenuModel::ValidateItem(const Item& item) { #ifndef NDEBUG if (item.type == TYPE_SEPARATOR) { DCHECK_EQ(item.command_id, kSeparatorId); } else { DCHECK_GE(item.command_id, 0); } #endif // NDEBUG } } // namespace ui <|endoftext|>
<commit_before> #include "../DynamicElement/ArcBall.h" #include "../DynamicElement/Camera.h" #include "../DynamicElement/lodepng.h" #include "ParticleSystemSyn.h" bool pause = false; //true; // int g_width = 720; //640; int g_height = 480; int g_bmpCount = 0; CArcBall* ptrArcBall = NULL; CCamera* ptrCamera = NULL; CParticleSystemSyn* ptrSynthesizer = NULL; void SaveSnapshot() { if ( ptrSynthesizer->GetStepCount() < 1 && pause == true ) return; if ( ptrSynthesizer->GetStepCount() > CSynConfigBase::m_stepCountMax && pause == false ) return; int wd_mod = g_width % 4; int wd = (wd_mod == 0) ? g_width : (g_width + 4 - wd_mod); GLvoid* ptrVoid = new unsigned char[4 * g_width * g_height]; glReadPixels(0, 0, g_width, g_height, GL_RGBA, GL_UNSIGNED_BYTE, ptrVoid); std::vector<unsigned char> vecByte(4 * wd * g_height); char fileName[MAX_PATH]; #ifdef WIN32 sprintf(fileName, "%sSnapshot\\snapshot_%04d.png", CSynConfigBase::m_outputPrefix.c_str(), ptrSynthesizer->GetStepCount()); #else sprintf(fileName, "%sSnapshot/snapshot_%04d.png", CSynConfigBase::m_outputPrefix.c_str(), ptrSynthesizer->GetStepCount()); #endif unsigned char* ptrSrc = (unsigned char*)ptrVoid; for ( int j=0; j<g_height; j++ ) { for ( int i=0; i<g_width; i++ ) { for ( int k=0; k<4; k++ ) { vecByte[4 * ((g_height - 1 - j) * g_width + i) + k] = *(ptrSrc + k); } ptrSrc += 4; } } unsigned error = lodepng::encode(fileName, vecByte, g_width, g_height); if(error) std::cout << "PNG encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; delete [] (unsigned char*)ptrVoid; } void DumpCameraAndArcBall() { string fileName = "CameraAndArcBall.txt"; FILE* file; file = fopen(fileName.c_str(), "w"); if ( !file ) { cout << "Failed to dump camera and arc-ball into config file " << fileName << "!\n"; return; } ptrCamera->DumpCamera(file); ptrArcBall->DumpArcBall(file); fclose(file); cout << "Have dumped camera and arc-ball into config file " << fileName << "!\n"; } void LoadCameraAndArcBall() { string fileName = "CameraAndArcBall.txt"; ptrCamera->LoadCamera(fileName); ptrArcBall->LoadArcBall(fileName); cout << "Have loaded camera and arc-ball from config file " << fileName << "!\n"; } void DisplayFunc() { glClearColor(1.0f, 1.0f, 1.0f, 0.0f); // White background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Set look-at matrix ptrCamera->Draw(); // Rotate according to the arc-ball glPushMatrix(); glMultMatrixf(ptrArcBall->GetBallMatrix()); ptrSynthesizer->RenderOutput(); glPopMatrix(); SaveSnapshot(); glutSwapBuffers(); if ( ptrSynthesizer->GetStepCount() == CSynConfigBase::m_stepCountMax ) ptrSynthesizer->RestartSynthesis(); } void IdleFunc() { if ( pause == false ) { ptrSynthesizer->UpdateOutput(); cout << "Frame " << ptrSynthesizer->GetStepCount() << "...\n"; } glutPostRedisplay(); } void ReshapeFunc(int width, int height) { if( height == 0 ) { height = 1; } glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //gluPerspective(45, float(width)/float(height), 0.01, 1000); //gluOrtho2D(-3, 3, -2, 2); glOrtho(-3, 3, -2, 2, 0.01, 1000); glMatrixMode(GL_MODELVIEW); } void KeyboardFunc(unsigned char key, int x, int y) { switch(key) { case 'a': ptrCamera->MoveLeft(0.2f); break; case 'd': ptrCamera->MoveRight(0.2f); break; case 'w': ptrCamera->MoveForward(0.2f); break; case 's': ptrCamera->MoveBackward(0.2f); break; case 'r': ptrCamera->MoveUp(0.2f); break; case 'f': ptrCamera->MoveDown(0.2f); break; case 'q': ptrCamera->RotateY(-3); break; case 'e': ptrCamera->RotateY(3); break; case 't': ptrCamera->RotateX(3); break; case 'g': ptrCamera->RotateX(-3); break; case 'u': DumpCameraAndArcBall(); break; case 'l': LoadCameraAndArcBall(); break; case ' ': pause = !pause; break; case 27: // 'Esc' exit(0); break; default: break; } } void MouseFunc(int button, int state, int x, int y) { x = g_width - x; y = g_height - y; POINT tPoint; tPoint.x = x; tPoint.y = y; if ( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN ) { ptrArcBall->MouseDown(tPoint, g_width, g_height); } else if ( button == GLUT_LEFT_BUTTON && state == GLUT_UP ) { ptrArcBall->MouseUp(tPoint, g_width, g_height); } DisplayFunc(); } void MouseMoveFunc(int x, int y) { x = g_width - x; y = g_height - y; POINT tPoint; tPoint.x = x; tPoint.y = y; ptrArcBall->MouseMove(tPoint, g_width, g_height); DisplayFunc(); } void Initialize(const char* config_file_path) { ptrArcBall = new CArcBall; ptrArcBall->InitBall(); ptrCamera = new CCamera(0, 0, 4); ptrCamera->RotateY(180); ptrSynthesizer = new CParticleSystemSyn(config_file_path); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE); // set display mode glutInitWindowSize(g_width, g_height); // set window size glutInitWindowPosition(0, 0); // set window position on screen glutCreateWindow("Flow-Guided Synthesis of Particle System"); // set window title glutMouseFunc(MouseFunc); glutMotionFunc(MouseMoveFunc); glutKeyboardFunc(KeyboardFunc); glutDisplayFunc(DisplayFunc); glutReshapeFunc(ReshapeFunc); glutIdleFunc(IdleFunc); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_POINT_SMOOTH); glEnable(GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable(GL_POLYGON_SMOOTH_HINT); glEnable(GL_BLEND); //glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); LoadCameraAndArcBall(); } void ReleasePtr() { DELETE_OBJECT(ptrArcBall); DELETE_OBJECT(ptrCamera); } void usage(char** argv) { std::cout << "Usage: " << argv[0] << " config_file_path\n"; } int main(int argc, char **argv) { if ( argc < 2 ) { usage(argv); return -1; } glutInit(&argc, argv); Initialize(argv[1]); glutMainLoop(); ReleasePtr(); return 0; } <commit_msg>set glBlendFunc to fix rendering of particles under Mac<commit_after> #include "../DynamicElement/ArcBall.h" #include "../DynamicElement/Camera.h" #include "../DynamicElement/lodepng.h" #include "ParticleSystemSyn.h" bool pause = false; //true; // int g_width = 720; //640; int g_height = 480; int g_bmpCount = 0; CArcBall* ptrArcBall = NULL; CCamera* ptrCamera = NULL; CParticleSystemSyn* ptrSynthesizer = NULL; void SaveSnapshot() { if ( ptrSynthesizer->GetStepCount() < 1 && pause == true ) return; if ( ptrSynthesizer->GetStepCount() > CSynConfigBase::m_stepCountMax && pause == false ) return; int wd_mod = g_width % 4; int wd = (wd_mod == 0) ? g_width : (g_width + 4 - wd_mod); GLvoid* ptrVoid = new unsigned char[4 * g_width * g_height]; glReadPixels(0, 0, g_width, g_height, GL_RGBA, GL_UNSIGNED_BYTE, ptrVoid); std::vector<unsigned char> vecByte(4 * wd * g_height); char fileName[MAX_PATH]; #ifdef WIN32 sprintf(fileName, "%sSnapshot\\snapshot_%04d.png", CSynConfigBase::m_outputPrefix.c_str(), ptrSynthesizer->GetStepCount()); #else sprintf(fileName, "%sSnapshot/snapshot_%04d.png", CSynConfigBase::m_outputPrefix.c_str(), ptrSynthesizer->GetStepCount()); #endif unsigned char* ptrSrc = (unsigned char*)ptrVoid; for ( int j=0; j<g_height; j++ ) { for ( int i=0; i<g_width; i++ ) { for ( int k=0; k<4; k++ ) { vecByte[4 * ((g_height - 1 - j) * g_width + i) + k] = *(ptrSrc + k); } ptrSrc += 4; } } unsigned error = lodepng::encode(fileName, vecByte, g_width, g_height); if(error) std::cout << "PNG encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; delete [] (unsigned char*)ptrVoid; } void DumpCameraAndArcBall() { string fileName = "CameraAndArcBall.txt"; FILE* file; file = fopen(fileName.c_str(), "w"); if ( !file ) { cout << "Failed to dump camera and arc-ball into config file " << fileName << "!\n"; return; } ptrCamera->DumpCamera(file); ptrArcBall->DumpArcBall(file); fclose(file); cout << "Have dumped camera and arc-ball into config file " << fileName << "!\n"; } void LoadCameraAndArcBall() { string fileName = "CameraAndArcBall.txt"; ptrCamera->LoadCamera(fileName); ptrArcBall->LoadArcBall(fileName); cout << "Have loaded camera and arc-ball from config file " << fileName << "!\n"; } void DisplayFunc() { glClearColor(1.0f, 1.0f, 1.0f, 0.0f); // White background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Set look-at matrix ptrCamera->Draw(); // Rotate according to the arc-ball glPushMatrix(); glMultMatrixf(ptrArcBall->GetBallMatrix()); ptrSynthesizer->RenderOutput(); glPopMatrix(); SaveSnapshot(); glutSwapBuffers(); if ( ptrSynthesizer->GetStepCount() == CSynConfigBase::m_stepCountMax ) ptrSynthesizer->RestartSynthesis(); } void IdleFunc() { if ( pause == false ) { ptrSynthesizer->UpdateOutput(); cout << "Frame " << ptrSynthesizer->GetStepCount() << "...\n"; } glutPostRedisplay(); } void ReshapeFunc(int width, int height) { if( height == 0 ) { height = 1; } glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //gluPerspective(45, float(width)/float(height), 0.01, 1000); //gluOrtho2D(-3, 3, -2, 2); glOrtho(-3, 3, -2, 2, 0.01, 1000); glMatrixMode(GL_MODELVIEW); } void KeyboardFunc(unsigned char key, int x, int y) { switch(key) { case 'a': ptrCamera->MoveLeft(0.2f); break; case 'd': ptrCamera->MoveRight(0.2f); break; case 'w': ptrCamera->MoveForward(0.2f); break; case 's': ptrCamera->MoveBackward(0.2f); break; case 'r': ptrCamera->MoveUp(0.2f); break; case 'f': ptrCamera->MoveDown(0.2f); break; case 'q': ptrCamera->RotateY(-3); break; case 'e': ptrCamera->RotateY(3); break; case 't': ptrCamera->RotateX(3); break; case 'g': ptrCamera->RotateX(-3); break; case 'u': DumpCameraAndArcBall(); break; case 'l': LoadCameraAndArcBall(); break; case ' ': pause = !pause; break; case 27: // 'Esc' exit(0); break; default: break; } } void MouseFunc(int button, int state, int x, int y) { x = g_width - x; y = g_height - y; POINT tPoint; tPoint.x = x; tPoint.y = y; if ( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN ) { ptrArcBall->MouseDown(tPoint, g_width, g_height); } else if ( button == GLUT_LEFT_BUTTON && state == GLUT_UP ) { ptrArcBall->MouseUp(tPoint, g_width, g_height); } DisplayFunc(); } void MouseMoveFunc(int x, int y) { x = g_width - x; y = g_height - y; POINT tPoint; tPoint.x = x; tPoint.y = y; ptrArcBall->MouseMove(tPoint, g_width, g_height); DisplayFunc(); } void Initialize(const char* config_file_path) { ptrArcBall = new CArcBall; ptrArcBall->InitBall(); ptrCamera = new CCamera(0, 0, 4); ptrCamera->RotateY(180); ptrSynthesizer = new CParticleSystemSyn(config_file_path); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE); // set display mode glutInitWindowSize(g_width, g_height); // set window size glutInitWindowPosition(0, 0); // set window position on screen glutCreateWindow("Flow-Guided Synthesis of Particle System"); // set window title glutMouseFunc(MouseFunc); glutMotionFunc(MouseMoveFunc); glutKeyboardFunc(KeyboardFunc); glutDisplayFunc(DisplayFunc); glutReshapeFunc(ReshapeFunc); glutIdleFunc(IdleFunc); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_POINT_SMOOTH); glEnable(GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable(GL_POLYGON_SMOOTH_HINT); glEnable(GL_BLEND); glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_DST_ALPHA); LoadCameraAndArcBall(); } void ReleasePtr() { DELETE_OBJECT(ptrArcBall); DELETE_OBJECT(ptrCamera); } void usage(char** argv) { std::cout << "Usage: " << argv[0] << " config_file_path\n"; } int main(int argc, char **argv) { if ( argc < 2 ) { usage(argv); return -1; } glutInit(&argc, argv); Initialize(argv[1]); glutMainLoop(); ReleasePtr(); return 0; } <|endoftext|>
<commit_before>/* * Chord.cpp * iPhone_p2p_engine * * Created by LogNet team 2010 - INRIA * Mediteranee - Sophia Antipolis - France * */ #include "AbstractChord.h" #include "ProtocolSingleton.h" #include <stdlib.h> #include <math.h> #include <iostream> #include <sstream> #include <vector> // /////////////////////////////////////////// // // INITIALISE // // /////////////////////////////////////////// // void AbstractChord::initialise(string ip, int id, int port) { thisNode = new Node(ip, id, port); successor = thisNode; predecessor = thisNode; next = 0; // C++ we have to set next to zero to avoid possible garbage... alive = true; spacesize = 9; timeToCheck = 250; // miliSecond for (int i = 0; i < spacesize; i++) { fingerTable.push_back(thisNode); } } // /////////////////////////////////////////// // // CHORD ALGORITHM // // /////////////////////////////////////////// // Node* AbstractChord::findSuccessor(int id) { if (insideRange(id, thisNode->getId() + 1, successor->getId())) return successor; Node *pred = closestPrecedingNode(id); //Forge the message that we will sendRequest (FINDSUCC) std::ostringstream oss; oss << id; //Create a request. Request *request = new Request(this->getIdentifier(), FINDSUCC); request->addArg("id", oss.str()); string succ = sendRequest(request, pred); return new Node(succ); } Node* AbstractChord::closestPrecedingNode(int nid) { // optimization if (thisNode == successor) { return thisNode; } for (int i = fingerTable.size() - 1; i > 0; i--) { if (insideRange(fingerTable[i]->getId(), thisNode->getId() + 1, nid - 1)) { return fingerTable[i]; } } return successor; } void AbstractChord::join(Node* chord) { //Forge the actual request. Request *request = new Request(this->getIdentifier(), FINDSUCC); request->addArg("overlay_id", this->getIdentifier()); request->addArg("id", thisNode->getIdString()); //Send the request. string succ = this->sendRequest(request, chord); // update the successor successor = new Node(succ); } void AbstractChord::stabilize() { //Forge the message that we will sendRequest (GETPRED) Request *pred_request = new Request(this->getIdentifier(), GETPRED); string pred = sendRequest(pred_request, successor); Node *x = new Node(pred); if (x->getId() != thisNode->getId() && insideRange(x->getId(), thisNode->getId() + 1, successor->getId() - 1)) { successor = x; } //Forge the message that we will sendRequest (NOTIF) Request *notif_request = new Request(this->getIdentifier(), NOTIF); notif_request->addArg("node", thisNode->toString()); sendRequest(notif_request, successor); } void AbstractChord::notify(Node *node) { // cout << "AbstractChord::notify()\n"; if ((predecessor == NULL) || (insideRange(node->getId(), predecessor->getId() + 1, thisNode->getId() - 1))) predecessor = node; } void AbstractChord::fixFingersTable() { next++; if (next > spacesize) { next = 1; } fingerTable[next - 1] = findSuccessor((thisNode->getId() + (int) pow(2, next - 1)) % (int) pow(2, spacesize - 1)); } Node* AbstractChord::fixBrokenFingersTable(Node *node) { for (int i = 0; i < fingerTable.size() - 1; i++) { if (fingerTable[i]->getId() == node->getId()) { fingerTable[i] = new Node(thisNode->toString()); } } if (predecessor->getId() == node->getId()) { cout << "predecessor fixed!\n"; predecessor = new Node(thisNode->toString()); } if (successor->getId() == node->getId()) { cout << "successor fixed!\n"; successor = new Node(thisNode->toString()); } return thisNode; } void AbstractChord::checkPredecessor() { Request *request = new Request(this->getIdentifier(), CHECKPRED); sendRequest(request, predecessor); } // /////////////////////////////////////////// // // HELPER METHODS // // /////////////////////////////////////////// // bool AbstractChord::insideRange(int id, int begin, int end) { int MAXid = pow(2, spacesize); int MINid = 0; return (begin < end && begin <= id && id <= end) || (begin > end && ((begin <= id && id <= MAXid) || (MINid <= id && id <= end))) || ((begin == end) && (id == begin)); } string AbstractChord::printStatus() { stringstream ss(stringstream::in | stringstream::out); ss << getIdentifier() << " on " << thisNode->getIp() << ":" << thisNode->getPort() << "\n" << "<NODE: " << thisNode->getId() << ", PRED: " << predecessor->getId() << ", SUCC: " << successor->getId() << ">\n" << "\tFingers Table: ["; for (int i = 0; i < fingerTable.size() - 1; i++) { ss << fingerTable[i]->getId() << ", "; } ss << fingerTable[fingerTable.size() - 1]->getId() << "]\n\n"; return ss.str(); } <commit_msg> FIX: - fixFingersTable bug: (spacesize -1 => spacesize), fixed<commit_after>/* * Chord.cpp * iPhone_p2p_engine * * Created by LogNet team 2010 - INRIA * Mediteranee - Sophia Antipolis - France * */ #include "AbstractChord.h" #include "ProtocolSingleton.h" #include <stdlib.h> #include <math.h> #include <iostream> #include <sstream> #include <vector> // /////////////////////////////////////////// // // INITIALISE // // /////////////////////////////////////////// // void AbstractChord::initialise(string ip, int id, int port) { thisNode = new Node(ip, id, port); successor = thisNode; predecessor = thisNode; next = 0; // C++ we have to set next to zero to avoid possible garbage... alive = true; spacesize = 9; timeToCheck = 250; // miliSecond for (int i = 0; i < spacesize; i++) { fingerTable.push_back(thisNode); } } // /////////////////////////////////////////// // // CHORD ALGORITHM // // /////////////////////////////////////////// // Node* AbstractChord::findSuccessor(int id) { if (insideRange(id, thisNode->getId() + 1, successor->getId())) return successor; Node *pred = closestPrecedingNode(id); //Forge the message that we will sendRequest (FINDSUCC) std::ostringstream oss; oss << id; //Create a request. Request *request = new Request(this->getIdentifier(), FINDSUCC); request->addArg("id", oss.str()); string succ = sendRequest(request, pred); return new Node(succ); } Node* AbstractChord::closestPrecedingNode(int nid) { // optimization if (thisNode == successor) { return thisNode; } for (int i = fingerTable.size() - 1; i > 0; i--) { if (insideRange(fingerTable[i]->getId(), thisNode->getId() + 1, nid - 1)) { return fingerTable[i]; } } return successor; } void AbstractChord::join(Node* chord) { //Forge the actual request. Request *request = new Request(this->getIdentifier(), FINDSUCC); request->addArg("overlay_id", this->getIdentifier()); request->addArg("id", thisNode->getIdString()); //Send the request. string succ = this->sendRequest(request, chord); // update the successor successor = new Node(succ); } void AbstractChord::stabilize() { //Forge the message that we will sendRequest (GETPRED) Request *pred_request = new Request(this->getIdentifier(), GETPRED); string pred = sendRequest(pred_request, successor); Node *x = new Node(pred); if (x->getId() != thisNode->getId() && insideRange(x->getId(), thisNode->getId() + 1, successor->getId() - 1)) { successor = x; } //Forge the message that we will sendRequest (NOTIF) Request *notif_request = new Request(this->getIdentifier(), NOTIF); notif_request->addArg("node", thisNode->toString()); sendRequest(notif_request, successor); } void AbstractChord::notify(Node *node) { // cout << "AbstractChord::notify()\n"; if ((predecessor == NULL) || (insideRange(node->getId(), predecessor->getId() + 1, thisNode->getId() - 1))) predecessor = node; } void AbstractChord::fixFingersTable() { next++; if (next > spacesize) { next = 1; } fingerTable[next - 1] = findSuccessor((thisNode->getId() + (int) pow(2, next - 1)) % (int) pow(2, spacesize)); } Node* AbstractChord::fixBrokenFingersTable(Node *node) { for (int i = 0; i < fingerTable.size() - 1; i++) { if (fingerTable[i]->getId() == node->getId()) { fingerTable[i] = new Node(thisNode->toString()); } } if (predecessor->getId() == node->getId()) { cout << "predecessor fixed!\n"; predecessor = new Node(thisNode->toString()); } if (successor->getId() == node->getId()) { cout << "successor fixed!\n"; successor = new Node(thisNode->toString()); } return thisNode; } void AbstractChord::checkPredecessor() { Request *request = new Request(this->getIdentifier(), CHECKPRED); sendRequest(request, predecessor); } // /////////////////////////////////////////// // // HELPER METHODS // // /////////////////////////////////////////// // bool AbstractChord::insideRange(int id, int begin, int end) { int MAXid = pow(2, spacesize); int MINid = 0; return (begin < end && begin <= id && id <= end) || (begin > end && ((begin <= id && id <= MAXid) || (MINid <= id && id <= end))) || ((begin == end) && (id == begin)); } string AbstractChord::printStatus() { stringstream ss(stringstream::in | stringstream::out); ss << getIdentifier() << " on " << thisNode->getIp() << ":" << thisNode->getPort() << "\n" << "<NODE: " << thisNode->getId() << ", PRED: " << predecessor->getId() << ", SUCC: " << successor->getId() << ">\n" << "\tFingers Table: ["; for (int i = 0; i < fingerTable.size() - 1; i++) { ss << fingerTable[i]->getId() << ", "; } ss << fingerTable[fingerTable.size() - 1]->getId() << "]\n\n"; return ss.str(); } <|endoftext|>
<commit_before>#include "VMDCameraAnimation.h" #include <glm/gtc/matrix_transform.hpp> namespace saba { namespace { void SetVMDBezier(VMDBezier& bezier, int x0, int x1, int y0, int y1) { bezier.m_cp[0] = glm::vec2(0, 0); bezier.m_cp[1] = glm::vec2((float)x0 / 127.0f, (float)y0 / 127.0f); bezier.m_cp[2] = glm::vec2((float)x1 / 127.0f, (float)y1 / 127.0f); bezier.m_cp[3] = glm::vec2(1, 1); } } // namespace VMDCameraController::VMDCameraController() { } void VMDCameraController::Evaluate(float t) { if (m_keys.empty()) { return; } auto boundIt = std::upper_bound( std::begin(m_keys), std::end(m_keys), int32_t(t), [](int32_t lhs, const KeyType& rhs) { return lhs < rhs.m_time; } ); if (boundIt == std::end(m_keys)) { const auto& selectKey = m_keys[m_keys.size() - 1]; m_camera.m_interest = selectKey.m_interest; m_camera.m_rotate = selectKey.m_rotate; m_camera.m_distance = selectKey.m_distance; m_camera.m_fov = selectKey.m_fov; } else { const auto& selectKey = (*boundIt); m_camera.m_interest = selectKey.m_interest; m_camera.m_rotate = selectKey.m_rotate; m_camera.m_distance = selectKey.m_distance; m_camera.m_fov = selectKey.m_fov; if (boundIt != std::begin(m_keys)) { const auto& key0 = *(boundIt - 1); const auto& key1 = *boundIt; float timeRange = float(key1.m_time - key0.m_time); float time = (t - float(key0.m_time)) / timeRange; float ix_x = key0.m_ixBezier.FindBezierX(time); float iy_x = key0.m_iyBezier.FindBezierX(time); float iz_x = key0.m_izBezier.FindBezierX(time); float rotate_x = key0.m_rotateBezier.FindBezierX(time); float distance_x = key0.m_distanceBezier.FindBezierX(time); float fov_x = key0.m_fovBezier.FindBezierX(time); float ix_y = key0.m_ixBezier.EvalY(ix_x); float iy_y = key0.m_ixBezier.EvalY(iy_x); float iz_y = key0.m_ixBezier.EvalY(iz_x); float rotate_y = key0.m_rotateBezier.EvalY(rotate_x); float distance_y = key0.m_distanceBezier.EvalY(distance_x); float fov_y = key0.m_fovBezier.EvalY(fov_x); glm::vec3 di = key1.m_interest - key0.m_interest; m_camera.m_interest = di * glm::vec3(ix_y, iy_y, iz_y) + key0.m_interest; m_camera.m_rotate = glm::mix(key0.m_rotate, key1.m_rotate, rotate_y); m_camera.m_distance = glm::mix(key0.m_distance, key1.m_distance, distance_y); m_camera.m_fov = glm::mix(key0.m_fov, key1.m_fov, fov_y); } } } void VMDCameraController::SortKeys() { std::sort( std::begin(m_keys), std::end(m_keys), [](const KeyType& a, const KeyType& b) { return a.m_time < b.m_time; } ); } VMDCameraAnimation::VMDCameraAnimation() { Destroy(); } bool VMDCameraAnimation::Create(const VMDFile & vmd) { if (!vmd.m_cameras.empty()) { m_cameraController = std::make_unique<VMDCameraController>(); for (const auto& cam : vmd.m_cameras) { VMDCameraAnimationKey key; key.m_time = int32_t(cam.m_frame); key.m_interest = cam.m_interest * glm::vec3(1, 1, -1); key.m_rotate = cam.m_rotate; key.m_distance = cam.m_distance; key.m_fov = glm::radians((float)cam.m_viewAngle); const uint8_t* ip = cam.m_interpolation.data(); SetVMDBezier(key.m_ixBezier, ip[0], ip[1], ip[2], ip[3]); SetVMDBezier(key.m_iyBezier, ip[4], ip[5], ip[6], ip[7]); SetVMDBezier(key.m_izBezier, ip[8], ip[9], ip[10], ip[11]); SetVMDBezier(key.m_rotateBezier, ip[12], ip[13], ip[14], ip[15]); SetVMDBezier(key.m_distanceBezier, ip[16], ip[17], ip[18], ip[19]); SetVMDBezier(key.m_fovBezier, ip[20], ip[21], ip[22], ip[23]); m_cameraController->AddKey(key); } m_cameraController->SortKeys(); } else { return false; } return true; } void VMDCameraAnimation::Destroy() { m_cameraController.reset(); } void VMDCameraAnimation::Evaluate(float t) { m_cameraController->Evaluate(t); m_camera = m_cameraController->GetCamera(); } } <commit_msg>VMDCameraAnimation でカメラの切り替え時に補間を行わないようにした<commit_after>#include "VMDCameraAnimation.h" #include <glm/gtc/matrix_transform.hpp> namespace saba { namespace { void SetVMDBezier(VMDBezier& bezier, int x0, int x1, int y0, int y1) { bezier.m_cp[0] = glm::vec2(0, 0); bezier.m_cp[1] = glm::vec2((float)x0 / 127.0f, (float)y0 / 127.0f); bezier.m_cp[2] = glm::vec2((float)x1 / 127.0f, (float)y1 / 127.0f); bezier.m_cp[3] = glm::vec2(1, 1); } } // namespace VMDCameraController::VMDCameraController() { } void VMDCameraController::Evaluate(float t) { if (m_keys.empty()) { return; } auto boundIt = std::upper_bound( std::begin(m_keys), std::end(m_keys), int32_t(t), [](int32_t lhs, const KeyType& rhs) { return lhs < rhs.m_time; } ); if (boundIt == std::end(m_keys)) { const auto& selectKey = m_keys[m_keys.size() - 1]; m_camera.m_interest = selectKey.m_interest; m_camera.m_rotate = selectKey.m_rotate; m_camera.m_distance = selectKey.m_distance; m_camera.m_fov = selectKey.m_fov; } else { const auto& selectKey = (*boundIt); m_camera.m_interest = selectKey.m_interest; m_camera.m_rotate = selectKey.m_rotate; m_camera.m_distance = selectKey.m_distance; m_camera.m_fov = selectKey.m_fov; if (boundIt != std::begin(m_keys)) { const auto& key0 = *(boundIt - 1); const auto& key1 = *boundIt; if ((key1.m_time - key0.m_time) > 1) { float timeRange = float(key1.m_time - key0.m_time); float time = (t - float(key0.m_time)) / timeRange; float ix_x = key0.m_ixBezier.FindBezierX(time); float iy_x = key0.m_iyBezier.FindBezierX(time); float iz_x = key0.m_izBezier.FindBezierX(time); float rotate_x = key0.m_rotateBezier.FindBezierX(time); float distance_x = key0.m_distanceBezier.FindBezierX(time); float fov_x = key0.m_fovBezier.FindBezierX(time); float ix_y = key0.m_ixBezier.EvalY(ix_x); float iy_y = key0.m_ixBezier.EvalY(iy_x); float iz_y = key0.m_ixBezier.EvalY(iz_x); float rotate_y = key0.m_rotateBezier.EvalY(rotate_x); float distance_y = key0.m_distanceBezier.EvalY(distance_x); float fov_y = key0.m_fovBezier.EvalY(fov_x); glm::vec3 di = key1.m_interest - key0.m_interest; m_camera.m_interest = di * glm::vec3(ix_y, iy_y, iz_y) + key0.m_interest; m_camera.m_rotate = glm::mix(key0.m_rotate, key1.m_rotate, rotate_y); m_camera.m_distance = glm::mix(key0.m_distance, key1.m_distance, distance_y); m_camera.m_fov = glm::mix(key0.m_fov, key1.m_fov, fov_y); } else { /* カメラアニメーションでキーが1フレーム間隔で打たれている場合、 カメラの切り替えと判定し補間を行わないようにする(key0を使用する) */ m_camera.m_interest = key0.m_interest; m_camera.m_rotate = key0.m_rotate; m_camera.m_distance = key0.m_distance; m_camera.m_fov = key0.m_fov; } } } } void VMDCameraController::SortKeys() { std::sort( std::begin(m_keys), std::end(m_keys), [](const KeyType& a, const KeyType& b) { return a.m_time < b.m_time; } ); } VMDCameraAnimation::VMDCameraAnimation() { Destroy(); } bool VMDCameraAnimation::Create(const VMDFile & vmd) { if (!vmd.m_cameras.empty()) { m_cameraController = std::make_unique<VMDCameraController>(); for (const auto& cam : vmd.m_cameras) { VMDCameraAnimationKey key; key.m_time = int32_t(cam.m_frame); key.m_interest = cam.m_interest * glm::vec3(1, 1, -1); key.m_rotate = cam.m_rotate; key.m_distance = cam.m_distance; key.m_fov = glm::radians((float)cam.m_viewAngle); const uint8_t* ip = cam.m_interpolation.data(); SetVMDBezier(key.m_ixBezier, ip[0], ip[1], ip[2], ip[3]); SetVMDBezier(key.m_iyBezier, ip[4], ip[5], ip[6], ip[7]); SetVMDBezier(key.m_izBezier, ip[8], ip[9], ip[10], ip[11]); SetVMDBezier(key.m_rotateBezier, ip[12], ip[13], ip[14], ip[15]); SetVMDBezier(key.m_distanceBezier, ip[16], ip[17], ip[18], ip[19]); SetVMDBezier(key.m_fovBezier, ip[20], ip[21], ip[22], ip[23]); m_cameraController->AddKey(key); } m_cameraController->SortKeys(); } else { return false; } return true; } void VMDCameraAnimation::Destroy() { m_cameraController.reset(); } void VMDCameraAnimation::Evaluate(float t) { m_cameraController->Evaluate(t); m_camera = m_cameraController->GetCamera(); } } <|endoftext|>
<commit_before>/* Based on Allocore Example: Audio To Graphics by Lance Putnam */ #include <iostream> #include "allocore/io/al_App.hpp" #include "alloaudio/al_OutputMaster.hpp" #include "alloaudio/al_Convolver.hpp" #include "Gamma/SoundFile.h" #define BLOCK_SIZE 64 using namespace std; using namespace al; class MyApp : public App{ public: double phase; OutputMaster outMaster; Convolver conv; MyApp(int num_chnls, double sampleRate, const char * address = "", int inport = 19375, const char * sendAddress = "localhost", int sendPort = -1) : outMaster(num_chnls, sampleRate, address, inport, sendAddress, sendPort) { nav().pos(0,0,4); initWindow(); // Load IRs const char * path = "r1_ortf.wav"; SoundFile sf(path); sf.openRead(); int numIRChannels = sf.channels(), numFrames = sf.frames(); double fSR = sf.frameRate(); float * deinterleavedChannels[numIRChannels][numFrames]; if(sf.readAllD(deinterleavedChannels) == numFrames){ cout << "Could not read impulse response file" << endl; } int numActiveChannels; vector<int> disabledChannels; if(numIRChannels > num_chnls){ numActiveChannels = num_chnls; } else{ numActiveChannels = numIRChannels; if(numActiveChannels != num_chnls){//more outputs than IR channels for(int i = numActiveChannels; i < num_chnls; ++i){ disabledChannels.push_back(i); } } } initAudio(fSR, BLOCK_SIZE, numActiveChannels, numActiveChannels);//convolver also supports a mode with mono input // Setup convolver vector<float *> IRchannels; for(int i = 0; i< num_chnls; ++i){ IRchannels.push_back(*deinterleavedChannels[i]); } unsigned int options = 1;//uses FFTW_MEASURE //many to many mode conv.configure(this->audioIO(), IRchannels, numFrames, -1, false, disabledChannels, BLOCK_SIZE, options); } // Audio callback void onSound(AudioIOData& io){ outMaster.processBlock(io); } void onAnimate(double dt){ } void onDraw(Graphics& g, const Viewpoint& v){ } }; int main(){ int num_chnls = 4; double sampleRate = 44100; const char * address = "localhost"; int inport = 3002; const char * sendAddress = "localhost"; int sendPort = 3003; cout << "Listening to \"" << address << "\" on port " << inport << endl; cout << "Sending to \"" << sendAddress << "\" on port " << sendPort << endl; MyApp(num_chnls, sampleRate, address, inport, sendAddress, sendPort).start(); } <commit_msg>filled in convolver call in audio callback in example app, set num_chnls=2<commit_after>/* Based on Allocore Example: Audio To Graphics by Lance Putnam */ #include <iostream> #include "allocore/io/al_App.hpp" #include "alloaudio/al_OutputMaster.hpp" #include "alloaudio/al_Convolver.hpp" #include "Gamma/SoundFile.h" #define BLOCK_SIZE 64 using namespace std; using namespace al; class MyApp : public App{ public: double phase; OutputMaster outMaster; Convolver conv; MyApp(int num_chnls, double sampleRate, const char * address = "", int inport = 19375, const char * sendAddress = "localhost", int sendPort = -1) : outMaster(num_chnls, sampleRate, address, inport, sendAddress, sendPort) { nav().pos(0,0,4); initWindow(); // Load IRs const char * path = "r1_ortf.wav"; SoundFile sf(path); sf.openRead(); int numIRChannels = sf.channels(), numFrames = sf.frames(); double fSR = sf.frameRate(); float * deinterleavedChannels[numIRChannels][numFrames]; if(sf.readAllD(deinterleavedChannels) == numFrames){ cout << "Could not read impulse response file" << endl; } int numActiveChannels; vector<int> disabledChannels; if(numIRChannels > num_chnls){ numActiveChannels = num_chnls; } else{ numActiveChannels = numIRChannels; if(numActiveChannels != num_chnls){//more outputs than IR channels for(int i = numActiveChannels; i < num_chnls; ++i){ disabledChannels.push_back(i); } } } initAudio(fSR, BLOCK_SIZE, numActiveChannels, numActiveChannels);//convolver also supports a mode with mono input // Setup convolver vector<float *> IRchannels; for(int i = 0; i< num_chnls; ++i){ IRchannels.push_back(*deinterleavedChannels[i]); } unsigned int options = 1;//uses FFTW_MEASURE //many to many mode conv.configure(this->audioIO(), IRchannels, numFrames, -1, false, disabledChannels, BLOCK_SIZE, options); } // Audio callback void onSound(AudioIOData& io){ conv->processBlock(io); outMaster.processBlock(io); } void onAnimate(double dt){ } void onDraw(Graphics& g, const Viewpoint& v){ } }; int main(){ int num_chnls = 2; double sampleRate = 44100; const char * address = "localhost"; int inport = 3002; const char * sendAddress = "localhost"; int sendPort = 3003; cout << "Listening to \"" << address << "\" on port " << inport << endl; cout << "Sending to \"" << sendAddress << "\" on port " << sendPort << endl; MyApp(num_chnls, sampleRate, address, inport, sendAddress, sendPort).start(); } <|endoftext|>
<commit_before>#include "Framework.hpp" #include "../core/jni_helper.hpp" #include "coding/internal/file_data.hpp" #include "platform/mwm_version.hpp" #include "storage/storage.hpp" #include "std/bind.hpp" #include "std/shared_ptr.hpp" namespace { using namespace storage; enum ItemCategory : uint32_t { NEAR_ME, DOWNLOADED, ALL, }; jmethodID g_listAddMethod; jclass g_countryItemClass; jobject g_countryChangedListener; Storage & GetStorage() { return g_framework->Storage(); } void PrepareClassRefs(JNIEnv * env) { if (g_listAddMethod) return; jclass listClass = env->FindClass("java/util/List"); g_listAddMethod = env->GetMethodID(listClass, "add", "(Ljava/lang/Object;)Z"); g_countryItemClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/downloader/CountryItem"); } } // namespace extern "C" { // static boolean nativeMoveFile(String oldFile, String newFile); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_MapStorage_nativeMoveFile(JNIEnv * env, jclass clazz, jstring oldFile, jstring newFile) { return my::RenameFileX(jni::ToNativeString(env, oldFile), jni::ToNativeString(env, newFile)); } // static native boolean nativeIsLegacyMode(); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeIsLegacyMode(JNIEnv * env, jclass clazz) { return g_framework->NeedMigrate(); } // static void nativeMigrate(); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeMigrate(JNIEnv * env, jclass clazz) { g_framework->Migrate(); } // static int nativeGetDownloadedCount(); JNIEXPORT jint JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetDownloadedCount(JNIEnv * env, jclass clazz) { return GetStorage().GetDownloadedFilesCount(); } // static String nativeGetRootNode(); JNIEXPORT jstring JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetRootNode(JNIEnv * env, jclass clazz) { return jni::ToJavaString(env, Storage().GetRootId()); } // static @Nullable UpdateInfo nativeGetUpdateInfo(); JNIEXPORT jobject JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetUpdateInfo(JNIEnv * env, jclass clazz) { Storage::UpdateInfo info = { 0 }; if (!GetStorage().GetUpdateInfo(GetStorage().GetRootId(), info)) return nullptr; static jclass const infoClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/downloader/UpdateInfo"); ASSERT(infoClass, (jni::DescribeException())); static jmethodID const ctor = jni::GetConstructorID(env, infoClass, "(II)V"); ASSERT(ctor, (jni::DescribeException())); return env->NewObject(infoClass, ctor, info.m_numberOfMwmFilesToUpdate, info.m_totalUpdateSizeInBytes); } static void UpdateItem(JNIEnv * env, jobject item, NodeAttrs const & attrs) { static jfieldID const countryItemFieldName = env->GetFieldID(g_countryItemClass, "name", "Ljava/lang/String;"); static jfieldID const countryItemFieldParentId = env->GetFieldID(g_countryItemClass, "parentId", "Ljava/lang/String;"); static jfieldID const countryItemFieldParentName = env->GetFieldID(g_countryItemClass, "parentName", "Ljava/lang/String;"); static jfieldID const countryItemFieldSize = env->GetFieldID(g_countryItemClass, "size", "J"); static jfieldID const countryItemFieldTotalSize = env->GetFieldID(g_countryItemClass, "totalSize", "J"); static jfieldID const countryItemFieldChildCount = env->GetFieldID(g_countryItemClass, "childCount", "I"); static jfieldID const countryItemFieldTotalChildCount = env->GetFieldID(g_countryItemClass, "totalChildCount", "I"); static jfieldID const countryItemFieldStatus = env->GetFieldID(g_countryItemClass, "status", "I"); static jfieldID const countryItemFieldErrorCode = env->GetFieldID(g_countryItemClass, "errorCode", "I"); static jfieldID const countryItemFieldPresent = env->GetFieldID(g_countryItemClass, "present", "Z"); static jfieldID const countryItemFieldProgress = env->GetFieldID(g_countryItemClass, "progress", "I"); // Localized name jni::TScopedLocalRef const name(env, jni::ToJavaString(env, attrs.m_nodeLocalName)); env->SetObjectField(item, countryItemFieldName, name.get()); // Info about parent[s]. Do not specify if there are multiple parents or none. if (attrs.m_parentInfo.size() == 1) { CountryIdAndName const & info = attrs.m_parentInfo[0]; jni::TScopedLocalRef const parentId(env, jni::ToJavaString(env, info.m_id)); env->SetObjectField(item, countryItemFieldParentId, parentId.get()); jni::TScopedLocalRef const parentName(env, jni::ToJavaString(env, info.m_localName)); env->SetObjectField(item, countryItemFieldParentName, parentName.get()); } else { env->SetObjectField(item, countryItemFieldParentId, nullptr); env->SetObjectField(item, countryItemFieldParentName, nullptr); } // Sizes env->SetLongField(item, countryItemFieldSize, attrs.m_localMwmSize); env->SetLongField(item, countryItemFieldTotalSize, attrs.m_mwmSize); // Child counts env->SetIntField(item, countryItemFieldChildCount, attrs.m_localMwmCounter); env->SetIntField(item, countryItemFieldTotalChildCount, attrs.m_mwmCounter); // Status and error code env->SetIntField(item, countryItemFieldStatus, static_cast<jint>(attrs.m_status)); env->SetIntField(item, countryItemFieldErrorCode, static_cast<jint>(attrs.m_error)); // Presence flag env->SetBooleanField(item, countryItemFieldPresent, attrs.m_present); // Progress env->SetIntField(item, countryItemFieldProgress,static_cast<jint>(attrs.m_downloadingMwmSize)); } static void PutItemsToList(JNIEnv * env, jobject const list, vector<TCountryId> const & children, TCountryId const & parent, int category) { static jmethodID const countryItemCtor = jni::GetConstructorID(env, g_countryItemClass, "(Ljava/lang/String;)V"); static jfieldID const countryItemFieldCategory = env->GetFieldID(g_countryItemClass, "category", "I"); NodeAttrs attrs; for (TCountryId const & child : children) { GetStorage().GetNodeAttrs(child, attrs); jni::TScopedLocalRef const id(env, jni::ToJavaString(env, child)); jni::TScopedLocalRef const item(env, env->NewObject(g_countryItemClass, countryItemCtor, id.get())); env->SetIntField(item.get(), countryItemFieldCategory, category); UpdateItem(env, item.get(), attrs); // Put to resulting list env->CallBooleanMethod(list, g_listAddMethod, item.get()); } } // static void nativeListItems(@Nullable String parent, List<CountryItem> result); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeListItems(JNIEnv * env, jclass clazz, jstring parent, jobject result) { PrepareClassRefs(env); Storage const & storage = GetStorage(); TCountryId const parentId = (parent ? jni::ToNativeString(env, parent) : storage.GetRootId()); static jfieldID const countryItemFieldParentId = env->GetFieldID(g_countryItemClass, "parentId", "Ljava/lang/String;"); if (parent) { vector<TCountryId> children; storage.GetChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::ALL); } else { // TODO (trashkalmar): Countries near me // Downloaded vector<TCountryId> children; storage.GetDownloadedChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::DOWNLOADED); // All storage.GetChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::ALL); } } // static void nativeUpdateItem(CountryItem item); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetAttributes(JNIEnv * env, jclass clazz, jobject item) { PrepareClassRefs(env); NodeAttrs attrs; static jfieldID countryItemFieldId = env->GetFieldID(g_countryItemClass, "id", "Ljava/lang/String;"); jstring id = static_cast<jstring>(env->GetObjectField(item, countryItemFieldId)); GetStorage().GetNodeAttrs(jni::ToNativeString(env, id), attrs); UpdateItem(env, item, attrs); } // static @Nullable String nativeFindCountry(double lat, double lon); JNIEXPORT jstring JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeFindCountry(JNIEnv * env, jclass clazz, jdouble lat, jdouble lon) { return jni::ToJavaString(env, g_framework->NativeFramework()->CountryInfoGetter().GetRegionCountryId(MercatorBounds::FromLatLon(lat, lon))); } // static boolean nativeIsDownloading(); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeIsDownloading(JNIEnv * env, jclass clazz) { return GetStorage().IsDownloadInProgress(); } // static boolean nativeDownload(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeDownload(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().DownloadNode(jni::ToNativeString(env, root)); } // static boolean nativeRetry(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeRetry(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().RetryDownloadNode(jni::ToNativeString(env, root)); } // static boolean nativeUpdate(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUpdate(JNIEnv * env, jclass clazz, jstring root) { // FIXME (trashkalmar): Uncomment after method is implemented. //return GetStorage().UpdateNode(jni::ToNativeString(env, root)); return true; } // static boolean nativeCancel(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeCancel(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().CancelDownloadNode(jni::ToNativeString(env, root)); } // static void nativeDelete(String root); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeDelete(JNIEnv * env, jclass clazz, jstring root) { GetStorage().DeleteNode(jni::ToNativeString(env, root)); } static void StatusChangedCallback(shared_ptr<jobject> const & listenerRef, TCountryId const & countryId) { JNIEnv * env = jni::GetEnv(); // TODO: The core will do this itself NodeAttrs attrs; GetStorage().GetNodeAttrs(countryId, attrs); jmethodID const methodID = jni::GetMethodID(env, *listenerRef, "onStatusChanged", "(Ljava/lang/String;I)V"); env->CallVoidMethod(*listenerRef, methodID, jni::ToJavaString(env, countryId), attrs.m_status); } static void ProgressChangedCallback(shared_ptr<jobject> const & listenerRef, TCountryId const & countryId, TLocalAndRemoteSize const & sizes) { JNIEnv * env = jni::GetEnv(); jmethodID const methodID = jni::GetMethodID(env, *listenerRef, "onProgress", "(Ljava/lang/String;JJ)V"); env->CallVoidMethod(*listenerRef, methodID, jni::ToJavaString(env, countryId), sizes.first, sizes.second); } // static int nativeSubscribe(StorageCallback listener); JNIEXPORT jint JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeSubscribe(JNIEnv * env, jclass clazz, jobject listener) { PrepareClassRefs(env); return GetStorage().Subscribe(bind(&StatusChangedCallback, jni::make_global_ref(listener), _1), bind(&ProgressChangedCallback, jni::make_global_ref(listener), _1, _2)); } // static void nativeUnsubscribe(int slot); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUnsubscribe(JNIEnv * env, jclass clazz, jint slot) { GetStorage().Unsubscribe(slot); } // static void nativeSubscribeOnCountryChanged(CurrentCountryChangedListener listener); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeSubscribeOnCountryChanged(JNIEnv * env, jclass clazz, jobject listener) { ASSERT(!g_countryChangedListener, ()); g_countryChangedListener = env->NewGlobalRef(listener); auto const callback = [](TCountryId const & countryId) { JNIEnv * env = jni::GetEnv(); jmethodID methodID = jni::GetMethodID(env, g_countryChangedListener, "onCurrentCountryChanged", "(Ljava/lang/String;)V"); env->CallVoidMethod(g_countryChangedListener, methodID, jni::TScopedLocalRef(env, jni::ToJavaString(env, countryId)).get()); }; TCountryId const & prev = g_framework->NativeFramework()->GetLastReportedCountry(); g_framework->NativeFramework()->SetCurrentCountryChangedListener(callback); // Report previous value callback(prev); } // static void nativeUnsubscribeOnCountryChanged(); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUnsubscribeOnCountryChanged(JNIEnv * env, jclass clazz) { g_framework->NativeFramework()->SetCurrentCountryChangedListener(nullptr); ASSERT(g_countryChangedListener, ()); env->DeleteGlobalRef(g_countryChangedListener); g_countryChangedListener = nullptr; } } // extern "C" <commit_msg>[new downloader] Android buildfix.<commit_after>#include "Framework.hpp" #include "../core/jni_helper.hpp" #include "coding/internal/file_data.hpp" #include "platform/mwm_version.hpp" #include "storage/storage.hpp" #include "std/bind.hpp" #include "std/shared_ptr.hpp" namespace { using namespace storage; enum ItemCategory : uint32_t { NEAR_ME, DOWNLOADED, ALL, }; jmethodID g_listAddMethod; jclass g_countryItemClass; jobject g_countryChangedListener; Storage & GetStorage() { return g_framework->Storage(); } void PrepareClassRefs(JNIEnv * env) { if (g_listAddMethod) return; jclass listClass = env->FindClass("java/util/List"); g_listAddMethod = env->GetMethodID(listClass, "add", "(Ljava/lang/Object;)Z"); g_countryItemClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/downloader/CountryItem"); } } // namespace extern "C" { // static boolean nativeMoveFile(String oldFile, String newFile); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_MapStorage_nativeMoveFile(JNIEnv * env, jclass clazz, jstring oldFile, jstring newFile) { return my::RenameFileX(jni::ToNativeString(env, oldFile), jni::ToNativeString(env, newFile)); } // static native boolean nativeIsLegacyMode(); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeIsLegacyMode(JNIEnv * env, jclass clazz) { return g_framework->NeedMigrate(); } // static void nativeMigrate(); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeMigrate(JNIEnv * env, jclass clazz) { g_framework->Migrate(); } // static int nativeGetDownloadedCount(); JNIEXPORT jint JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetDownloadedCount(JNIEnv * env, jclass clazz) { return GetStorage().GetDownloadedFilesCount(); } // static String nativeGetRootNode(); JNIEXPORT jstring JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetRootNode(JNIEnv * env, jclass clazz) { return jni::ToJavaString(env, Storage().GetRootId()); } // static @Nullable UpdateInfo nativeGetUpdateInfo(); JNIEXPORT jobject JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetUpdateInfo(JNIEnv * env, jclass clazz) { Storage::UpdateInfo info = { 0 }; if (!GetStorage().GetUpdateInfo(GetStorage().GetRootId(), info)) return nullptr; static jclass const infoClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/downloader/UpdateInfo"); ASSERT(infoClass, (jni::DescribeException())); static jmethodID const ctor = jni::GetConstructorID(env, infoClass, "(II)V"); ASSERT(ctor, (jni::DescribeException())); return env->NewObject(infoClass, ctor, info.m_numberOfMwmFilesToUpdate, info.m_totalUpdateSizeInBytes); } static void UpdateItem(JNIEnv * env, jobject item, NodeAttrs const & attrs) { static jfieldID const countryItemFieldName = env->GetFieldID(g_countryItemClass, "name", "Ljava/lang/String;"); static jfieldID const countryItemFieldParentId = env->GetFieldID(g_countryItemClass, "parentId", "Ljava/lang/String;"); static jfieldID const countryItemFieldParentName = env->GetFieldID(g_countryItemClass, "parentName", "Ljava/lang/String;"); static jfieldID const countryItemFieldSize = env->GetFieldID(g_countryItemClass, "size", "J"); static jfieldID const countryItemFieldTotalSize = env->GetFieldID(g_countryItemClass, "totalSize", "J"); static jfieldID const countryItemFieldChildCount = env->GetFieldID(g_countryItemClass, "childCount", "I"); static jfieldID const countryItemFieldTotalChildCount = env->GetFieldID(g_countryItemClass, "totalChildCount", "I"); static jfieldID const countryItemFieldStatus = env->GetFieldID(g_countryItemClass, "status", "I"); static jfieldID const countryItemFieldErrorCode = env->GetFieldID(g_countryItemClass, "errorCode", "I"); static jfieldID const countryItemFieldPresent = env->GetFieldID(g_countryItemClass, "present", "Z"); static jfieldID const countryItemFieldProgress = env->GetFieldID(g_countryItemClass, "progress", "I"); // Localized name jni::TScopedLocalRef const name(env, jni::ToJavaString(env, attrs.m_nodeLocalName)); env->SetObjectField(item, countryItemFieldName, name.get()); // Info about parent[s]. Do not specify if there are multiple parents or none. if (attrs.m_parentInfo.size() == 1) { CountryIdAndName const & info = attrs.m_parentInfo[0]; jni::TScopedLocalRef const parentId(env, jni::ToJavaString(env, info.m_id)); env->SetObjectField(item, countryItemFieldParentId, parentId.get()); jni::TScopedLocalRef const parentName(env, jni::ToJavaString(env, info.m_localName)); env->SetObjectField(item, countryItemFieldParentName, parentName.get()); } else { env->SetObjectField(item, countryItemFieldParentId, nullptr); env->SetObjectField(item, countryItemFieldParentName, nullptr); } // Sizes env->SetLongField(item, countryItemFieldSize, attrs.m_localMwmSize); env->SetLongField(item, countryItemFieldTotalSize, attrs.m_mwmSize); // Child counts env->SetIntField(item, countryItemFieldChildCount, attrs.m_localMwmCounter); env->SetIntField(item, countryItemFieldTotalChildCount, attrs.m_mwmCounter); // Status and error code env->SetIntField(item, countryItemFieldStatus, static_cast<jint>(attrs.m_status)); env->SetIntField(item, countryItemFieldErrorCode, static_cast<jint>(attrs.m_error)); // Presence flag env->SetBooleanField(item, countryItemFieldPresent, attrs.m_present); // Progress env->SetIntField(item, countryItemFieldProgress,static_cast<jint>(attrs.m_downloadingProgress.first)); } static void PutItemsToList(JNIEnv * env, jobject const list, vector<TCountryId> const & children, TCountryId const & parent, int category) { static jmethodID const countryItemCtor = jni::GetConstructorID(env, g_countryItemClass, "(Ljava/lang/String;)V"); static jfieldID const countryItemFieldCategory = env->GetFieldID(g_countryItemClass, "category", "I"); NodeAttrs attrs; for (TCountryId const & child : children) { GetStorage().GetNodeAttrs(child, attrs); jni::TScopedLocalRef const id(env, jni::ToJavaString(env, child)); jni::TScopedLocalRef const item(env, env->NewObject(g_countryItemClass, countryItemCtor, id.get())); env->SetIntField(item.get(), countryItemFieldCategory, category); UpdateItem(env, item.get(), attrs); // Put to resulting list env->CallBooleanMethod(list, g_listAddMethod, item.get()); } } // static void nativeListItems(@Nullable String parent, List<CountryItem> result); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeListItems(JNIEnv * env, jclass clazz, jstring parent, jobject result) { PrepareClassRefs(env); Storage const & storage = GetStorage(); TCountryId const parentId = (parent ? jni::ToNativeString(env, parent) : storage.GetRootId()); static jfieldID const countryItemFieldParentId = env->GetFieldID(g_countryItemClass, "parentId", "Ljava/lang/String;"); if (parent) { vector<TCountryId> children; storage.GetChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::ALL); } else { // TODO (trashkalmar): Countries near me // Downloaded vector<TCountryId> children; storage.GetDownloadedChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::DOWNLOADED); // All storage.GetChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::ALL); } } // static void nativeUpdateItem(CountryItem item); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetAttributes(JNIEnv * env, jclass clazz, jobject item) { PrepareClassRefs(env); NodeAttrs attrs; static jfieldID countryItemFieldId = env->GetFieldID(g_countryItemClass, "id", "Ljava/lang/String;"); jstring id = static_cast<jstring>(env->GetObjectField(item, countryItemFieldId)); GetStorage().GetNodeAttrs(jni::ToNativeString(env, id), attrs); UpdateItem(env, item, attrs); } // static @Nullable String nativeFindCountry(double lat, double lon); JNIEXPORT jstring JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeFindCountry(JNIEnv * env, jclass clazz, jdouble lat, jdouble lon) { return jni::ToJavaString(env, g_framework->NativeFramework()->CountryInfoGetter().GetRegionCountryId(MercatorBounds::FromLatLon(lat, lon))); } // static boolean nativeIsDownloading(); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeIsDownloading(JNIEnv * env, jclass clazz) { return GetStorage().IsDownloadInProgress(); } // static boolean nativeDownload(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeDownload(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().DownloadNode(jni::ToNativeString(env, root)); } // static boolean nativeRetry(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeRetry(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().RetryDownloadNode(jni::ToNativeString(env, root)); } // static boolean nativeUpdate(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUpdate(JNIEnv * env, jclass clazz, jstring root) { // FIXME (trashkalmar): Uncomment after method is implemented. //return GetStorage().UpdateNode(jni::ToNativeString(env, root)); return true; } // static boolean nativeCancel(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeCancel(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().CancelDownloadNode(jni::ToNativeString(env, root)); } // static void nativeDelete(String root); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeDelete(JNIEnv * env, jclass clazz, jstring root) { GetStorage().DeleteNode(jni::ToNativeString(env, root)); } static void StatusChangedCallback(shared_ptr<jobject> const & listenerRef, TCountryId const & countryId) { JNIEnv * env = jni::GetEnv(); // TODO: The core will do this itself NodeAttrs attrs; GetStorage().GetNodeAttrs(countryId, attrs); jmethodID const methodID = jni::GetMethodID(env, *listenerRef, "onStatusChanged", "(Ljava/lang/String;I)V"); env->CallVoidMethod(*listenerRef, methodID, jni::ToJavaString(env, countryId), attrs.m_status); } static void ProgressChangedCallback(shared_ptr<jobject> const & listenerRef, TCountryId const & countryId, TLocalAndRemoteSize const & sizes) { JNIEnv * env = jni::GetEnv(); jmethodID const methodID = jni::GetMethodID(env, *listenerRef, "onProgress", "(Ljava/lang/String;JJ)V"); env->CallVoidMethod(*listenerRef, methodID, jni::ToJavaString(env, countryId), sizes.first, sizes.second); } // static int nativeSubscribe(StorageCallback listener); JNIEXPORT jint JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeSubscribe(JNIEnv * env, jclass clazz, jobject listener) { PrepareClassRefs(env); return GetStorage().Subscribe(bind(&StatusChangedCallback, jni::make_global_ref(listener), _1), bind(&ProgressChangedCallback, jni::make_global_ref(listener), _1, _2)); } // static void nativeUnsubscribe(int slot); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUnsubscribe(JNIEnv * env, jclass clazz, jint slot) { GetStorage().Unsubscribe(slot); } // static void nativeSubscribeOnCountryChanged(CurrentCountryChangedListener listener); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeSubscribeOnCountryChanged(JNIEnv * env, jclass clazz, jobject listener) { ASSERT(!g_countryChangedListener, ()); g_countryChangedListener = env->NewGlobalRef(listener); auto const callback = [](TCountryId const & countryId) { JNIEnv * env = jni::GetEnv(); jmethodID methodID = jni::GetMethodID(env, g_countryChangedListener, "onCurrentCountryChanged", "(Ljava/lang/String;)V"); env->CallVoidMethod(g_countryChangedListener, methodID, jni::TScopedLocalRef(env, jni::ToJavaString(env, countryId)).get()); }; TCountryId const & prev = g_framework->NativeFramework()->GetLastReportedCountry(); g_framework->NativeFramework()->SetCurrentCountryChangedListener(callback); // Report previous value callback(prev); } // static void nativeUnsubscribeOnCountryChanged(); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUnsubscribeOnCountryChanged(JNIEnv * env, jclass clazz) { g_framework->NativeFramework()->SetCurrentCountryChangedListener(nullptr); ASSERT(g_countryChangedListener, ()); env->DeleteGlobalRef(g_countryChangedListener); g_countryChangedListener = nullptr; } } // extern "C" <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkExtractUnstructuredGridPiece.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkExtractUnstructuredGridPiece.h" #include "vtkCell.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkGenericCell.h" #include "vtkIdList.h" #include "vtkIntArray.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkUnsignedCharArray.h" #include "vtkUnstructuredGrid.h" vtkCxxRevisionMacro(vtkExtractUnstructuredGridPiece, "1.16"); vtkStandardNewMacro(vtkExtractUnstructuredGridPiece); vtkExtractUnstructuredGridPiece::vtkExtractUnstructuredGridPiece() { this->CreateGhostCells = 1; } void vtkExtractUnstructuredGridPiece::ComputeInputUpdateExtents(vtkDataObject *out) { vtkUnstructuredGrid *input = this->GetInput(); if (this->GetInput() == NULL) { vtkErrorMacro("Missing input"); return; } out = out; input->SetUpdateExtent(0, 1, 0); } void vtkExtractUnstructuredGridPiece::ExecuteInformation() { if (this->GetInput() == NULL) { vtkErrorMacro("Missing input"); return; } this->GetOutput()->SetMaximumNumberOfPieces(-1); } void vtkExtractUnstructuredGridPiece::ComputeCellTags(vtkIntArray *tags, vtkIdList *pointOwnership, int piece, int numPieces) { vtkUnstructuredGrid *input; int j; vtkIdType idx, numCells, ptId; vtkIdType* cellPointer; vtkIdType* ids; vtkIdType numCellPts; input = this->GetInput(); numCells = input->GetNumberOfCells(); // Clear Point ownership. This is only necessary if we // Are creating ghost points. if (pointOwnership) { for (idx = 0; idx < input->GetNumberOfPoints(); ++idx) { pointOwnership->SetId(idx, -1); } } // Brute force division. cellPointer = input->GetCells()->GetPointer(); for (idx = 0; idx < numCells; ++idx) { if ((idx * numPieces / numCells) == piece) { tags->SetValue(idx, 0); } else { tags->SetValue(idx, -1); } // Fill in point ownership mapping. if (pointOwnership) { numCellPts = cellPointer[0]; ids = cellPointer+1; // Move to the next cell. cellPointer += (1 + numCellPts); for (j = 0; j < numCellPts; ++j) { ptId = ids[j]; if (pointOwnership->GetId(ptId) == -1) { pointOwnership->SetId(ptId, idx); } } } } } void vtkExtractUnstructuredGridPiece::Execute() { vtkUnstructuredGrid *input = this->GetInput(); vtkUnstructuredGrid *output = this->GetOutput(); vtkPointData *pd=input->GetPointData(), *outPD=output->GetPointData(); vtkCellData *cd=input->GetCellData(), *outCD=output->GetCellData(); unsigned char* cellTypes = input->GetCellTypesArray()->GetPointer(0); int cellType; vtkIntArray *cellTags; int ghostLevel, piece, numPieces; vtkIdType cellId, newCellId; vtkIdList *pointMap; vtkIdList *newCellPts = vtkIdList::New(); vtkPoints *newPoints; vtkUnsignedCharArray* cellGhostLevels = 0; vtkIdList *pointOwnership = 0; vtkUnsignedCharArray* pointGhostLevels = 0; vtkIdType i, ptId, newId, numPts, numCells; int numCellPts; vtkIdType *cellPointer; vtkIdType *ids; double *x; // Pipeline update piece will tell us what to generate. ghostLevel = output->GetUpdateGhostLevel(); piece = output->GetUpdatePiece(); numPieces = output->GetUpdateNumberOfPieces(); outPD->CopyAllocate(pd); outCD->CopyAllocate(cd); numPts = input->GetNumberOfPoints(); numCells = input->GetNumberOfCells(); if (ghostLevel > 0 && this->CreateGhostCells) { cellGhostLevels = vtkUnsignedCharArray::New(); cellGhostLevels->Allocate(numCells); // We may want to create point ghost levels even // if there are no ghost cells. Since it cost extra, // and no filter really uses it, and the filter did not // create a point ghost level array for this case before, // I will leave it the way it was. pointOwnership = vtkIdList::New(); pointOwnership->Allocate(numPts); pointGhostLevels = vtkUnsignedCharArray::New(); pointGhostLevels->Allocate(numPts); } // Break up cells based on which piece they belong to. cellTags = vtkIntArray::New(); cellTags->Allocate(input->GetNumberOfCells(), 1000); // Cell tags end up being 0 for cells in piece and -1 for all others. // Point ownership is the cell that owns the point. this->ComputeCellTags(cellTags, pointOwnership, piece, numPieces); // Find the layers of ghost cells. if (this->CreateGhostCells) { for (i = 0; i < ghostLevel; i++) { this->AddGhostLevel(input, cellTags, i+1); } } // Filter the cells. output->Allocate(input->GetNumberOfCells()); newPoints = vtkPoints::New(); newPoints->Allocate(numPts); pointMap = vtkIdList::New(); //maps old point ids into new pointMap->SetNumberOfIds(numPts); for (i=0; i < numPts; i++) { pointMap->SetId(i,-1); } // Filter the cells cellPointer = input->GetCells()->GetPointer(); for (cellId=0; cellId < numCells; cellId++) { // Direct access to cells. cellType = cellTypes[cellId]; numCellPts = cellPointer[0]; ids = cellPointer+1; // Move to the next cell. cellPointer += (1 + *cellPointer); if ( cellTags->GetValue(cellId) != -1) // satisfied thresholding { if (cellGhostLevels) { cellGhostLevels->InsertNextValue( (unsigned char)(cellTags->GetValue(cellId))); } for (i=0; i < numCellPts; i++) { ptId = ids[i]; if ( (newId = pointMap->GetId(ptId)) < 0 ) { x = input->GetPoint(ptId); newId = newPoints->InsertNextPoint(x); if (pointGhostLevels && pointOwnership) { pointGhostLevels->InsertNextValue( cellTags->GetValue(pointOwnership->GetId(ptId))); } pointMap->SetId(ptId,newId); outPD->CopyData(pd,ptId,newId); } newCellPts->InsertId(i,newId); } newCellId = output->InsertNextCell(cellType,newCellPts); outCD->CopyData(cd,cellId,newCellId); newCellPts->Reset(); } // satisfied thresholding } // for all cells // Split up points that are not used by cells, // and have not been assigned to any piece. // Count the number of unassigned points. This is an extra pass through // the points, but the pieces will be better load balanced and // more spatially coherent. vtkIdType count = 0; vtkIdType idx; for (idx = 0; idx < input->GetNumberOfPoints(); ++idx) { if (pointOwnership->GetId(idx) == -1) { ++count; } } vtkIdType count2 = 0; for (idx = 0; idx < input->GetNumberOfPoints(); ++idx) { if (pointOwnership->GetId(idx) == -1) { if ((count2 * numPieces / count) == piece) { x = input->GetPoint(idx); newId = newPoints->InsertNextPoint(x); if (pointGhostLevels) { pointGhostLevels->InsertNextValue(0); } outPD->CopyData(pd,idx,newId); } } } vtkDebugMacro(<< "Extracted " << output->GetNumberOfCells() << " number of cells."); // now clean up / update ourselves pointMap->Delete(); newCellPts->Delete(); if (cellGhostLevels) { cellGhostLevels->SetName("vtkGhostLevels"); output->GetCellData()->AddArray(cellGhostLevels); cellGhostLevels->Delete(); cellGhostLevels = 0; } if (pointGhostLevels) { pointGhostLevels->SetName("vtkGhostLevels"); output->GetPointData()->AddArray(pointGhostLevels); pointGhostLevels->Delete(); pointGhostLevels = 0; } output->SetPoints(newPoints); newPoints->Delete(); output->Squeeze(); cellTags->Delete(); if (pointOwnership) { pointOwnership->Delete(); pointOwnership = 0; } } void vtkExtractUnstructuredGridPiece::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Create Ghost Cells: " << (this->CreateGhostCells ? "On\n" : "Off\n"); } // This method is still slow... void vtkExtractUnstructuredGridPiece::AddGhostLevel(vtkUnstructuredGrid *input, vtkIntArray *cellTags, int level) { vtkIdType numCells, pointId, cellId, i; int j, k; vtkGenericCell *cell1 = vtkGenericCell::New(); vtkGenericCell *cell2 = vtkGenericCell::New(); vtkIdList *cellIds = vtkIdList::New(); numCells = input->GetNumberOfCells(); for (i = 0; i < numCells; i++) { if (cellTags->GetValue(i) == level - 1) { input->GetCell(i, cell1); for (j = 0; j < cell1->GetNumberOfPoints(); j++) { pointId = cell1->GetPointId(j); input->GetPointCells(pointId, cellIds); for (k = 0; k < cellIds->GetNumberOfIds(); k++) { cellId = cellIds->GetId(k); if (cellTags->GetValue(cellId) == -1) { input->GetCell(cellId, cell2); cellTags->SetValue(cellId, level); } } } } } cell1->Delete(); cell2->Delete(); cellIds->Delete(); } <commit_msg>BUG: Was using null pointer<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkExtractUnstructuredGridPiece.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkExtractUnstructuredGridPiece.h" #include "vtkCell.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkGenericCell.h" #include "vtkIdList.h" #include "vtkIntArray.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkUnsignedCharArray.h" #include "vtkUnstructuredGrid.h" vtkCxxRevisionMacro(vtkExtractUnstructuredGridPiece, "1.17"); vtkStandardNewMacro(vtkExtractUnstructuredGridPiece); vtkExtractUnstructuredGridPiece::vtkExtractUnstructuredGridPiece() { this->CreateGhostCells = 1; } void vtkExtractUnstructuredGridPiece::ComputeInputUpdateExtents(vtkDataObject *out) { vtkUnstructuredGrid *input = this->GetInput(); if (this->GetInput() == NULL) { vtkErrorMacro("Missing input"); return; } out = out; input->SetUpdateExtent(0, 1, 0); } void vtkExtractUnstructuredGridPiece::ExecuteInformation() { if (this->GetInput() == NULL) { vtkErrorMacro("Missing input"); return; } this->GetOutput()->SetMaximumNumberOfPieces(-1); } void vtkExtractUnstructuredGridPiece::ComputeCellTags(vtkIntArray *tags, vtkIdList *pointOwnership, int piece, int numPieces) { vtkUnstructuredGrid *input; int j; vtkIdType idx, numCells, ptId; vtkIdType* cellPointer; vtkIdType* ids; vtkIdType numCellPts; input = this->GetInput(); numCells = input->GetNumberOfCells(); // Clear Point ownership. This is only necessary if we // Are creating ghost points. if (pointOwnership) { for (idx = 0; idx < input->GetNumberOfPoints(); ++idx) { pointOwnership->SetId(idx, -1); } } // Brute force division. cellPointer = input->GetCells()->GetPointer(); for (idx = 0; idx < numCells; ++idx) { if ((idx * numPieces / numCells) == piece) { tags->SetValue(idx, 0); } else { tags->SetValue(idx, -1); } // Fill in point ownership mapping. if (pointOwnership) { numCellPts = cellPointer[0]; ids = cellPointer+1; // Move to the next cell. cellPointer += (1 + numCellPts); for (j = 0; j < numCellPts; ++j) { ptId = ids[j]; if (pointOwnership->GetId(ptId) == -1) { pointOwnership->SetId(ptId, idx); } } } } } void vtkExtractUnstructuredGridPiece::Execute() { vtkUnstructuredGrid *input = this->GetInput(); vtkUnstructuredGrid *output = this->GetOutput(); vtkPointData *pd=input->GetPointData(), *outPD=output->GetPointData(); vtkCellData *cd=input->GetCellData(), *outCD=output->GetCellData(); unsigned char* cellTypes = input->GetCellTypesArray()->GetPointer(0); int cellType; vtkIntArray *cellTags; int ghostLevel, piece, numPieces; vtkIdType cellId, newCellId; vtkIdList *pointMap; vtkIdList *newCellPts = vtkIdList::New(); vtkPoints *newPoints; vtkUnsignedCharArray* cellGhostLevels = 0; vtkIdList *pointOwnership = 0; vtkUnsignedCharArray* pointGhostLevels = 0; vtkIdType i, ptId, newId, numPts, numCells; int numCellPts; vtkIdType *cellPointer; vtkIdType *ids; double *x; // Pipeline update piece will tell us what to generate. ghostLevel = output->GetUpdateGhostLevel(); piece = output->GetUpdatePiece(); numPieces = output->GetUpdateNumberOfPieces(); outPD->CopyAllocate(pd); outCD->CopyAllocate(cd); numPts = input->GetNumberOfPoints(); numCells = input->GetNumberOfCells(); if (ghostLevel > 0 && this->CreateGhostCells) { cellGhostLevels = vtkUnsignedCharArray::New(); cellGhostLevels->Allocate(numCells); // We may want to create point ghost levels even // if there are no ghost cells. Since it cost extra, // and no filter really uses it, and the filter did not // create a point ghost level array for this case before, // I will leave it the way it was. pointOwnership = vtkIdList::New(); pointOwnership->Allocate(numPts); pointGhostLevels = vtkUnsignedCharArray::New(); pointGhostLevels->Allocate(numPts); } // Break up cells based on which piece they belong to. cellTags = vtkIntArray::New(); cellTags->Allocate(input->GetNumberOfCells(), 1000); // Cell tags end up being 0 for cells in piece and -1 for all others. // Point ownership is the cell that owns the point. this->ComputeCellTags(cellTags, pointOwnership, piece, numPieces); // Find the layers of ghost cells. if (this->CreateGhostCells) { for (i = 0; i < ghostLevel; i++) { this->AddGhostLevel(input, cellTags, i+1); } } // Filter the cells. output->Allocate(input->GetNumberOfCells()); newPoints = vtkPoints::New(); newPoints->Allocate(numPts); pointMap = vtkIdList::New(); //maps old point ids into new pointMap->SetNumberOfIds(numPts); for (i=0; i < numPts; i++) { pointMap->SetId(i,-1); } // Filter the cells cellPointer = input->GetCells()->GetPointer(); for (cellId=0; cellId < numCells; cellId++) { // Direct access to cells. cellType = cellTypes[cellId]; numCellPts = cellPointer[0]; ids = cellPointer+1; // Move to the next cell. cellPointer += (1 + *cellPointer); if ( cellTags->GetValue(cellId) != -1) // satisfied thresholding { if (cellGhostLevels) { cellGhostLevels->InsertNextValue( (unsigned char)(cellTags->GetValue(cellId))); } for (i=0; i < numCellPts; i++) { ptId = ids[i]; if ( (newId = pointMap->GetId(ptId)) < 0 ) { x = input->GetPoint(ptId); newId = newPoints->InsertNextPoint(x); if (pointGhostLevels && pointOwnership) { pointGhostLevels->InsertNextValue( cellTags->GetValue(pointOwnership->GetId(ptId))); } pointMap->SetId(ptId,newId); outPD->CopyData(pd,ptId,newId); } newCellPts->InsertId(i,newId); } newCellId = output->InsertNextCell(cellType,newCellPts); outCD->CopyData(cd,cellId,newCellId); newCellPts->Reset(); } // satisfied thresholding } // for all cells // Split up points that are not used by cells, // and have not been assigned to any piece. // Count the number of unassigned points. This is an extra pass through // the points, but the pieces will be better load balanced and // more spatially coherent. vtkIdType count = 0; vtkIdType idx; for (idx = 0; idx < input->GetNumberOfPoints(); ++idx) { if (pointMap->GetId(idx) == -1) { ++count; } } vtkIdType count2 = 0; for (idx = 0; idx < input->GetNumberOfPoints(); ++idx) { if (pointMap->GetId(idx) == -1) { if ((count2 * numPieces / count) == piece) { x = input->GetPoint(idx); newId = newPoints->InsertNextPoint(x); if (pointGhostLevels) { pointGhostLevels->InsertNextValue(0); } outPD->CopyData(pd,idx,newId); } } } vtkDebugMacro(<< "Extracted " << output->GetNumberOfCells() << " number of cells."); // now clean up / update ourselves pointMap->Delete(); newCellPts->Delete(); if (cellGhostLevels) { cellGhostLevels->SetName("vtkGhostLevels"); output->GetCellData()->AddArray(cellGhostLevels); cellGhostLevels->Delete(); cellGhostLevels = 0; } if (pointGhostLevels) { pointGhostLevels->SetName("vtkGhostLevels"); output->GetPointData()->AddArray(pointGhostLevels); pointGhostLevels->Delete(); pointGhostLevels = 0; } output->SetPoints(newPoints); newPoints->Delete(); output->Squeeze(); cellTags->Delete(); if (pointOwnership) { pointOwnership->Delete(); pointOwnership = 0; } } void vtkExtractUnstructuredGridPiece::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Create Ghost Cells: " << (this->CreateGhostCells ? "On\n" : "Off\n"); } // This method is still slow... void vtkExtractUnstructuredGridPiece::AddGhostLevel(vtkUnstructuredGrid *input, vtkIntArray *cellTags, int level) { vtkIdType numCells, pointId, cellId, i; int j, k; vtkGenericCell *cell1 = vtkGenericCell::New(); vtkGenericCell *cell2 = vtkGenericCell::New(); vtkIdList *cellIds = vtkIdList::New(); numCells = input->GetNumberOfCells(); for (i = 0; i < numCells; i++) { if (cellTags->GetValue(i) == level - 1) { input->GetCell(i, cell1); for (j = 0; j < cell1->GetNumberOfPoints(); j++) { pointId = cell1->GetPointId(j); input->GetPointCells(pointId, cellIds); for (k = 0; k < cellIds->GetNumberOfIds(); k++) { cellId = cellIds->GetId(k); if (cellTags->GetValue(cellId) == -1) { input->GetCell(cellId, cell2); cellTags->SetValue(cellId, level); } } } } } cell1->Delete(); cell2->Delete(); cellIds->Delete(); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XALAN_NUMBERINGRESOURCEBUNDLE_HEADER_GUARD) #define XALAN_NUMBERINGRESOURCEBUNDLE_HEADER_GUARD // Base include file. Must be first. #include <XSLT/XSLTDefinitions.hpp> #include <vector> #include <PlatformSupport/DOMStringHelper.hpp> class XalanNumberingResourceBundle { public: typedef unsigned long NumberType; #if defined(XALAN_NO_NAMESPACES) typedef vector<NumberType> NumberTypeVectorType; typedef vector<NumberType> DigitsTableVectorType; #else typedef std::vector<unsigned long> NumberTypeVectorType; typedef std::vector<XalanDOMCharVectorType> DigitsTableVectorType; #endif // Enum to describe language orientation. (English is left-to-right, // Hebrew is right-to-left, etc.) enum eOrientation { eLeftToRight, eRightToLeft, eTopToBottom, eBottomToTop }; // Enum to describe how numbering is done. enum eNumberingMethod { eAdditive, eMultiplicativeAdditive }; // Enum to describe the where the multiplier goes. enum eMultiplierOrder { eFollows, ePrecedes }; XalanNumberingResourceBundle( const XalanDOMString& theLanguage, const XalanDOMString& theUILanguage, const XalanDOMString& theHelpLanguage, const XalanDOMCharVectorType& theAlphabet, const XalanDOMCharVectorType& theTraditionalAlphabet, eOrientation theOrientation, eNumberingMethod theNumberingMethod, eMultiplierOrder theMultiplierOrder, NumberType theMaxNumericalValue, const NumberTypeVectorType& theNumberGroups, const NumberTypeVectorType& theMultipliers, const XalanDOMCharVectorType& theZeroChar, const XalanDOMCharVectorType& theMultiplierChars, const DigitsTableVectorType& theDigitsTable, const NumberTypeVectorType& theDigitsTableTable); explicit XalanNumberingResourceBundle(); XalanNumberingResourceBundle(const XalanNumberingResourceBundle& theSource); ~XalanNumberingResourceBundle(); bool operator==(const XalanNumberingResourceBundle& theRHS) const { return equals(m_language, theRHS.m_language); } const XalanDOMString& getLanguage() const { return m_language; } const XalanDOMString& getUILanguage() const { return m_uiLanguage; } const XalanDOMString& getHelpLanguage() const { return m_helpLanguage; } const XalanDOMCharVectorType& getAlphabet() const { return m_alphabet; } const XalanDOMCharVectorType& getTraditionalAlphabet() const { return m_traditionalAlphabet; } eOrientation getOrientation() const { return m_orientation; } eNumberingMethod getNumberingMethod() const { return m_numberingMethod; } eMultiplierOrder getMultiplierOrder() const { return m_multiplierOrder; } NumberType getMaxNumericalValue() const { return m_maxNumericalValue; } const NumberTypeVectorType& getNumberGroups() const { return m_numberGroups; } const NumberTypeVectorType& getMultipliers() const { return m_multipliers; } const XalanDOMCharVectorType& getZeroChar() const { return m_zeroChar; } const XalanDOMCharVectorType& getMultiplierChars() const { return m_multiplierChars; } const DigitsTableVectorType& getDigitsTable() const { return m_digitsTable; } const NumberTypeVectorType& getDigitsTableTable() const { return m_digitsTableTable; } void swap(XalanNumberingResourceBundle& theOther); private: XalanDOMString m_language; XalanDOMString m_uiLanguage; XalanDOMString m_helpLanguage; XalanDOMCharVectorType m_alphabet; XalanDOMCharVectorType m_traditionalAlphabet; eOrientation m_orientation; eNumberingMethod m_numberingMethod; eMultiplierOrder m_multiplierOrder; NumberType m_maxNumericalValue; NumberTypeVectorType m_numberGroups; NumberTypeVectorType m_multipliers; XalanDOMCharVectorType m_zeroChar; XalanDOMCharVectorType m_multiplierChars; DigitsTableVectorType m_digitsTable; NumberTypeVectorType m_digitsTableTable; }; #endif // XALAN_NUMBERINGRESOURCEBUNDLE_HEADER_GUARD <commit_msg>Fixed glitch with typedef.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XALAN_NUMBERINGRESOURCEBUNDLE_HEADER_GUARD) #define XALAN_NUMBERINGRESOURCEBUNDLE_HEADER_GUARD // Base include file. Must be first. #include <XSLT/XSLTDefinitions.hpp> #include <vector> #include <PlatformSupport/DOMStringHelper.hpp> class XalanNumberingResourceBundle { public: typedef unsigned long NumberType; #if defined(XALAN_NO_NAMESPACES) typedef vector<NumberType> NumberTypeVectorType; typedef vector<XalanDOMCharVectorType> DigitsTableVectorType; #else typedef std::vector<unsigned long> NumberTypeVectorType; typedef std::vector<XalanDOMCharVectorType> DigitsTableVectorType; #endif // Enum to describe language orientation. (English is left-to-right, // Hebrew is right-to-left, etc.) enum eOrientation { eLeftToRight, eRightToLeft, eTopToBottom, eBottomToTop }; // Enum to describe how numbering is done. enum eNumberingMethod { eAdditive, eMultiplicativeAdditive }; // Enum to describe the where the multiplier goes. enum eMultiplierOrder { eFollows, ePrecedes }; XalanNumberingResourceBundle( const XalanDOMString& theLanguage, const XalanDOMString& theUILanguage, const XalanDOMString& theHelpLanguage, const XalanDOMCharVectorType& theAlphabet, const XalanDOMCharVectorType& theTraditionalAlphabet, eOrientation theOrientation, eNumberingMethod theNumberingMethod, eMultiplierOrder theMultiplierOrder, NumberType theMaxNumericalValue, const NumberTypeVectorType& theNumberGroups, const NumberTypeVectorType& theMultipliers, const XalanDOMCharVectorType& theZeroChar, const XalanDOMCharVectorType& theMultiplierChars, const DigitsTableVectorType& theDigitsTable, const NumberTypeVectorType& theDigitsTableTable); explicit XalanNumberingResourceBundle(); XalanNumberingResourceBundle(const XalanNumberingResourceBundle& theSource); ~XalanNumberingResourceBundle(); bool operator==(const XalanNumberingResourceBundle& theRHS) const { return equals(m_language, theRHS.m_language); } const XalanDOMString& getLanguage() const { return m_language; } const XalanDOMString& getUILanguage() const { return m_uiLanguage; } const XalanDOMString& getHelpLanguage() const { return m_helpLanguage; } const XalanDOMCharVectorType& getAlphabet() const { return m_alphabet; } const XalanDOMCharVectorType& getTraditionalAlphabet() const { return m_traditionalAlphabet; } eOrientation getOrientation() const { return m_orientation; } eNumberingMethod getNumberingMethod() const { return m_numberingMethod; } eMultiplierOrder getMultiplierOrder() const { return m_multiplierOrder; } NumberType getMaxNumericalValue() const { return m_maxNumericalValue; } const NumberTypeVectorType& getNumberGroups() const { return m_numberGroups; } const NumberTypeVectorType& getMultipliers() const { return m_multipliers; } const XalanDOMCharVectorType& getZeroChar() const { return m_zeroChar; } const XalanDOMCharVectorType& getMultiplierChars() const { return m_multiplierChars; } const DigitsTableVectorType& getDigitsTable() const { return m_digitsTable; } const NumberTypeVectorType& getDigitsTableTable() const { return m_digitsTableTable; } void swap(XalanNumberingResourceBundle& theOther); private: XalanDOMString m_language; XalanDOMString m_uiLanguage; XalanDOMString m_helpLanguage; XalanDOMCharVectorType m_alphabet; XalanDOMCharVectorType m_traditionalAlphabet; eOrientation m_orientation; eNumberingMethod m_numberingMethod; eMultiplierOrder m_multiplierOrder; NumberType m_maxNumericalValue; NumberTypeVectorType m_numberGroups; NumberTypeVectorType m_multipliers; XalanDOMCharVectorType m_zeroChar; XalanDOMCharVectorType m_multiplierChars; DigitsTableVectorType m_digitsTable; NumberTypeVectorType m_digitsTableTable; }; #endif // XALAN_NUMBERINGRESOURCEBUNDLE_HEADER_GUARD <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/threading/thread.h" #include "base/bind.h" #include "base/lazy_instance.h" #include "base/location.h" #include "base/profiler/scoped_tracker.h" #include "base/synchronization/waitable_event.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/threading/thread_id_name_manager.h" #include "base/threading/thread_local.h" #include "base/threading/thread_restrictions.h" #if defined(OS_WIN) #include "base/win/scoped_com_initializer.h" #endif namespace base { namespace { // We use this thread-local variable to record whether or not a thread exited // because its Stop method was called. This allows us to catch cases where // MessageLoop::QuitWhenIdle() is called directly, which is unexpected when // using a Thread to setup and run a MessageLoop. base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool = LAZY_INSTANCE_INITIALIZER; } // namespace // This is used to trigger the message loop to exit. void ThreadQuitHelper() { MessageLoop::current()->QuitWhenIdle(); Thread::SetThreadWasQuitProperly(true); } Thread::Options::Options() : message_loop_type(MessageLoop::TYPE_DEFAULT), timer_slack(TIMER_SLACK_NONE), stack_size(0), priority(ThreadPriority::NORMAL) { } Thread::Options::Options(MessageLoop::Type type, size_t size) : message_loop_type(type), timer_slack(TIMER_SLACK_NONE), stack_size(size), priority(ThreadPriority::NORMAL) { } Thread::Options::~Options() { } Thread::Thread(const std::string& name) : #if defined(OS_WIN) com_status_(NONE), #endif stopping_(false), running_(false), thread_(0), id_(kInvalidThreadId), id_event_(true, false), message_loop_(nullptr), message_loop_timer_slack_(TIMER_SLACK_NONE), name_(name) { } Thread::~Thread() { Stop(); } bool Thread::Start() { Options options; #if defined(OS_WIN) if (com_status_ == STA) options.message_loop_type = MessageLoop::TYPE_UI; #endif return StartWithOptions(options); } bool Thread::StartWithOptions(const Options& options) { DCHECK(!message_loop_); #if defined(OS_WIN) DCHECK((com_status_ != STA) || (options.message_loop_type == MessageLoop::TYPE_UI)); #endif // Reset |id_| here to support restarting the thread. id_event_.Reset(); id_ = kInvalidThreadId; SetThreadWasQuitProperly(false); MessageLoop::Type type = options.message_loop_type; if (!options.message_pump_factory.is_null()) type = MessageLoop::TYPE_CUSTOM; message_loop_timer_slack_ = options.timer_slack; scoped_ptr<MessageLoop> message_loop = MessageLoop::CreateUnbound( type, options.message_pump_factory); message_loop_ = message_loop.get(); start_event_.reset(new WaitableEvent(false, false)); // Hold the thread_lock_ while starting a new thread, so that we can make sure // that thread_ is populated before the newly created thread accesses it. { AutoLock lock(thread_lock_); if (!PlatformThread::CreateWithPriority(options.stack_size, this, &thread_, options.priority)) { DLOG(ERROR) << "failed to create thread"; message_loop_ = nullptr; start_event_.reset(); return false; } } // The ownership of message_loop is managemed by the newly created thread // within the ThreadMain. ignore_result(message_loop.release()); DCHECK(message_loop_); return true; } bool Thread::StartAndWaitForTesting() { bool result = Start(); if (!result) return false; WaitUntilThreadStarted(); return true; } bool Thread::WaitUntilThreadStarted() { if (!start_event_) return false; base::ThreadRestrictions::ScopedAllowWait allow_wait; start_event_->Wait(); return true; } void Thread::Stop() { if (!start_event_) return; StopSoon(); // Wait for the thread to exit. // // TODO(darin): Unfortunately, we need to keep message_loop_ around until // the thread exits. Some consumers are abusing the API. Make them stop. // PlatformThread::Join(thread_); // The thread should NULL message_loop_ on exit. DCHECK(!message_loop_); // The thread no longer needs to be joined. start_event_.reset(); stopping_ = false; } void Thread::StopSoon() { // We should only be called on the same thread that started us. DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); if (stopping_ || !message_loop_) return; stopping_ = true; task_runner()->PostTask(FROM_HERE, base::Bind(&ThreadQuitHelper)); } PlatformThreadId Thread::GetThreadId() const { // If the thread is created but not started yet, wait for |id_| being ready. base::ThreadRestrictions::ScopedAllowWait allow_wait; // TODO(toyoshim): Remove this after a few days (crbug.com/495097) tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "495097 base::Thread::GetThreadId")); id_event_.Wait(); return id_; } bool Thread::IsRunning() const { // If the thread's already started (i.e. message_loop_ is non-null) and // not yet requested to stop (i.e. stopping_ is false) we can just return // true. (Note that stopping_ is touched only on the same thread that // starts / started the new thread so we need no locking here.) if (message_loop_ && !stopping_) return true; // Otherwise check the running_ flag, which is set to true by the new thread // only while it is inside Run(). AutoLock lock(running_lock_); return running_; } void Thread::Run(MessageLoop* message_loop) { message_loop->Run(); } void Thread::SetThreadWasQuitProperly(bool flag) { lazy_tls_bool.Pointer()->Set(flag); } bool Thread::GetThreadWasQuitProperly() { bool quit_properly = true; #ifndef NDEBUG quit_properly = lazy_tls_bool.Pointer()->Get(); #endif return quit_properly; } void Thread::ThreadMain() { // First, make GetThreadId() available to avoid deadlocks. It could be called // any place in the following thread initialization code. id_ = PlatformThread::CurrentId(); DCHECK_NE(kInvalidThreadId, id_); id_event_.Signal(); // Complete the initialization of our Thread object. PlatformThread::SetName(name_.c_str()); ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector. // Lazily initialize the message_loop so that it can run on this thread. DCHECK(message_loop_); scoped_ptr<MessageLoop> message_loop(message_loop_); message_loop_->BindToCurrentThread(); message_loop_->set_thread_name(name_); message_loop_->SetTimerSlack(message_loop_timer_slack_); #if defined(OS_WIN) scoped_ptr<win::ScopedCOMInitializer> com_initializer; if (com_status_ != NONE) { com_initializer.reset((com_status_ == STA) ? new win::ScopedCOMInitializer() : new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA)); } #endif // Let the thread do extra initialization. Init(); { AutoLock lock(running_lock_); running_ = true; } start_event_->Signal(); Run(message_loop_); { AutoLock lock(running_lock_); running_ = false; } // Let the thread do extra cleanup. CleanUp(); #if defined(OS_WIN) com_initializer.reset(); #endif // Assert that MessageLoop::Quit was called by ThreadQuitHelper. DCHECK(GetThreadWasQuitProperly()); // We can't receive messages anymore. // (The message loop is destructed at the end of this block) message_loop_ = NULL; } } // namespace base <commit_msg>base/threading: remove ScopedTracker placed for experiments<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/threading/thread.h" #include "base/bind.h" #include "base/lazy_instance.h" #include "base/location.h" #include "base/synchronization/waitable_event.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/threading/thread_id_name_manager.h" #include "base/threading/thread_local.h" #include "base/threading/thread_restrictions.h" #if defined(OS_WIN) #include "base/win/scoped_com_initializer.h" #endif namespace base { namespace { // We use this thread-local variable to record whether or not a thread exited // because its Stop method was called. This allows us to catch cases where // MessageLoop::QuitWhenIdle() is called directly, which is unexpected when // using a Thread to setup and run a MessageLoop. base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool = LAZY_INSTANCE_INITIALIZER; } // namespace // This is used to trigger the message loop to exit. void ThreadQuitHelper() { MessageLoop::current()->QuitWhenIdle(); Thread::SetThreadWasQuitProperly(true); } Thread::Options::Options() : message_loop_type(MessageLoop::TYPE_DEFAULT), timer_slack(TIMER_SLACK_NONE), stack_size(0), priority(ThreadPriority::NORMAL) { } Thread::Options::Options(MessageLoop::Type type, size_t size) : message_loop_type(type), timer_slack(TIMER_SLACK_NONE), stack_size(size), priority(ThreadPriority::NORMAL) { } Thread::Options::~Options() { } Thread::Thread(const std::string& name) : #if defined(OS_WIN) com_status_(NONE), #endif stopping_(false), running_(false), thread_(0), id_(kInvalidThreadId), id_event_(true, false), message_loop_(nullptr), message_loop_timer_slack_(TIMER_SLACK_NONE), name_(name) { } Thread::~Thread() { Stop(); } bool Thread::Start() { Options options; #if defined(OS_WIN) if (com_status_ == STA) options.message_loop_type = MessageLoop::TYPE_UI; #endif return StartWithOptions(options); } bool Thread::StartWithOptions(const Options& options) { DCHECK(!message_loop_); #if defined(OS_WIN) DCHECK((com_status_ != STA) || (options.message_loop_type == MessageLoop::TYPE_UI)); #endif // Reset |id_| here to support restarting the thread. id_event_.Reset(); id_ = kInvalidThreadId; SetThreadWasQuitProperly(false); MessageLoop::Type type = options.message_loop_type; if (!options.message_pump_factory.is_null()) type = MessageLoop::TYPE_CUSTOM; message_loop_timer_slack_ = options.timer_slack; scoped_ptr<MessageLoop> message_loop = MessageLoop::CreateUnbound( type, options.message_pump_factory); message_loop_ = message_loop.get(); start_event_.reset(new WaitableEvent(false, false)); // Hold the thread_lock_ while starting a new thread, so that we can make sure // that thread_ is populated before the newly created thread accesses it. { AutoLock lock(thread_lock_); if (!PlatformThread::CreateWithPriority(options.stack_size, this, &thread_, options.priority)) { DLOG(ERROR) << "failed to create thread"; message_loop_ = nullptr; start_event_.reset(); return false; } } // The ownership of message_loop is managemed by the newly created thread // within the ThreadMain. ignore_result(message_loop.release()); DCHECK(message_loop_); return true; } bool Thread::StartAndWaitForTesting() { bool result = Start(); if (!result) return false; WaitUntilThreadStarted(); return true; } bool Thread::WaitUntilThreadStarted() { if (!start_event_) return false; base::ThreadRestrictions::ScopedAllowWait allow_wait; start_event_->Wait(); return true; } void Thread::Stop() { if (!start_event_) return; StopSoon(); // Wait for the thread to exit. // // TODO(darin): Unfortunately, we need to keep message_loop_ around until // the thread exits. Some consumers are abusing the API. Make them stop. // PlatformThread::Join(thread_); // The thread should NULL message_loop_ on exit. DCHECK(!message_loop_); // The thread no longer needs to be joined. start_event_.reset(); stopping_ = false; } void Thread::StopSoon() { // We should only be called on the same thread that started us. DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); if (stopping_ || !message_loop_) return; stopping_ = true; task_runner()->PostTask(FROM_HERE, base::Bind(&ThreadQuitHelper)); } PlatformThreadId Thread::GetThreadId() const { // If the thread is created but not started yet, wait for |id_| being ready. base::ThreadRestrictions::ScopedAllowWait allow_wait; id_event_.Wait(); return id_; } bool Thread::IsRunning() const { // If the thread's already started (i.e. message_loop_ is non-null) and // not yet requested to stop (i.e. stopping_ is false) we can just return // true. (Note that stopping_ is touched only on the same thread that // starts / started the new thread so we need no locking here.) if (message_loop_ && !stopping_) return true; // Otherwise check the running_ flag, which is set to true by the new thread // only while it is inside Run(). AutoLock lock(running_lock_); return running_; } void Thread::Run(MessageLoop* message_loop) { message_loop->Run(); } void Thread::SetThreadWasQuitProperly(bool flag) { lazy_tls_bool.Pointer()->Set(flag); } bool Thread::GetThreadWasQuitProperly() { bool quit_properly = true; #ifndef NDEBUG quit_properly = lazy_tls_bool.Pointer()->Get(); #endif return quit_properly; } void Thread::ThreadMain() { // First, make GetThreadId() available to avoid deadlocks. It could be called // any place in the following thread initialization code. id_ = PlatformThread::CurrentId(); DCHECK_NE(kInvalidThreadId, id_); id_event_.Signal(); // Complete the initialization of our Thread object. PlatformThread::SetName(name_.c_str()); ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector. // Lazily initialize the message_loop so that it can run on this thread. DCHECK(message_loop_); scoped_ptr<MessageLoop> message_loop(message_loop_); message_loop_->BindToCurrentThread(); message_loop_->set_thread_name(name_); message_loop_->SetTimerSlack(message_loop_timer_slack_); #if defined(OS_WIN) scoped_ptr<win::ScopedCOMInitializer> com_initializer; if (com_status_ != NONE) { com_initializer.reset((com_status_ == STA) ? new win::ScopedCOMInitializer() : new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA)); } #endif // Let the thread do extra initialization. Init(); { AutoLock lock(running_lock_); running_ = true; } start_event_->Signal(); Run(message_loop_); { AutoLock lock(running_lock_); running_ = false; } // Let the thread do extra cleanup. CleanUp(); #if defined(OS_WIN) com_initializer.reset(); #endif // Assert that MessageLoop::Quit was called by ThreadQuitHelper. DCHECK(GetThreadWasQuitProperly()); // We can't receive messages anymore. // (The message loop is destructed at the end of this block) message_loop_ = NULL; } } // namespace base <|endoftext|>
<commit_before>// ImGui - standalone example application for DirectX 9 // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. #include <imgui.h> #include "imgui_impl_dx9.h" #include <d3d9.h> #define DIRECTINPUT_VERSION 0x0800 #include <dinput.h> #include <tchar.h> // Data static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; static D3DPRESENT_PARAMETERS g_d3dpp; extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) return true; switch (msg) { case WM_SIZE: if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) { ImGui_ImplDX9_InvalidateDeviceObjects(); g_d3dpp.BackBufferWidth = LOWORD(lParam); g_d3dpp.BackBufferHeight = HIWORD(lParam); HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); if (hr == D3DERR_INVALIDCALL) IM_ASSERT(0); ImGui_ImplDX9_CreateDeviceObjects(); } return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu return 0; break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wParam, lParam); } int main(int, char**) { // Create application window WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, _T("ImGui Example"), NULL }; RegisterClassEx(&wc); HWND hwnd = CreateWindow(_T("ImGui Example"), _T("ImGui DirectX9 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D LPDIRECT3D9 pD3D; if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) { UnregisterClass(_T("ImGui Example"), wc.hInstance); return 0; } ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); g_d3dpp.Windowed = TRUE; g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; g_d3dpp.EnableAutoDepthStencil = TRUE; g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync //g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate // Create the D3DDevice if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) { pD3D->Release(); UnregisterClass(_T("ImGui Example"), wc.hInstance); return 0; } // Setup ImGui binding ImGui_ImplDX9_Init(hwnd, g_pd3dDevice); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Read 'extra_fonts/README.txt' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //ImGuiIO& io = ImGui::GetIO(); //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f); //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); bool show_test_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); // Main loop MSG msg; ZeroMemory(&msg, sizeof(msg)); ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); while (msg.message != WM_QUIT) { // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); continue; } ImGui_ImplDX9_NewFrame(); // 1. Show a simple window. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug". { static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", (float*)&clear_color); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window. if (show_another_window) { ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello from another window!"); ImGui::End(); } // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow(). if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); ImGui::ShowTestWindow(&show_test_window); } // Rendering g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false); D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f)); g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); if (g_pd3dDevice->BeginScene() >= 0) { ImGui::Render(); g_pd3dDevice->EndScene(); } g_pd3dDevice->Present(NULL, NULL, NULL, NULL); } ImGui_ImplDX9_Shutdown(); if (g_pd3dDevice) g_pd3dDevice->Release(); if (pD3D) pD3D->Release(); UnregisterClass(_T("ImGui Example"), wc.hInstance); return 0; } <commit_msg>Examples: DirectX9: Handle loss of D3D9 device (D3DERR_DEVICELOST). (#1464)<commit_after>// ImGui - standalone example application for DirectX 9 // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. #include <imgui.h> #include "imgui_impl_dx9.h" #include <d3d9.h> #define DIRECTINPUT_VERSION 0x0800 #include <dinput.h> #include <tchar.h> // Data static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; static D3DPRESENT_PARAMETERS g_d3dpp; extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) return true; switch (msg) { case WM_SIZE: if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) { ImGui_ImplDX9_InvalidateDeviceObjects(); g_d3dpp.BackBufferWidth = LOWORD(lParam); g_d3dpp.BackBufferHeight = HIWORD(lParam); HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); if (hr == D3DERR_INVALIDCALL) IM_ASSERT(0); ImGui_ImplDX9_CreateDeviceObjects(); } return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu return 0; break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wParam, lParam); } int main(int, char**) { // Create application window WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, _T("ImGui Example"), NULL }; RegisterClassEx(&wc); HWND hwnd = CreateWindow(_T("ImGui Example"), _T("ImGui DirectX9 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D LPDIRECT3D9 pD3D; if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) { UnregisterClass(_T("ImGui Example"), wc.hInstance); return 0; } ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); g_d3dpp.Windowed = TRUE; g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; g_d3dpp.EnableAutoDepthStencil = TRUE; g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync //g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate // Create the D3DDevice if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) { pD3D->Release(); UnregisterClass(_T("ImGui Example"), wc.hInstance); return 0; } // Setup ImGui binding ImGui_ImplDX9_Init(hwnd, g_pd3dDevice); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Read 'extra_fonts/README.txt' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //ImGuiIO& io = ImGui::GetIO(); //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f); //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); bool show_test_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); // Main loop MSG msg; ZeroMemory(&msg, sizeof(msg)); ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); while (msg.message != WM_QUIT) { // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); continue; } ImGui_ImplDX9_NewFrame(); // 1. Show a simple window. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug". { static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", (float*)&clear_color); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window. if (show_another_window) { ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello from another window!"); ImGui::End(); } // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow(). if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); ImGui::ShowTestWindow(&show_test_window); } // Rendering g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false); D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f)); g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); if (g_pd3dDevice->BeginScene() >= 0) { ImGui::Render(); g_pd3dDevice->EndScene(); } HRESULT result = g_pd3dDevice->Present(NULL, NULL, NULL, NULL); // Handle loss of D3D9 device if (result == D3DERR_DEVICELOST && g_pd3dDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET) { ImGui_ImplDX9_InvalidateDeviceObjects(); g_pd3dDevice->Reset(&g_d3dpp); ImGui_ImplDX9_CreateDeviceObjects(); } } ImGui_ImplDX9_Shutdown(); if (g_pd3dDevice) g_pd3dDevice->Release(); if (pD3D) pD3D->Release(); UnregisterClass(_T("ImGui Example"), wc.hInstance); return 0; } <|endoftext|>
<commit_before>#include "PerfectSquares.hpp" #include <vector> using namespace std; int PerfectSquares::numSquares(int n) { vector<int> dp(n + 1, 0); for (int i = 1; i <= n; i++) { dp[i] = dp[i - 1]; for (int j = 2; j * j <= i; j++) dp[i] = min(dp[i], dp[i - j * j]); dp[i] += 1; } return dp[n]; } <commit_msg>Refine Problem 279. Perfect Squares<commit_after>#include "PerfectSquares.hpp" #include <vector> using namespace std; int PerfectSquares::numSquares(int n) { vector<int> dp(n + 1, n); dp[0] = 0; for (int i = 1; i <= n; i++) for (int j = 1; j * j <= i; j++) dp[i] = min(dp[i], dp[i - j * j] + 1); return dp[n]; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015-17 Luke Montalvo <lukemontalvo@gmail.com> * * This file is part of BEE. * BEE is free software and comes with ABSOLUTELY NO WARANTY. * See LICENSE for more details. */ #ifndef BEE_CORE_ENGINESTATE_H #define BEE_CORE_ENGINESTATE_H 1 #include <sstream> #include <list> #include <memory> #include <functional> #include <map> #include <vector> #include <unordered_map> #include <unordered_set> #include "../enum.hpp" namespace bee { // Forward declarations class ProgramFlags; class GameOptions; class Console; class MessageRecipient; class MessageContents; class NetworkData; class Renderer; class RGBA; class Sprite; class Font; class Room; struct EngineState { // These contain data about the engine initialization int argc; char** argv; // The provided commandline flags std::list<ProgramFlags*> flags; // The available commandline flags GameOptions* options; // The engine options // These contain data about the event loop bool quit, is_ready, is_paused; Room *first_room, *current_room; // This defines the platform where 0=Linux, 1=Windows, 2=OSX, 3=other #ifdef __linux__ const unsigned int platform = 0; #elif _WIN32 const unsigned int platform = 1; #elif __APPLE__engine. const unsigned int platform = 2; #else const unsigned int platform = 3; #endif unsigned int width, height; SDL_Cursor* cursor; Renderer* renderer; // This is the current drawing color RGBA* color; Font* font_default; // A default font for engine drawing // These contain data about the current window state bool has_mouse, has_focus; Uint32 tickstamp, new_tickstamp, fps_ticks, tick_delta; NetworkData* net; double volume; unsigned int fps_goal, fps_max, fps_unfocused; unsigned int fps_count; Uint32 frame_number; Sprite* texture_before; Sprite* texture_after; E_TRANSITION transition_type; double transition_speed; std::function<void (Sprite*, Sprite*)> transition_custom_func; const Uint8* keystate; std::map<std::string,SDL_Keycode> keystrings_keys; std::map<SDL_Keycode,std::string> keystrings_strings; std::vector<std::string> commandline_input; unsigned int commandline_current; std::unordered_map<std::string,std::unordered_set<std::shared_ptr<MessageRecipient>>> recipients; const std::unordered_set<std::string> protected_tags; std::vector<std::shared_ptr<MessageContents>> messages; E_OUTPUT messenger_output_level; Console* console; unsigned int fps_stable; EngineState(); }; extern EngineState* engine; } #endif // BEE_CORE_ENGINESTATE_H <commit_msg>Fix typo in EngineState header<commit_after>/* * Copyright (c) 2015-17 Luke Montalvo <lukemontalvo@gmail.com> * * This file is part of BEE. * BEE is free software and comes with ABSOLUTELY NO WARANTY. * See LICENSE for more details. */ #ifndef BEE_CORE_ENGINESTATE_H #define BEE_CORE_ENGINESTATE_H 1 #include <sstream> #include <list> #include <memory> #include <functional> #include <map> #include <vector> #include <unordered_map> #include <unordered_set> #include "../enum.hpp" namespace bee { // Forward declarations class ProgramFlags; class GameOptions; class Console; class MessageRecipient; class MessageContents; class NetworkData; class Renderer; class RGBA; class Sprite; class Font; class Room; struct EngineState { // These contain data about the engine initialization int argc; char** argv; // The provided commandline flags std::list<ProgramFlags*> flags; // The available commandline flags GameOptions* options; // The engine options // These contain data about the event loop bool quit, is_ready, is_paused; Room *first_room, *current_room; // This defines the platform where 0=Linux, 1=Windows, 2=OSX, 3=other #ifdef __linux__ const unsigned int platform = 0; #elif _WIN32 const unsigned int platform = 1; #elif __APPLE__ const unsigned int platform = 2; #else const unsigned int platform = 3; #endif unsigned int width, height; SDL_Cursor* cursor; Renderer* renderer; // This is the current drawing color RGBA* color; Font* font_default; // A default font for engine drawing // These contain data about the current window state bool has_mouse, has_focus; Uint32 tickstamp, new_tickstamp, fps_ticks, tick_delta; NetworkData* net; double volume; unsigned int fps_goal, fps_max, fps_unfocused; unsigned int fps_count; Uint32 frame_number; Sprite* texture_before; Sprite* texture_after; E_TRANSITION transition_type; double transition_speed; std::function<void (Sprite*, Sprite*)> transition_custom_func; const Uint8* keystate; std::map<std::string,SDL_Keycode> keystrings_keys; std::map<SDL_Keycode,std::string> keystrings_strings; std::vector<std::string> commandline_input; unsigned int commandline_current; std::unordered_map<std::string,std::unordered_set<std::shared_ptr<MessageRecipient>>> recipients; const std::unordered_set<std::string> protected_tags; std::vector<std::shared_ptr<MessageContents>> messages; E_OUTPUT messenger_output_level; Console* console; unsigned int fps_stable; EngineState(); }; extern EngineState* engine; } #endif // BEE_CORE_ENGINESTATE_H <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "logger.h" // appleseed.foundation headers. #include "foundation/platform/snprintf.h" #include "foundation/platform/system.h" #include "foundation/platform/thread.h" #include "foundation/utility/foreach.h" #include "foundation/utility/log/ilogtarget.h" #include "foundation/utility/string.h" // Boost headers. #include "boost/date_time/posix_time/posix_time.hpp" // Standard headers. #include <algorithm> #include <cassert> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <list> #include <map> #include <vector> using namespace boost::posix_time; using namespace std; namespace foundation { // // Internal utilities. // namespace { class FormatEvaluator : public NonCopyable { public: FormatEvaluator( const LogMessage::Category category, const ptime& datetime, const size_t thread, const string& message) : m_category(LogMessage::get_category_name(category)) , m_padded_category(LogMessage::get_padded_category_name(category)) , m_datetime(to_iso_extended_string(datetime) + 'Z') , m_thread(pad_left(to_string(thread), '0', 3)) , m_process_size(pad_left(to_string(System::get_process_virtual_memory_size() / (1024 * 1024)) + " MB", ' ', 8)) , m_message(message) { } string evaluate(const string& format) const { string result = format; result = replace(result, "{category}", m_category); result = replace(result, "{padded-category}", m_padded_category); result = replace(result, "{datetime-utc}", m_datetime); result = replace(result, "{thread}", m_thread); result = replace(result, "{process-size}", m_process_size); result = replace(result, "{message}", m_message); return result; } private: const string m_category; const string m_padded_category; const string m_datetime; const string m_thread; const string m_process_size; const string m_message; }; class Formatter : public NonCopyable { public: Formatter() { reset_all_formats(); } void reset_all_formats() { for (size_t i = 0; i < LogMessage::NumMessageCategories; ++i) reset_format(static_cast<LogMessage::Category>(i)); } void reset_format(const LogMessage::Category category) { set_format(category, "{datetime-utc} <{thread}> {process-size} {padded-category} | {message}"); } void set_all_formats(const string& format) { for (size_t i = 0; i < LogMessage::NumMessageCategories; ++i) set_format(static_cast<LogMessage::Category>(i), format); } void set_format( const LogMessage::Category category, const string& format) { const string::size_type message_start = format.find("{message}"); m_formats[category].m_format = format; m_formats[category].m_header_format = format.substr(0, message_start); m_formats[category].m_message_format = message_start != string::npos ? format.substr(message_start) : !format.empty() ? "\n" : string(); } const string& get_format(const LogMessage::Category category) const { return m_formats[category].m_format; } const string& get_header_format(const LogMessage::Category category) const { return m_formats[category].m_header_format; } const string& get_message_format(const LogMessage::Category category) const { return m_formats[category].m_message_format; } private: struct Format { string m_format; string m_header_format; string m_message_format; }; Format m_formats[LogMessage::NumMessageCategories]; }; class ThreadMap : public NonCopyable { public: ThreadMap() : m_thread_count(0) { } size_t thread_id_to_int(const boost::thread::id id) { const ThreadIdToIntMap::const_iterator i = m_thread_id_to_int.find(id); if (i != m_thread_id_to_int.end()) return i->second; m_thread_id_to_int[id] = ++m_thread_count; return m_thread_count; } private: typedef map<boost::thread::id, size_t> ThreadIdToIntMap; size_t m_thread_count; ThreadIdToIntMap m_thread_id_to_int; }; } // // Logger class implementation. // struct Logger::Impl { typedef list<ILogTarget*> LogTargetContainer; boost::mutex m_mutex; bool m_enabled; LogMessage::Category m_verbosity_level; LogTargetContainer m_targets; vector<char> m_message_buffer; ThreadMap m_thread_map; Formatter m_formatter; }; namespace { const size_t InitialBufferSize = 1024; // in bytes const size_t MaxBufferSize = 1024 * 1024; // in bytes } Logger::Logger() : impl(new Impl()) { impl->m_enabled = true; impl->m_verbosity_level = LogMessage::Info; impl->m_message_buffer.resize(InitialBufferSize); } Logger::~Logger() { delete impl; } void Logger::initialize_from(const Logger& source) { boost::mutex::scoped_lock source_lock(source.impl->m_mutex); boost::mutex::scoped_lock this_lock(impl->m_mutex); impl->m_enabled = source.impl->m_enabled; impl->m_verbosity_level = source.impl->m_verbosity_level; impl->m_targets.clear(); for (const_each<Impl::LogTargetContainer> i = source.impl->m_targets; i; ++i) impl->m_targets.push_back(*i); for (size_t i = 0; i < LogMessage::NumMessageCategories; ++i) { const LogMessage::Category category = static_cast<LogMessage::Category>(i); impl->m_formatter.set_format(category, source.impl->m_formatter.get_format(category)); } } void Logger::set_enabled(const bool enabled) { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_enabled = enabled; } void Logger::set_verbosity_level(const LogMessage::Category level) { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_verbosity_level = level; } LogMessage::Category Logger::get_verbosity_level() const { boost::mutex::scoped_lock lock(impl->m_mutex); return impl->m_verbosity_level; } void Logger::reset_all_formats() { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_formatter.reset_all_formats(); } void Logger::reset_format(const LogMessage::Category category) { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_formatter.reset_format(category); } void Logger::set_all_formats(const char* format) { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_formatter.set_all_formats(format); } void Logger::set_format(const LogMessage::Category category, const char* format) { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_formatter.set_format(category, format); } const char* Logger::get_format(const LogMessage::Category category) const { boost::mutex::scoped_lock lock(impl->m_mutex); return impl->m_formatter.get_format(category).c_str(); } void Logger::add_target(ILogTarget* target) { boost::mutex::scoped_lock lock(impl->m_mutex); assert(target); impl->m_targets.push_back(target); } void Logger::remove_target(ILogTarget* target) { boost::mutex::scoped_lock lock(impl->m_mutex); assert(target); impl->m_targets.remove(target); } namespace { bool write_to_buffer( vector<char>& buffer, const size_t max_buffer_size, const char* format, va_list argptr) { while (true) { va_list argptr_copy; va_copy(argptr_copy, argptr); const size_t buffer_size = buffer.size(); const int result = portable_vsnprintf(&buffer[0], buffer_size, format, argptr_copy); if (result < 0) { sprintf( &buffer[0], "(failed to format message, format string is \"%s\".)", replace(format, "\n", "\\n").c_str()); return false; } const size_t needed_buffer_size = static_cast<size_t>(result) + 1; if (needed_buffer_size <= buffer_size) return true; if (buffer_size >= max_buffer_size) return false; buffer.resize(min(needed_buffer_size, max_buffer_size)); } } } void Logger::write( const LogMessage::Category category, const char* file, const size_t line, APPLESEED_PRINTF_FMT const char* format, ...) { boost::mutex::scoped_lock lock(impl->m_mutex); if (category < impl->m_verbosity_level) return; LogMessage::Category effective_category = category; if (impl->m_enabled) { // Format the message into the temporary buffer. va_list argptr; va_start(argptr, format); const bool formatting_succeeded = write_to_buffer(impl->m_message_buffer, MaxBufferSize, format, argptr); // If formatting failed, print the message as an error. if (!formatting_succeeded) effective_category = LogMessage::Error; // Retrieve the current UTC time. const ptime datetime(microsec_clock::universal_time()); // Format the header and message. const size_t thread = impl->m_thread_map.thread_id_to_int(boost::this_thread::get_id()); const FormatEvaluator format_evaluator(effective_category, datetime, thread, &impl->m_message_buffer[0]); const string header = format_evaluator.evaluate(impl->m_formatter.get_header_format(effective_category)); const string message = format_evaluator.evaluate(impl->m_formatter.get_message_format(effective_category)); if (!message.empty()) { // Send the header and message to all log targets. for (const_each<Impl::LogTargetContainer> i = impl->m_targets; i; ++i) { ILogTarget* target = *i; target->write( effective_category, file, line, header.c_str(), message.c_str()); } } } // Terminate the application if the message category is 'Fatal'. if (effective_category == LogMessage::Fatal) exit(EXIT_FAILURE); } } // namespace foundation <commit_msg>Fix gcc build<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "logger.h" // appleseed.foundation headers. #include "foundation/platform/compiler.h" #include "foundation/platform/snprintf.h" #include "foundation/platform/system.h" #include "foundation/platform/thread.h" #include "foundation/utility/foreach.h" #include "foundation/utility/log/ilogtarget.h" #include "foundation/utility/string.h" // Boost headers. #include "boost/date_time/posix_time/posix_time.hpp" // Standard headers. #include <algorithm> #include <cassert> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <list> #include <map> #include <vector> using namespace boost::posix_time; using namespace std; namespace foundation { // // Internal utilities. // namespace { class FormatEvaluator : public NonCopyable { public: FormatEvaluator( const LogMessage::Category category, const ptime& datetime, const size_t thread, const string& message) : m_category(LogMessage::get_category_name(category)) , m_padded_category(LogMessage::get_padded_category_name(category)) , m_datetime(to_iso_extended_string(datetime) + 'Z') , m_thread(pad_left(to_string(thread), '0', 3)) , m_process_size(pad_left(to_string(System::get_process_virtual_memory_size() / (1024 * 1024)) + " MB", ' ', 8)) , m_message(message) { } string evaluate(const string& format) const { string result = format; result = replace(result, "{category}", m_category); result = replace(result, "{padded-category}", m_padded_category); result = replace(result, "{datetime-utc}", m_datetime); result = replace(result, "{thread}", m_thread); result = replace(result, "{process-size}", m_process_size); result = replace(result, "{message}", m_message); return result; } private: const string m_category; const string m_padded_category; const string m_datetime; const string m_thread; const string m_process_size; const string m_message; }; class Formatter : public NonCopyable { public: Formatter() { reset_all_formats(); } void reset_all_formats() { for (size_t i = 0; i < LogMessage::NumMessageCategories; ++i) reset_format(static_cast<LogMessage::Category>(i)); } void reset_format(const LogMessage::Category category) { set_format(category, "{datetime-utc} <{thread}> {process-size} {padded-category} | {message}"); } void set_all_formats(const string& format) { for (size_t i = 0; i < LogMessage::NumMessageCategories; ++i) set_format(static_cast<LogMessage::Category>(i), format); } void set_format( const LogMessage::Category category, const string& format) { const string::size_type message_start = format.find("{message}"); m_formats[category].m_format = format; m_formats[category].m_header_format = format.substr(0, message_start); m_formats[category].m_message_format = message_start != string::npos ? format.substr(message_start) : !format.empty() ? "\n" : string(); } const string& get_format(const LogMessage::Category category) const { return m_formats[category].m_format; } const string& get_header_format(const LogMessage::Category category) const { return m_formats[category].m_header_format; } const string& get_message_format(const LogMessage::Category category) const { return m_formats[category].m_message_format; } private: struct Format { string m_format; string m_header_format; string m_message_format; }; Format m_formats[LogMessage::NumMessageCategories]; }; class ThreadMap : public NonCopyable { public: ThreadMap() : m_thread_count(0) { } size_t thread_id_to_int(const boost::thread::id id) { const ThreadIdToIntMap::const_iterator i = m_thread_id_to_int.find(id); if (i != m_thread_id_to_int.end()) return i->second; m_thread_id_to_int[id] = ++m_thread_count; return m_thread_count; } private: typedef map<boost::thread::id, size_t> ThreadIdToIntMap; size_t m_thread_count; ThreadIdToIntMap m_thread_id_to_int; }; } // // Logger class implementation. // struct Logger::Impl { typedef list<ILogTarget*> LogTargetContainer; boost::mutex m_mutex; bool m_enabled; LogMessage::Category m_verbosity_level; LogTargetContainer m_targets; vector<char> m_message_buffer; ThreadMap m_thread_map; Formatter m_formatter; }; namespace { const size_t InitialBufferSize = 1024; // in bytes const size_t MaxBufferSize = 1024 * 1024; // in bytes } Logger::Logger() : impl(new Impl()) { impl->m_enabled = true; impl->m_verbosity_level = LogMessage::Info; impl->m_message_buffer.resize(InitialBufferSize); } Logger::~Logger() { delete impl; } void Logger::initialize_from(const Logger& source) { boost::mutex::scoped_lock source_lock(source.impl->m_mutex); boost::mutex::scoped_lock this_lock(impl->m_mutex); impl->m_enabled = source.impl->m_enabled; impl->m_verbosity_level = source.impl->m_verbosity_level; impl->m_targets.clear(); for (const_each<Impl::LogTargetContainer> i = source.impl->m_targets; i; ++i) impl->m_targets.push_back(*i); for (size_t i = 0; i < LogMessage::NumMessageCategories; ++i) { const LogMessage::Category category = static_cast<LogMessage::Category>(i); impl->m_formatter.set_format(category, source.impl->m_formatter.get_format(category)); } } void Logger::set_enabled(const bool enabled) { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_enabled = enabled; } void Logger::set_verbosity_level(const LogMessage::Category level) { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_verbosity_level = level; } LogMessage::Category Logger::get_verbosity_level() const { boost::mutex::scoped_lock lock(impl->m_mutex); return impl->m_verbosity_level; } void Logger::reset_all_formats() { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_formatter.reset_all_formats(); } void Logger::reset_format(const LogMessage::Category category) { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_formatter.reset_format(category); } void Logger::set_all_formats(const char* format) { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_formatter.set_all_formats(format); } void Logger::set_format(const LogMessage::Category category, const char* format) { boost::mutex::scoped_lock lock(impl->m_mutex); impl->m_formatter.set_format(category, format); } const char* Logger::get_format(const LogMessage::Category category) const { boost::mutex::scoped_lock lock(impl->m_mutex); return impl->m_formatter.get_format(category).c_str(); } void Logger::add_target(ILogTarget* target) { boost::mutex::scoped_lock lock(impl->m_mutex); assert(target); impl->m_targets.push_back(target); } void Logger::remove_target(ILogTarget* target) { boost::mutex::scoped_lock lock(impl->m_mutex); assert(target); impl->m_targets.remove(target); } namespace { bool write_to_buffer( vector<char>& buffer, const size_t max_buffer_size, const char* format, va_list argptr) { while (true) { va_list argptr_copy; va_copy(argptr_copy, argptr); const size_t buffer_size = buffer.size(); const int result = portable_vsnprintf(&buffer[0], buffer_size, format, argptr_copy); if (result < 0) { sprintf( &buffer[0], "(failed to format message, format string is \"%s\".)", replace(format, "\n", "\\n").c_str()); return false; } const size_t needed_buffer_size = static_cast<size_t>(result) + 1; if (needed_buffer_size <= buffer_size) return true; if (buffer_size >= max_buffer_size) return false; buffer.resize(min(needed_buffer_size, max_buffer_size)); } } } void Logger::write( const LogMessage::Category category, const char* file, const size_t line, APPLESEED_PRINTF_FMT const char* format, ...) { boost::mutex::scoped_lock lock(impl->m_mutex); if (category < impl->m_verbosity_level) return; LogMessage::Category effective_category = category; if (impl->m_enabled) { // Format the message into the temporary buffer. va_list argptr; va_start(argptr, format); const bool formatting_succeeded = write_to_buffer(impl->m_message_buffer, MaxBufferSize, format, argptr); // If formatting failed, print the message as an error. if (!formatting_succeeded) effective_category = LogMessage::Error; // Retrieve the current UTC time. const ptime datetime(microsec_clock::universal_time()); // Format the header and message. const size_t thread = impl->m_thread_map.thread_id_to_int(boost::this_thread::get_id()); const FormatEvaluator format_evaluator(effective_category, datetime, thread, &impl->m_message_buffer[0]); const string header = format_evaluator.evaluate(impl->m_formatter.get_header_format(effective_category)); const string message = format_evaluator.evaluate(impl->m_formatter.get_message_format(effective_category)); if (!message.empty()) { // Send the header and message to all log targets. for (const_each<Impl::LogTargetContainer> i = impl->m_targets; i; ++i) { ILogTarget* target = *i; target->write( effective_category, file, line, header.c_str(), message.c_str()); } } } // Terminate the application if the message category is 'Fatal'. if (effective_category == LogMessage::Fatal) exit(EXIT_FAILURE); } } // namespace foundation <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "scene.h" // appleseed.renderer headers. #include "renderer/modeling/color/colorentity.h" #include "renderer/modeling/environmentedf/environmentedf.h" #include "renderer/modeling/environmentshader/environmentshader.h" #include "renderer/modeling/frame/frame.h" #include "renderer/modeling/object/object.h" #include "renderer/modeling/project/project.h" #include "renderer/modeling/scene/assembly.h" #include "renderer/modeling/scene/assemblyinstance.h" #include "renderer/modeling/scene/objectinstance.h" #include "renderer/modeling/scene/proceduralassembly.h" #include "renderer/modeling/scene/textureinstance.h" #include "renderer/modeling/scene/visibilityflags.h" #include "renderer/modeling/shadergroup/shadergroup.h" #include "renderer/modeling/surfaceshader/physicalsurfaceshader.h" #include "renderer/modeling/surfaceshader/surfaceshader.h" #include "renderer/modeling/texture/texture.h" #include "renderer/utility/bbox.h" // appleseed.foundation headers. #include "foundation/math/vector.h" #include "foundation/utility/api/specializedapiarrays.h" #include "foundation/utility/foreach.h" #include "foundation/utility/job/abortswitch.h" // Standard headers. #include <set> using namespace foundation; using namespace std; namespace renderer { // // Scene class implementation. // namespace { const UniqueID g_class_uid = new_guid(); } UniqueID Scene::get_class_uid() { return g_class_uid; } struct Scene::Impl { UniqueID m_uid; CameraContainer m_cameras; auto_release_ptr<Environment> m_environment; EnvironmentEDFContainer m_environment_edfs; EnvironmentShaderContainer m_environment_shaders; auto_release_ptr<SurfaceShader> m_default_surface_shader; explicit Impl(Entity* parent) : m_cameras(parent) , m_environment_edfs(parent) , m_environment_shaders(parent) , m_default_surface_shader( PhysicalSurfaceShaderFactory().create( "default_surface_shader", ParamArray())) { } }; Scene::Scene() : Entity(g_class_uid) , BaseGroup(this) , impl(new Impl(this)) , m_has_render_data(false) , m_camera(nullptr) { set_name("scene"); } Scene::~Scene() { delete impl; } void Scene::release() { delete this; } Camera* Scene::get_active_camera() const { return m_camera; } CameraContainer& Scene::cameras() const { return impl->m_cameras; } void Scene::set_environment(auto_release_ptr<Environment> environment) { impl->m_environment = environment; if (impl->m_environment.get()) impl->m_environment->set_parent(this); } Environment* Scene::get_environment() const { return impl->m_environment.get(); } EnvironmentEDFContainer& Scene::environment_edfs() const { return impl->m_environment_edfs; } EnvironmentShaderContainer& Scene::environment_shaders() const { return impl->m_environment_shaders; } SurfaceShader* Scene::get_default_surface_shader() const { return impl->m_default_surface_shader.get(); } GAABB3 Scene::compute_bbox() const { const AssemblyInstanceContainer& instances = assembly_instances(); const GAABB3 bbox = compute_parent_bbox<GAABB3>(instances.begin(), instances.end()); return bbox.is_valid() ? bbox : GAABB3(GVector3(0.0f), GVector3(0.0f)); } namespace { bool assembly_instances_use_alpha_mapping( const AssemblyInstanceContainer& assembly_instances, set<UniqueID>& visited_assemblies) { // Regarding transparency in the Tracer, // we only care about camera and shadow rays. const VisibilityFlags::Type visibility_mask = VisibilityFlags::CameraRay | VisibilityFlags::ShadowRay; for (const_each<AssemblyInstanceContainer> i = assembly_instances; i; ++i) { // Retrieve the assembly instance. const AssemblyInstance& assembly_instance = *i; // Skip invisible assembly instances. if ((assembly_instance.get_vis_flags() & visibility_mask) == 0) continue; // Retrieve the assembly. const Assembly& assembly = assembly_instance.get_assembly(); if (visited_assemblies.find(assembly.get_uid()) == visited_assemblies.end()) { visited_assemblies.insert(assembly.get_uid()); // Check the assembly contents. for (const_each<ObjectInstanceContainer> i = assembly.object_instances(); i; ++i) { // Skip invisible object instances. if ((i->get_vis_flags() & visibility_mask) == 0) continue; if (i->uses_alpha_mapping()) return true; } // Recurse into child assembly instances. if (assembly_instances_use_alpha_mapping(assembly.assembly_instances(), visited_assemblies)) return true; } } return false; } bool assembly_instances_has_participating_media( const AssemblyInstanceContainer& assembly_instances, set<UniqueID>& visited_assemblies) { // Regarding participating media in the Tracer, // we only care about camera and shadow rays. const VisibilityFlags::Type visibility_mask = VisibilityFlags::CameraRay | VisibilityFlags::ShadowRay; for (const_each<AssemblyInstanceContainer> i = assembly_instances; i; ++i) { // Retrieve the assembly instance. const AssemblyInstance& assembly_instance = *i; // Skip invisible assembly instances. if ((assembly_instance.get_vis_flags() & visibility_mask) == 0) continue; // Retrieve the assembly. const Assembly& assembly = assembly_instance.get_assembly(); if (visited_assemblies.find(assembly.get_uid()) == visited_assemblies.end()) { visited_assemblies.insert(assembly.get_uid()); // Check the assembly contents. for (const_each<ObjectInstanceContainer> i = assembly.object_instances(); i; ++i) { // Skip invisible object instances. if ((i->get_vis_flags() & visibility_mask) == 0) continue; if (i->has_participating_media()) return true; } // Recurse into child assembly instances. if (assembly_instances_use_alpha_mapping(assembly.assembly_instances(), visited_assemblies)) return true; } } return false; } } bool Scene::uses_alpha_mapping() const { set<UniqueID> visited_assemblies; return assembly_instances_use_alpha_mapping(assembly_instances(), visited_assemblies); } bool Scene::has_participating_media() const { set<UniqueID> visited_assemblies; return assembly_instances_has_participating_media(assembly_instances(), visited_assemblies); } namespace { template <typename EntityCollection> void do_collect_asset_paths( StringArray& paths, const EntityCollection& entities) { for (const_each<EntityCollection> i = entities; i; ++i) i->collect_asset_paths(paths); } template <typename EntityCollection> void do_update_asset_paths( const StringDictionary& mappings, EntityCollection& entities) { for (each<EntityCollection> i = entities; i; ++i) i->update_asset_paths(mappings); } } void Scene::collect_asset_paths(StringArray& paths) const { BaseGroup::collect_asset_paths(paths); do_collect_asset_paths(paths, cameras()); if (impl->m_environment.get()) impl->m_environment->collect_asset_paths(paths); do_collect_asset_paths(paths, environment_edfs()); do_collect_asset_paths(paths, environment_shaders()); } void Scene::update_asset_paths(const StringDictionary& mappings) { BaseGroup::update_asset_paths(mappings); do_update_asset_paths(mappings, cameras()); if (impl->m_environment.get()) impl->m_environment->update_asset_paths(mappings); do_update_asset_paths(mappings, environment_edfs()); do_update_asset_paths(mappings, environment_shaders()); } bool Scene::on_render_begin( const Project& project, IAbortSwitch* abort_switch) { bool success = true; create_render_data(); for (each<CameraContainer> i = cameras(); i; ++i) success = success && i->on_render_begin(project, abort_switch); return success; } void Scene::on_render_end(const Project& project) { for (each<CameraContainer> i = cameras(); i; ++i) i->on_render_end(project); m_has_render_data = false; } namespace { bool invoke_procedural_expand( Assembly& assembly, const Project& project, const Assembly* parent, IAbortSwitch* abort_switch) { ProceduralAssembly* proc_assembly = dynamic_cast<ProceduralAssembly*>(&assembly); if (proc_assembly) { if (!proc_assembly->expand_contents(project, parent, abort_switch)) return false; } for (each<AssemblyContainer> i = assembly.assemblies(); i; ++i) { if (!invoke_procedural_expand(*i, project, &assembly, abort_switch)) return false; } return true; } } bool Scene::expand_procedural_assemblies( const Project& project, IAbortSwitch* abort_switch) { for (each<AssemblyContainer> i = assemblies(); i; ++i) { if (!invoke_procedural_expand(*i, project, nullptr, abort_switch)) return false; } return true; } namespace { template <typename EntityCollection> bool invoke_on_frame_begin( const Project& project, const BaseGroup* parent, EntityCollection& entities, OnFrameBeginRecorder& recorder, IAbortSwitch* abort_switch) { bool success = true; for (each<EntityCollection> i = entities; i; ++i) { if (is_aborted(abort_switch)) break; success = success && i->on_frame_begin(project, parent, recorder, abort_switch); } return success; } } bool Scene::on_frame_begin( const Project& project, const BaseGroup* parent, OnFrameBeginRecorder& recorder, IAbortSwitch* abort_switch) { if (!Entity::on_frame_begin(project, parent, recorder, abort_switch)) return false; m_camera = project.get_uncached_active_camera(); bool success = true; success = success && impl->m_default_surface_shader->on_frame_begin(project, this, recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, colors(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, textures(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, texture_instances(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, shader_groups(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, cameras(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, environment_edfs(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, environment_shaders(), recorder, abort_switch); if (!is_aborted(abort_switch) && impl->m_environment.get()) success = success && impl->m_environment->on_frame_begin(project, this, recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, assemblies(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, assembly_instances(), recorder, abort_switch); return success; } void Scene::on_frame_end( const Project& project, const BaseGroup* parent) { m_camera = nullptr; Entity::on_frame_end(project, parent); } void Scene::create_render_data() { assert(!m_has_render_data); m_render_data.m_bbox = compute_bbox(); m_render_data.m_center = m_render_data.m_bbox.center(); m_render_data.m_radius = m_render_data.m_bbox.radius(); m_render_data.m_diameter = m_render_data.m_bbox.diameter(); m_render_data.m_safe_diameter = m_render_data.m_diameter * GScalar(1.01); m_has_render_data = true; } // // SceneFactory class implementation. // auto_release_ptr<Scene> SceneFactory::create() { return auto_release_ptr<Scene>(new Scene()); } } // namespace renderer <commit_msg>Invoke on_frame_begin() on cameras last<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "scene.h" // appleseed.renderer headers. #include "renderer/modeling/color/colorentity.h" #include "renderer/modeling/environmentedf/environmentedf.h" #include "renderer/modeling/environmentshader/environmentshader.h" #include "renderer/modeling/frame/frame.h" #include "renderer/modeling/object/object.h" #include "renderer/modeling/project/project.h" #include "renderer/modeling/scene/assembly.h" #include "renderer/modeling/scene/assemblyinstance.h" #include "renderer/modeling/scene/objectinstance.h" #include "renderer/modeling/scene/proceduralassembly.h" #include "renderer/modeling/scene/textureinstance.h" #include "renderer/modeling/scene/visibilityflags.h" #include "renderer/modeling/shadergroup/shadergroup.h" #include "renderer/modeling/surfaceshader/physicalsurfaceshader.h" #include "renderer/modeling/surfaceshader/surfaceshader.h" #include "renderer/modeling/texture/texture.h" #include "renderer/utility/bbox.h" // appleseed.foundation headers. #include "foundation/math/vector.h" #include "foundation/utility/api/specializedapiarrays.h" #include "foundation/utility/foreach.h" #include "foundation/utility/job/abortswitch.h" // Standard headers. #include <set> using namespace foundation; using namespace std; namespace renderer { // // Scene class implementation. // namespace { const UniqueID g_class_uid = new_guid(); } UniqueID Scene::get_class_uid() { return g_class_uid; } struct Scene::Impl { UniqueID m_uid; CameraContainer m_cameras; auto_release_ptr<Environment> m_environment; EnvironmentEDFContainer m_environment_edfs; EnvironmentShaderContainer m_environment_shaders; auto_release_ptr<SurfaceShader> m_default_surface_shader; explicit Impl(Entity* parent) : m_cameras(parent) , m_environment_edfs(parent) , m_environment_shaders(parent) , m_default_surface_shader( PhysicalSurfaceShaderFactory().create( "default_surface_shader", ParamArray())) { } }; Scene::Scene() : Entity(g_class_uid) , BaseGroup(this) , impl(new Impl(this)) , m_has_render_data(false) , m_camera(nullptr) { set_name("scene"); } Scene::~Scene() { delete impl; } void Scene::release() { delete this; } Camera* Scene::get_active_camera() const { return m_camera; } CameraContainer& Scene::cameras() const { return impl->m_cameras; } void Scene::set_environment(auto_release_ptr<Environment> environment) { impl->m_environment = environment; if (impl->m_environment.get()) impl->m_environment->set_parent(this); } Environment* Scene::get_environment() const { return impl->m_environment.get(); } EnvironmentEDFContainer& Scene::environment_edfs() const { return impl->m_environment_edfs; } EnvironmentShaderContainer& Scene::environment_shaders() const { return impl->m_environment_shaders; } SurfaceShader* Scene::get_default_surface_shader() const { return impl->m_default_surface_shader.get(); } GAABB3 Scene::compute_bbox() const { const AssemblyInstanceContainer& instances = assembly_instances(); const GAABB3 bbox = compute_parent_bbox<GAABB3>(instances.begin(), instances.end()); return bbox.is_valid() ? bbox : GAABB3(GVector3(0.0f), GVector3(0.0f)); } namespace { bool assembly_instances_use_alpha_mapping( const AssemblyInstanceContainer& assembly_instances, set<UniqueID>& visited_assemblies) { // Regarding transparency in the Tracer, // we only care about camera and shadow rays. const VisibilityFlags::Type visibility_mask = VisibilityFlags::CameraRay | VisibilityFlags::ShadowRay; for (const_each<AssemblyInstanceContainer> i = assembly_instances; i; ++i) { // Retrieve the assembly instance. const AssemblyInstance& assembly_instance = *i; // Skip invisible assembly instances. if ((assembly_instance.get_vis_flags() & visibility_mask) == 0) continue; // Retrieve the assembly. const Assembly& assembly = assembly_instance.get_assembly(); if (visited_assemblies.find(assembly.get_uid()) == visited_assemblies.end()) { visited_assemblies.insert(assembly.get_uid()); // Check the assembly contents. for (const_each<ObjectInstanceContainer> i = assembly.object_instances(); i; ++i) { // Skip invisible object instances. if ((i->get_vis_flags() & visibility_mask) == 0) continue; if (i->uses_alpha_mapping()) return true; } // Recurse into child assembly instances. if (assembly_instances_use_alpha_mapping(assembly.assembly_instances(), visited_assemblies)) return true; } } return false; } bool assembly_instances_has_participating_media( const AssemblyInstanceContainer& assembly_instances, set<UniqueID>& visited_assemblies) { // Regarding participating media in the Tracer, // we only care about camera and shadow rays. const VisibilityFlags::Type visibility_mask = VisibilityFlags::CameraRay | VisibilityFlags::ShadowRay; for (const_each<AssemblyInstanceContainer> i = assembly_instances; i; ++i) { // Retrieve the assembly instance. const AssemblyInstance& assembly_instance = *i; // Skip invisible assembly instances. if ((assembly_instance.get_vis_flags() & visibility_mask) == 0) continue; // Retrieve the assembly. const Assembly& assembly = assembly_instance.get_assembly(); if (visited_assemblies.find(assembly.get_uid()) == visited_assemblies.end()) { visited_assemblies.insert(assembly.get_uid()); // Check the assembly contents. for (const_each<ObjectInstanceContainer> i = assembly.object_instances(); i; ++i) { // Skip invisible object instances. if ((i->get_vis_flags() & visibility_mask) == 0) continue; if (i->has_participating_media()) return true; } // Recurse into child assembly instances. if (assembly_instances_use_alpha_mapping(assembly.assembly_instances(), visited_assemblies)) return true; } } return false; } } bool Scene::uses_alpha_mapping() const { set<UniqueID> visited_assemblies; return assembly_instances_use_alpha_mapping(assembly_instances(), visited_assemblies); } bool Scene::has_participating_media() const { set<UniqueID> visited_assemblies; return assembly_instances_has_participating_media(assembly_instances(), visited_assemblies); } namespace { template <typename EntityCollection> void do_collect_asset_paths( StringArray& paths, const EntityCollection& entities) { for (const_each<EntityCollection> i = entities; i; ++i) i->collect_asset_paths(paths); } template <typename EntityCollection> void do_update_asset_paths( const StringDictionary& mappings, EntityCollection& entities) { for (each<EntityCollection> i = entities; i; ++i) i->update_asset_paths(mappings); } } void Scene::collect_asset_paths(StringArray& paths) const { BaseGroup::collect_asset_paths(paths); do_collect_asset_paths(paths, cameras()); if (impl->m_environment.get()) impl->m_environment->collect_asset_paths(paths); do_collect_asset_paths(paths, environment_edfs()); do_collect_asset_paths(paths, environment_shaders()); } void Scene::update_asset_paths(const StringDictionary& mappings) { BaseGroup::update_asset_paths(mappings); do_update_asset_paths(mappings, cameras()); if (impl->m_environment.get()) impl->m_environment->update_asset_paths(mappings); do_update_asset_paths(mappings, environment_edfs()); do_update_asset_paths(mappings, environment_shaders()); } bool Scene::on_render_begin( const Project& project, IAbortSwitch* abort_switch) { bool success = true; create_render_data(); for (each<CameraContainer> i = cameras(); i; ++i) success = success && i->on_render_begin(project, abort_switch); return success; } void Scene::on_render_end(const Project& project) { for (each<CameraContainer> i = cameras(); i; ++i) i->on_render_end(project); m_has_render_data = false; } namespace { bool invoke_procedural_expand( Assembly& assembly, const Project& project, const Assembly* parent, IAbortSwitch* abort_switch) { ProceduralAssembly* proc_assembly = dynamic_cast<ProceduralAssembly*>(&assembly); if (proc_assembly) { if (!proc_assembly->expand_contents(project, parent, abort_switch)) return false; } for (each<AssemblyContainer> i = assembly.assemblies(); i; ++i) { if (!invoke_procedural_expand(*i, project, &assembly, abort_switch)) return false; } return true; } } bool Scene::expand_procedural_assemblies( const Project& project, IAbortSwitch* abort_switch) { for (each<AssemblyContainer> i = assemblies(); i; ++i) { if (!invoke_procedural_expand(*i, project, nullptr, abort_switch)) return false; } return true; } namespace { template <typename EntityCollection> bool invoke_on_frame_begin( const Project& project, const BaseGroup* parent, EntityCollection& entities, OnFrameBeginRecorder& recorder, IAbortSwitch* abort_switch) { bool success = true; for (each<EntityCollection> i = entities; i; ++i) { if (is_aborted(abort_switch)) break; success = success && i->on_frame_begin(project, parent, recorder, abort_switch); } return success; } } bool Scene::on_frame_begin( const Project& project, const BaseGroup* parent, OnFrameBeginRecorder& recorder, IAbortSwitch* abort_switch) { if (!Entity::on_frame_begin(project, parent, recorder, abort_switch)) return false; m_camera = project.get_uncached_active_camera(); bool success = true; success = success && impl->m_default_surface_shader->on_frame_begin(project, this, recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, colors(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, textures(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, texture_instances(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, shader_groups(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, environment_edfs(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, environment_shaders(), recorder, abort_switch); if (!is_aborted(abort_switch) && impl->m_environment.get()) success = success && impl->m_environment->on_frame_begin(project, this, recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, assemblies(), recorder, abort_switch); success = success && invoke_on_frame_begin(project, this, assembly_instances(), recorder, abort_switch); // Call on_frame_begin() on cameras last because some of them cast rays to sense depth in their autofocus mechanism. success = success && invoke_on_frame_begin(project, this, cameras(), recorder, abort_switch); return success; } void Scene::on_frame_end( const Project& project, const BaseGroup* parent) { m_camera = nullptr; Entity::on_frame_end(project, parent); } void Scene::create_render_data() { assert(!m_has_render_data); m_render_data.m_bbox = compute_bbox(); m_render_data.m_center = m_render_data.m_bbox.center(); m_render_data.m_radius = m_render_data.m_bbox.radius(); m_render_data.m_diameter = m_render_data.m_bbox.diameter(); m_render_data.m_safe_diameter = m_render_data.m_diameter * GScalar(1.01); m_has_render_data = true; } // // SceneFactory class implementation. // auto_release_ptr<Scene> SceneFactory::create() { return auto_release_ptr<Scene>(new Scene()); } } // namespace renderer <|endoftext|>
<commit_before>#include <benchmark/benchmark.h> #include <cstdlib> #include <map> #include <iostream> #include <random> #include <set> #include "database.h" #include "util.h" using namespace naivedb; using namespace std::chrono; double total = 0; #define TIMED_TEST_BEGIN \ do{ steady_clock::time_point t1 = steady_clock::now(); #define TIMED_TEST_END(TEST_NAME) \ steady_clock::time_point t2 = steady_clock::now(); \ auto time = duration_cast<duration<double>>(t2 - t1).count(); \ total+=time; \ std::cout << TEST_NAME << " finished in " << time << " seconds. " << std::endl; \ } while(0); void MixedTest(int nrec) { /* (1) 向数据库写nrec条记录。 (2) 通过关键字读回nrec条记录。 (3) 执行下面的循环nrec×5次。 (a) 随机读一条记录。 (b) 每循环37次,随机删除一条记录。 (c) 每循环11次,随机添加一条记录并读取这条记录。 (d) 每循环17次,随机替换一条记录为新记录。在连续两次替换中,一次用同样大小的记录替换,一次用比以前更长的记录替换。 (4) 将此进程写的所有记录删除。每删除一条记录,随机地寻找10条记录。 */ unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator(seed); const int KeySize = 16; const int ValueSize = 100; DatabaseOption option; option.memory_limitation = 1024 * 1024 * 1024; Database database(std::tmpnam(nullptr), option); std::vector<std::string> keys; std::set<std::string> values; char *buf = new char[ValueSize * 2]; int ikey = 0; for (; ikey < nrec; ikey++) { std::string key = numberToString(ikey, KeySize - 1); keys.push_back(key); } for (int i = 0; i < nrec * 2; i++) { values.emplace(generateRandomString(ValueSize)); } auto iter_value = values.begin(); std::shuffle(keys.begin(), keys.end(), generator); // Test 1 TIMED_TEST_BEGIN for (const auto &key:keys) { database.set(key, (++iter_value)->c_str(), ValueSize, false); } TIMED_TEST_END("Test 1") std::shuffle(keys.begin(), keys.end(), generator); // Test 2 TIMED_TEST_BEGIN for (const auto &key:keys) { database.get(key, buf); } TIMED_TEST_END("Test 2") // Test 3 TIMED_TEST_BEGIN for (int i = 0; i < nrec * 5; i++) { std::uniform_int_distribution<int> dist(0, keys.size() - 1); const std::string key_to_search = keys.at(dist(generator)); // (a) database.get(key_to_search, buf); // (b) if (i % 37 == 0) { std::uniform_int_distribution<int> dist(0, keys.size() - 1); int index = dist(generator); const std::string key_to_delete = keys[index]; keys[index] = keys.back(); keys.pop_back(); database.remove(key_to_delete); } // (c) if (i % 11 == 0) { const std::string key_to_insert = numberToString(ikey++, KeySize - 1); keys.push_back(key_to_insert); database.set(key_to_insert, (++iter_value)->c_str(), ValueSize, false); database.get(key_to_insert, buf); } // (d) if (i % 17 == 0) { std::uniform_int_distribution<int> dist(0, keys.size() - 1); const std::string key = keys.at(dist(generator)); int len = ValueSize; if (i % 34 == 0)len *= 2; const std::string value = generateRandomString(len); database.set(key, value.c_str(), len, true); } } TIMED_TEST_END("Test 3") std::shuffle(keys.begin(), keys.end(), generator); // Test 4 TIMED_TEST_BEGIN for (int i = 0; i < keys.size(); i++) { const std::string &key = keys[i]; database.remove(key); if (i == keys.size() - 1)break; // no more keys for query for (int j = 0; j < 10; j++) { std::uniform_int_distribution<int> dist(i + 1, keys.size() - 1); const std::string key_to_search = keys.at(dist(generator)); database.get(key_to_search, buf); } } TIMED_TEST_END("Test 4") delete[] buf; } int main() { int nrec = 2; int max_nrec = 1 << 21; while(nrec < max_nrec) { total = 0; int iteration = 1000; for(int i = 0; i < iteration; i++) { MixedTest(nrec); } double mean_time = total / iteration; std::cout << "nrec = " << nrec << " time = " << mean_time << std::endl; nrec <<= 1; } return 0; }<commit_msg>Fix missing headers<commit_after>#include <benchmark/benchmark.h> #include <cstdlib> #include <map> #include <iostream> #include <random> #include <set> #include <algorithm> #include <vector> #include <chrono> #include "database.h" #include "util.h" using namespace naivedb; using namespace std::chrono; double total = 0; #define TIMED_TEST_BEGIN \ do{ steady_clock::time_point t1 = steady_clock::now(); #define TIMED_TEST_END(TEST_NAME) \ steady_clock::time_point t2 = steady_clock::now(); \ auto time = duration_cast<duration<double>>(t2 - t1).count(); \ total+=time; \ std::cout << TEST_NAME << " finished in " << time << " seconds. " << std::endl; \ } while(0); void MixedTest(int nrec) { /* (1) 向数据库写nrec条记录。 (2) 通过关键字读回nrec条记录。 (3) 执行下面的循环nrec×5次。 (a) 随机读一条记录。 (b) 每循环37次,随机删除一条记录。 (c) 每循环11次,随机添加一条记录并读取这条记录。 (d) 每循环17次,随机替换一条记录为新记录。在连续两次替换中,一次用同样大小的记录替换,一次用比以前更长的记录替换。 (4) 将此进程写的所有记录删除。每删除一条记录,随机地寻找10条记录。 */ unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator(seed); const int KeySize = 16; const int ValueSize = 100; DatabaseOption option; option.memory_limitation = 1024 * 1024 * 128; Database database(std::tmpnam(nullptr), option); std::vector<std::string> keys; std::set<std::string> values; char *buf = new char[ValueSize * 2]; int ikey = 0; for (; ikey < nrec; ikey++) { std::string key = numberToString(ikey, KeySize - 1); keys.push_back(key); } for (int i = 0; i < nrec * 2; i++) { values.emplace(generateRandomString(ValueSize)); } auto iter_value = values.begin(); std::shuffle(keys.begin(), keys.end(), generator); // Test 1 TIMED_TEST_BEGIN for (const auto &key:keys) { database.set(key, (++iter_value)->c_str(), ValueSize, false); } TIMED_TEST_END("Test 1") std::shuffle(keys.begin(), keys.end(), generator); // Test 2 TIMED_TEST_BEGIN for (const auto &key:keys) { database.get(key, buf); } TIMED_TEST_END("Test 2") // Test 3 TIMED_TEST_BEGIN for (int i = 0; i < nrec * 5; i++) { std::uniform_int_distribution<int> dist(0, keys.size() - 1); const std::string key_to_search = keys.at(dist(generator)); // (a) database.get(key_to_search, buf); // (b) if (i % 37 == 0) { std::uniform_int_distribution<int> dist(0, keys.size() - 1); int index = dist(generator); const std::string key_to_delete = keys[index]; keys[index] = keys.back(); keys.pop_back(); database.remove(key_to_delete); } // (c) if (i % 11 == 0) { const std::string key_to_insert = numberToString(ikey++, KeySize - 1); keys.push_back(key_to_insert); database.set(key_to_insert, (++iter_value)->c_str(), ValueSize, false); database.get(key_to_insert, buf); } // (d) if (i % 17 == 0) { std::uniform_int_distribution<int> dist(0, keys.size() - 1); const std::string key = keys.at(dist(generator)); int len = ValueSize; if (i % 34 == 0)len *= 2; const std::string value = generateRandomString(len); database.set(key, value.c_str(), len, true); } } TIMED_TEST_END("Test 3") std::shuffle(keys.begin(), keys.end(), generator); // Test 4 TIMED_TEST_BEGIN for (int i = 0; i < keys.size(); i++) { const std::string &key = keys[i]; database.remove(key); if (i == keys.size() - 1)break; // no more keys for query for (int j = 0; j < 10; j++) { std::uniform_int_distribution<int> dist(i + 1, keys.size() - 1); const std::string key_to_search = keys.at(dist(generator)); database.get(key_to_search, buf); } } TIMED_TEST_END("Test 4") delete[] buf; } int main() { int nrec = 2; int max_nrec = 1 << 21; /*while(nrec < max_nrec) { total = 0; int iteration = 1000; for(int i = 0; i < iteration; i++) { MixedTest(nrec); } double mean_time = total / iteration; std::cout << "nrec = " << nrec << " time = " << mean_time << std::endl; nrec <<= 1; }*/ MixedTest(1000000); return 0; }<|endoftext|>
<commit_before>#include "RMHD_converter.hpp" extern int myrank, nprocs; inline ptrdiff_t part1by2(ptrdiff_t x) { ptrdiff_t n = x & 0x000003ff; n = (n ^ (n << 16)) & 0xff0000ff; n = (n ^ (n << 8)) & 0x0300f00f; n = (n ^ (n << 4)) & 0x030c30c3; n = (n ^ (n << 2)) & 0x09249249; return n; } inline ptrdiff_t unpart1by2(ptrdiff_t z) { ptrdiff_t n = z & 0x09249249; n = (n ^ (n >> 2)) & 0x030c30c3; n = (n ^ (n >> 4)) & 0x0300f00f; n = (n ^ (n >> 8)) & 0xff0000ff; n = (n ^ (n >> 16)) & 0x000003ff; return n; } inline ptrdiff_t regular_to_zindex( ptrdiff_t x0, ptrdiff_t x1, ptrdiff_t x2) { return part1by2(x0) | (part1by2(x1) << 1) | (part1by2(x2) << 2); } inline void zindex_to_grid3D( ptrdiff_t z, ptrdiff_t &x0, ptrdiff_t &x1, ptrdiff_t &x2) { x0 = unpart1by2(z ); x1 = unpart1by2(z >> 1); x2 = unpart1by2(z >> 2); } RMHD_converter::RMHD_converter( int n0, int n1, int n2, int N0, int N1, int N2) { int n[7]; // first 3 arguments are dimensions for input array // i.e. actual dimensions for the Fourier representation. // NOT real space grid dimensions // the input array is read in as a 2D array, // since the first dimension must be a multiple of nprocs // (which is generally an even number) n[0] = n0*n1; n[1] = n2; this->f0c = new field_descriptor(2, n, MPI_COMPLEX8); // f1c will be pointing at the input array after it has been // transposed in 2D, therefore we have this correspondence: // f0c->sizes[0] = f1c->sizes[1]*f1c->sizes[2] n[0] = n2; n[1] = n0; n[2] = n1; this->f1c = new field_descriptor(3, n, MPI_COMPLEX8); // the description for the fully transposed field n[0] = n2; n[1] = n1; n[2] = n0; this->f2c = new field_descriptor(3, n, MPI_COMPLEX8); // following 3 arguments are dimensions for real space grid dimensions // f3r and f3c will be allocated in this call fftwf_get_descriptors_3D( N0, N1, N2, &this->f3r, &this->f3c); //allocate fields this->c0 = fftwf_alloc_complex(this->f0c->local_size); this->c12 = fftwf_alloc_complex(this->f1c->local_size); this->c3 = fftwf_alloc_complex(this->f3c->local_size); // 4 instead of 2, because we have 2 fields to write this->r3 = fftwf_alloc_real( 4*this->f3c->local_size); // allocate plans this->complex2real0 = fftwf_mpi_plan_dft_c2r_3d( f3r->sizes[0], f3r->sizes[1], f3r->sizes[2], this->c3, this->r3, MPI_COMM_WORLD, FFTW_ESTIMATE); this->complex2real1 = fftwf_mpi_plan_dft_c2r_3d( f3r->sizes[0], f3r->sizes[1], f3r->sizes[2], this->c3, this->r3 + 2*this->f3c->local_size, MPI_COMM_WORLD, FFTW_PATIENT); // various descriptions for the real data n[0] = N0*2; n[1] = N1; n[2] = N2; this->f4r = new field_descriptor(3, n, MPI_REAL4); n[0] = N0/8; n[1] = N1/8; n[2] = N2/8; n[3] = 8*8*8*2; this->drcubbie = new field_descriptor(4, n, MPI_REAL4); n[0] = (N0/8) * (N1/8) * (N2/8); n[1] = 8*8*8*2; this->dzcubbie = new field_descriptor(2, n, MPI_REAL4); } RMHD_converter::~RMHD_converter() { if (this->f0c != NULL) delete this->f0c; if (this->f1c != NULL) delete this->f1c; if (this->f2c != NULL) delete this->f2c; if (this->f3c != NULL) delete this->f3c; if (this->f3r != NULL) delete this->f3r; if (this->f4r != NULL) delete this->f4r; if (this->drcubbie != NULL) delete this->drcubbie; if (this->dzcubbie != NULL) delete this->dzcubbie; if (this->c0 != NULL) fftwf_free(this->c0); if (this->c12 != NULL) fftwf_free(this->c12); if (this->c3 != NULL) fftwf_free(this->c3); if (this->r3 != NULL) fftwf_free(this->r3); fftwf_destroy_plan(this->complex2real0); fftwf_destroy_plan(this->complex2real1); } int RMHD_converter::convert( const char *ifile0, const char *ifile1, const char *ofile) { //read first field this->f0c->read(ifile0, (void*)this->c0); this->f0c->transpose(this->c0, this->c12); this->f1c->transpose(this->c12); fftwf_copy_complex_array( this->f2c, this->c12, this->f3c, this->c3); fftwf_execute(this->complex2real0); //read second field this->f0c->read(ifile1, (void*)this->c0); this->f0c->transpose(this->c0, this->c12); this->f1c->transpose(this->c12); fftwf_copy_complex_array( this->f2c, this->c12, this->f3c, this->c3); fftwf_execute(this->complex2real1); fftwf_clip_zero_padding(this->f4r, this->r3); // new array where mixed components will be placed float *rtmp = fftwf_alloc_real( 4*this->f3c->local_size); float *tpointer; // mix components for (int k = 0; k < this->f3r->local_size; k++) for (int j = 0; j < 2; j++) rtmp[k*2 + j] = this->r3[j*this->f3r->local_size + k]; // point to mixed data tpointer = this->r3; this->r3 = rtmp; rtmp = tpointer; // shuffle into z order ptrdiff_t z, zz; int rid, zid; int kk; ptrdiff_t cubbie_size = 8*8*8*2; ptrdiff_t cc; float *rz = fftwf_alloc_real(cubbie_size); for (int k = 0; k < this->drcubbie->sizes[0]; k++) { rid = this->drcubbie->rank(k); kk = k - this->drcubbie->starts[0]; for (int j = 0; j < this->drcubbie->sizes[1]; j++) for (int i = 0; i < this->drcubbie->sizes[2]; i++) { z = regular_to_zindex(k, j, i); zid = this->dzcubbie->rank(z); zz = z - this->dzcubbie->starts[0]; //if (myrank == 0) // std::cerr << // z << " " << // k << " " << // j << " " << // i << std::endl; if (myrank == rid || myrank == zid) { // first, do actual shuffling if (myrank == rid) for (int tk = 0; tk < 8; tk++) for (int tj = 0; tj < 8; tj++) { cc = (((kk*8+tk)*this->f3r->sizes[1] + (j*8+tj)) * this->f3r->sizes[2] + i*8)*2; std::copy( this->r3 + cc, this->r3 + cc + 16, rz + (tk*8 + tj)*16); } // now copy or send/receive if (rid == zid) std::copy( rz, rz + cubbie_size, rtmp + zz*cubbie_size); else { if (myrank == rid) MPI_Send( rz, cubbie_size, MPI_REAL4, zid, z, MPI_COMM_WORLD); else MPI_Recv( rtmp + zz*cubbie_size, cubbie_size, MPI_REAL4, rid, z, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } } fftwf_free(rz); //point to shuffled data tpointer = this->r3; this->r3 = rtmp; rtmp = tpointer; fftwf_free(rtmp); this->dzcubbie->write(ofile, (void*)this->r3); return EXIT_SUCCESS; } <commit_msg>improve some comments<commit_after>#include "RMHD_converter.hpp" extern int myrank, nprocs; inline ptrdiff_t part1by2(ptrdiff_t x) { ptrdiff_t n = x & 0x000003ff; n = (n ^ (n << 16)) & 0xff0000ff; n = (n ^ (n << 8)) & 0x0300f00f; n = (n ^ (n << 4)) & 0x030c30c3; n = (n ^ (n << 2)) & 0x09249249; return n; } inline ptrdiff_t unpart1by2(ptrdiff_t z) { ptrdiff_t n = z & 0x09249249; n = (n ^ (n >> 2)) & 0x030c30c3; n = (n ^ (n >> 4)) & 0x0300f00f; n = (n ^ (n >> 8)) & 0xff0000ff; n = (n ^ (n >> 16)) & 0x000003ff; return n; } inline ptrdiff_t regular_to_zindex( ptrdiff_t x0, ptrdiff_t x1, ptrdiff_t x2) { return part1by2(x0) | (part1by2(x1) << 1) | (part1by2(x2) << 2); } inline void zindex_to_grid3D( ptrdiff_t z, ptrdiff_t &x0, ptrdiff_t &x1, ptrdiff_t &x2) { x0 = unpart1by2(z ); x1 = unpart1by2(z >> 1); x2 = unpart1by2(z >> 2); } RMHD_converter::RMHD_converter( int n0, int n1, int n2, int N0, int N1, int N2) { int n[7]; // first 3 arguments are dimensions for input array // i.e. actual dimensions for the Fourier representation. // NOT real space grid dimensions // the input array is read in as a 2D array, // since the first dimension must be a multiple of nprocs // (which is generally an even number) n[0] = n0*n1; n[1] = n2; this->f0c = new field_descriptor(2, n, MPI_COMPLEX8); // f1c will be pointing at the input array after it has been // transposed in 2D, therefore we have this correspondence: // f0c->sizes[0] = f1c->sizes[1]*f1c->sizes[2] n[0] = n2; n[1] = n0; n[2] = n1; this->f1c = new field_descriptor(3, n, MPI_COMPLEX8); // the description for the fully transposed field n[0] = n2; n[1] = n1; n[2] = n0; this->f2c = new field_descriptor(3, n, MPI_COMPLEX8); // following 3 arguments are dimensions for real space grid dimensions // f3r and f3c will be allocated in this call fftwf_get_descriptors_3D( N0, N1, N2, &this->f3r, &this->f3c); //allocate fields this->c0 = fftwf_alloc_complex(this->f0c->local_size); this->c12 = fftwf_alloc_complex(this->f1c->local_size); this->c3 = fftwf_alloc_complex(this->f3c->local_size); // 4 instead of 2, because we have 2 fields to write this->r3 = fftwf_alloc_real( 4*this->f3c->local_size); // allocate plans this->complex2real0 = fftwf_mpi_plan_dft_c2r_3d( f3r->sizes[0], f3r->sizes[1], f3r->sizes[2], this->c3, this->r3, MPI_COMM_WORLD, FFTW_ESTIMATE); this->complex2real1 = fftwf_mpi_plan_dft_c2r_3d( f3r->sizes[0], f3r->sizes[1], f3r->sizes[2], this->c3, this->r3 + 2*this->f3c->local_size, MPI_COMM_WORLD, FFTW_PATIENT); // various descriptions for the real data n[0] = N0*2; n[1] = N1; n[2] = N2; this->f4r = new field_descriptor(3, n, MPI_REAL4); n[0] = N0/8; n[1] = N1/8; n[2] = N2/8; n[3] = 8*8*8*2; this->drcubbie = new field_descriptor(4, n, MPI_REAL4); n[0] = (N0/8) * (N1/8) * (N2/8); n[1] = 8*8*8*2; this->dzcubbie = new field_descriptor(2, n, MPI_REAL4); } RMHD_converter::~RMHD_converter() { if (this->f0c != NULL) delete this->f0c; if (this->f1c != NULL) delete this->f1c; if (this->f2c != NULL) delete this->f2c; if (this->f3c != NULL) delete this->f3c; if (this->f3r != NULL) delete this->f3r; if (this->f4r != NULL) delete this->f4r; if (this->drcubbie != NULL) delete this->drcubbie; if (this->dzcubbie != NULL) delete this->dzcubbie; if (this->c0 != NULL) fftwf_free(this->c0); if (this->c12 != NULL) fftwf_free(this->c12); if (this->c3 != NULL) fftwf_free(this->c3); if (this->r3 != NULL) fftwf_free(this->r3); fftwf_destroy_plan(this->complex2real0); fftwf_destroy_plan(this->complex2real1); } int RMHD_converter::convert( const char *ifile0, const char *ifile1, const char *ofile) { //read first field this->f0c->read(ifile0, (void*)this->c0); this->f0c->transpose(this->c0, this->c12); this->f1c->transpose(this->c12); fftwf_copy_complex_array( this->f2c, this->c12, this->f3c, this->c3); fftwf_execute(this->complex2real0); //read second field this->f0c->read(ifile1, (void*)this->c0); this->f0c->transpose(this->c0, this->c12); this->f1c->transpose(this->c12); fftwf_copy_complex_array( this->f2c, this->c12, this->f3c, this->c3); fftwf_execute(this->complex2real1); fftwf_clip_zero_padding(this->f4r, this->r3); // new array where mixed components will be placed float *rtmp = fftwf_alloc_real( 4*this->f3c->local_size); float *tpointer; // mix components for (int k = 0; k < this->f3r->local_size; k++) for (int j = 0; j < 2; j++) rtmp[k*2 + j] = this->r3[j*this->f3r->local_size + k]; // point to mixed data tpointer = this->r3; this->r3 = rtmp; rtmp = tpointer; // shuffle into z order ptrdiff_t z, zz; int rid, zid; int kk; ptrdiff_t cubbie_size = 8*8*8*2; ptrdiff_t cc; float *rz = fftwf_alloc_real(cubbie_size); for (int k = 0; k < this->drcubbie->sizes[0]; k++) { rid = this->drcubbie->rank(k); kk = k - this->drcubbie->starts[0]; for (int j = 0; j < this->drcubbie->sizes[1]; j++) for (int i = 0; i < this->drcubbie->sizes[2]; i++) { z = regular_to_zindex(k, j, i); zid = this->dzcubbie->rank(z); zz = z - this->dzcubbie->starts[0]; if (myrank == rid || myrank == zid) { // first, copy data into cubbie if (myrank == rid) for (int tk = 0; tk < 8; tk++) for (int tj = 0; tj < 8; tj++) { cc = (((kk*8+tk)*this->f3r->sizes[1] + (j*8+tj)) * this->f3r->sizes[2] + i*8)*2; std::copy( this->r3 + cc, this->r3 + cc + 16, rz + (tk*8 + tj)*16); } // now copy or send/receive to zindexed array if (rid == zid) std::copy( rz, rz + cubbie_size, rtmp + zz*cubbie_size); else { if (myrank == rid) MPI_Send( rz, cubbie_size, MPI_REAL4, zid, z, MPI_COMM_WORLD); else MPI_Recv( rtmp + zz*cubbie_size, cubbie_size, MPI_REAL4, rid, z, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } } fftwf_free(rz); //point to shuffled data tpointer = this->r3; this->r3 = rtmp; rtmp = tpointer; fftwf_free(rtmp); this->dzcubbie->write(ofile, (void*)this->r3); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright 2015 Realm Inc - All Rights Reserved * Proprietary and Confidential */ #ifndef REALM_OBJECT_ACCESSOR_HPP #define REALM_OBJECT_ACCESSOR_HPP #include <string> #include "shared_realm.hpp" #include "schema.hpp" #include "list.hpp" namespace realm { class Object { public: Object(SharedRealm r, const ObjectSchema &s, Row o) : m_realm(r), m_object_schema(&s), m_row(o) {} // property getter/setter template<typename ValueType, typename ContextType> inline void set_property_value(ContextType ctx, std::string prop_name, ValueType value, bool try_update); template<typename ValueType, typename ContextType> inline ValueType get_property_value(ContextType ctx, std::string prop_name); // create an Object from a native representation template<typename ValueType, typename ContextType> static inline Object create(ContextType ctx, SharedRealm realm, const ObjectSchema &object_schema, ValueType value, bool try_update); SharedRealm realm() { return m_realm; } const ObjectSchema &get_object_schema() { return *m_object_schema; } Row row() { return m_row; } private: SharedRealm m_realm; const ObjectSchema *m_object_schema; Row m_row; template<typename ValueType, typename ContextType> inline void set_property_value_impl(ContextType ctx, const Property &property, ValueType value, bool try_update); template<typename ValueType, typename ContextType> inline ValueType get_property_value_impl(ContextType ctx, const Property &property); }; // // Value converters - template specializations must be implemented for each platform in order to call templated methods on Object // template<typename ValueType, typename ContextType> class NativeAccessor { public: static bool dict_has_value_for_key(ContextType ctx, ValueType dict, const std::string &prop_name); static ValueType dict_value_for_key(ContextType ctx, ValueType dict, const std::string &prop_name); static bool has_default_value_for_property(ContextType ctx, Realm *realm, const ObjectSchema &object_schema, const std::string &prop_name); static ValueType default_value_for_property(ContextType ctx, Realm *realm, const ObjectSchema &object_schema, const std::string &prop_name); static bool to_bool(ContextType, ValueType &); static ValueType from_bool(ContextType, bool); static long long to_long(ContextType, ValueType &); static ValueType from_long(ContextType, long long); static float to_float(ContextType, ValueType &); static ValueType from_float(ContextType, float); static double to_double(ContextType, ValueType &); static ValueType from_double(ContextType, double); static std::string to_string(ContextType, ValueType &); static ValueType from_string(ContextType, StringData); static std::string to_binary(ContextType, ValueType &); static ValueType from_binary(ContextType, BinaryData); static DateTime to_datetime(ContextType, ValueType &); static ValueType from_datetime(ContextType, DateTime); static bool is_null(ContextType, ValueType &); static ValueType null_value(ContextType); // convert value to persisted object // for existing objects return the existing row index // for new/updated objects return the row index static size_t to_object_index(ContextType ctx, SharedRealm realm, ValueType &val, const std::string &type, bool try_update); static ValueType from_object(ContextType ctx, Object); // object index for an existing object static size_t to_existing_object_index(ContextType ctx, ValueType &val); // list value acessors static size_t list_size(ContextType ctx, ValueType &val); static ValueType list_value_at_index(ContextType ctx, ValueType &val, size_t index); static ValueType from_list(ContextType ctx, List); // // Deprecated // static Mixed to_mixed(ContextType ctx, ValueType &val) { throw std::runtime_error("'Any' type is unsupported"); } }; class InvalidPropertyException : public std::runtime_error { public: InvalidPropertyException(const std::string object_type, const std::string property_name, const std::string message) : std::runtime_error(message), object_type(object_type), property_name(property_name) {} const std::string object_type; const std::string property_name; }; class MissingPropertyValueException : public std::runtime_error { public: MissingPropertyValueException(const std::string object_type, const std::string property_name, const std::string message) : std::runtime_error(message), object_type(object_type), property_name(property_name) {} const std::string object_type; const std::string property_name; }; class MutationOutsideTransactionException : public std::runtime_error { public: MutationOutsideTransactionException(std::string message) : std::runtime_error(message) {} }; // // template method implementations // template <typename ValueType, typename ContextType> inline void Object::set_property_value(ContextType ctx, std::string prop_name, ValueType value, bool try_update) { const Property *prop = m_object_schema->property_for_name(prop_name); if (!prop) { throw InvalidPropertyException(m_object_schema->name, prop_name, "Setting invalid property '" + prop_name + "' on object '" + m_object_schema->name + "'."); } set_property_value_impl(ctx, *prop, value, try_update); }; template <typename ValueType, typename ContextType> inline ValueType Object::get_property_value(ContextType ctx, std::string prop_name) { const Property *prop = m_object_schema->property_for_name(prop_name); if (!prop) { throw InvalidPropertyException(m_object_schema->name, prop_name, "Getting invalid property '" + prop_name + "' on object '" + m_object_schema->name + "'."); } return get_property_value_impl<ValueType>(ctx, *prop); }; template <typename ValueType, typename ContextType> inline void Object::set_property_value_impl(ContextType ctx, const Property &property, ValueType value, bool try_update) { using Accessor = NativeAccessor<ValueType, ContextType>; if (!m_realm->is_in_transaction()) { throw MutationOutsideTransactionException("Can only set property values within a transaction."); } size_t column = property.table_column; if (property.is_nullable && Accessor::is_null(ctx, value)) { m_row.set_null(column); return; } switch (property.type) { case PropertyTypeBool: m_row.set_bool(column, Accessor::to_bool(ctx, value)); break; case PropertyTypeInt: m_row.set_int(column, Accessor::to_long(ctx, value)); break; case PropertyTypeFloat: m_row.set_float(column, Accessor::to_float(ctx, value)); break; case PropertyTypeDouble: m_row.set_double(column, Accessor::to_double(ctx, value)); break; case PropertyTypeString: m_row.set_string(column, Accessor::to_string(ctx, value)); break; case PropertyTypeData: m_row.set_binary(column, BinaryData(Accessor::to_binary(ctx, value))); break; case PropertyTypeAny: m_row.set_mixed(column, Accessor::to_mixed(ctx, value)); break; case PropertyTypeDate: m_row.set_datetime(column, Accessor::to_datetime(ctx, value)); break; case PropertyTypeObject: { if (Accessor::is_null(ctx, value)) { m_row.nullify_link(column); } else { m_row.set_link(column, Accessor::to_object_index(ctx, m_realm, value, property.object_type, try_update)); } break; } case PropertyTypeArray: { realm::LinkViewRef link_view = m_row.get_linklist(column); link_view->clear(); size_t count = Accessor::list_size(ctx, value); for (size_t i = 0; i < count; i++) { ValueType element = Accessor::list_value_at_index(ctx, value, i); link_view->add(Accessor::to_object_index(ctx, m_realm, element, property.object_type, try_update)); } break; } } } template <typename ValueType, typename ContextType> inline ValueType Object::get_property_value_impl(ContextType ctx, const Property &property) { using Accessor = NativeAccessor<ValueType, ContextType>; size_t column = property.table_column; if (property.is_nullable && m_row.is_null(column)) { return Accessor::null_value(ctx); } switch (property.type) { case PropertyTypeBool: return Accessor::from_bool(ctx, m_row.get_bool(column)); case PropertyTypeInt: return Accessor::from_long(ctx, m_row.get_int(column)); case PropertyTypeFloat: return Accessor::from_float(ctx, m_row.get_float(column)); case PropertyTypeDouble: return Accessor::from_double(ctx, m_row.get_double(column)); case PropertyTypeString: return Accessor::from_string(ctx, m_row.get_string(column)); case PropertyTypeData: return Accessor::from_binary(ctx, m_row.get_binary(column)); case PropertyTypeAny: throw "Any not supported"; case PropertyTypeDate: return Accessor::from_datetime(ctx, m_row.get_datetime(column)); case PropertyTypeObject: { auto linkObjectSchema = m_realm->config().schema->find(property.object_type); TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), linkObjectSchema->name); if (m_row.is_null_link(property.table_column)) { return Accessor::null_value(ctx); } return Accessor::from_object(ctx, std::move(Object(m_realm, *linkObjectSchema, table->get(m_row.get_link(column))))); } case PropertyTypeArray: { auto arrayObjectSchema = m_realm->config().schema->find(property.object_type); return Accessor::from_list(ctx, std::move(List(m_realm, *arrayObjectSchema, static_cast<LinkViewRef>(m_row.get_linklist(column))))); } } } template<typename ValueType, typename ContextType> inline Object Object::create(ContextType ctx, SharedRealm realm, const ObjectSchema &object_schema, ValueType value, bool try_update) { using Accessor = NativeAccessor<ValueType, ContextType>; if (!realm->is_in_transaction()) { throw MutationOutsideTransactionException("Can only create objects within a transaction."); } // get or create our accessor bool created; // try to get existing row if updating size_t row_index = realm::not_found; realm::TableRef table = ObjectStore::table_for_object_type(realm->read_group(), object_schema.name); const Property *primary_prop = object_schema.primary_key_property(); if (primary_prop) { // search for existing object based on primary key type ValueType primary_value = Accessor::dict_value_for_key(ctx, value, object_schema.primary_key); if (primary_prop->type == PropertyTypeString) { row_index = table->find_first_string(primary_prop->table_column, Accessor::to_string(ctx, primary_value)); } else { row_index = table->find_first_int(primary_prop->table_column, Accessor::to_long(ctx, primary_value)); } if (!try_update && row_index != realm::not_found) { throw DuplicatePrimaryKeyValueException(object_schema.name, *primary_prop, "Attempting to create an object of type '" + object_schema.name + "' with an exising primary key value."); } } // if no existing, create row created = false; if (row_index == realm::not_found) { row_index = table->add_empty_row(); created = true; } // populate Object object(realm, object_schema, table->get(row_index)); for (const Property &prop : object_schema.properties) { if (created || !prop.is_primary) { if (Accessor::dict_has_value_for_key(ctx, value, prop.name)) { object.set_property_value_impl(ctx, prop, Accessor::dict_value_for_key(ctx, value, prop.name), try_update); } else if (created) { if (Accessor::has_default_value_for_property(ctx, realm.get(), object_schema, prop.name)) { object.set_property_value_impl(ctx, prop, Accessor::default_value_for_property(ctx, realm.get(), object_schema, prop.name), try_update); } else { throw MissingPropertyValueException(object_schema.name, prop.name, "Missing property value for property " + prop.name); } } } } return object; } // // List implementation // template<typename ValueType, typename ContextType> void List::add(ContextType ctx, ValueType value) { add(NativeAccessor<ValueType, ContextType>::to_object_index(ctx, m_realm, value, get_object_schema().name, false)); } template<typename ValueType, typename ContextType> void List::insert(ContextType ctx, ValueType value, size_t list_ndx) { insert(list_ndx, NativeAccessor<ValueType, ContextType>::to_object_index(ctx, m_realm, value, get_object_schema().name, false)); } template<typename ValueType, typename ContextType> void List::set(ContextType ctx, ValueType value, size_t list_ndx) { set(list_ndx, NativeAccessor<ValueType, ContextType>::to_object_index(ctx, m_realm, value, get_object_schema().name, false)); } } #endif /* defined(REALM_OBJECT_ACCESSOR_HPP) */ <commit_msg>no message<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_OBJECT_ACCESSOR_HPP #define REALM_OBJECT_ACCESSOR_HPP #include <string> #include "shared_realm.hpp" #include "schema.hpp" #include "list.hpp" namespace realm { class Object { public: Object(SharedRealm r, const ObjectSchema &s, Row o) : m_realm(r), m_object_schema(&s), m_row(o) {} // property getter/setter template<typename ValueType, typename ContextType> inline void set_property_value(ContextType ctx, std::string prop_name, ValueType value, bool try_update); template<typename ValueType, typename ContextType> inline ValueType get_property_value(ContextType ctx, std::string prop_name); // create an Object from a native representation template<typename ValueType, typename ContextType> static inline Object create(ContextType ctx, SharedRealm realm, const ObjectSchema &object_schema, ValueType value, bool try_update); SharedRealm realm() { return m_realm; } const ObjectSchema &get_object_schema() { return *m_object_schema; } Row row() { return m_row; } private: SharedRealm m_realm; const ObjectSchema *m_object_schema; Row m_row; template<typename ValueType, typename ContextType> inline void set_property_value_impl(ContextType ctx, const Property &property, ValueType value, bool try_update); template<typename ValueType, typename ContextType> inline ValueType get_property_value_impl(ContextType ctx, const Property &property); }; // // Value converters - template specializations must be implemented for each platform in order to call templated methods on Object // template<typename ValueType, typename ContextType> class NativeAccessor { public: static bool dict_has_value_for_key(ContextType ctx, ValueType dict, const std::string &prop_name); static ValueType dict_value_for_key(ContextType ctx, ValueType dict, const std::string &prop_name); static bool has_default_value_for_property(ContextType ctx, Realm *realm, const ObjectSchema &object_schema, const std::string &prop_name); static ValueType default_value_for_property(ContextType ctx, Realm *realm, const ObjectSchema &object_schema, const std::string &prop_name); static bool to_bool(ContextType, ValueType &); static ValueType from_bool(ContextType, bool); static long long to_long(ContextType, ValueType &); static ValueType from_long(ContextType, long long); static float to_float(ContextType, ValueType &); static ValueType from_float(ContextType, float); static double to_double(ContextType, ValueType &); static ValueType from_double(ContextType, double); static std::string to_string(ContextType, ValueType &); static ValueType from_string(ContextType, StringData); static std::string to_binary(ContextType, ValueType &); static ValueType from_binary(ContextType, BinaryData); static DateTime to_datetime(ContextType, ValueType &); static ValueType from_datetime(ContextType, DateTime); static bool is_null(ContextType, ValueType &); static ValueType null_value(ContextType); // convert value to persisted object // for existing objects return the existing row index // for new/updated objects return the row index static size_t to_object_index(ContextType ctx, SharedRealm realm, ValueType &val, const std::string &type, bool try_update); static ValueType from_object(ContextType ctx, Object); // object index for an existing object static size_t to_existing_object_index(ContextType ctx, ValueType &val); // list value acessors static size_t list_size(ContextType ctx, ValueType &val); static ValueType list_value_at_index(ContextType ctx, ValueType &val, size_t index); static ValueType from_list(ContextType ctx, List); // // Deprecated // static Mixed to_mixed(ContextType ctx, ValueType &val) { throw std::runtime_error("'Any' type is unsupported"); } }; class InvalidPropertyException : public std::runtime_error { public: InvalidPropertyException(const std::string object_type, const std::string property_name, const std::string message) : std::runtime_error(message), object_type(object_type), property_name(property_name) {} const std::string object_type; const std::string property_name; }; class MissingPropertyValueException : public std::runtime_error { public: MissingPropertyValueException(const std::string object_type, const std::string property_name, const std::string message) : std::runtime_error(message), object_type(object_type), property_name(property_name) {} const std::string object_type; const std::string property_name; }; class MutationOutsideTransactionException : public std::runtime_error { public: MutationOutsideTransactionException(std::string message) : std::runtime_error(message) {} }; // // template method implementations // template <typename ValueType, typename ContextType> inline void Object::set_property_value(ContextType ctx, std::string prop_name, ValueType value, bool try_update) { const Property *prop = m_object_schema->property_for_name(prop_name); if (!prop) { throw InvalidPropertyException(m_object_schema->name, prop_name, "Setting invalid property '" + prop_name + "' on object '" + m_object_schema->name + "'."); } set_property_value_impl(ctx, *prop, value, try_update); }; template <typename ValueType, typename ContextType> inline ValueType Object::get_property_value(ContextType ctx, std::string prop_name) { const Property *prop = m_object_schema->property_for_name(prop_name); if (!prop) { throw InvalidPropertyException(m_object_schema->name, prop_name, "Getting invalid property '" + prop_name + "' on object '" + m_object_schema->name + "'."); } return get_property_value_impl<ValueType>(ctx, *prop); }; template <typename ValueType, typename ContextType> inline void Object::set_property_value_impl(ContextType ctx, const Property &property, ValueType value, bool try_update) { using Accessor = NativeAccessor<ValueType, ContextType>; if (!m_realm->is_in_transaction()) { throw MutationOutsideTransactionException("Can only set property values within a transaction."); } size_t column = property.table_column; if (property.is_nullable && Accessor::is_null(ctx, value)) { m_row.set_null(column); return; } switch (property.type) { case PropertyTypeBool: m_row.set_bool(column, Accessor::to_bool(ctx, value)); break; case PropertyTypeInt: m_row.set_int(column, Accessor::to_long(ctx, value)); break; case PropertyTypeFloat: m_row.set_float(column, Accessor::to_float(ctx, value)); break; case PropertyTypeDouble: m_row.set_double(column, Accessor::to_double(ctx, value)); break; case PropertyTypeString: m_row.set_string(column, Accessor::to_string(ctx, value)); break; case PropertyTypeData: m_row.set_binary(column, BinaryData(Accessor::to_binary(ctx, value))); break; case PropertyTypeAny: m_row.set_mixed(column, Accessor::to_mixed(ctx, value)); break; case PropertyTypeDate: m_row.set_datetime(column, Accessor::to_datetime(ctx, value)); break; case PropertyTypeObject: { if (Accessor::is_null(ctx, value)) { m_row.nullify_link(column); } else { m_row.set_link(column, Accessor::to_object_index(ctx, m_realm, value, property.object_type, try_update)); } break; } case PropertyTypeArray: { realm::LinkViewRef link_view = m_row.get_linklist(column); link_view->clear(); size_t count = Accessor::list_size(ctx, value); for (size_t i = 0; i < count; i++) { ValueType element = Accessor::list_value_at_index(ctx, value, i); link_view->add(Accessor::to_object_index(ctx, m_realm, element, property.object_type, try_update)); } break; } } } template <typename ValueType, typename ContextType> inline ValueType Object::get_property_value_impl(ContextType ctx, const Property &property) { using Accessor = NativeAccessor<ValueType, ContextType>; size_t column = property.table_column; if (property.is_nullable && m_row.is_null(column)) { return Accessor::null_value(ctx); } switch (property.type) { case PropertyTypeBool: return Accessor::from_bool(ctx, m_row.get_bool(column)); case PropertyTypeInt: return Accessor::from_long(ctx, m_row.get_int(column)); case PropertyTypeFloat: return Accessor::from_float(ctx, m_row.get_float(column)); case PropertyTypeDouble: return Accessor::from_double(ctx, m_row.get_double(column)); case PropertyTypeString: return Accessor::from_string(ctx, m_row.get_string(column)); case PropertyTypeData: return Accessor::from_binary(ctx, m_row.get_binary(column)); case PropertyTypeAny: throw "Any not supported"; case PropertyTypeDate: return Accessor::from_datetime(ctx, m_row.get_datetime(column)); case PropertyTypeObject: { auto linkObjectSchema = m_realm->config().schema->find(property.object_type); TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), linkObjectSchema->name); if (m_row.is_null_link(property.table_column)) { return Accessor::null_value(ctx); } return Accessor::from_object(ctx, std::move(Object(m_realm, *linkObjectSchema, table->get(m_row.get_link(column))))); } case PropertyTypeArray: { auto arrayObjectSchema = m_realm->config().schema->find(property.object_type); return Accessor::from_list(ctx, std::move(List(m_realm, *arrayObjectSchema, static_cast<LinkViewRef>(m_row.get_linklist(column))))); } } } template<typename ValueType, typename ContextType> inline Object Object::create(ContextType ctx, SharedRealm realm, const ObjectSchema &object_schema, ValueType value, bool try_update) { using Accessor = NativeAccessor<ValueType, ContextType>; if (!realm->is_in_transaction()) { throw MutationOutsideTransactionException("Can only create objects within a transaction."); } // get or create our accessor bool created; // try to get existing row if updating size_t row_index = realm::not_found; realm::TableRef table = ObjectStore::table_for_object_type(realm->read_group(), object_schema.name); const Property *primary_prop = object_schema.primary_key_property(); if (primary_prop) { // search for existing object based on primary key type ValueType primary_value = Accessor::dict_value_for_key(ctx, value, object_schema.primary_key); if (primary_prop->type == PropertyTypeString) { row_index = table->find_first_string(primary_prop->table_column, Accessor::to_string(ctx, primary_value)); } else { row_index = table->find_first_int(primary_prop->table_column, Accessor::to_long(ctx, primary_value)); } if (!try_update && row_index != realm::not_found) { throw DuplicatePrimaryKeyValueException(object_schema.name, *primary_prop, "Attempting to create an object of type '" + object_schema.name + "' with an exising primary key value."); } } // if no existing, create row created = false; if (row_index == realm::not_found) { row_index = table->add_empty_row(); created = true; } // populate Object object(realm, object_schema, table->get(row_index)); for (const Property &prop : object_schema.properties) { if (created || !prop.is_primary) { if (Accessor::dict_has_value_for_key(ctx, value, prop.name)) { object.set_property_value_impl(ctx, prop, Accessor::dict_value_for_key(ctx, value, prop.name), try_update); } else if (created) { if (Accessor::has_default_value_for_property(ctx, realm.get(), object_schema, prop.name)) { object.set_property_value_impl(ctx, prop, Accessor::default_value_for_property(ctx, realm.get(), object_schema, prop.name), try_update); } else { throw MissingPropertyValueException(object_schema.name, prop.name, "Missing property value for property " + prop.name); } } } } return object; } // // List implementation // template<typename ValueType, typename ContextType> void List::add(ContextType ctx, ValueType value) { add(NativeAccessor<ValueType, ContextType>::to_object_index(ctx, m_realm, value, get_object_schema().name, false)); } template<typename ValueType, typename ContextType> void List::insert(ContextType ctx, ValueType value, size_t list_ndx) { insert(list_ndx, NativeAccessor<ValueType, ContextType>::to_object_index(ctx, m_realm, value, get_object_schema().name, false)); } template<typename ValueType, typename ContextType> void List::set(ContextType ctx, ValueType value, size_t list_ndx) { set(list_ndx, NativeAccessor<ValueType, ContextType>::to_object_index(ctx, m_realm, value, get_object_schema().name, false)); } } #endif /* defined(REALM_OBJECT_ACCESSOR_HPP) */ <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_test.h" class MediaLeakTest : public TestShellTest { }; #if defined(OS_WIN) || defined(OS_LINUX) // This test plays a Theora video file for 1 second. It tries to expose // memory leaks during a normal playback. TEST_F(MediaLeakTest, VideoBear) { FilePath media_file; ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &media_file)); media_file = media_file.Append(FILE_PATH_LITERAL("webkit")) .Append(FILE_PATH_LITERAL("data")) .Append(FILE_PATH_LITERAL("media")) .Append(FILE_PATH_LITERAL("bear.html")); test_shell_->LoadURL(media_file.ToWStringHack().c_str()); test_shell_->WaitTestFinished(); } // This test loads a Theora video file and unloads it many times. It tries // to expose memory leaks in the glue layer with WebKit. TEST_F(MediaLeakTest, ManyVideoBear) { FilePath media_file; ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &media_file)); media_file = media_file.Append(FILE_PATH_LITERAL("webkit")) .Append(FILE_PATH_LITERAL("data")) .Append(FILE_PATH_LITERAL("media")) .Append(FILE_PATH_LITERAL("manybear.html")); test_shell_->LoadURL(media_file.ToWStringHack().c_str()); test_shell_->WaitTestFinished(); } #endif <commit_msg>Revert "Enable MediaLeakTest.*"<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_test.h" class MediaLeakTest : public TestShellTest { }; #if defined(OS_WIN) || defined(OS_LINUX) // This test plays a Theora video file for 1 second. It tries to expose // memory leaks during a normal playback. TEST_F(MediaLeakTest, DISABLED_VideoBear) { FilePath media_file; ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &media_file)); media_file = media_file.Append(FILE_PATH_LITERAL("webkit")) .Append(FILE_PATH_LITERAL("data")) .Append(FILE_PATH_LITERAL("media")) .Append(FILE_PATH_LITERAL("bear.html")); test_shell_->LoadURL(media_file.ToWStringHack().c_str()); test_shell_->WaitTestFinished(); } // This test loads a Theora video file and unloads it many times. It tries // to expose memory leaks in the glue layer with WebKit. TEST_F(MediaLeakTest, DISABLED_ManyVideoBear) { FilePath media_file; ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &media_file)); media_file = media_file.Append(FILE_PATH_LITERAL("webkit")) .Append(FILE_PATH_LITERAL("data")) .Append(FILE_PATH_LITERAL("media")) .Append(FILE_PATH_LITERAL("manybear.html")); test_shell_->LoadURL(media_file.ToWStringHack().c_str()); test_shell_->WaitTestFinished(); } #endif <|endoftext|>
<commit_before>#include <cstdio> #define ELEMENT_COUNT 1000 using namespace std; int n, d[ELEMENT_COUNT]; void insertion_sort() { for (int i = 1; i < n; i++) { for (int j = i - 1; j >= 0; j--) { if (d[j] > d[j + 1]) { int temp = d[j]; d[j] = d[j + 1]; d[j + 1] = temp; } else { break; } } } } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &d[i]); } insertion_sort(); for (int i = 0; i < n; i++) { printf("%d\n", d[i]); } return 0; } <commit_msg>更改循环边界,使代码更简短<commit_after>#include <cstdio> #define ELEMENT_COUNT 1000 using namespace std; int n, d[ELEMENT_COUNT]; void insertion_sort() { for (int i = 1; i < n; i++) { for (int j = i; j > 0; j--) { if (d[j] < d[j - 1]) { int temp = d[j]; d[j] = d[j - 1]; d[j - 1] = temp; } else { break; } } } } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &d[i]); } insertion_sort(); for (int i = 0; i < n; i++) { printf("%d\n", d[i]); } return 0; } <|endoftext|>
<commit_before>/// /// @file S2LoadBalancer.cpp /// @brief The S2LoadBalancer evenly distributes the work load between /// the threads in the computation of the special leaves. /// /// Simply parallelizing the computation of the special leaves in the /// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by /// subdividing the sieve interval by the number of threads into /// equally sized subintervals does not scale because the distribution /// of the special leaves is highly skewed, especially if the interval /// size is large and if the intervals are not adjacent. Also most /// special leaves are in the first few segments whereas later on /// there are very few special leaves. /// /// Based on the above observations it is clear that we need some kind /// of load balancing in order to scale our parallel algorithm for /// computing the special leaves. Below are the ideas I used to /// develop a load balancing algorithm which scales linearly up to a /// large number of CPU cores (tested with 300 threads). /// /// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x) /// and one segment per thread. Our algorithm uses equally sized /// intervals, for each thread the interval_size is /// segment_size * segments_per_thread and the threads process /// adjacent intervals i.e. /// [base + interval_size * thread_id, base + interval_size * (thread_id + 1)]. /// /// 2) If the relative standard deviation of the run times of the /// threads is low then increase the segment size and/or segments /// per thread, else if the relative standard deviation is large /// then decrease the segment size and/or segments per thread. This /// rule is derived from the observation that intervals with /// roughly the same number of special leaves take about the same /// time to process and the next intervals tend to have a similar /// distribution of special leaves (especially if the interval size /// is small). /// /// 3) We can't use a static threshold for as to when the relative /// standard deviation is low or large as this threshold varies for /// different PC architectures e.g. 15 might be large relative /// standard deviation for a quad-core CPU system whereas it is a /// low standard deviation for a dual-socket system with 64 CPU /// cores. So instead of using a static threshold we compare the /// current relative standard deviation to the previous one. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <aligned_vector.hpp> #include <pmath.hpp> #include <inttypes.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_average(aligned_vector<double>& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } double relative_standard_deviation(aligned_vector<double>& timings) { size_t n = timings.size(); double average = get_average(timings); double sum = 0; if (average == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - average; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / average; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z, int64_t threads) : x_((double) x), z_((double) z), rsd_(40), avg_seconds_(0), count_(0) { double log_threads = max(1.0, log((double) threads)); decrease_dividend_ = max(0.5, log_threads / 3); min_seconds_ = 0.02 * log_threads; max_size_ = next_power_of_2(isqrt(z)); update_min_size(log(x_) * log(log(x_))); } double S2LoadBalancer::get_rsd() const { return rsd_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } bool S2LoadBalancer::decrease_size(double seconds, double decrease) const { return seconds > min_seconds_ && rsd_ > decrease; } bool S2LoadBalancer::increase_size(double seconds, double decrease) const { return seconds < avg_seconds_ && !decrease_size(seconds, decrease); } /// Used to decide whether to use a smaller or larger /// segment_size and/or segments_per_thread. /// double S2LoadBalancer::get_decrease_threshold(double seconds) const { double log_seconds = max(min_seconds_, log(seconds)); double dont_decrease = min(decrease_dividend_ / (seconds * log_seconds), rsd_); return rsd_ + dont_decrease; } void S2LoadBalancer::update_avg_seconds(double seconds) { seconds = max(seconds, min_seconds_); double dividend = avg_seconds_ * count_ + seconds; avg_seconds_ = dividend / (count_ + 1); count_++; } void S2LoadBalancer::update_min_size(double divisor) { double size = sqrt(z_) / max(1.0, divisor); min_size_ = max((int64_t) (1 << 9), (int64_t) size); min_size_ = next_power_of_2(min_size_); } /// Balance the load in the computation of the special leaves /// by dynamically adjusting the segment_size and segments_per_thread. /// @param timings Timings of the threads. /// void S2LoadBalancer::update(int64_t low, int64_t threads, int64_t* segment_size, int64_t* segments_per_thread, aligned_vector<double>& timings) { double seconds = get_average(timings); update_avg_seconds(seconds); double decrease_threshold = get_decrease_threshold(seconds); rsd_ = max(0.1, relative_standard_deviation(timings)); // if low > sqrt(z) we use a larger min_size_ as the // special leaves are distributed more evenly if (low > max_size_) { update_min_size(log(x_)); *segment_size = max(*segment_size, min_size_); } // 1 segment per thread if (*segment_size < max_size_) { if (increase_size(seconds, decrease_threshold)) *segment_size <<= 1; else if (decrease_size(seconds, decrease_threshold)) if (*segment_size > min_size_) *segment_size >>= 1; // near sqrt(z) there is a short peak of special // leaves so we use the minium segment size int64_t high = low + *segment_size * *segments_per_thread * threads; if (low <= max_size_ && high > max_size_) *segment_size = min_size_; } else // many segments per thread { double factor = decrease_threshold / rsd_; factor = in_between(0.5, factor, 2); double n = *segments_per_thread * factor; n = max(1.0, n); if ((n < *segments_per_thread && seconds > min_seconds_) || (n > *segments_per_thread && seconds < avg_seconds_)) { *segments_per_thread = (int) n; } } } } // namespace <commit_msg>Update documentation<commit_after>/// /// @file S2LoadBalancer.cpp /// @brief The S2LoadBalancer evenly distributes the work load between /// the threads in the computation of the special leaves. /// /// Simply parallelizing the computation of the special leaves in the /// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by /// subdividing the sieve interval by the number of threads into /// equally sized subintervals does not scale because the distribution /// of the special leaves is highly skewed and most special leaves are /// in the first few segments whereas later on there are very few /// special leaves. /// /// Based on the above observations it is clear that we need some kind /// of load balancing in order to scale our parallel algorithm for /// computing special leaves. Below are the ideas I used to develop a /// load balancing algorithm that achieves a high load balance by /// dynamically increasing or decreasing the interval size based on /// the relative standard deviation of the thread run-times. /// /// 1) Start with a tiny segment_size of x^(1/3) / (log x * log log x) /// and one segment_per_thread. Our algorithm uses equally sized /// intervals, for each thread the interval_size is /// segment_size * segments_per_thread and the threads process /// adjacent intervals i.e. /// [base + interval_size * thread_id, base + interval_size * (thread_id + 1)]. /// /// 2) If the relative standard deviation of the thread run-times is /// large then we know the special leaves are distributed unevenly, /// else if the relative standard deviation is low the special /// leaves are more evenly distributed. /// /// 3) If the special leaves are distributed unevenly then we can /// increase the load balance by decreasing the interval_size. /// Contrary if the special leaves are more evenly distributed /// we can increase the interval_size in order to improve the /// algorithm's efficiency. /// /// 4) We can't use a static threshold for as to when the relative /// standard deviation is low or large as this threshold varies for /// different PC architectures. So Instead we compare the current /// relative standard deviation to the previous one in order to /// decide whether to increase or decrease the interval_size. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <aligned_vector.hpp> #include <pmath.hpp> #include <inttypes.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_average(aligned_vector<double>& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } double relative_standard_deviation(aligned_vector<double>& timings) { size_t n = timings.size(); double average = get_average(timings); double sum = 0; if (average == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - average; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / average; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z, int64_t threads) : x_((double) x), z_((double) z), rsd_(40), avg_seconds_(0), count_(0) { double log_threads = max(1.0, log((double) threads)); decrease_dividend_ = max(0.5, log_threads / 3); min_seconds_ = 0.02 * log_threads; max_size_ = next_power_of_2(isqrt(z)); update_min_size(log(x_) * log(log(x_))); } double S2LoadBalancer::get_rsd() const { return rsd_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } bool S2LoadBalancer::decrease_size(double seconds, double decrease) const { return seconds > min_seconds_ && rsd_ > decrease; } bool S2LoadBalancer::increase_size(double seconds, double decrease) const { return seconds < avg_seconds_ && !decrease_size(seconds, decrease); } /// Used to decide whether to use a smaller or larger /// segment_size and/or segments_per_thread. /// double S2LoadBalancer::get_decrease_threshold(double seconds) const { double log_seconds = max(min_seconds_, log(seconds)); double dont_decrease = min(decrease_dividend_ / (seconds * log_seconds), rsd_); return rsd_ + dont_decrease; } void S2LoadBalancer::update_avg_seconds(double seconds) { seconds = max(seconds, min_seconds_); double dividend = avg_seconds_ * count_ + seconds; avg_seconds_ = dividend / (count_ + 1); count_++; } void S2LoadBalancer::update_min_size(double divisor) { double size = sqrt(z_) / max(1.0, divisor); min_size_ = max((int64_t) (1 << 9), (int64_t) size); min_size_ = next_power_of_2(min_size_); } /// Balance the load in the computation of the special leaves /// by dynamically adjusting the segment_size and segments_per_thread. /// @param timings Timings of the threads. /// void S2LoadBalancer::update(int64_t low, int64_t threads, int64_t* segment_size, int64_t* segments_per_thread, aligned_vector<double>& timings) { double seconds = get_average(timings); update_avg_seconds(seconds); double decrease_threshold = get_decrease_threshold(seconds); rsd_ = max(0.1, relative_standard_deviation(timings)); // if low > sqrt(z) we use a larger min_size_ as the // special leaves are distributed more evenly if (low > max_size_) { update_min_size(log(x_)); *segment_size = max(*segment_size, min_size_); } // 1 segment per thread if (*segment_size < max_size_) { if (increase_size(seconds, decrease_threshold)) *segment_size <<= 1; else if (decrease_size(seconds, decrease_threshold)) if (*segment_size > min_size_) *segment_size >>= 1; // near sqrt(z) there is a short peak of special // leaves so we use the minium segment size int64_t high = low + *segment_size * *segments_per_thread * threads; if (low <= max_size_ && high > max_size_) *segment_size = min_size_; } else // many segments per thread { double factor = decrease_threshold / rsd_; factor = in_between(0.5, factor, 2); double n = *segments_per_thread * factor; n = max(1.0, n); if ((n < *segments_per_thread && seconds > min_seconds_) || (n > *segments_per_thread && seconds < avg_seconds_)) { *segments_per_thread = (int) n; } } } } // namespace <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * 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 :: Plugins * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <Compliant/config.h> #include "misc/CompliantSolverMerger.h" #include "contact/CompliantContact.h" namespace sofa { namespace component { //Here are just several convenient functions to help user to know what contains the plugin extern "C" { SOFA_Compliant_API void initExternalModule(); SOFA_Compliant_API const char* getModuleName(); SOFA_Compliant_API const char* getModuleVersion(); SOFA_Compliant_API const char* getModuleLicense(); SOFA_Compliant_API const char* getModuleDescription(); SOFA_Compliant_API const char* getModuleComponentList(); } void initExternalModule() { static bool first = true; if (first) { first = false; component::collision::CompliantSolverMerger::add(); } } const char* getModuleName() { return "Compliant"; } const char* getModuleVersion() { return "0"; } const char* getModuleLicense() { return "LGPL"; } const char* getModuleDescription() { return "Simulation of deformable object using a formulation similar to the KKT system for hard constraints, regularized using a compliance matrix"; } const char* getModuleComponentList() { return ""; /// @TODO } } // Ensure that our abstract factories do the registration and avoid symbol stripping on agressive // compilers like the ones found on consoles. SOFA_Compliant_API void initCompliant() { component::collision::registerContactClasses(); } } //SOFA_LINK_CLASS(MyMappingPendulumInPlane) <commit_msg>Compliant: static check Eigen version<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * 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 :: Plugins * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <Compliant/config.h> #include "misc/CompliantSolverMerger.h" #include "contact/CompliantContact.h" namespace sofa { namespace component { //Here are just several convenient functions to help user to know what contains the plugin extern "C" { SOFA_Compliant_API void initExternalModule(); SOFA_Compliant_API const char* getModuleName(); SOFA_Compliant_API const char* getModuleVersion(); SOFA_Compliant_API const char* getModuleLicense(); SOFA_Compliant_API const char* getModuleDescription(); SOFA_Compliant_API const char* getModuleComponentList(); } void initExternalModule() { static bool first = true; if (first) { first = false; component::collision::CompliantSolverMerger::add(); // previous Eigen versions have a critical bug (v.noalias()+=w does not work in every situations) BOOST_STATIC_ASSERT( EIGEN_WORLD_VERSION>=3 && EIGEN_MAJOR_VERSION>=2 && EIGEN_MINOR_VERSION>=5 ); } } const char* getModuleName() { return "Compliant"; } const char* getModuleVersion() { return "0"; } const char* getModuleLicense() { return "LGPL"; } const char* getModuleDescription() { return "Simulation of deformable object using a formulation similar to the KKT system for hard constraints, regularized using a compliance matrix"; } const char* getModuleComponentList() { return ""; /// @TODO } } // Ensure that our abstract factories do the registration and avoid symbol stripping on agressive // compilers like the ones found on consoles. SOFA_Compliant_API void initCompliant() { component::collision::registerContactClasses(); } } //SOFA_LINK_CLASS(MyMappingPendulumInPlane) <|endoftext|>
<commit_before>#include <boost/test/test_case_template.hpp> #include <boost/test/unit_test.hpp> #include "args.hpp" #include "coordinates.hpp" #include "equal_json.hpp" #include "fixture.hpp" #include "osrm/coordinate.hpp" #include "osrm/engine_config.hpp" #include "osrm/json_container.hpp" #include "osrm/json_container.hpp" #include "osrm/osrm.hpp" #include "osrm/route_parameters.hpp" #include "osrm/status.hpp" BOOST_AUTO_TEST_SUITE(route) BOOST_AUTO_TEST_CASE(test_route_same_coordinates_fixture) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; RouteParameters params; params.steps = true; params.coordinates.push_back(get_dummy_location()); params.coordinates.push_back(get_dummy_location()); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); // unset snapping dependent hint for (auto &itr : result.values["waypoints"].get<json::Array>().values) itr.get<json::Object>().values["hint"] = ""; const auto location = json::Array{{{7.437070}, {43.749248}}}; json::Object reference{ {{"code", "Ok"}, {"waypoints", json::Array{ {json::Object{ {{"name", "Boulevard du Larvotto"}, {"location", location}, {"hint", ""}}}, json::Object{ {{"name", "Boulevard du Larvotto"}, {"location", location}, {"hint", ""}}}}}}, {"routes", json::Array{{json::Object{ {{"distance", 0.}, {"duration", 0.}, {"weight", 0.}, {"weight_name", "routability"}, {"geometry", "yw_jGupkl@??"}, {"legs", json::Array{{json::Object{ {{"distance", 0.}, {"duration", 0.}, {"weight", 0.}, {"summary", "Boulevard du Larvotto"}, {"steps", json::Array{{{json::Object{{{"duration", 0.}, {"distance", 0.}, {"weight", 0.}, {"geometry", "yw_jGupkl@??"}, {"name", "Boulevard du Larvotto"}, {"mode", "driving"}, {"maneuver", json::Object{{ {"location", location}, {"bearing_before", 0}, {"bearing_after", 0}, {"type", "depart"}, }}}, {"intersections", json::Array{{json::Object{ {{"location", location}, {"bearings", json::Array{{0}}}, {"entry", json::Array{{json::True()}}}, {"out", 0}}}}}}}}}, json::Object{{{"duration", 0.}, {"distance", 0.}, {"weight", 0.}, {"geometry", "yw_jGupkl@"}, {"name", "Boulevard du Larvotto"}, {"mode", "driving"}, {"maneuver", json::Object{{{"location", location}, {"bearing_before", 0}, {"bearing_after", 0}, {"type", "arrive"}}}}, {"intersections", json::Array{{json::Object{ {{"location", location}, {"bearings", json::Array{{180}}}, {"entry", json::Array{{json::True()}}}, {"in", 0}}}}}} }}}}}}}}}}}}}}}}}; CHECK_EQUAL_JSON(reference, result); } BOOST_AUTO_TEST_CASE(test_route_same_coordinates) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; RouteParameters params; params.steps = true; params.coordinates.push_back(get_dummy_location()); params.coordinates.push_back(get_dummy_location()); params.coordinates.push_back(get_dummy_location()); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); const auto code = result.values.at("code").get<json::String>().value; BOOST_CHECK_EQUAL(code, "Ok"); const auto &waypoints = result.values.at("waypoints").get<json::Array>().values; BOOST_CHECK(waypoints.size() == params.coordinates.size()); for (const auto &waypoint : waypoints) { const auto &waypoint_object = waypoint.get<json::Object>(); // nothing can be said about name, empty or contains name of the street const auto name = waypoint_object.values.at("name").get<json::String>().value; BOOST_CHECK(((void)name, true)); const auto location = waypoint_object.values.at("location").get<json::Array>().values; const auto longitude = location[0].get<json::Number>().value; const auto latitude = location[1].get<json::Number>().value; BOOST_CHECK(longitude >= -180. && longitude <= 180.); BOOST_CHECK(latitude >= -90. && latitude <= 90.); const auto hint = waypoint_object.values.at("hint").get<json::String>().value; BOOST_CHECK(!hint.empty()); } const auto &routes = result.values.at("routes").get<json::Array>().values; BOOST_REQUIRE_GT(routes.size(), 0); for (const auto &route : routes) { const auto &route_object = route.get<json::Object>(); const auto distance = route_object.values.at("distance").get<json::Number>().value; BOOST_CHECK_EQUAL(distance, 0); const auto duration = route_object.values.at("duration").get<json::Number>().value; BOOST_CHECK_EQUAL(duration, 0); // geometries=polyline by default const auto geometry = route_object.values.at("geometry").get<json::String>().value; BOOST_CHECK(!geometry.empty()); const auto &legs = route_object.values.at("legs").get<json::Array>().values; BOOST_CHECK(!legs.empty()); for (const auto &leg : legs) { const auto &leg_object = leg.get<json::Object>(); const auto distance = leg_object.values.at("distance").get<json::Number>().value; BOOST_CHECK_EQUAL(distance, 0); const auto duration = leg_object.values.at("duration").get<json::Number>().value; BOOST_CHECK_EQUAL(duration, 0); // nothing can be said about summary, empty or contains human readable summary const auto summary = leg_object.values.at("summary").get<json::String>().value; BOOST_CHECK(((void)summary, true)); const auto &steps = leg_object.values.at("steps").get<json::Array>().values; BOOST_CHECK(!steps.empty()); std::size_t step_count = 0; for (const auto &step : steps) { const auto &step_object = step.get<json::Object>(); const auto distance = step_object.values.at("distance").get<json::Number>().value; BOOST_CHECK_EQUAL(distance, 0); const auto duration = step_object.values.at("duration").get<json::Number>().value; BOOST_CHECK_EQUAL(duration, 0); // geometries=polyline by default const auto geometry = step_object.values.at("geometry").get<json::String>().value; BOOST_CHECK(!geometry.empty()); // nothing can be said about name, empty or contains way name const auto name = step_object.values.at("name").get<json::String>().value; BOOST_CHECK(((void)name, true)); // nothing can be said about mode, contains mode of transportation const auto mode = step_object.values.at("mode").get<json::String>().value; BOOST_CHECK(!name.empty()); const auto &maneuver = step_object.values.at("maneuver").get<json::Object>().values; const auto type = maneuver.at("type").get<json::String>().value; BOOST_CHECK(!type.empty()); const auto &intersections = step_object.values.at("intersections").get<json::Array>().values; for (auto &intersection : intersections) { const auto &intersection_object = intersection.get<json::Object>().values; const auto location = intersection_object.at("location").get<json::Array>().values; const auto longitude = location[0].get<json::Number>().value; const auto latitude = location[1].get<json::Number>().value; BOOST_CHECK(longitude >= -180. && longitude <= 180.); BOOST_CHECK(latitude >= -90. && latitude <= 90.); const auto &bearings = intersection_object.at("bearings").get<json::Array>().values; BOOST_CHECK(!bearings.empty()); const auto &entries = intersection_object.at("entry").get<json::Array>().values; BOOST_CHECK(bearings.size() == entries.size()); for (const auto bearing : bearings) BOOST_CHECK(0. <= bearing.get<json::Number>().value && bearing.get<json::Number>().value <= 360.); if (step_count > 0) { const auto in = intersection_object.at("in").get<json::Number>().value; BOOST_CHECK(in < bearings.size()); } if (step_count + 1 < steps.size()) { const auto out = intersection_object.at("out").get<json::Number>().value; BOOST_CHECK(out < bearings.size()); } } // modifier is optional // TODO(daniel-j-h): // exit is optional // TODO(daniel-j-h): ++step_count; } } } } BOOST_AUTO_TEST_CASE(test_route_response_for_locations_in_small_component) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; const auto locations = get_locations_in_small_component(); RouteParameters params; params.coordinates.push_back(locations.at(0)); params.coordinates.push_back(locations.at(1)); params.coordinates.push_back(locations.at(2)); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); const auto code = result.values.at("code").get<json::String>().value; BOOST_CHECK_EQUAL(code, "Ok"); const auto &waypoints = result.values.at("waypoints").get<json::Array>().values; BOOST_CHECK_EQUAL(waypoints.size(), params.coordinates.size()); for (const auto &waypoint : waypoints) { const auto &waypoint_object = waypoint.get<json::Object>(); const auto location = waypoint_object.values.at("location").get<json::Array>().values; const auto longitude = location[0].get<json::Number>().value; const auto latitude = location[1].get<json::Number>().value; BOOST_CHECK(longitude >= -180. && longitude <= 180.); BOOST_CHECK(latitude >= -90. && latitude <= 90.); } } BOOST_AUTO_TEST_CASE(test_route_response_for_locations_in_big_component) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; const auto locations = get_locations_in_big_component(); RouteParameters params; params.coordinates.push_back(locations.at(0)); params.coordinates.push_back(locations.at(1)); params.coordinates.push_back(locations.at(2)); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); const auto code = result.values.at("code").get<json::String>().value; BOOST_CHECK_EQUAL(code, "Ok"); const auto &waypoints = result.values.at("waypoints").get<json::Array>().values; BOOST_CHECK_EQUAL(waypoints.size(), params.coordinates.size()); for (const auto &waypoint : waypoints) { const auto &waypoint_object = waypoint.get<json::Object>(); const auto location = waypoint_object.values.at("location").get<json::Array>().values; const auto longitude = location[0].get<json::Number>().value; const auto latitude = location[1].get<json::Number>().value; BOOST_CHECK(longitude >= -180. && longitude <= 180.); BOOST_CHECK(latitude >= -90. && latitude <= 90.); } } BOOST_AUTO_TEST_CASE(test_route_response_for_locations_across_components) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; const auto big_component = get_locations_in_big_component(); const auto small_component = get_locations_in_small_component(); RouteParameters params; params.coordinates.push_back(small_component.at(0)); params.coordinates.push_back(big_component.at(0)); params.coordinates.push_back(small_component.at(1)); params.coordinates.push_back(big_component.at(1)); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); const auto code = result.values.at("code").get<json::String>().value; BOOST_CHECK_EQUAL(code, "Ok"); const auto &waypoints = result.values.at("waypoints").get<json::Array>().values; BOOST_CHECK_EQUAL(waypoints.size(), params.coordinates.size()); for (const auto &waypoint : waypoints) { const auto &waypoint_object = waypoint.get<json::Object>(); const auto location = waypoint_object.values.at("location").get<json::Array>().values; const auto longitude = location[0].get<json::Number>().value; const auto latitude = location[1].get<json::Number>().value; BOOST_CHECK(longitude >= -180. && longitude <= 180.); BOOST_CHECK(latitude >= -90. && latitude <= 90.); } } BOOST_AUTO_TEST_CASE(test_route_user_disables_generating_hints) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; RouteParameters params; params.steps = true; params.coordinates.push_back(get_dummy_location()); params.coordinates.push_back(get_dummy_location()); params.generate_hints = false; json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); for (auto waypoint : result.values["waypoints"].get<json::Array>().values) BOOST_CHECK_EQUAL(waypoint.get<json::Object>().values.count("hint"), 0); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>add unit test to check that speeds are equal to distance/duration<commit_after>#include <boost/test/test_case_template.hpp> #include <boost/test/unit_test.hpp> #include "args.hpp" #include "coordinates.hpp" #include "equal_json.hpp" #include "fixture.hpp" #include "osrm/coordinate.hpp" #include "osrm/engine_config.hpp" #include "osrm/json_container.hpp" #include "osrm/json_container.hpp" #include "osrm/osrm.hpp" #include "osrm/route_parameters.hpp" #include "osrm/status.hpp" BOOST_AUTO_TEST_SUITE(route) BOOST_AUTO_TEST_CASE(test_route_same_coordinates_fixture) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; RouteParameters params; params.steps = true; params.coordinates.push_back(get_dummy_location()); params.coordinates.push_back(get_dummy_location()); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); // unset snapping dependent hint for (auto &itr : result.values["waypoints"].get<json::Array>().values) itr.get<json::Object>().values["hint"] = ""; const auto location = json::Array{{{7.437070}, {43.749248}}}; json::Object reference{ {{"code", "Ok"}, {"waypoints", json::Array{ {json::Object{ {{"name", "Boulevard du Larvotto"}, {"location", location}, {"hint", ""}}}, json::Object{ {{"name", "Boulevard du Larvotto"}, {"location", location}, {"hint", ""}}}}}}, {"routes", json::Array{{json::Object{ {{"distance", 0.}, {"duration", 0.}, {"weight", 0.}, {"weight_name", "routability"}, {"geometry", "yw_jGupkl@??"}, {"legs", json::Array{{json::Object{ {{"distance", 0.}, {"duration", 0.}, {"weight", 0.}, {"summary", "Boulevard du Larvotto"}, {"steps", json::Array{{{json::Object{{{"duration", 0.}, {"distance", 0.}, {"weight", 0.}, {"geometry", "yw_jGupkl@??"}, {"name", "Boulevard du Larvotto"}, {"mode", "driving"}, {"maneuver", json::Object{{ {"location", location}, {"bearing_before", 0}, {"bearing_after", 0}, {"type", "depart"}, }}}, {"intersections", json::Array{{json::Object{ {{"location", location}, {"bearings", json::Array{{0}}}, {"entry", json::Array{{json::True()}}}, {"out", 0}}}}}}}}}, json::Object{{{"duration", 0.}, {"distance", 0.}, {"weight", 0.}, {"geometry", "yw_jGupkl@"}, {"name", "Boulevard du Larvotto"}, {"mode", "driving"}, {"maneuver", json::Object{{{"location", location}, {"bearing_before", 0}, {"bearing_after", 0}, {"type", "arrive"}}}}, {"intersections", json::Array{{json::Object{ {{"location", location}, {"bearings", json::Array{{180}}}, {"entry", json::Array{{json::True()}}}, {"in", 0}}}}}} }}}}}}}}}}}}}}}}}; CHECK_EQUAL_JSON(reference, result); } BOOST_AUTO_TEST_CASE(test_route_same_coordinates) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; RouteParameters params; params.steps = true; params.coordinates.push_back(get_dummy_location()); params.coordinates.push_back(get_dummy_location()); params.coordinates.push_back(get_dummy_location()); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); const auto code = result.values.at("code").get<json::String>().value; BOOST_CHECK_EQUAL(code, "Ok"); const auto &waypoints = result.values.at("waypoints").get<json::Array>().values; BOOST_CHECK(waypoints.size() == params.coordinates.size()); for (const auto &waypoint : waypoints) { const auto &waypoint_object = waypoint.get<json::Object>(); // nothing can be said about name, empty or contains name of the street const auto name = waypoint_object.values.at("name").get<json::String>().value; BOOST_CHECK(((void)name, true)); const auto location = waypoint_object.values.at("location").get<json::Array>().values; const auto longitude = location[0].get<json::Number>().value; const auto latitude = location[1].get<json::Number>().value; BOOST_CHECK(longitude >= -180. && longitude <= 180.); BOOST_CHECK(latitude >= -90. && latitude <= 90.); const auto hint = waypoint_object.values.at("hint").get<json::String>().value; BOOST_CHECK(!hint.empty()); } const auto &routes = result.values.at("routes").get<json::Array>().values; BOOST_REQUIRE_GT(routes.size(), 0); for (const auto &route : routes) { const auto &route_object = route.get<json::Object>(); const auto distance = route_object.values.at("distance").get<json::Number>().value; BOOST_CHECK_EQUAL(distance, 0); const auto duration = route_object.values.at("duration").get<json::Number>().value; BOOST_CHECK_EQUAL(duration, 0); // geometries=polyline by default const auto geometry = route_object.values.at("geometry").get<json::String>().value; BOOST_CHECK(!geometry.empty()); const auto &legs = route_object.values.at("legs").get<json::Array>().values; BOOST_CHECK(!legs.empty()); for (const auto &leg : legs) { const auto &leg_object = leg.get<json::Object>(); const auto distance = leg_object.values.at("distance").get<json::Number>().value; BOOST_CHECK_EQUAL(distance, 0); const auto duration = leg_object.values.at("duration").get<json::Number>().value; BOOST_CHECK_EQUAL(duration, 0); // nothing can be said about summary, empty or contains human readable summary const auto summary = leg_object.values.at("summary").get<json::String>().value; BOOST_CHECK(((void)summary, true)); const auto &steps = leg_object.values.at("steps").get<json::Array>().values; BOOST_CHECK(!steps.empty()); std::size_t step_count = 0; for (const auto &step : steps) { const auto &step_object = step.get<json::Object>(); const auto distance = step_object.values.at("distance").get<json::Number>().value; BOOST_CHECK_EQUAL(distance, 0); const auto duration = step_object.values.at("duration").get<json::Number>().value; BOOST_CHECK_EQUAL(duration, 0); // geometries=polyline by default const auto geometry = step_object.values.at("geometry").get<json::String>().value; BOOST_CHECK(!geometry.empty()); // nothing can be said about name, empty or contains way name const auto name = step_object.values.at("name").get<json::String>().value; BOOST_CHECK(((void)name, true)); // nothing can be said about mode, contains mode of transportation const auto mode = step_object.values.at("mode").get<json::String>().value; BOOST_CHECK(!name.empty()); const auto &maneuver = step_object.values.at("maneuver").get<json::Object>().values; const auto type = maneuver.at("type").get<json::String>().value; BOOST_CHECK(!type.empty()); const auto &intersections = step_object.values.at("intersections").get<json::Array>().values; for (auto &intersection : intersections) { const auto &intersection_object = intersection.get<json::Object>().values; const auto location = intersection_object.at("location").get<json::Array>().values; const auto longitude = location[0].get<json::Number>().value; const auto latitude = location[1].get<json::Number>().value; BOOST_CHECK(longitude >= -180. && longitude <= 180.); BOOST_CHECK(latitude >= -90. && latitude <= 90.); const auto &bearings = intersection_object.at("bearings").get<json::Array>().values; BOOST_CHECK(!bearings.empty()); const auto &entries = intersection_object.at("entry").get<json::Array>().values; BOOST_CHECK(bearings.size() == entries.size()); for (const auto bearing : bearings) BOOST_CHECK(0. <= bearing.get<json::Number>().value && bearing.get<json::Number>().value <= 360.); if (step_count > 0) { const auto in = intersection_object.at("in").get<json::Number>().value; BOOST_CHECK(in < bearings.size()); } if (step_count + 1 < steps.size()) { const auto out = intersection_object.at("out").get<json::Number>().value; BOOST_CHECK(out < bearings.size()); } } // modifier is optional // TODO(daniel-j-h): // exit is optional // TODO(daniel-j-h): ++step_count; } } } } BOOST_AUTO_TEST_CASE(test_route_response_for_locations_in_small_component) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; const auto locations = get_locations_in_small_component(); RouteParameters params; params.coordinates.push_back(locations.at(0)); params.coordinates.push_back(locations.at(1)); params.coordinates.push_back(locations.at(2)); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); const auto code = result.values.at("code").get<json::String>().value; BOOST_CHECK_EQUAL(code, "Ok"); const auto &waypoints = result.values.at("waypoints").get<json::Array>().values; BOOST_CHECK_EQUAL(waypoints.size(), params.coordinates.size()); for (const auto &waypoint : waypoints) { const auto &waypoint_object = waypoint.get<json::Object>(); const auto location = waypoint_object.values.at("location").get<json::Array>().values; const auto longitude = location[0].get<json::Number>().value; const auto latitude = location[1].get<json::Number>().value; BOOST_CHECK(longitude >= -180. && longitude <= 180.); BOOST_CHECK(latitude >= -90. && latitude <= 90.); } } BOOST_AUTO_TEST_CASE(test_route_response_for_locations_in_big_component) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; const auto locations = get_locations_in_big_component(); RouteParameters params; params.coordinates.push_back(locations.at(0)); params.coordinates.push_back(locations.at(1)); params.coordinates.push_back(locations.at(2)); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); const auto code = result.values.at("code").get<json::String>().value; BOOST_CHECK_EQUAL(code, "Ok"); const auto &waypoints = result.values.at("waypoints").get<json::Array>().values; BOOST_CHECK_EQUAL(waypoints.size(), params.coordinates.size()); for (const auto &waypoint : waypoints) { const auto &waypoint_object = waypoint.get<json::Object>(); const auto location = waypoint_object.values.at("location").get<json::Array>().values; const auto longitude = location[0].get<json::Number>().value; const auto latitude = location[1].get<json::Number>().value; BOOST_CHECK(longitude >= -180. && longitude <= 180.); BOOST_CHECK(latitude >= -90. && latitude <= 90.); } } BOOST_AUTO_TEST_CASE(test_route_response_for_locations_across_components) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; const auto big_component = get_locations_in_big_component(); const auto small_component = get_locations_in_small_component(); RouteParameters params; params.coordinates.push_back(small_component.at(0)); params.coordinates.push_back(big_component.at(0)); params.coordinates.push_back(small_component.at(1)); params.coordinates.push_back(big_component.at(1)); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); const auto code = result.values.at("code").get<json::String>().value; BOOST_CHECK_EQUAL(code, "Ok"); const auto &waypoints = result.values.at("waypoints").get<json::Array>().values; BOOST_CHECK_EQUAL(waypoints.size(), params.coordinates.size()); for (const auto &waypoint : waypoints) { const auto &waypoint_object = waypoint.get<json::Object>(); const auto location = waypoint_object.values.at("location").get<json::Array>().values; const auto longitude = location[0].get<json::Number>().value; const auto latitude = location[1].get<json::Number>().value; BOOST_CHECK(longitude >= -180. && longitude <= 180.); BOOST_CHECK(latitude >= -90. && latitude <= 90.); } } BOOST_AUTO_TEST_CASE(test_route_user_disables_generating_hints) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; RouteParameters params; params.steps = true; params.coordinates.push_back(get_dummy_location()); params.coordinates.push_back(get_dummy_location()); params.generate_hints = false; json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); for (auto waypoint : result.values["waypoints"].get<json::Array>().values) BOOST_CHECK_EQUAL(waypoint.get<json::Object>().values.count("hint"), 0); } BOOST_AUTO_TEST_CASE(speed_annotation_matches_duration_and_distance) { const auto args = get_args(); auto osrm = getOSRM(args.at(0)); using namespace osrm; RouteParameters params{}; params.annotations_type = RouteParameters::AnnotationsType::Duration | RouteParameters::AnnotationsType::Distance | RouteParameters::AnnotationsType::Speed; params.coordinates.push_back(get_dummy_location()); params.coordinates.push_back(get_dummy_location()); json::Object result; const auto rc = osrm.Route(params, result); BOOST_CHECK(rc == Status::Ok); const auto &routes = result.values["routes"].get<json::Array>().values; const auto &legs = routes[0].get<json::Object>().values.at("legs").get<json::Array>().values; const auto &annotation = legs[0].get<json::Object>().values.at("annotation").get<json::Object>(); const auto &speeds = annotation.values.at("speed").get<json::Array>().values; const auto &durations = annotation.values.at("duration").get<json::Array>().values; const auto &distances = annotation.values.at("distance").get<json::Array>().values; int length = speeds.size(); for (int i = 0; i < length; i++) { auto speed = speeds[i].get<json::Number>().value; auto duration = durations[i].get<json::Number>().value; auto distance = distances[i].get<json::Number>().value; BOOST_CHECK_EQUAL(speed, distance / duration); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) [2016] [BTC.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. */ #include "gtest/gtest.h" #include "Common.h" #include "bitcoin/StratumBitcoin.h" #include "bitcoin/StatisticsBitcoin.h" #include "bitcoin/BitcoinUtils.h" #include "eth/StratumEth.h" #include "eth/StatisticsEth.h" //////////////////////////////// StatsWindow ///////////////////////////////// TEST(StatsWindow, clear) { int windowSize = 60; for (int j = 0; j < 10; j++) { StatsWindow<int64_t> sw(windowSize); ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0); int64_t val = 3; for (int i = 0; i < windowSize; i++) { sw.insert(i, val); } ASSERT_EQ(sw.sum(windowSize - 1, windowSize), windowSize * val); sw.clear(); ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0); } } TEST(StatsWindow, sum01) { int windowSize = 60; StatsWindow<int64_t> sw(windowSize); int64_t val = 5; for (int i = 0; i < windowSize; i++) { sw.insert(i, val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(i, 1), val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(windowSize - 1, i), i * val); } for (int i = windowSize; i < windowSize * 2; i++) { ASSERT_EQ(sw.sum(i, 1), 0); } for (int i = windowSize; i < windowSize * 2; i++) { ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val); } for (int i = windowSize * 2; i < windowSize * 3; i++) { ASSERT_EQ(sw.sum(i, windowSize), 0); } } TEST(StatsWindow, sum02) { int windowSize = 60; StatsWindow<int64_t> sw(windowSize); int64_t val = 5; for (int i = windowSize - 1; i >= 0; i--) { sw.insert(i, val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(i, 1), val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(windowSize - 1, i), i * val); } for (int i = windowSize; i < windowSize * 2; i++) { ASSERT_EQ(sw.sum(i, 1), 0); } for (int i = windowSize; i < windowSize * 2; i++) { ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val); } for (int i = windowSize * 2; i < windowSize * 3; i++) { ASSERT_EQ(sw.sum(i, windowSize), 0); } } TEST(StatsWindow, sum03) { StatsWindow<int64_t> sw(5); sw.insert(0, 1); ASSERT_EQ(sw.sum(0, 1), 1); sw.clear(); ASSERT_EQ(sw.sum(0, 1), 0); sw.insert(0, 1); sw.insert(5, 5); ASSERT_EQ(sw.sum(5, 1), 5); ASSERT_EQ(sw.sum(5, 5), 5); sw.clear(); sw.insert(0, 1); sw.insert(1, 2); sw.insert(2, 3); sw.insert(3, 4); sw.insert(4, 5); ASSERT_EQ(sw.sum(4, 1), 5); ASSERT_EQ(sw.sum(4, 2), 9); ASSERT_EQ(sw.sum(4, 3), 12); ASSERT_EQ(sw.sum(4, 4), 14); ASSERT_EQ(sw.sum(4, 5), 15); sw.insert(8, 9); ASSERT_EQ(sw.sum(8, 5), 14); sw.insert(7, 8); ASSERT_EQ(sw.sum(8, 5), 22); sw.insert(6, 7); ASSERT_EQ(sw.sum(8, 5), 29); sw.insert(5, 6); ASSERT_EQ(sw.sum(8, 5), 35); } TEST(StatsWindow, map) { int windowSize = 10; StatsWindow<int64_t> sw(windowSize); for (int i = 0; i < windowSize; i++) { sw.insert(i, i * 2); } ASSERT_EQ(sw.sum(windowSize - 1), sw.sum(windowSize - 1, windowSize)); int64_t sum = sw.sum(windowSize - 1, windowSize); sw.mapDivide(2); int64_t sum2 = sw.sum(windowSize - 1, windowSize); ASSERT_EQ(sum / 2, sum2); sw.mapMultiply(2); int64_t sum3 = sw.sum(windowSize - 1, windowSize); ASSERT_EQ(sum, sum3); } //////////////////////////////// ShareStatsDay /////////////////////////////// TEST(ShareStatsDay, ShareStatsDay) { // using mainnet SelectParams(CBaseChainParams::MAIN); // 1 { ShareStatsDay<ShareBitcoin> stats; ShareBitcoin share; share.set_height(527259); share.set_status(StratumStatus::ACCEPT); uint64_t shareValue = 1ll; auto reward = GetBlockReward(share.height(), Params().GetConsensus()); // share -> socre = 1 : 1 // https://btc.com/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f share.set_blkbits(0x1d00ffffu); // accept for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23] share.set_sharediff(shareValue); stats.processShare(i, share); } // reject share.set_status(StratumStatus::REJECT_NO_REASON); for (uint32_t i = 0; i < 24; i++) { share.set_sharediff(shareValue); stats.processShare(i, share); } ShareStats ss; for (uint32_t i = 0; i < 24; i++) { stats.getShareStatsHour(i, &ss); ASSERT_EQ(ss.shareAccept_, shareValue); ASSERT_EQ(ss.shareReject_, shareValue); ASSERT_EQ(ss.earn_, 1 * reward); } stats.getShareStatsDay(&ss); ASSERT_EQ(ss.shareAccept_, shareValue * 24); ASSERT_EQ(ss.shareReject_, shareValue * 24); ASSERT_EQ(ss.earn_, 1 * 24 * reward); } // UINT32_MAX { ShareStatsDay<ShareBitcoin> stats; ShareBitcoin share; share.set_height(527259); share.set_status(StratumStatus::ACCEPT); uint64_t shareValue = UINT32_MAX; // share -> socre = UINT32_MAX : 0.0197582875516673 // https://btc.com/00000000000000000015f613f161b431acc6bbcb34533d2ca47d3cde4ec58b76 share.set_blkbits(0x18050edcu); // accept for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23] share.set_sharediff(shareValue); stats.processShare(i, share); // LOG(INFO) << score2Str(share.score()); } // reject share.set_status(StratumStatus::REJECT_NO_REASON); for (uint32_t i = 0; i < 24; i++) { share.set_sharediff(shareValue); stats.processShare(i, share); } ShareStats ss; for (uint32_t i = 0; i < 24; i++) { stats.getShareStatsHour(i, &ss); ASSERT_EQ(ss.shareAccept_, shareValue); ASSERT_EQ(ss.shareReject_, shareValue); #ifndef CHAIN_TYPE_UBTC ASSERT_EQ((uint64_t)ss.earn_, 24697859UL); // satoshi #else ASSERT_EQ((uint64_t)ss.earn_, 1975828UL); // satoshi, only for UBTC #endif } stats.getShareStatsDay(&ss); ASSERT_EQ(ss.shareAccept_, shareValue * 24); ASSERT_EQ(ss.shareReject_, shareValue * 24); #ifndef CHAIN_TYPE_UBTC ASSERT_EQ((uint64_t)ss.earn_, 592748626UL); // satoshi #else ASSERT_EQ((uint64_t)ss.earn_, 47419890UL); // satoshi, only for UBTC #endif } } //////////////////////////////// GlobalShare /////////////////////////////// TEST(GlobalShare, GlobalShareEth) { ShareEth share1; share1.set_headerhash(0x12345678); share1.set_nonce(0x87654321); ShareEth share2; share2.set_headerhash(0x12345678); share2.set_nonce(0x33333333); ShareEth share3; share3.set_headerhash(0x33333333); share3.set_nonce(0x55555555); GlobalShareEth a(share1); GlobalShareEth b(share2); GlobalShareEth c(share3); GlobalShareEth d(share3); ASSERT_EQ(a < a, false); ASSERT_EQ(c < d, false); ASSERT_EQ(d < c, false); ASSERT_EQ(a < b, false); ASSERT_EQ(b < a, true); ASSERT_EQ(a < c, true); ASSERT_EQ(c < a, false); ASSERT_EQ(b < c, true); ASSERT_EQ(c < b, false); } //////////////////////////////// DuplicateShareChecker ////////////////////////////////// TEST(DuplicateShareChecker, DuplicateShareCheckerEth) { // same share { DuplicateShareCheckerEth dsc(3); ShareEth share; share.set_height(12345); share.set_headerhash(0x12345678); share.set_nonce(0x87654321); ASSERT_EQ(dsc.addShare(share), true); ASSERT_EQ(dsc.addShare(share), false); ASSERT_EQ(dsc.addShare(share), false); } // different height { DuplicateShareCheckerEth dsc(3); ShareEth share; share.set_height(12345); share.set_headerhash(0x12345678); share.set_nonce(0x87654321); ASSERT_EQ(dsc.addShare(share), true); share.set_height(12346); ASSERT_EQ(dsc.addShare(share), true); share.set_height(12347); ASSERT_EQ(dsc.addShare(share), true); share.set_height(12348); ASSERT_EQ(dsc.addShare(share), true); share.set_height(12347); ASSERT_EQ(dsc.addShare(share), false); share.set_height(12346); ASSERT_EQ(dsc.addShare(share), false); share.set_height(12349); ASSERT_EQ(dsc.addShare(share), true); ASSERT_EQ(dsc.gshareSetMapSize(), 3ull); } // different headerHash { DuplicateShareCheckerEth dsc(3); ShareEth share; share.set_height(12345); share.set_headerhash(0x12345678); share.set_nonce(0x87654321); ASSERT_EQ(dsc.addShare(share), true); share.set_headerhash(0x123); ASSERT_EQ(dsc.addShare(share), true); share.set_headerhash(0x456); ASSERT_EQ(dsc.addShare(share), true); share.set_headerhash(0x123); ASSERT_EQ(dsc.addShare(share), false); share.set_headerhash(0x456); ASSERT_EQ(dsc.addShare(share), false); share.set_headerhash(0x12345678); ASSERT_EQ(dsc.addShare(share), false); share.set_headerhash(0x87654321); ASSERT_EQ(dsc.addShare(share), true); } // different nonce { DuplicateShareCheckerEth dsc(3); ShareEth share; share.set_height(12345); share.set_headerhash(0x12345678); share.set_nonce(0x87654321); ASSERT_EQ(dsc.addShare(share), true); share.set_nonce(0x123); ASSERT_EQ(dsc.addShare(share), true); share.set_nonce(0x456); ASSERT_EQ(dsc.addShare(share), true); share.set_nonce(0x123); ASSERT_EQ(dsc.addShare(share), false); share.set_nonce(0x456); ASSERT_EQ(dsc.addShare(share), false); share.set_nonce(0x12345678); ASSERT_EQ(dsc.addShare(share), true); share.set_nonce(0x87654321); ASSERT_EQ(dsc.addShare(share), false); } } <commit_msg>Fix TestStatistics.cc<commit_after>/* The MIT License (MIT) Copyright (c) [2016] [BTC.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. */ #include "gtest/gtest.h" #include "Common.h" #include "bitcoin/StratumBitcoin.h" #include "bitcoin/StatisticsBitcoin.h" #include "bitcoin/BitcoinUtils.h" #include "eth/StratumEth.h" #include "eth/StatisticsEth.h" //////////////////////////////// StatsWindow ///////////////////////////////// TEST(StatsWindow, clear) { int windowSize = 60; for (int j = 0; j < 10; j++) { StatsWindow<int64_t> sw(windowSize); ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0); int64_t val = 3; for (int i = 0; i < windowSize; i++) { sw.insert(i, val); } ASSERT_EQ(sw.sum(windowSize - 1, windowSize), windowSize * val); sw.clear(); ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0); } } TEST(StatsWindow, sum01) { int windowSize = 60; StatsWindow<int64_t> sw(windowSize); int64_t val = 5; for (int i = 0; i < windowSize; i++) { sw.insert(i, val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(i, 1), val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(windowSize - 1, i), i * val); } for (int i = windowSize; i < windowSize * 2; i++) { ASSERT_EQ(sw.sum(i, 1), 0); } for (int i = windowSize; i < windowSize * 2; i++) { ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val); } for (int i = windowSize * 2; i < windowSize * 3; i++) { ASSERT_EQ(sw.sum(i, windowSize), 0); } } TEST(StatsWindow, sum02) { int windowSize = 60; StatsWindow<int64_t> sw(windowSize); int64_t val = 5; for (int i = windowSize - 1; i >= 0; i--) { sw.insert(i, val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(i, 1), val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(windowSize - 1, i), i * val); } for (int i = windowSize; i < windowSize * 2; i++) { ASSERT_EQ(sw.sum(i, 1), 0); } for (int i = windowSize; i < windowSize * 2; i++) { ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val); } for (int i = windowSize * 2; i < windowSize * 3; i++) { ASSERT_EQ(sw.sum(i, windowSize), 0); } } TEST(StatsWindow, sum03) { StatsWindow<int64_t> sw(5); sw.insert(0, 1); ASSERT_EQ(sw.sum(0, 1), 1); sw.clear(); ASSERT_EQ(sw.sum(0, 1), 0); sw.insert(0, 1); sw.insert(5, 5); ASSERT_EQ(sw.sum(5, 1), 5); ASSERT_EQ(sw.sum(5, 5), 5); sw.clear(); sw.insert(0, 1); sw.insert(1, 2); sw.insert(2, 3); sw.insert(3, 4); sw.insert(4, 5); ASSERT_EQ(sw.sum(4, 1), 5); ASSERT_EQ(sw.sum(4, 2), 9); ASSERT_EQ(sw.sum(4, 3), 12); ASSERT_EQ(sw.sum(4, 4), 14); ASSERT_EQ(sw.sum(4, 5), 15); sw.insert(8, 9); ASSERT_EQ(sw.sum(8, 5), 14); sw.insert(7, 8); ASSERT_EQ(sw.sum(8, 5), 22); sw.insert(6, 7); ASSERT_EQ(sw.sum(8, 5), 29); sw.insert(5, 6); ASSERT_EQ(sw.sum(8, 5), 35); } TEST(StatsWindow, map) { int windowSize = 10; StatsWindow<int64_t> sw(windowSize); for (int i = 0; i < windowSize; i++) { sw.insert(i, i * 2); } ASSERT_EQ(sw.sum(windowSize - 1), sw.sum(windowSize - 1, windowSize)); int64_t sum = sw.sum(windowSize - 1, windowSize); sw.mapDivide(2); int64_t sum2 = sw.sum(windowSize - 1, windowSize); ASSERT_EQ(sum / 2, sum2); sw.mapMultiply(2); int64_t sum3 = sw.sum(windowSize - 1, windowSize); ASSERT_EQ(sum, sum3); } //////////////////////////////// ShareStatsDay /////////////////////////////// TEST(ShareStatsDay, ShareStatsDay) { // using mainnet SelectParams(CBaseChainParams::MAIN); // 1 { ShareStatsDay<ShareBitcoin> stats; ShareBitcoin share; share.set_height(527259); share.set_status(StratumStatus::ACCEPT); uint64_t shareValue = 1ll; auto reward = GetBlockReward(share.height(), Params().GetConsensus()); // share -> socre = 1 : 1 // https://btc.com/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f share.set_blkbits(0x1d00ffffu); // accept for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23] share.set_sharediff(shareValue); stats.processShare(i, share, false); } // reject share.set_status(StratumStatus::REJECT_NO_REASON); for (uint32_t i = 0; i < 24; i++) { share.set_sharediff(shareValue); stats.processShare(i, share, false); } ShareStats ss; for (uint32_t i = 0; i < 24; i++) { stats.getShareStatsHour(i, &ss); ASSERT_EQ(ss.shareAccept_, shareValue); ASSERT_EQ(ss.shareReject_, shareValue); ASSERT_EQ(ss.earn_, 1 * reward); } stats.getShareStatsDay(&ss); ASSERT_EQ(ss.shareAccept_, shareValue * 24); ASSERT_EQ(ss.shareReject_, shareValue * 24); ASSERT_EQ(ss.earn_, 1 * 24 * reward); } // UINT32_MAX { ShareStatsDay<ShareBitcoin> stats; ShareBitcoin share; share.set_height(527259); share.set_status(StratumStatus::ACCEPT); uint64_t shareValue = UINT32_MAX; // share -> socre = UINT32_MAX : 0.0197582875516673 // https://btc.com/00000000000000000015f613f161b431acc6bbcb34533d2ca47d3cde4ec58b76 share.set_blkbits(0x18050edcu); // accept for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23] share.set_sharediff(shareValue); stats.processShare(i, share, false); // LOG(INFO) << score2Str(share.score()); } // reject share.set_status(StratumStatus::REJECT_NO_REASON); for (uint32_t i = 0; i < 24; i++) { share.set_sharediff(shareValue); stats.processShare(i, share, false); } ShareStats ss; for (uint32_t i = 0; i < 24; i++) { stats.getShareStatsHour(i, &ss); ASSERT_EQ(ss.shareAccept_, shareValue); ASSERT_EQ(ss.shareReject_, shareValue); #ifndef CHAIN_TYPE_UBTC ASSERT_EQ((uint64_t)ss.earn_, 24697859UL); // satoshi #else ASSERT_EQ((uint64_t)ss.earn_, 1975828UL); // satoshi, only for UBTC #endif } stats.getShareStatsDay(&ss); ASSERT_EQ(ss.shareAccept_, shareValue * 24); ASSERT_EQ(ss.shareReject_, shareValue * 24); #ifndef CHAIN_TYPE_UBTC ASSERT_EQ((uint64_t)ss.earn_, 592748626UL); // satoshi #else ASSERT_EQ((uint64_t)ss.earn_, 47419890UL); // satoshi, only for UBTC #endif } } //////////////////////////////// GlobalShare /////////////////////////////// TEST(GlobalShare, GlobalShareEth) { ShareEth share1; share1.set_headerhash(0x12345678); share1.set_nonce(0x87654321); ShareEth share2; share2.set_headerhash(0x12345678); share2.set_nonce(0x33333333); ShareEth share3; share3.set_headerhash(0x33333333); share3.set_nonce(0x55555555); GlobalShareEth a(share1); GlobalShareEth b(share2); GlobalShareEth c(share3); GlobalShareEth d(share3); ASSERT_EQ(a < a, false); ASSERT_EQ(c < d, false); ASSERT_EQ(d < c, false); ASSERT_EQ(a < b, false); ASSERT_EQ(b < a, true); ASSERT_EQ(a < c, true); ASSERT_EQ(c < a, false); ASSERT_EQ(b < c, true); ASSERT_EQ(c < b, false); } //////////////////////////////// DuplicateShareChecker ////////////////////////////////// TEST(DuplicateShareChecker, DuplicateShareCheckerEth) { // same share { DuplicateShareCheckerEth dsc(3); ShareEth share; share.set_height(12345); share.set_headerhash(0x12345678); share.set_nonce(0x87654321); ASSERT_EQ(dsc.addShare(share), true); ASSERT_EQ(dsc.addShare(share), false); ASSERT_EQ(dsc.addShare(share), false); } // different height { DuplicateShareCheckerEth dsc(3); ShareEth share; share.set_height(12345); share.set_headerhash(0x12345678); share.set_nonce(0x87654321); ASSERT_EQ(dsc.addShare(share), true); share.set_height(12346); ASSERT_EQ(dsc.addShare(share), true); share.set_height(12347); ASSERT_EQ(dsc.addShare(share), true); share.set_height(12348); ASSERT_EQ(dsc.addShare(share), true); share.set_height(12347); ASSERT_EQ(dsc.addShare(share), false); share.set_height(12346); ASSERT_EQ(dsc.addShare(share), false); share.set_height(12349); ASSERT_EQ(dsc.addShare(share), true); ASSERT_EQ(dsc.gshareSetMapSize(), 3ull); } // different headerHash { DuplicateShareCheckerEth dsc(3); ShareEth share; share.set_height(12345); share.set_headerhash(0x12345678); share.set_nonce(0x87654321); ASSERT_EQ(dsc.addShare(share), true); share.set_headerhash(0x123); ASSERT_EQ(dsc.addShare(share), true); share.set_headerhash(0x456); ASSERT_EQ(dsc.addShare(share), true); share.set_headerhash(0x123); ASSERT_EQ(dsc.addShare(share), false); share.set_headerhash(0x456); ASSERT_EQ(dsc.addShare(share), false); share.set_headerhash(0x12345678); ASSERT_EQ(dsc.addShare(share), false); share.set_headerhash(0x87654321); ASSERT_EQ(dsc.addShare(share), true); } // different nonce { DuplicateShareCheckerEth dsc(3); ShareEth share; share.set_height(12345); share.set_headerhash(0x12345678); share.set_nonce(0x87654321); ASSERT_EQ(dsc.addShare(share), true); share.set_nonce(0x123); ASSERT_EQ(dsc.addShare(share), true); share.set_nonce(0x456); ASSERT_EQ(dsc.addShare(share), true); share.set_nonce(0x123); ASSERT_EQ(dsc.addShare(share), false); share.set_nonce(0x456); ASSERT_EQ(dsc.addShare(share), false); share.set_nonce(0x12345678); ASSERT_EQ(dsc.addShare(share), true); share.set_nonce(0x87654321); ASSERT_EQ(dsc.addShare(share), false); } } <|endoftext|>
<commit_before>/** @section license License 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 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <ts/ts.h> #include <ts/remap.h> static const char* PLUGIN_NAME = "dscp_remap"; struct DscpRemapInstance { int tos; DscpRemapInstance() : tos(0) { } ; }; TSReturnCode TSRemapInit(TSRemapInterface* api_info, char *errbuf, int errbuf_size) { if (!api_info) { strncpy(errbuf, "[tsremap_init] - Invalid TSRemapInterface argument", (size_t)(errbuf_size - 1)); return TS_ERROR; } if (api_info->tsremap_version < TSREMAP_VERSION) { snprintf(errbuf, errbuf_size - 1, "[TSRemapInit] - Incorrect API version %ld.%ld", api_info->tsremap_version >> 16, (api_info->tsremap_version & 0xffff)); return TS_ERROR; } TSDebug(PLUGIN_NAME, "plugin is succesfully initialized"); return TS_SUCCESS; } TSReturnCode TSRemapNewInstance(int argc, char* argv[], void** ih, char* errbuf, int errbuf_size) { int dscp; DscpRemapInstance* di; dscp = atoi(argv[2]); di = new DscpRemapInstance(); *ih = (void *) di; di->tos = dscp << 2; return TS_SUCCESS; } void TSRemapDeleteInstance(void* ih) { DscpRemapInstance* di = static_cast<DscpRemapInstance*>(ih); delete di; } TSRemapStatus TSRemapDoRemap(void* ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) { int sockfd; DscpRemapInstance* di = static_cast<DscpRemapInstance*>(ih); int tos = di->tos; int retval; retval = TSHttpTxnClientFdGet(txnp, &sockfd); if (retval != TS_SUCCESS) { TSError("Error getting sockfd: %d\n", retval); return TSREMAP_NO_REMAP; } // Find out if this is a v4 or v6 connection, there's a different way of // setting the marking TSHttpSsn ssnp = TSHttpTxnSsnGet(txnp); const struct sockaddr *client_addr = TSHttpSsnClientAddrGet(ssnp); if (client_addr->sa_family == AF_INET6) { retval = setsockopt(sockfd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)); } else { retval = setsockopt(sockfd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); } if (retval != TS_SUCCESS) { TSError("Error setting sockfd: %d\n", retval); } return TSREMAP_NO_REMAP; } <commit_msg>Revert "TS-2999: Add dscp_remap plugin code"<commit_after><|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * What is this file about? * * Revision history: * xxxx-xx-xx, author, first version * xxxx-xx-xx, author, fix bug about xxx */ #include "prepare_list.h" #include "mutation.h" # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "prepare_list" namespace dsn { namespace replication { prepare_list::prepare_list( decree init_decree, int max_count, mutation_committer committer ) : mutation_cache(init_decree, max_count) { _committer = committer; _last_committed_decree = init_decree; } void prepare_list::sanity_check() { } void prepare_list::reset(decree init_decree) { _last_committed_decree = init_decree; mutation_cache::reset(init_decree, true); } void prepare_list::truncate(decree init_decree) { while (min_decree() <= init_decree && count() > 0) { pop_min(); } if (count() == 0) { mutation_cache::reset(init_decree, true); } _last_committed_decree = init_decree; } error_code prepare_list::prepare(mutation_ptr& mu, partition_status status) { decree d = mu->data.header.decree; dassert (d > last_committed_decree(), ""); error_code err; switch (status) { case PS_PRIMARY: // pop committed mutations if buffer is full while (d - min_decree() >= capacity() && last_committed_decree() > min_decree()) { pop_min(); } return mutation_cache::put(mu); case PS_SECONDARY: case PS_POTENTIAL_SECONDARY: // all mutations with lower decree must be ready commit(mu->data.header.last_committed_decree, COMMIT_TO_DECREE_HARD); // pop committed mutations if buffer is full while (d - min_decree() >= capacity() && last_committed_decree() > min_decree()) { pop_min(); } err = mutation_cache::put(mu); dassert (err == ERR_OK, ""); return err; //// delayed commit - only when capacity is an issue //case PS_POTENTIAL_SECONDARY: // while (true) // { // err = mutation_cache::put(mu); // if (err == ERR_CAPACITY_EXCEEDED) // { // dassert(mu->data.header.last_committed_decree >= min_decree(), ""); // commit (min_decree(), true); // pop_min(); // } // else // break; // } // dassert (err == ERR_OK, ""); // return err; case PS_INACTIVE: // only possible during init if (mu->data.header.last_committed_decree > max_decree()) { reset(mu->data.header.last_committed_decree); } else if (mu->data.header.last_committed_decree > _last_committed_decree) { // all mutations with lower decree must be ready commit(mu->data.header.last_committed_decree, COMMIT_TO_DECREE_HARD); // pop committed mutations if buffer is full while (d - min_decree() >= capacity() && last_committed_decree() > min_decree()) { pop_min(); } } err = mutation_cache::put(mu); dassert (err == ERR_OK, ""); return err; default: dassert (false, ""); return 0; } } // // ordered commit // bool prepare_list::commit(decree d, commit_type ct) { if (d <= last_committed_decree()) return false; ballot last_bt = 0; switch (ct) { case COMMIT_TO_DECREE_HARD: { for (decree d0 = last_committed_decree() + 1; d0 <= d; d0++) { mutation_ptr mu = get_mutation_by_decree(d0); dassert(mu != nullptr && (mu->is_logged()) && mu->data.header.ballot >= last_bt, "mutation %" PRId64 " is missing in prepare list", d0 ); _last_committed_decree++; last_bt = mu->data.header.ballot; _committer(mu); } sanity_check(); return true; } case COMMIT_TO_DECREE_SOFT: { for (decree d0 = last_committed_decree() + 1; d0 <= d; d0++) { mutation_ptr mu = get_mutation_by_decree(d0); if (mu != nullptr && mu->is_ready_for_commit() && mu->data.header.ballot >= last_bt) { _last_committed_decree++; last_bt = mu->data.header.ballot; _committer(mu); } else break; } sanity_check(); return true; } case COMMIT_ALL_READY: { if (d != last_committed_decree() + 1) return false; int count = 0; mutation_ptr mu = get_mutation_by_decree(last_committed_decree() + 1); while (mu != nullptr && mu->is_ready_for_commit() && mu->data.header.ballot >= last_bt) { _last_committed_decree++; last_bt = mu->data.header.ballot; _committer(mu); count++; mu = mutation_cache::get_mutation_by_decree(_last_committed_decree + 1); } sanity_check(); return count > 0; } default: dassert(false, "invalid commit type %d", (int)ct); } return false; } }} // namespace end <commit_msg>fix prepare_list<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * What is this file about? * * Revision history: * xxxx-xx-xx, author, first version * xxxx-xx-xx, author, fix bug about xxx */ #include "prepare_list.h" #include "mutation.h" # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "prepare_list" namespace dsn { namespace replication { prepare_list::prepare_list( decree init_decree, int max_count, mutation_committer committer ) : mutation_cache(init_decree, max_count) { _committer = committer; _last_committed_decree = init_decree; } void prepare_list::sanity_check() { } void prepare_list::reset(decree init_decree) { _last_committed_decree = init_decree; mutation_cache::reset(init_decree, true); } void prepare_list::truncate(decree init_decree) { while (min_decree() <= init_decree && count() > 0) { pop_min(); } if (count() == 0) { mutation_cache::reset(init_decree, true); } _last_committed_decree = init_decree; } error_code prepare_list::prepare(mutation_ptr& mu, partition_status status) { decree d = mu->data.header.decree; dassert (d > last_committed_decree(), ""); error_code err; switch (status) { case PS_PRIMARY: // pop committed mutations if buffer is full while (d - min_decree() >= capacity() && last_committed_decree() > min_decree()) { pop_min(); } return mutation_cache::put(mu); case PS_SECONDARY: case PS_POTENTIAL_SECONDARY: // all mutations with lower decree must be ready commit(mu->data.header.last_committed_decree, COMMIT_TO_DECREE_HARD); // pop committed mutations if buffer is full while (d - min_decree() >= capacity() && last_committed_decree() > min_decree()) { pop_min(); } err = mutation_cache::put(mu); dassert (err == ERR_OK, ""); return err; //// delayed commit - only when capacity is an issue //case PS_POTENTIAL_SECONDARY: // while (true) // { // err = mutation_cache::put(mu); // if (err == ERR_CAPACITY_EXCEEDED) // { // dassert(mu->data.header.last_committed_decree >= min_decree(), ""); // commit (min_decree(), true); // pop_min(); // } // else // break; // } // dassert (err == ERR_OK, ""); // return err; case PS_INACTIVE: // only possible during init if (mu->data.header.last_committed_decree > max_decree()) { reset(mu->data.header.last_committed_decree); } else if (mu->data.header.last_committed_decree > _last_committed_decree) { // all mutations with lower decree must be ready commit(mu->data.header.last_committed_decree, COMMIT_TO_DECREE_HARD); } // pop committed mutations if buffer is full while (d - min_decree() >= capacity() && last_committed_decree() > min_decree()) { pop_min(); } err = mutation_cache::put(mu); dassert (err == ERR_OK, ""); return err; default: dassert (false, ""); return 0; } } // // ordered commit // bool prepare_list::commit(decree d, commit_type ct) { if (d <= last_committed_decree()) return false; ballot last_bt = 0; switch (ct) { case COMMIT_TO_DECREE_HARD: { for (decree d0 = last_committed_decree() + 1; d0 <= d; d0++) { mutation_ptr mu = get_mutation_by_decree(d0); dassert(mu != nullptr && (mu->is_logged()) && mu->data.header.ballot >= last_bt, "mutation %" PRId64 " is missing in prepare list", d0 ); _last_committed_decree++; last_bt = mu->data.header.ballot; _committer(mu); } sanity_check(); return true; } case COMMIT_TO_DECREE_SOFT: { for (decree d0 = last_committed_decree() + 1; d0 <= d; d0++) { mutation_ptr mu = get_mutation_by_decree(d0); if (mu != nullptr && mu->is_ready_for_commit() && mu->data.header.ballot >= last_bt) { _last_committed_decree++; last_bt = mu->data.header.ballot; _committer(mu); } else break; } sanity_check(); return true; } case COMMIT_ALL_READY: { if (d != last_committed_decree() + 1) return false; int count = 0; mutation_ptr mu = get_mutation_by_decree(last_committed_decree() + 1); while (mu != nullptr && mu->is_ready_for_commit() && mu->data.header.ballot >= last_bt) { _last_committed_decree++; last_bt = mu->data.header.ballot; _committer(mu); count++; mu = mutation_cache::get_mutation_by_decree(_last_committed_decree + 1); } sanity_check(); return count > 0; } default: dassert(false, "invalid commit type %d", (int)ct); } return false; } }} // namespace end <|endoftext|>
<commit_before>// // ConsoleMVC.cpp // MultitouchPadOsc is released under the MIT License. // // Copyright (c) 2011 - 2012, Paul Vollmer http://www.wrong-entertainment.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. // #include "ConsoleMVC.h" ConsoleMVC::ConsoleMVC(){} void ConsoleMVC::init() { /* Set the currentConsoleStrings to 0 */ currentConsoleStrings = 0; } void ConsoleMVC::draw(ofTrueTypeFont font) { /* Ground */ ofEnableAlphaBlending(); ofSetColor(0, 150); ofFill(); ofRect(10, 30, ofGetWidth()-20, ofGetHeight()-40); ofDisableAlphaBlending(); /* headline text */ ofSetColor(COLOR_LIGHT_GREY); for(int i=0; i<NUM_STRINGS; i++) { font.drawString(consoleStrings[i], FONT_POSITION_X, 50+(i*15)); } } void ConsoleMVC::addString(string msg, bool log) { consoleStrings[currentConsoleStrings] = msg; if (log == true) { ofLog() << msg; } if (currentConsoleStrings < NUM_STRINGS) { currentConsoleStrings++; } if (currentConsoleStrings == NUM_STRINGS) { currentConsoleStrings = 0; } } void ConsoleMVC::mousePressed(int x, int y) { } void ConsoleMVC::keyPressed(int key) { /* Open the settings xml file */ if(key == 's') { string commandStr = "open " + ofFilePath::getCurrentWorkingDirectory() + "/ofSettings.xml"; system(commandStr.c_str()); addString("Open XML settings file."); } } <commit_msg>small color changes at drawing text<commit_after>// // ConsoleMVC.cpp // MultitouchPadOsc is released under the MIT License. // // Copyright (c) 2011 - 2012, Paul Vollmer http://www.wrong-entertainment.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. // #include "ConsoleMVC.h" ConsoleMVC::ConsoleMVC(){} void ConsoleMVC::init() { /* Set the currentConsoleStrings to 0 */ currentConsoleStrings = 0; } void ConsoleMVC::draw(ofTrueTypeFont font) { /* Ground */ ofEnableAlphaBlending(); ofSetColor(0, 150); ofFill(); ofRect(10, 30, ofGetWidth()-20, ofGetHeight()-40); ofDisableAlphaBlending(); /* console text */ for(int i=0; i<NUM_STRINGS; i++) { if (i == (currentConsoleStrings-1)) { ofSetColor(ofColor::white); } else { ofSetColor(COLOR_LIGHT_GREY); } font.drawString(consoleStrings[i], FONT_POSITION_X, 50+(i*15)); } } void ConsoleMVC::addString(string msg, bool log) { consoleStrings[currentConsoleStrings] = msg; if (log == true) { ofLog() << msg; } if (currentConsoleStrings < NUM_STRINGS) { currentConsoleStrings++; } if (currentConsoleStrings == NUM_STRINGS) { currentConsoleStrings = 0; } } void ConsoleMVC::mousePressed(int x, int y) { } void ConsoleMVC::keyPressed(int key) { /* Open the settings xml file */ if(key == 's') { string commandStr = "open " + ofFilePath::getCurrentWorkingDirectory() + "/ofSettings.xml"; system(commandStr.c_str()); addString("Open XML settings file."); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ extern "C" { #include <breezystm32.h> #include "flash.h" extern void SetSysClock(bool overclock); void WWDG_IRQHandler() { volatile int debug = 1; } } #include "naze32.h" namespace rosflight_firmware { Naze32::Naze32(){} void Naze32::init_board(void) { // Configure clock, this figures out HSE for hardware autodetect SetSysClock(0); systemInit(); _board_revision = 2; } void Naze32::board_reset(bool bootloader) { systemReset(bootloader); } // clock uint32_t Naze32::clock_millis() { return millis(); } uint64_t Naze32::clock_micros() { return micros(); } void Naze32::clock_delay(uint32_t milliseconds) { delay(milliseconds); } // serial void Naze32::serial_init(uint32_t baud_rate) { Serial1 = uartOpen(USART1, NULL, baud_rate, MODE_RXTX); } void Naze32::serial_write(const uint8_t *src, size_t len) { for (size_t i = 0; i < len; i++) { serialWrite(Serial1, src[i]); } } uint16_t Naze32::serial_bytes_available(void) { return serialTotalBytesWaiting(Serial1); } uint8_t Naze32::serial_read(void) { return serialRead(Serial1); } // sensors void Naze32::sensors_init() { _board_revision = 2; // Initialize I2c i2cInit(I2CDEV_2); while(millis() < 50); i2cWrite(0,0,0); ms5611_init(); hmc5883lInit(_board_revision); mb1242_init(); ms4525_init(); // IMU uint16_t acc1G; mpu6050_init(true, &acc1G, &_gyro_scale, _board_revision); _accel_scale = 9.80665f/acc1G; } uint16_t Naze32::num_sensor_errors(void) { return i2cGetErrorCounter(); } bool Naze32::new_imu_data() { return mpu6050_new_data(); } bool Naze32::imu_read(float accel[3], float* temperature, float gyro[3], uint64_t* time_us) { volatile int16_t gyro_raw[3], accel_raw[3]; volatile int16_t raw_temp; mpu6050_async_read_all(accel_raw, &raw_temp, gyro_raw, time_us); accel[0] = accel_raw[0] * _accel_scale; accel[1] = -accel_raw[1] * _accel_scale; accel[2] = -accel_raw[2] * _accel_scale; gyro[0] = gyro_raw[0] * _gyro_scale; gyro[1] = -gyro_raw[1] * _gyro_scale; gyro[2] = -gyro_raw[2] * _gyro_scale; (*temperature) = (float)raw_temp/340.0f + 36.53f; if (accel[0] == 0 && accel[1] == 0 && accel[2] == 0) { return false; } else return true; } void Naze32::imu_not_responding_error(void) { // If the IMU is not responding, then we need to change where we look for the // interrupt _board_revision = (_board_revision < 4) ? 5 : 2; sensors_init(); } void Naze32::mag_read(float mag[3]) { // Convert to NED int16_t raw_mag[3]; // hmc5883l_update(); hmc5883l_request_async_update(); hmc5883l_async_read(raw_mag); mag[0] = (float)raw_mag[0]; mag[1] = (float)raw_mag[1]; mag[2] = (float)raw_mag[2]; } bool Naze32::mag_check(void) { // _mag_present = hmc5883lInit(_board_revision); return hmc5883l_present(_board_revision); } void Naze32::baro_read(float *pressure, float *temperature) { ms5611_async_update(); ms5611_async_read(pressure, temperature); } bool Naze32::baro_check() { ms5611_async_update(); return ms5611_present(); } bool Naze32::diff_pressure_check(void) { ms4525_async_update(); return ms4525_present(); } void Naze32::diff_pressure_read(float *diff_pressure, float *temperature) { ms4525_async_update(); ms4525_async_read(diff_pressure, temperature); } bool Naze32::sonar_check(void) { return sonarPresent(); } float Naze32::sonar_read(void) { return sonarRead(6); } uint16_t num_sensor_errors(void) { return i2cGetErrorCounter(); } // PWM void Naze32::pwm_init(bool cppm, uint32_t refresh_rate, uint16_t idle_pwm) { pwmInit(cppm, false, false, refresh_rate, idle_pwm); } uint16_t Naze32::pwm_read(uint8_t channel) { return pwmRead(channel); } void Naze32::pwm_write(uint8_t channel, uint16_t value) { pwmWriteMotor(channel, value); } bool Naze32::pwm_lost() { return ((millis() - pwmLastUpdate()) > 40); } // non-volatile memory void Naze32::memory_init(void) { initEEPROM(); } bool Naze32::memory_read(void * dest, size_t len) { return readEEPROM(dest, len); } bool Naze32::memory_write(const void * src, size_t len) { return writeEEPROM(src, len); } // LED void Naze32::led0_on(void) { LED0_ON; } void Naze32::led0_off(void) { LED0_OFF; } void Naze32::led0_toggle(void) { LED0_TOGGLE; } void Naze32::led1_on(void) { LED1_ON; } void Naze32::led1_off(void) { LED1_OFF; } void Naze32::led1_toggle(void) { LED1_TOGGLE; } } <commit_msg>update board layer a little bit<commit_after>/* * Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ extern "C" { #include <breezystm32.h> #include "flash.h" extern void SetSysClock(bool overclock); void WWDG_IRQHandler() { volatile int debug = 1; } } #include "naze32.h" namespace rosflight_firmware { Naze32::Naze32(){} void Naze32::init_board(void) { // Configure clock, this figures out HSE for hardware autodetect SetSysClock(0); systemInit(); _board_revision = 2; } void Naze32::board_reset(bool bootloader) { systemReset(bootloader); } // clock uint32_t Naze32::clock_millis() { return millis(); } uint64_t Naze32::clock_micros() { return micros(); } void Naze32::clock_delay(uint32_t milliseconds) { delay(milliseconds); } // serial void Naze32::serial_init(uint32_t baud_rate) { Serial1 = uartOpen(USART1, NULL, baud_rate, MODE_RXTX); } void Naze32::serial_write(const uint8_t *src, size_t len) { for (size_t i = 0; i < len; i++) { serialWrite(Serial1, src[i]); } } uint16_t Naze32::serial_bytes_available(void) { return serialTotalBytesWaiting(Serial1); } uint8_t Naze32::serial_read(void) { return serialRead(Serial1); } // sensors void Naze32::sensors_init() { _board_revision = 2; // Initialize I2c i2cInit(I2CDEV_2); while(millis() < 50); i2cWrite(0,0,0); ms5611_init(); hmc5883lInit(_board_revision); mb1242_init(); ms4525_init(); // IMU uint16_t acc1G; mpu6050_init(true, &acc1G, &_gyro_scale, _board_revision); _accel_scale = 9.80665f/acc1G; } uint16_t Naze32::num_sensor_errors(void) { return i2cGetErrorCounter(); } bool Naze32::new_imu_data() { return mpu6050_new_data(); } bool Naze32::imu_read(float accel[3], float* temperature, float gyro[3], uint64_t* time_us) { volatile int16_t gyro_raw[3], accel_raw[3]; volatile int16_t raw_temp; mpu6050_async_read_all(accel_raw, &raw_temp, gyro_raw, time_us); accel[0] = accel_raw[0] * _accel_scale; accel[1] = -accel_raw[1] * _accel_scale; accel[2] = -accel_raw[2] * _accel_scale; gyro[0] = gyro_raw[0] * _gyro_scale; gyro[1] = -gyro_raw[1] * _gyro_scale; gyro[2] = -gyro_raw[2] * _gyro_scale; (*temperature) = (float)raw_temp/340.0f + 36.53f; if (accel[0] == 0 && accel[1] == 0 && accel[2] == 0) { return false; } else return true; } void Naze32::imu_not_responding_error(void) { // If the IMU is not responding, then we need to change where we look for the // interrupt _board_revision = (_board_revision < 4) ? 5 : 2; sensors_init(); } void Naze32::mag_read(float mag[3]) { // Convert to NED int16_t raw_mag[3]; // hmc5883l_update(); hmc5883l_request_async_update(); hmc5883l_async_read(raw_mag); mag[0] = (float)raw_mag[0]; mag[1] = (float)raw_mag[1]; mag[2] = (float)raw_mag[2]; } bool Naze32::mag_check(void) { return hmc5883l_present(); } void Naze32::baro_read(float *pressure, float *temperature) { ms5611_async_update(); ms5611_async_read(pressure, temperature); } bool Naze32::baro_check() { ms5611_async_update(); return ms5611_present(); } bool Naze32::diff_pressure_check(void) { ms4525_async_update(); return ms4525_present(); } void Naze32::diff_pressure_read(float *diff_pressure, float *temperature) { ms4525_async_update(); ms4525_async_read(diff_pressure, temperature); } bool Naze32::sonar_check(void) { return sonarPresent(); } float Naze32::sonar_read(void) { return sonarRead(6); } uint16_t num_sensor_errors(void) { return i2cGetErrorCounter(); } // PWM void Naze32::pwm_init(bool cppm, uint32_t refresh_rate, uint16_t idle_pwm) { pwmInit(cppm, false, false, refresh_rate, idle_pwm); } uint16_t Naze32::pwm_read(uint8_t channel) { return pwmRead(channel); } void Naze32::pwm_write(uint8_t channel, uint16_t value) { pwmWriteMotor(channel, value); } bool Naze32::pwm_lost() { return ((millis() - pwmLastUpdate()) > 40); } // non-volatile memory void Naze32::memory_init(void) { initEEPROM(); } bool Naze32::memory_read(void * dest, size_t len) { return readEEPROM(dest, len); } bool Naze32::memory_write(const void * src, size_t len) { return writeEEPROM(src, len); } // LED void Naze32::led0_on(void) { LED0_ON; } void Naze32::led0_off(void) { LED0_OFF; } void Naze32::led0_toggle(void) { LED0_TOGGLE; } void Naze32::led1_on(void) { LED1_ON; } void Naze32::led1_off(void) { LED1_OFF; } void Naze32::led1_toggle(void) { LED1_TOGGLE; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebM 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 <climits> #include <vector> #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/util.h" namespace { class CpuSpeedTest : public ::libvpx_test::EncoderTest, public ::libvpx_test::CodecTestWith2Params< libvpx_test::TestMode, int> { protected: CpuSpeedTest() : EncoderTest(GET_PARAM(0)) {} virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); set_cpu_used_ = GET_PARAM(2); } virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1); encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7); encoder->Control(VP8E_SET_ARNR_STRENGTH, 5); encoder->Control(VP8E_SET_ARNR_TYPE, 3); } } virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) { } } int set_cpu_used_; }; TEST_P(CpuSpeedTest, TestQ0) { // Validate that this non multiple of 64 wide clip encodes and decodes // without a mismatch when passing in a very low max q. This pushes // the encoder to producing lots of big partitions which will likely // extend into the border and test the border condition. cfg_.g_lag_in_frames = 25; cfg_.rc_2pass_vbr_minsection_pct = 5; cfg_.rc_2pass_vbr_minsection_pct = 2000; cfg_.rc_target_bitrate = 400; cfg_.rc_max_quantizer = 0; cfg_.rc_min_quantizer = 0; ::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0, 20); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } TEST_P(CpuSpeedTest, TestEncodeHighBitrate) { // Validate that this non multiple of 64 wide clip encodes and decodes // without a mismatch when passing in a very low max q. This pushes // the encoder to producing lots of big partitions which will likely // extend into the border and test the border condition. cfg_.g_lag_in_frames = 25; cfg_.rc_2pass_vbr_minsection_pct = 5; cfg_.rc_2pass_vbr_minsection_pct = 2000; cfg_.rc_target_bitrate = 12000; cfg_.rc_max_quantizer = 10; cfg_.rc_min_quantizer = 0; ::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0, 40); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } TEST_P(CpuSpeedTest, TestLowBitrate) { // Validate that this clip encodes and decodes without a mismatch // when passing in a very high min q. This pushes the encoder to producing // lots of small partitions which might will test the other condition. cfg_.g_lag_in_frames = 25; cfg_.rc_2pass_vbr_minsection_pct = 5; cfg_.rc_2pass_vbr_minsection_pct = 2000; cfg_.rc_target_bitrate = 200; cfg_.rc_min_quantizer = 40; ::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0, 40); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } using std::tr1::make_tuple; #define VP9_FACTORY \ static_cast<const libvpx_test::CodecFactory*> (&libvpx_test::kVP9) VP9_INSTANTIATE_TEST_CASE( CpuSpeedTest, ::testing::Values(::libvpx_test::kTwoPassGood), ::testing::Range(0, 5)); } // namespace <commit_msg>cpu_speed_test - now test one pass and more speeds<commit_after>/* * Copyright (c) 2012 The WebM 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 <climits> #include <vector> #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/util.h" namespace { class CpuSpeedTest : public ::libvpx_test::EncoderTest, public ::libvpx_test::CodecTestWith2Params< libvpx_test::TestMode, int> { protected: CpuSpeedTest() : EncoderTest(GET_PARAM(0)) {} virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); set_cpu_used_ = GET_PARAM(2); } virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1); encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7); encoder->Control(VP8E_SET_ARNR_STRENGTH, 5); encoder->Control(VP8E_SET_ARNR_TYPE, 3); } } virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) { } } int set_cpu_used_; }; TEST_P(CpuSpeedTest, TestQ0) { // Validate that this non multiple of 64 wide clip encodes and decodes // without a mismatch when passing in a very low max q. This pushes // the encoder to producing lots of big partitions which will likely // extend into the border and test the border condition. cfg_.g_lag_in_frames = 25; cfg_.rc_2pass_vbr_minsection_pct = 5; cfg_.rc_2pass_vbr_minsection_pct = 2000; cfg_.rc_target_bitrate = 400; cfg_.rc_max_quantizer = 0; cfg_.rc_min_quantizer = 0; ::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0, 20); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } TEST_P(CpuSpeedTest, TestEncodeHighBitrate) { // Validate that this non multiple of 64 wide clip encodes and decodes // without a mismatch when passing in a very low max q. This pushes // the encoder to producing lots of big partitions which will likely // extend into the border and test the border condition. cfg_.g_lag_in_frames = 25; cfg_.rc_2pass_vbr_minsection_pct = 5; cfg_.rc_2pass_vbr_minsection_pct = 2000; cfg_.rc_target_bitrate = 12000; cfg_.rc_max_quantizer = 10; cfg_.rc_min_quantizer = 0; ::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0, 20); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } TEST_P(CpuSpeedTest, TestLowBitrate) { // Validate that this clip encodes and decodes without a mismatch // when passing in a very high min q. This pushes the encoder to producing // lots of small partitions which might will test the other condition. cfg_.g_lag_in_frames = 25; cfg_.rc_2pass_vbr_minsection_pct = 5; cfg_.rc_2pass_vbr_minsection_pct = 2000; cfg_.rc_target_bitrate = 200; cfg_.rc_min_quantizer = 40; ::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0, 20); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } using std::tr1::make_tuple; #define VP9_FACTORY \ static_cast<const libvpx_test::CodecFactory*> (&libvpx_test::kVP9) VP9_INSTANTIATE_TEST_CASE( CpuSpeedTest, ::testing::Values(::libvpx_test::kTwoPassGood, ::libvpx_test::kOnePassGood), ::testing::Range(0, 8)); } // namespace <|endoftext|>
<commit_before>#include <FWPlatform.h> #include <pthread.h> #include <PlatformThread.h> #include <Runnable.h> #include <SysEvent.h> #include <iostream> #include <unistd.h> using namespace std; class PosixThread : public PlatformThread { public: PosixThread(std::shared_ptr<Runnable> & _runnable, FWPlatform * _platform) : PlatformThread(_runnable), platform(_platform) { } void start() override { if (pthread_create(&thread, NULL, PosixThread::entryPoint, this) == 0) { } else { cerr << "failed to create thread\n"; } } bool testDestroy() override { return false; // !terminate_thread; } void terminate() override { assert(0); terminate_thread = true; } void disconnect() override { platform = 0; } void logMessage(const char * message) override { // wxLogMessage(wxString::FromUTF8(message)); } // void postEventToThread(Event & event) { // event.dispatch(getRunnable()); // } void sleep(float t) override { usleep(int(t * 1000000)); } protected: void sendEventFromThread(const Event & ev) override { if (platform) { platform->pushEvent(ev); } } private: static void * entryPoint(void * pthis); pthread_t thread; pthread_t thread_id; volatile bool terminate_thread = false; FWPlatform * platform; }; void * PosixThread::entryPoint(void * pthis) { // OS::getInstance().ignoreSigPipe(); PosixThread * pt = static_cast<PosixThread*>(pthis); pt->thread_id = pthread_self(); // pt->setupThread(); pt->getRunnable().start(pt); // pt->getRunnable().stop(); // pt->deinitializeThread(); // { // MutexLocker l(pt->mutex); // pt->is_running = false; // } // cerr << "thread really exiting\n"; pthread_exit(0); return 0; } std::shared_ptr<PlatformThread> FWPlatform::run(std::shared_ptr<Runnable> runnable) { auto thread = run2(runnable); num_running_threads++; threads.push_back(thread); return thread; } std::shared_ptr<PlatformThread> FWPlatform::run2(std::shared_ptr<Runnable> & runnable) { std::shared_ptr<PlatformThread> thread(new PosixThread(runnable, this)); thread->start(); return thread; } void FWPlatform::terminateThreads() { cerr << "terminating " << threads.size() << " threads\n"; for (auto & thread : threads) { assert(thread.get()); thread->terminate(); } } void FWPlatform::disconnectThreads() { for (auto & thread : threads) { thread->disconnect(); } } void FWPlatform::onSysEvent(SysEvent & ev) { if (ev.getType() == SysEvent::THREAD_TERMINATED) { for (auto it = threads.begin(); it != threads.end(); it++) { PlatformThread * thread = it->get(); if (thread == ev.getThread()) { threads.erase(it); num_running_threads--; break; } } } } <commit_msg>refactor<commit_after>#include <FWPlatform.h> #include <pthread.h> #include <PlatformThread.h> #include <Runnable.h> #include <SysEvent.h> #include <iostream> #include <unistd.h> using namespace std; class PosixThread : public PlatformThread { public: PosixThread(FWPlatform * _platform, std::shared_ptr<Runnable> & _runnable) : PlatformThread(_platform, _runnable) { } void start() override { if (pthread_create(&thread, NULL, PosixThread::entryPoint, this) == 0) { } else { cerr << "failed to create thread\n"; } } bool testDestroy() override { return false; // !terminate_thread; } void terminate() override { assert(0); terminate_thread = true; } void disconnect() override { // platform = 0; } void logMessage(const char * message) override { // wxLogMessage(wxString::FromUTF8(message)); } // void postEventToThread(Event & event) { // event.dispatch(getRunnable()); // } void sleep(float t) override { usleep(int(t * 1000000)); } protected: void sendEventFromThread(const Event & ev) override { getPlatform().pushEvent(ev); } private: static void * entryPoint(void * pthis); pthread_t thread; pthread_t thread_id; volatile bool terminate_thread = false; }; void * PosixThread::entryPoint(void * pthis) { // OS::getInstance().ignoreSigPipe(); PosixThread * pt = static_cast<PosixThread*>(pthis); pt->thread_id = pthread_self(); // pt->setupThread(); pt->getRunnable().start(pt); // pt->getRunnable().stop(); // pt->deinitializeThread(); // { // MutexLocker l(pt->mutex); // pt->is_running = false; // } // cerr << "thread really exiting\n"; pthread_exit(0); return 0; } std::shared_ptr<PlatformThread> FWPlatform::run(std::shared_ptr<Runnable> runnable) { auto thread = run2(runnable); num_running_threads++; threads.push_back(thread); return thread; } std::shared_ptr<PlatformThread> FWPlatform::run2(std::shared_ptr<Runnable> & runnable) { std::shared_ptr<PlatformThread> thread(new PosixThread(this, runnable)); thread->start(); return thread; } void FWPlatform::terminateThreads() { cerr << "terminating " << threads.size() << " threads\n"; for (auto & thread : threads) { assert(thread.get()); thread->terminate(); } } void FWPlatform::disconnectThreads() { for (auto & thread : threads) { thread->disconnect(); } } void FWPlatform::onSysEvent(SysEvent & ev) { if (ev.getType() == SysEvent::THREAD_TERMINATED) { for (auto it = threads.begin(); it != threads.end(); it++) { PlatformThread * thread = it->get(); if (thread == ev.getThread()) { threads.erase(it); num_running_threads--; break; } } } } <|endoftext|>
<commit_before>/* * Project: FullereneViewer * Version: 1.0 * Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext) * Create: 2011/12/26 18:06:18 JST */ #include <assert.h> #include "ThreeViewNormal.h" #include "CarbonAllotrope.h" #include "OpenGLUtil.h" int ThreeViewNormal::p_get_nth() const { return sequence_no(); } ThreeViewNormal::ThreeViewNormal(CarbonAllotrope* ca, int nth) : InteractiveRegularPolygon(ca, nth, 1.0, 2), p_ca(ca) { } ThreeViewNormal::~ThreeViewNormal() { } void ThreeViewNormal::reset_interaction() { InteractiveRegularPolygon::reset_interaction(); p_ca->reset_three_axes(); } void ThreeViewNormal::interaction_original(OriginalForceType force_type, Interactives* interactives, double delta) { p_ca->calculate_three_axes(); double Eigenvalue; Vector3 Eigenvector; switch (p_get_nth()) { case 1: p_ca->get_primary_Eigenvalue_and_Eigenvector(Eigenvalue, Eigenvector); break; case 2: p_ca->get_secondary_Eigenvalue_and_Eigenvector(Eigenvalue, Eigenvector); break; default: p_ca->get_tertiary_Eigenvalue_and_Eigenvector(Eigenvalue, Eigenvector); break; } p_normal.clockwise = 1; fix_center_location(p_ca->get_center_location()); fix_radius_length(Eigenvalue * 0.5); fix_posture(Matrix3(Quaternion(Vector3(0.0, 0.0, 1.0), Eigenvector))); } void ThreeViewNormal::draw_opaque_by_OpenGL(bool selection) const { Vector3 norm = get_normal(); norm *= p_radius.length; switch (p_get_nth()) { case 1: OpenGLUtil::set_color(0xff0000); break; case 2: OpenGLUtil::set_color(0x00ff00); break; default: OpenGLUtil::set_color(0x0000ff); break; } OpenGLUtil::draw_cylinder(0.4, get_center_location() - norm, get_center_location() + norm); } /* Local Variables: */ /* mode: c++ */ /* End: */ <commit_msg>3方向線(長径・中径・短径)もスマートな軸に変更。<commit_after>/* * Project: FullereneViewer * Version: 1.0 * Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext) * Create: 2011/12/26 18:06:18 JST */ #include <assert.h> #include "ThreeViewNormal.h" #include "CarbonAllotrope.h" #include "OpenGLUtil.h" int ThreeViewNormal::p_get_nth() const { return sequence_no(); } ThreeViewNormal::ThreeViewNormal(CarbonAllotrope* ca, int nth) : InteractiveRegularPolygon(ca, nth, 1.0, 2), p_ca(ca) { } ThreeViewNormal::~ThreeViewNormal() { } void ThreeViewNormal::reset_interaction() { InteractiveRegularPolygon::reset_interaction(); p_ca->reset_three_axes(); } void ThreeViewNormal::interaction_original(OriginalForceType force_type, Interactives* interactives, double delta) { p_ca->calculate_three_axes(); double Eigenvalue; Vector3 Eigenvector; switch (p_get_nth()) { case 1: p_ca->get_primary_Eigenvalue_and_Eigenvector(Eigenvalue, Eigenvector); break; case 2: p_ca->get_secondary_Eigenvalue_and_Eigenvector(Eigenvalue, Eigenvector); break; default: p_ca->get_tertiary_Eigenvalue_and_Eigenvector(Eigenvalue, Eigenvector); break; } p_normal.clockwise = 1; fix_center_location(p_ca->get_center_location()); fix_radius_length(Eigenvalue * 0.5); fix_posture(Matrix3(Quaternion(Vector3(0.0, 0.0, 1.0), Eigenvector))); } void ThreeViewNormal::draw_opaque_by_OpenGL(bool selection) const { Vector3 norm = get_normal(); norm *= p_radius.length; switch (p_get_nth()) { case 1: OpenGLUtil::set_color(0xff80b0); break; case 2: OpenGLUtil::set_color(0xb0ff80); break; default: OpenGLUtil::set_color(0x80b0ff); break; } OpenGLUtil::draw_cylinder(0.1, get_center_location() - norm, get_center_location() + norm); } /* Local Variables: */ /* mode: c++ */ /* End: */ <|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 "TestPanel.hxx" #include "taskpane/ScrollPanel.hxx" #include "taskpane/TaskPaneControlFactory.hxx" #include <vcl/lstbox.hxx> #include <vcl/button.hxx> namespace sd { namespace toolpanel { #ifdef SHOW_TEST_PANEL /** This factory class is used to create instances of TestPanel. It can be extended so that its constructor stores arguments that later are passed to new TestPanel objects. */ class TestPanelFactory : public ControlFactory { protected: virtual TreeNode* InternalCreateControl( ::Window& i_rParent ) { return new TestPanel (i_rParent); } }; class Wrapper : public TreeNode { public: Wrapper ( TreeNode* pParent, Size aPreferredSize, ::Window* pWrappedControl, bool bIsResizable) : TreeNode (pParent), maPreferredSize(aPreferredSize), mpWrappedControl(pWrappedControl), mbIsResizable(bIsResizable) { mpWrappedControl->Show(); } virtual ~Wrapper (void) { delete mpWrappedControl; } virtual Size GetPreferredSize (void) { return maPreferredSize; } virtual sal_Int32 GetPreferredWidth (sal_Int32 ) { return maPreferredSize.Width(); } virtual sal_Int32 GetPreferredHeight (sal_Int32 ) { return maPreferredSize.Height(); } virtual ::Window* GetWindow (void) { return mpWrappedControl; } virtual bool IsResizable (void) { return mbIsResizable; } virtual bool IsExpandable (void) const { return false; } virtual bool IsExpanded (void) const { return true; } private: Size maPreferredSize; ::Window* mpWrappedControl; bool mbIsResizable; }; TestPanel::TestPanel (::Window& i_rParent) : SubToolPanel (i_rParent) { // Create a scrollable panel with two list boxes. ScrollPanel* pScrollPanel = new ScrollPanel (this); ListBox* pBox = new ListBox (pScrollPanel->GetWindow()); for (sal_Int32 i=1; i<=20; i++) { XubString aString (XubString::CreateFromAscii("Text ")); aString.Append (XubString::CreateFromInt32(i)); aString.Append (XubString::CreateFromAscii("/20")); pBox->InsertEntry (aString); } pScrollPanel->AddControl ( ::std::auto_ptr<TreeNode>(new Wrapper ( pScrollPanel, Size (200,300), pBox, true)), String::CreateFromAscii ("First ListBox"), ""); pBox = new ListBox (pScrollPanel->GetWindow()); for (sal_Int32 i=1; i<=20; i++) { XubString aString (XubString::CreateFromAscii("More Text ")); aString.Append (XubString::CreateFromInt32(i)); aString.Append (XubString::CreateFromAscii("/20")); pBox->InsertEntry (aString); } pScrollPanel->AddControl ( ::std::auto_ptr<TreeNode>(new Wrapper ( pScrollPanel, Size (200,300), pBox, true)), String::CreateFromAscii ("Second ListBox"), ""); AddControl (::std::auto_ptr<TreeNode>(pScrollPanel)); // Add a fixed size button. Button* pButton = new OKButton (this); AddControl ( ::std::auto_ptr<TreeNode>(new Wrapper ( this, Size (100,30), pButton, false)), String::CreateFromAscii ("Button Area"), ""); } TestPanel::~TestPanel (void) { } std::auto_ptr<ControlFactory> TestPanel::CreateControlFactory (void) { return std::auto_ptr<ControlFactory>(new TestPanelFactory()); } #endif } } // end of namespace ::sd::toolpanel /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>XubString->rtl::OUStringBuffer<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 "TestPanel.hxx" #include "taskpane/ScrollPanel.hxx" #include "taskpane/TaskPaneControlFactory.hxx" #include <vcl/lstbox.hxx> #include <vcl/button.hxx> namespace sd { namespace toolpanel { #ifdef SHOW_TEST_PANEL /** This factory class is used to create instances of TestPanel. It can be extended so that its constructor stores arguments that later are passed to new TestPanel objects. */ class TestPanelFactory : public ControlFactory { protected: virtual TreeNode* InternalCreateControl( ::Window& i_rParent ) { return new TestPanel (i_rParent); } }; class Wrapper : public TreeNode { public: Wrapper ( TreeNode* pParent, Size aPreferredSize, ::Window* pWrappedControl, bool bIsResizable) : TreeNode (pParent), maPreferredSize(aPreferredSize), mpWrappedControl(pWrappedControl), mbIsResizable(bIsResizable) { mpWrappedControl->Show(); } virtual ~Wrapper (void) { delete mpWrappedControl; } virtual Size GetPreferredSize (void) { return maPreferredSize; } virtual sal_Int32 GetPreferredWidth (sal_Int32 ) { return maPreferredSize.Width(); } virtual sal_Int32 GetPreferredHeight (sal_Int32 ) { return maPreferredSize.Height(); } virtual ::Window* GetWindow (void) { return mpWrappedControl; } virtual bool IsResizable (void) { return mbIsResizable; } virtual bool IsExpandable (void) const { return false; } virtual bool IsExpanded (void) const { return true; } private: Size maPreferredSize; ::Window* mpWrappedControl; bool mbIsResizable; }; TestPanel::TestPanel (::Window& i_rParent) : SubToolPanel (i_rParent) { // Create a scrollable panel with two list boxes. ScrollPanel* pScrollPanel = new ScrollPanel (this); ListBox* pBox = new ListBox (pScrollPanel->GetWindow()); for (sal_Int32 i=1; i<=20; i++) { rtl::OUStringBuffer aString ("Text "); aString.append(i).append("/20"); pBox->InsertEntry(aString.makeStringAndClear()); } pScrollPanel->AddControl ( ::std::auto_ptr<TreeNode>(new Wrapper ( pScrollPanel, Size (200,300), pBox, true)), rtl::OUString("First ListBox"), ""); pBox = new ListBox (pScrollPanel->GetWindow()); for (sal_Int32 i=1; i<=20; i++) { rtl::OUStringBuffer aString("More Text "); aString.append(i).append("/20"); pBox->InsertEntry(aString.makeStringAndClear()); } pScrollPanel->AddControl ( ::std::auto_ptr<TreeNode>(new Wrapper ( pScrollPanel, Size (200,300), pBox, true)), String::CreateFromAscii ("Second ListBox"), ""); AddControl (::std::auto_ptr<TreeNode>(pScrollPanel)); // Add a fixed size button. Button* pButton = new OKButton (this); AddControl ( ::std::auto_ptr<TreeNode>(new Wrapper ( this, Size (100,30), pButton, false)), String::CreateFromAscii ("Button Area"), ""); } TestPanel::~TestPanel (void) { } std::auto_ptr<ControlFactory> TestPanel::CreateControlFactory (void) { return std::auto_ptr<ControlFactory>(new TestPanelFactory()); } #endif } } // end of namespace ::sd::toolpanel /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#ifndef PRESET_HPP #define PRESET_HPP #include "PrintConfig.hpp" #include "Config.hpp" namespace Slic3r { namespace GUI { /// Preset types list. We assign numbers to permit static_casts and use as preset tab indices enum class preset_t : uint8_t { Print = 0, Material, Printer, Last // This MUST be the last enumeration. Don't use it for anything. }; /// Convenience counter to determine how many preset tabs exist. constexpr uint8_t preset(preset_t preset) { return static_cast<uint8_t>(preset); } constexpr size_t preset_types = preset(preset_t::Last); class Preset; using Presets = std::vector<Preset>; class Preset { preset_t group; std::string name {""}; /// Preset bool default_preset {false}; /// Search the compatible_printers config option list for this preset name. /// Assume that Printer configs are compatible with other Printer configs bool compatible(std::string printer_name) { return true; } bool compatible(const Preset& other) {return (this->group == preset_t::Printer || (compatible(other.name) && other.group == preset_t::Printer));} /// Format the name appropriately. wxString dropdown_name() { return (this->dirty() ? wxString(this->name) << " " << _("(modified)") : this->name); } bool file_exists(wxString name); bool prompt_unsaved_changes(wxWindow* parent); /// Apply dirty config to config and save. bool save(t_config_option_keys opt_keys); /// Apply dirty config to config and save with an alternate name. bool save_as(wxString name, t_config_option_keys opt_keys); /// Delete this preset from the system. void delete_preset(); /// Returns list of options that have been modified from the config. t_config_option_keys dirty_options(); /// Returns whether or not this config is different from its modified state. bool dirty(); /// Loads the selected config from file and return a reference. Slic3r::Config& load_config(); /// Pass-through to Slic3r::Config, returns whether or not a config was loaded. bool loaded() { return !this->config.empty(); } /// Clear the dirty config. void dismiss_changes(); private: bool external {false}; /// store to keep config options for this preset Slic3r::Config config { Slic3r::Config() }; /// Alternative config store for a modified configuration. Slic3r::Config dirty_config {Slic3r::Config()}; std::string file {""}; /// reach through to the appropriate material type t_config_option_keys _group_class(); }; }} // namespace Slic3r::GUI #endif // PRESET_HPP <commit_msg>Made Preset methods public (as originally intended), added == for wxString and std::string to let std::find behave nicely.<commit_after>#ifndef PRESET_HPP #define PRESET_HPP #include "PrintConfig.hpp" #include "Config.hpp" namespace Slic3r { namespace GUI { /// Preset types list. We assign numbers to permit static_casts and use as preset tab indices enum class preset_t : uint8_t { Print = 0, Material, Printer, Last // This MUST be the last enumeration. Don't use it for anything. }; /// Convenience counter to determine how many preset tabs exist. constexpr uint8_t preset(preset_t preset) { return static_cast<uint8_t>(preset); } constexpr size_t preset_types = preset(preset_t::Last); class Preset; using Presets = std::vector<Preset>; class Preset { public: preset_t group; std::string name {""}; /// Preset bool default_preset {false}; /// Search the compatible_printers config option list for this preset name. /// Assume that Printer configs are compatible with other Printer configs bool compatible(std::string printer_name) { return true; } bool compatible(const Preset& other) {return (this->group == preset_t::Printer || (compatible(other.name) && other.group == preset_t::Printer));} /// Format the name appropriately. wxString dropdown_name() { return (this->dirty() ? wxString(this->name) << " " << _("(modified)") : this->name); } bool file_exists(wxString name); bool prompt_unsaved_changes(wxWindow* parent); /// Apply dirty config to config and save. bool save(t_config_option_keys opt_keys); /// Apply dirty config to config and save with an alternate name. bool save_as(wxString name, t_config_option_keys opt_keys); /// Delete this preset from the system. void delete_preset(); /// Returns list of options that have been modified from the config. t_config_option_keys dirty_options(); /// Returns whether or not this config is different from its modified state. bool dirty(); /// Loads the selected config from file and return a reference. Slic3r::Config& load_config(); /// Pass-through to Slic3r::Config, returns whether or not a config was loaded. bool loaded() { return !this->config.empty(); } /// Clear the dirty config. void dismiss_changes(); void apply_dirty(const Slic3r::Config& other) { this->dirty_config.apply(other); } void apply_dirty(const config_ptr& other) { this->apply_dirty(*other); } bool operator==(const wxString& _name) const { return this->operator==(_name.ToStdString()); } bool operator==(const std::string& _name) const { return _name.compare(this->name) == 0; } private: bool external {false}; /// store to keep config options for this preset Slic3r::Config config { Slic3r::Config() }; /// Alternative config store for a modified configuration. Slic3r::Config dirty_config {Slic3r::Config()}; std::string file {""}; /// reach through to the appropriate material type t_config_option_keys _group_class(); }; }} // namespace Slic3r::GUI #endif // PRESET_HPP <|endoftext|>
<commit_before>#include "Utility/String.h" #include <string> #include <vector> #include <stdexcept> #include <algorithm> #include <cctype> #include <chrono> #include <iomanip> #include <sstream> #include <cmath> std::vector<std::string> String::split(const std::string& s, const std::string& delim, const size_t count) noexcept { if(delim.empty()) { return split(remove_extra_whitespace(s), " ", count); } if(s.empty()) { return {}; } std::vector<std::string> result; size_t start_index = 0; size_t end_index = 0; size_t split_count = 0; while(end_index < s.size() && split_count < count) { end_index = s.find(delim, start_index); result.push_back(s.substr(start_index, end_index - start_index)); start_index = std::min(end_index, s.size()) + delim.size(); ++split_count; } if(start_index <= s.size()) { result.push_back(s.substr(start_index)); } return result; } bool String::starts_with(const std::string& s, const std::string& beginning) noexcept { return std::mismatch(beginning.begin(), beginning.end(), s.begin(), s.end()).first == beginning.end(); } std::string String::trim_outer_whitespace(const std::string& s) noexcept { constexpr auto whitespace = " \t\n\r"; const auto text_start = s.find_first_not_of(whitespace); if(text_start == std::string::npos) { return {}; } const auto text_end = s.find_last_not_of(whitespace); return s.substr(text_start, text_end - text_start + 1); } std::string String::remove_extra_whitespace(const std::string& s) noexcept { std::string result; std::copy_if(s.begin(), s.end(), std::back_inserter(result), [&result](auto c) { return ! isspace(c) || ( ! result.empty() && ! std::isspace(result.back())); }); return trim_outer_whitespace(result); } std::string String::strip_comments(const std::string& str, const std::string& comment) noexcept { return trim_outer_whitespace(str.substr(0, str.find(comment))); } std::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end) { const auto start_comment_index = str.find(start); const auto end_comment_index = str.find(end); if(start_comment_index == std::string::npos && end_comment_index == std::string::npos) { return trim_outer_whitespace(str); } if(start_comment_index == std::string::npos || end_comment_index == std::string::npos) { throw std::invalid_argument("\"" + str + "\" is missing a comment delimiter: " + start + end); } if(start_comment_index >= end_comment_index) { throw std::invalid_argument("\"" + str + "\" contains bad comment delimiters: " + start + end); } try { const auto first_part = str.substr(0, start_comment_index); const auto last_part = str.substr(end_comment_index + end.size()); return strip_block_comment(trim_outer_whitespace(first_part) + " " + trim_outer_whitespace(last_part), start, end); } catch(const std::invalid_argument& e) { throw std::invalid_argument(e.what() + std::string("\nOriginal line: ") + str); } } std::string String::strip_nested_block_comments(const std::string& str, const std::string& start, const std::string& end) { if(contains(start, end) || contains(end, start)) { throw std::invalid_argument("Delimiters cannot share substrings: " + start + "," + end + "."); } const auto error_message = "Invalid nesting of delimiters " + start + "," + end + ": " + str; std::string result; auto depth = 0; size_t index = 0; while(index < str.size()) { auto start_index = str.find(start, index); auto end_index = str.find(end, index); if(start_index < end_index) { if(depth == 0) { result += str.substr(index, start_index - index); } ++depth; index = start_index + start.size(); } else if(end_index < start_index) { if(depth == 0) { throw std::invalid_argument(error_message); } --depth; index = end_index + end.size(); } else // start_index == end_index == std::string::npos { result += str.substr(index); break; } } if(depth != 0) { throw std::invalid_argument(error_message); } return result; } std::string String::remove_pgn_comments(const std::string& line) { const auto index = line.find_first_of(";({"); const auto delimiter = index < std::string::npos ? line[index] : '\0'; switch(delimiter) { case ';' : return remove_pgn_comments(strip_comments(line, ";")); case '(' : return remove_pgn_comments(strip_nested_block_comments(line, "(", ")")); case '{' : return remove_pgn_comments(strip_block_comment(line, "{", "}")); default : return remove_extra_whitespace(line); } } std::string String::extract_delimited_text(const std::string& str, const std::string& start, const std::string& end) { const auto first_delimiter_index = str.find(start); if(first_delimiter_index == std::string::npos) { throw std::invalid_argument("Starting delimiter not found in \"" + str + "\": " + start + " " + end); } const auto text_start_index = first_delimiter_index + start.size(); const auto second_delimiter_index = str.find(end, text_start_index); if(second_delimiter_index == std::string::npos) { throw std::invalid_argument("Ending delimiter not found in \"" + str + "\": " + start + " " + end); } const auto text_length = second_delimiter_index - text_start_index; return str.substr(text_start_index, text_length); } char String::tolower(const char letter) noexcept { return char(std::tolower(letter)); } char String::toupper(const char letter) noexcept { return char(std::toupper(letter)); } std::string String::lowercase(std::string s) noexcept { std::transform(s.begin(), s.end(), s.begin(), String::tolower); return s; } std::string String::round_to_decimals(const double x, const size_t decimal_places) noexcept { auto result = std::ostringstream(); result << std::fixed << std::setprecision(int(decimal_places)) << x; return result.str(); } std::string String::date_and_time_format(const std::chrono::system_clock::time_point& point_in_time, const std::string& format) noexcept { const auto time_c = std::chrono::system_clock::to_time_t(point_in_time); std::tm time_out; #ifdef _WIN32 localtime_s(&time_out, &time_c); #elif defined(__linux__) localtime_r(&time_c, &time_out); #endif auto ss = std::ostringstream{}; ss << std::put_time(&time_out, format.c_str()); return ss.str(); } std::string String::add_to_file_name(const std::string& original_file_name, const std::string& addition) noexcept { const auto dot_index = std::min(original_file_name.find_last_of('.'), original_file_name.size()); return original_file_name.substr(0, dot_index) + addition + original_file_name.substr(dot_index); } <commit_msg>Add namespace qualifier to function isspace<commit_after>#include "Utility/String.h" #include <string> #include <vector> #include <stdexcept> #include <algorithm> #include <cctype> #include <chrono> #include <iomanip> #include <sstream> #include <cmath> std::vector<std::string> String::split(const std::string& s, const std::string& delim, const size_t count) noexcept { if(delim.empty()) { return split(remove_extra_whitespace(s), " ", count); } if(s.empty()) { return {}; } std::vector<std::string> result; size_t start_index = 0; size_t end_index = 0; size_t split_count = 0; while(end_index < s.size() && split_count < count) { end_index = s.find(delim, start_index); result.push_back(s.substr(start_index, end_index - start_index)); start_index = std::min(end_index, s.size()) + delim.size(); ++split_count; } if(start_index <= s.size()) { result.push_back(s.substr(start_index)); } return result; } bool String::starts_with(const std::string& s, const std::string& beginning) noexcept { return std::mismatch(beginning.begin(), beginning.end(), s.begin(), s.end()).first == beginning.end(); } std::string String::trim_outer_whitespace(const std::string& s) noexcept { constexpr auto whitespace = " \t\n\r"; const auto text_start = s.find_first_not_of(whitespace); if(text_start == std::string::npos) { return {}; } const auto text_end = s.find_last_not_of(whitespace); return s.substr(text_start, text_end - text_start + 1); } std::string String::remove_extra_whitespace(const std::string& s) noexcept { std::string result; std::copy_if(s.begin(), s.end(), std::back_inserter(result), [&result](auto c) { return ! std::isspace(c) || ( ! result.empty() && ! std::isspace(result.back())); }); return trim_outer_whitespace(result); } std::string String::strip_comments(const std::string& str, const std::string& comment) noexcept { return trim_outer_whitespace(str.substr(0, str.find(comment))); } std::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end) { const auto start_comment_index = str.find(start); const auto end_comment_index = str.find(end); if(start_comment_index == std::string::npos && end_comment_index == std::string::npos) { return trim_outer_whitespace(str); } if(start_comment_index == std::string::npos || end_comment_index == std::string::npos) { throw std::invalid_argument("\"" + str + "\" is missing a comment delimiter: " + start + end); } if(start_comment_index >= end_comment_index) { throw std::invalid_argument("\"" + str + "\" contains bad comment delimiters: " + start + end); } try { const auto first_part = str.substr(0, start_comment_index); const auto last_part = str.substr(end_comment_index + end.size()); return strip_block_comment(trim_outer_whitespace(first_part) + " " + trim_outer_whitespace(last_part), start, end); } catch(const std::invalid_argument& e) { throw std::invalid_argument(e.what() + std::string("\nOriginal line: ") + str); } } std::string String::strip_nested_block_comments(const std::string& str, const std::string& start, const std::string& end) { if(contains(start, end) || contains(end, start)) { throw std::invalid_argument("Delimiters cannot share substrings: " + start + "," + end + "."); } const auto error_message = "Invalid nesting of delimiters " + start + "," + end + ": " + str; std::string result; auto depth = 0; size_t index = 0; while(index < str.size()) { auto start_index = str.find(start, index); auto end_index = str.find(end, index); if(start_index < end_index) { if(depth == 0) { result += str.substr(index, start_index - index); } ++depth; index = start_index + start.size(); } else if(end_index < start_index) { if(depth == 0) { throw std::invalid_argument(error_message); } --depth; index = end_index + end.size(); } else // start_index == end_index == std::string::npos { result += str.substr(index); break; } } if(depth != 0) { throw std::invalid_argument(error_message); } return result; } std::string String::remove_pgn_comments(const std::string& line) { const auto index = line.find_first_of(";({"); const auto delimiter = index < std::string::npos ? line[index] : '\0'; switch(delimiter) { case ';' : return remove_pgn_comments(strip_comments(line, ";")); case '(' : return remove_pgn_comments(strip_nested_block_comments(line, "(", ")")); case '{' : return remove_pgn_comments(strip_block_comment(line, "{", "}")); default : return remove_extra_whitespace(line); } } std::string String::extract_delimited_text(const std::string& str, const std::string& start, const std::string& end) { const auto first_delimiter_index = str.find(start); if(first_delimiter_index == std::string::npos) { throw std::invalid_argument("Starting delimiter not found in \"" + str + "\": " + start + " " + end); } const auto text_start_index = first_delimiter_index + start.size(); const auto second_delimiter_index = str.find(end, text_start_index); if(second_delimiter_index == std::string::npos) { throw std::invalid_argument("Ending delimiter not found in \"" + str + "\": " + start + " " + end); } const auto text_length = second_delimiter_index - text_start_index; return str.substr(text_start_index, text_length); } char String::tolower(const char letter) noexcept { return char(std::tolower(letter)); } char String::toupper(const char letter) noexcept { return char(std::toupper(letter)); } std::string String::lowercase(std::string s) noexcept { std::transform(s.begin(), s.end(), s.begin(), String::tolower); return s; } std::string String::round_to_decimals(const double x, const size_t decimal_places) noexcept { auto result = std::ostringstream(); result << std::fixed << std::setprecision(int(decimal_places)) << x; return result.str(); } std::string String::date_and_time_format(const std::chrono::system_clock::time_point& point_in_time, const std::string& format) noexcept { const auto time_c = std::chrono::system_clock::to_time_t(point_in_time); std::tm time_out; #ifdef _WIN32 localtime_s(&time_out, &time_c); #elif defined(__linux__) localtime_r(&time_c, &time_out); #endif auto ss = std::ostringstream{}; ss << std::put_time(&time_out, format.c_str()); return ss.str(); } std::string String::add_to_file_name(const std::string& original_file_name, const std::string& addition) noexcept { const auto dot_index = std::min(original_file_name.find_last_of('.'), original_file_name.size()); return original_file_name.substr(0, dot_index) + addition + original_file_name.substr(dot_index); } <|endoftext|>
<commit_before>#ifndef _SNARKFRONT_MERKLE_AUTH_PATH_HPP_ #define _SNARKFRONT_MERKLE_AUTH_PATH_HPP_ #include <cstdint> #include <iostream> #include <istream> #include <ostream> #include <vector> #include "DSL_base.hpp" #include "DSL_bless.hpp" #include "DSL_utility.hpp" #include "PowersOf2.hpp" #include "SHA_256.hpp" #include "SHA_512.hpp" namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // authentication path from a binary Merkle tree // template <typename HASH, typename BIT> class MerkleAuthPath { public: typedef HASH HashType; typedef typename HASH::DigType DigType; MerkleAuthPath() : m_depth(0) {} // eval MerkleAuthPath(const std::size_t depth) : m_depth(depth), m_rootPath(depth) // first update initializes hash digests { m_siblings.reserve(depth); m_childBits.reserve(depth); for (std::size_t i = 0; i < depth; ++i) { m_siblings.emplace_back(zero()); m_childBits.emplace_back(0); } } // zk from eval template <typename OTHER_HASH, typename OTHER_BIT> MerkleAuthPath(const MerkleAuthPath<OTHER_HASH, OTHER_BIT>& other) : m_depth(other.depth()), m_rootPath(other.depth()) // first update initializes hash digests { m_siblings.reserve(other.depth()); for (const auto& a : other.siblings()) { DigType b; bless(b, a); m_siblings.emplace_back(b); } m_childBits.reserve(other.depth()); for (const auto& a : other.childBits()) { BIT b; bless(b, a); m_childBits.emplace_back(b); } } std::size_t depth() const { return m_depth; } const DigType& rootHash() const { return m_rootPath.back(); } // bottom-up order, index 0 is at the leaves of tree const std::vector<DigType>& rootPath() const { return m_rootPath; } const std::vector<DigType>& siblings() const { return m_siblings; } const std::vector<BIT>& childBits() const { return m_childBits; } // update hash codes along path back to root void updatePath(const DigType& leaf) { std::vector<MerkleAuthPath> dummy; updatePath(leaf, dummy); } // update hash codes along path back to root void updatePath(const DigType& leaf, std::vector<MerkleAuthPath>& oldPaths) { // root path overlap std::vector<int> overlap; overlap.reserve(oldPaths.size()); for (const auto& a : oldPaths) { overlap.push_back( matchMSB(m_childBits, a.childBits())); } HASH hashAlgo; auto dig = leaf; // ascend tree from leaf to root for (std::size_t i = 0; i < m_depth; ++i) { hashAlgo.clearMessage(); const auto& isRightChild = m_childBits[i]; const auto leftDigest = ternary(isRightChild, m_siblings[i], dig), rightDigest = ternary(isRightChild, dig, m_siblings[i]); hashAlgo.msgInput(leftDigest); hashAlgo.msgInput(rightDigest); hashAlgo.computeHash(); dig = m_rootPath[i] = hashAlgo.digest(); // path length from root to node with the new hash const int pathLen = m_depth - 1 - i; // update old authentication paths for (std::size_t j = 0; j < overlap.size(); ++j) { if (pathLen <= overlap[j]) { // update root path hashes oldPaths[j].m_rootPath[i] = dig; } else if (pathLen == overlap[j] + 1) { // update sibling hashes oldPaths[j].m_siblings[i + 1] = dig; } } } // update old authentication paths for (std::size_t j = 0; j < overlap.size(); ++j) { if (m_depth - 1 == overlap[j]) // differ in last bit only, leaf must be right sibling oldPaths[j].m_siblings[0] = leaf; } } // just added leaf becomes left sibling void leafSibling(const DigType& leaf) { m_siblings[0] = leaf; } // new branch in Merkle tree void hashSibling(const std::size_t index) { m_siblings[index] = m_rootPath[index - 1]; for (std::size_t i = 0; i < index; ++i) m_siblings[i] = zero(); } // returns index of first set bit (right child) int incChildBits() { for (std::size_t i = 0; i < m_depth; ++i) { auto& a = m_childBits[i]; if (bool(0 == a)) { // bit is zero, increment to one a = 1; return i; } else { // bit is one, increment to zero and carry a = 0; } } // increment all ones wraps back to zero with carry return -1; } void marshal_out(std::ostream& os) const { os << m_depth << std::endl << m_rootPath << m_siblings; for (const auto& a : m_childBits) { os << a << std::endl; } } bool marshal_in(std::istream& is) { m_depth = 0; // use as valid flag std::size_t len = 0; is >> len; if (!is || 0 == len) return false; m_rootPath.resize(len); is >> m_rootPath; if (!is) return false; m_siblings.resize(len); is >> m_siblings; if (!is) return false; m_childBits.resize(len); for (auto& r : m_childBits) { is >> r; if (!is) return false; } m_depth = len; return true; } private: // note: not called by proof generation static DigType zero() { return {0}; } std::size_t m_depth; // indices start from 0 at the leaves increasing up to the root std::vector<DigType> m_rootPath, m_siblings; // next available leaf element std::vector<BIT> m_childBits; }; template <typename HASH, typename BIT> std::ostream& operator<< (std::ostream& os, const MerkleAuthPath<HASH, BIT>& a) { a.marshal_out(os); return os; } template <typename HASH, typename BIT> std::istream& operator>> (std::istream& is, MerkleAuthPath<HASH, BIT>& a) { a.marshal_in(is); return is; } //////////////////////////////////////////////////////////////////////////////// // typedefs // namespace zk { template <typename FR> using MerkleAuthPath_SHA256 = MerkleAuthPath<SHA256<FR>, bool_x<FR>>; template <typename FR> using MerkleAuthPath_SHA512 = MerkleAuthPath<SHA512<FR>, bool_x<FR>>; } // namespace zk namespace eval { typedef MerkleAuthPath<SHA256, int> MerkleAuthPath_SHA256; typedef MerkleAuthPath<SHA512, int> MerkleAuthPath_SHA512; } // namespace eval } // namespace snarkfront #endif <commit_msg>failed stream extraction will clear<commit_after>#ifndef _SNARKFRONT_MERKLE_AUTH_PATH_HPP_ #define _SNARKFRONT_MERKLE_AUTH_PATH_HPP_ #include <cstdint> #include <iostream> #include <istream> #include <ostream> #include <vector> #include "DSL_base.hpp" #include "DSL_bless.hpp" #include "DSL_utility.hpp" #include "PowersOf2.hpp" #include "SHA_256.hpp" #include "SHA_512.hpp" namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // authentication path from a binary Merkle tree // template <typename HASH, typename BIT> class MerkleAuthPath { public: typedef HASH HashType; typedef typename HASH::DigType DigType; MerkleAuthPath() : m_depth(0) {} // eval MerkleAuthPath(const std::size_t depth) : m_depth(depth), m_rootPath(depth) // first update initializes hash digests { m_siblings.reserve(depth); m_childBits.reserve(depth); for (std::size_t i = 0; i < depth; ++i) { m_siblings.emplace_back(zero()); m_childBits.emplace_back(0); } } // zk from eval template <typename OTHER_HASH, typename OTHER_BIT> MerkleAuthPath(const MerkleAuthPath<OTHER_HASH, OTHER_BIT>& other) : m_depth(other.depth()), m_rootPath(other.depth()) // first update initializes hash digests { m_siblings.reserve(other.depth()); for (const auto& a : other.siblings()) { DigType b; bless(b, a); m_siblings.emplace_back(b); } m_childBits.reserve(other.depth()); for (const auto& a : other.childBits()) { BIT b; bless(b, a); m_childBits.emplace_back(b); } } std::size_t depth() const { return m_depth; } const DigType& rootHash() const { return m_rootPath.back(); } // bottom-up order, index 0 is at the leaves of tree const std::vector<DigType>& rootPath() const { return m_rootPath; } const std::vector<DigType>& siblings() const { return m_siblings; } const std::vector<BIT>& childBits() const { return m_childBits; } // update hash codes along path back to root void updatePath(const DigType& leaf) { std::vector<MerkleAuthPath> dummy; updatePath(leaf, dummy); } // update hash codes along path back to root void updatePath(const DigType& leaf, std::vector<MerkleAuthPath>& oldPaths) { // root path overlap std::vector<int> overlap; overlap.reserve(oldPaths.size()); for (const auto& a : oldPaths) { overlap.push_back( matchMSB(m_childBits, a.childBits())); } HASH hashAlgo; auto dig = leaf; // ascend tree from leaf to root for (std::size_t i = 0; i < m_depth; ++i) { hashAlgo.clearMessage(); const auto& isRightChild = m_childBits[i]; const auto leftDigest = ternary(isRightChild, m_siblings[i], dig), rightDigest = ternary(isRightChild, dig, m_siblings[i]); hashAlgo.msgInput(leftDigest); hashAlgo.msgInput(rightDigest); hashAlgo.computeHash(); dig = m_rootPath[i] = hashAlgo.digest(); // path length from root to node with the new hash const int pathLen = m_depth - 1 - i; // update old authentication paths for (std::size_t j = 0; j < overlap.size(); ++j) { if (pathLen <= overlap[j]) { // update root path hashes oldPaths[j].m_rootPath[i] = dig; } else if (pathLen == overlap[j] + 1) { // update sibling hashes oldPaths[j].m_siblings[i + 1] = dig; } } } // update old authentication paths for (std::size_t j = 0; j < overlap.size(); ++j) { if (m_depth - 1 == overlap[j]) // differ in last bit only, leaf must be right sibling oldPaths[j].m_siblings[0] = leaf; } } // just added leaf becomes left sibling void leafSibling(const DigType& leaf) { m_siblings[0] = leaf; } // new branch in Merkle tree void hashSibling(const std::size_t index) { m_siblings[index] = m_rootPath[index - 1]; for (std::size_t i = 0; i < index; ++i) m_siblings[i] = zero(); } // returns index of first set bit (right child) int incChildBits() { for (std::size_t i = 0; i < m_depth; ++i) { auto& a = m_childBits[i]; if (bool(0 == a)) { // bit is zero, increment to one a = 1; return i; } else { // bit is one, increment to zero and carry a = 0; } } // increment all ones wraps back to zero with carry return -1; } void marshal_out(std::ostream& os) const { os << m_depth << std::endl << m_rootPath << m_siblings; for (const auto& a : m_childBits) { os << a << std::endl; } } bool marshal_in(std::istream& is) { m_depth = 0; // use as valid flag std::size_t len = 0; is >> len; if (!is || 0 == len) return false; m_rootPath.resize(len); is >> m_rootPath; if (!is) return false; m_siblings.resize(len); is >> m_siblings; if (!is) return false; m_childBits.resize(len); for (auto& r : m_childBits) { is >> r; if (!is) return false; } m_depth = len; return true; } void clear() { m_depth = 0; m_rootPath.clear(); m_siblings.clear(); m_childBits.clear(); } bool empty() const { return 0 == m_depth || m_rootPath.empty() || m_siblings.empty() || m_childBits.empty(); } private: // note: not called by proof generation static DigType zero() { return {0}; } std::size_t m_depth; // indices start from 0 at the leaves increasing up to the root std::vector<DigType> m_rootPath, m_siblings; // next available leaf element std::vector<BIT> m_childBits; }; template <typename HASH, typename BIT> std::ostream& operator<< (std::ostream& os, const MerkleAuthPath<HASH, BIT>& a) { a.marshal_out(os); return os; } template <typename HASH, typename BIT> std::istream& operator>> (std::istream& is, MerkleAuthPath<HASH, BIT>& a) { if (! a.marshal_in(is)) a.clear(); return is; } //////////////////////////////////////////////////////////////////////////////// // typedefs // namespace zk { template <typename FR> using MerkleAuthPath_SHA256 = MerkleAuthPath<SHA256<FR>, bool_x<FR>>; template <typename FR> using MerkleAuthPath_SHA512 = MerkleAuthPath<SHA512<FR>, bool_x<FR>>; } // namespace zk namespace eval { typedef MerkleAuthPath<SHA256, int> MerkleAuthPath_SHA256; typedef MerkleAuthPath<SHA512, int> MerkleAuthPath_SHA512; } // namespace eval } // namespace snarkfront #endif <|endoftext|>
<commit_before>/** * @file delegate.hpp * @author Robin Dietrich <me (at) invokr (dot) org> * @version 1.0 * * @par License * Alice Replay Parser * Copyright 2014 Robin Dietrich * * 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. * */ #ifndef _DOTA_DELEGATE_HPP_ #define _DOTA_DELEGATE_HPP_ #include <memory> #include <cstddef> namespace dota { /// @defgroup CORE Core /// @{ /** A simple and fast delegate implementation, performing magnitudes better than std::function or Callback. */ template <typename R, typename ... ARGS> class delegate { public: /** Constructor, 0's object and function pointer */ delegate() : pObj(nullptr), pFunc(nullptr) { } /** Default copy constructor. */ delegate(const delegate&) = default; /** Default destructor */ ~delegate() = default; /** Compares two delegates with each other */ bool operator== (delegate &d1) { return (d1.pObj == pObj && d1.pFunc == pFunc); } /** Redirects all arguments to the function called and returns it's result */ inline R operator()(ARGS... args) const { return (*pFunc)(pObj, std::move(args)...); } /** * Creates a delegate from a member function. * * An example call might look like this: * ::fromMemberFunc<object_, &object_::function_>(obj) */ template <typename T, R (T::*method)(ARGS...)> static delegate fromMemberFunc(T* pObj) { delegate ret; ret.pObj = pObj; ret.pFunc = &callFwd<T, method>; return ret; } private: /** Function signature of the delegate */ typedef R (*func)(void* obj, ARGS...); /** Pointer to object. */ void* pObj; /** Pointer to member function. */ func pFunc; /** Internally used to forward the function call. */ template <typename T, R (T::*method)(ARGS...)> static R callFwd(void* pObj, ARGS... args) { T* p = static_cast<T*>(pObj); return (p->*method)(std::forward<ARGS>(args)...); } }; /// @} } #endif /* _DOTA_DELEGATE_HPP_ */<commit_msg>Added move constructor to delegate<commit_after>/** * @file delegate.hpp * @author Robin Dietrich <me (at) invokr (dot) org> * @version 1.1 * * @par License * Alice Replay Parser * Copyright 2014 Robin Dietrich * * 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. * */ #ifndef _DOTA_DELEGATE_HPP_ #define _DOTA_DELEGATE_HPP_ #include <memory> #include <cstddef> namespace dota { /// @defgroup CORE Core /// @{ /** A simple and fast delegate implementation, performing magnitudes better than std::function or Callback. */ template <typename R, typename ... ARGS> class delegate { public: /** Constructor, zero's object and function pointer */ delegate() : pObj(nullptr), pFunc(nullptr) { } /** Default copy constructor. */ delegate(const delegate&) = default; /** Default destructor */ ~delegate() = default; /** Move constructor, zero's old object and function pointer */ delegate(delegate&& d) { pObj = d.pObj; pFunc = d.pFunc; d.pObj = nullptr; d.pFunc = nullptr; } /** Compares two delegates with each other */ bool operator== (delegate &d1) { return (d1.pObj == pObj && d1.pFunc == pFunc); } /** Redirects all arguments to the function called and returns it's result */ inline R operator()(ARGS... args) const { return (*pFunc)(pObj, std::move(args)...); } /** * Creates a delegate from a member function. * * An example call might look like this: * ::fromMemberFunc<object_, &object_::function_>(obj) */ template <typename T, R (T::*method)(ARGS...)> static delegate fromMemberFunc(T* pObj) { delegate ret; ret.pObj = pObj; ret.pFunc = &callFwd<T, method>; return ret; } private: /** Function signature of the delegate */ typedef R (*func)(void* obj, ARGS...); /** Pointer to object. */ void* pObj; /** Pointer to member function. */ func pFunc; /** Internally used to forward the function call. */ template <typename T, R (T::*method)(ARGS...)> static R callFwd(void* pObj, ARGS... args) { T* p = static_cast<T*>(pObj); return (p->*method)(std::forward<ARGS>(args)...); } }; /// @} } #endif /* _DOTA_DELEGATE_HPP_ */<|endoftext|>
<commit_before>/* dtkDistributedController.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Wed May 25 14:15:13 2011 (+0200) * Version: $Id$ * Last-Updated: ven. juil. 1 15:06:22 2011 (+0200) * By: Nicolas Niclausse * Update #: 478 */ /* Commentary: * */ /* Change log: * */ #include "dtkDistributedController.h" #include "dtkDistributedServerManager.h" #include "dtkDistributedCore.h" #include "dtkDistributedNode.h" #include "dtkDistributedCpu.h" #include "dtkDistributedGpu.h" #include <dtkCore/dtkGlobal.h> #include <dtkCore/dtkLog.h> #include <QtNetwork> #include <QtXml> class dtkDistributedControllerPrivate { public: QHash<QString, QTcpSocket *> sockets; QHash<QString, QList<dtkDistributedNode *> > nodes; }; dtkDistributedController::dtkDistributedController(void) : d(new dtkDistributedControllerPrivate) { } dtkDistributedController::~dtkDistributedController(void) { delete d; d = NULL; } bool dtkDistributedController::isConnected(const QUrl& server) { if(d->sockets.keys().contains(server.toString())) { QTcpSocket *socket = d->sockets.value(server.toString()); return (socket->state() == QAbstractSocket::ConnectedState); } return false; } bool dtkDistributedController::isDisconnected(const QUrl& server) { if(d->sockets.keys().contains(server.toString())) { QTcpSocket *socket = d->sockets.value(server.toString()); return (socket->state() == QAbstractSocket::UnconnectedState); } return true; } void dtkDistributedController::connect(const QUrl& server) { if(!d->sockets.keys().contains(server.toString())) { QTcpSocket *socket = new QTcpSocket(this); socket->connectToHost(server.host(), server.port()); if(socket->waitForConnected()) { QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(read())); QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError))); d->sockets.insert(server.toString(), socket); emit connected(server); socket->write("** status **"); } else { qDebug() << "Unable to connect to" << server.toString(); } } } void dtkDistributedController::disconnect(const QUrl& server) { if(d->sockets.keys().contains(server.toString())) { QTcpSocket *socket = d->sockets.value(server.toString()); socket->disconnectFromHost(); d->sockets.remove(server.toString()); emit disconnected(server); } } void dtkDistributedController::read(void) { QTcpSocket *socket = (QTcpSocket *)sender(); static QString status_contents; QString buffer = socket->readAll(); if(buffer.startsWith("!! status !!")) { status_contents.clear(); status_contents += buffer.remove("!! status !!"); } if(buffer.endsWith("!! endstatus !!")) { if(!buffer.startsWith("version="+dtkDistributedServerManager::protocol())) { qDebug() << "WARNING: Bad protocol version"; } status_contents = buffer.remove("!! endstatus !!"); QStringList nodes = status_contents.split("\n"); // skip the first item (version=XXX), so start at 1 : for(int i = 1; i < nodes.size(); i++) { QStringList nodestr = nodes.at(i).split(";"); if (nodestr.size() < 9) { qDebug() << "Skipping line "; continue; } QString name = nodestr.at(0); int ncores = nodestr.at(1).toInt(); int usedcores = nodestr.at(2).toInt(); int ncpus = nodestr.at(3).toInt(); int ngpus = nodestr.at(4).toInt(); int usedgpus = nodestr.at(5).toInt(); QString state = nodestr.at(7); QStringList properties = nodestr.at(6).split(","); dtkDistributedNode *node = new dtkDistributedNode; node->setName(name); if(state == "free") node->setState(dtkDistributedNode::Free); if(state == "busy") node->setState(dtkDistributedNode::Busy); if(state == "down") node->setState(dtkDistributedNode::Down); if(properties.contains("dell")) node->setBrand(dtkDistributedNode::Dell); if(properties.contains("hp")) node->setBrand(dtkDistributedNode::Hp); if(properties.contains("ibm")) node->setBrand(dtkDistributedNode::Ibm); if(properties.contains("myrinet")) node->setNetwork(dtkDistributedNode::Myrinet10G); else if(properties.contains("QDR")) node->setNetwork(dtkDistributedNode::Infiniband40G); else node->setNetwork(dtkDistributedNode::Ethernet1G); if(properties.contains("gpu")) for(int i = 0; i < ngpus; i++) { dtkDistributedGpu *gpu = new dtkDistributedGpu(node); if(properties.contains("nvidia-T10")) gpu->setModel(dtkDistributedGpu::T10); else if(properties.contains("nvidia-C2050")) gpu->setModel(dtkDistributedGpu::C2050); else if(properties.contains("nvidia-C2070")) gpu->setModel(dtkDistributedGpu::C2070); if(properties.contains("nvidia")) gpu->setArchitecture(dtkDistributedGpu::Nvidia); if(properties.contains("amd")) gpu->setArchitecture(dtkDistributedGpu::AMD); *node << gpu; } for(int i = 0; i < ncpus; i++) { dtkDistributedCpu *cpu = new dtkDistributedCpu(node); int cores = ncores / ncpus; cpu->setCardinality(cores); if(properties.contains("x86")) cpu->setArchitecture(dtkDistributedCpu::x86); else cpu->setArchitecture(dtkDistributedCpu::x86_64); if(properties.contains("opteron")) cpu->setModel(dtkDistributedCpu::Opteron); if(properties.contains("xeon")) cpu->setModel(dtkDistributedCpu::Xeon); for(int j = 0; j < cores; j++) *cpu << new dtkDistributedCore(cpu); *node << cpu; } d->nodes[d->sockets.key(socket)] << node; qDebug() << "Found node" << node->name() << "with" << node->cpus().count() << "cpus"; } status_contents.clear(); } } void dtkDistributedController::error(QAbstractSocket::SocketError error) { switch(error) { case QAbstractSocket::ConnectionRefusedError: qDebug() << DTK_PRETTY_FUNCTION << "The connection was refused by the peer (or timed out)."; break; case QAbstractSocket::RemoteHostClosedError: qDebug() << DTK_PRETTY_FUNCTION << "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."; break; case QAbstractSocket::HostNotFoundError: qDebug() << DTK_PRETTY_FUNCTION << "The host address was not found."; break; case QAbstractSocket::SocketAccessError: qDebug() << DTK_PRETTY_FUNCTION << "The socket operation failed because the application lacked the required privileges."; break; case QAbstractSocket::SocketResourceError: qDebug() << DTK_PRETTY_FUNCTION << "The local system ran out of resources (e.g., too many sockets)."; break; case QAbstractSocket::SocketTimeoutError: qDebug() << DTK_PRETTY_FUNCTION << "The socket operation timed out."; break; case QAbstractSocket::DatagramTooLargeError: qDebug() << DTK_PRETTY_FUNCTION << "The datagram was larger than the operating system's limit (which can be as low as 8192 bytes)."; break; case QAbstractSocket::NetworkError: qDebug() << DTK_PRETTY_FUNCTION << "An error occurred with the network (e.g., the network cable was accidentally plugged out)."; break; case QAbstractSocket::AddressInUseError: qDebug() << DTK_PRETTY_FUNCTION << "The address specified to QUdpSocket::bind() is already in use and was set to be exclusive."; break; case QAbstractSocket::SocketAddressNotAvailableError: qDebug() << DTK_PRETTY_FUNCTION << "The address specified to QUdpSocket::bind() does not belong to the host."; break; case QAbstractSocket::UnsupportedSocketOperationError: qDebug() << DTK_PRETTY_FUNCTION << "The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support)."; break; case QAbstractSocket::ProxyAuthenticationRequiredError: qDebug() << DTK_PRETTY_FUNCTION << "The socket is using a proxy, and the proxy requires authentication."; break; case QAbstractSocket::SslHandshakeFailedError: qDebug() << DTK_PRETTY_FUNCTION << "The SSL/TLS handshake failed, so the connection was closed (only used in QSslSocket)"; break; case QAbstractSocket::UnfinishedSocketOperationError: qDebug() << DTK_PRETTY_FUNCTION << "Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background)."; break; case QAbstractSocket::ProxyConnectionRefusedError: qDebug() << DTK_PRETTY_FUNCTION << "Could not contact the proxy server because the connection to that server was denied"; break; case QAbstractSocket::ProxyConnectionClosedError: qDebug() << DTK_PRETTY_FUNCTION << "The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)"; break; case QAbstractSocket::ProxyConnectionTimeoutError: qDebug() << DTK_PRETTY_FUNCTION << "The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase."; break; case QAbstractSocket::ProxyNotFoundError: qDebug() << DTK_PRETTY_FUNCTION << "The proxy address set with setProxy() (or the application proxy) was not found."; break; case QAbstractSocket::ProxyProtocolError: qDebug() << DTK_PRETTY_FUNCTION << "The connection negotiation with the proxy server because the response from the proxy server could not be understood."; break; case QAbstractSocket::UnknownSocketError: qDebug() << DTK_PRETTY_FUNCTION << "An unidentified error occurred."; break; default: break; } } <commit_msg>status output has 8 columns, not 9<commit_after>/* dtkDistributedController.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Wed May 25 14:15:13 2011 (+0200) * Version: $Id$ * Last-Updated: ven. juil. 1 15:09:38 2011 (+0200) * By: Nicolas Niclausse * Update #: 479 */ /* Commentary: * */ /* Change log: * */ #include "dtkDistributedController.h" #include "dtkDistributedServerManager.h" #include "dtkDistributedCore.h" #include "dtkDistributedNode.h" #include "dtkDistributedCpu.h" #include "dtkDistributedGpu.h" #include <dtkCore/dtkGlobal.h> #include <dtkCore/dtkLog.h> #include <QtNetwork> #include <QtXml> class dtkDistributedControllerPrivate { public: QHash<QString, QTcpSocket *> sockets; QHash<QString, QList<dtkDistributedNode *> > nodes; }; dtkDistributedController::dtkDistributedController(void) : d(new dtkDistributedControllerPrivate) { } dtkDistributedController::~dtkDistributedController(void) { delete d; d = NULL; } bool dtkDistributedController::isConnected(const QUrl& server) { if(d->sockets.keys().contains(server.toString())) { QTcpSocket *socket = d->sockets.value(server.toString()); return (socket->state() == QAbstractSocket::ConnectedState); } return false; } bool dtkDistributedController::isDisconnected(const QUrl& server) { if(d->sockets.keys().contains(server.toString())) { QTcpSocket *socket = d->sockets.value(server.toString()); return (socket->state() == QAbstractSocket::UnconnectedState); } return true; } void dtkDistributedController::connect(const QUrl& server) { if(!d->sockets.keys().contains(server.toString())) { QTcpSocket *socket = new QTcpSocket(this); socket->connectToHost(server.host(), server.port()); if(socket->waitForConnected()) { QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(read())); QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError))); d->sockets.insert(server.toString(), socket); emit connected(server); socket->write("** status **"); } else { qDebug() << "Unable to connect to" << server.toString(); } } } void dtkDistributedController::disconnect(const QUrl& server) { if(d->sockets.keys().contains(server.toString())) { QTcpSocket *socket = d->sockets.value(server.toString()); socket->disconnectFromHost(); d->sockets.remove(server.toString()); emit disconnected(server); } } void dtkDistributedController::read(void) { QTcpSocket *socket = (QTcpSocket *)sender(); static QString status_contents; QString buffer = socket->readAll(); if(buffer.startsWith("!! status !!")) { status_contents.clear(); status_contents += buffer.remove("!! status !!"); } if(buffer.endsWith("!! endstatus !!")) { if(!buffer.startsWith("version="+dtkDistributedServerManager::protocol())) { qDebug() << "WARNING: Bad protocol version"; } status_contents = buffer.remove("!! endstatus !!"); QStringList nodes = status_contents.split("\n"); // skip the first item (version=XXX), so start at 1 : for(int i = 1; i < nodes.size(); i++) { QStringList nodestr = nodes.at(i).split(";"); if (nodestr.size() < 8) { qDebug() << "Skipping line "; continue; } QString name = nodestr.at(0); int ncores = nodestr.at(1).toInt(); int usedcores = nodestr.at(2).toInt(); int ncpus = nodestr.at(3).toInt(); int ngpus = nodestr.at(4).toInt(); int usedgpus = nodestr.at(5).toInt(); QString state = nodestr.at(7); QStringList properties = nodestr.at(6).split(","); dtkDistributedNode *node = new dtkDistributedNode; node->setName(name); if(state == "free") node->setState(dtkDistributedNode::Free); if(state == "busy") node->setState(dtkDistributedNode::Busy); if(state == "down") node->setState(dtkDistributedNode::Down); if(properties.contains("dell")) node->setBrand(dtkDistributedNode::Dell); if(properties.contains("hp")) node->setBrand(dtkDistributedNode::Hp); if(properties.contains("ibm")) node->setBrand(dtkDistributedNode::Ibm); if(properties.contains("myrinet")) node->setNetwork(dtkDistributedNode::Myrinet10G); else if(properties.contains("QDR")) node->setNetwork(dtkDistributedNode::Infiniband40G); else node->setNetwork(dtkDistributedNode::Ethernet1G); if(properties.contains("gpu")) for(int i = 0; i < ngpus; i++) { dtkDistributedGpu *gpu = new dtkDistributedGpu(node); if(properties.contains("nvidia-T10")) gpu->setModel(dtkDistributedGpu::T10); else if(properties.contains("nvidia-C2050")) gpu->setModel(dtkDistributedGpu::C2050); else if(properties.contains("nvidia-C2070")) gpu->setModel(dtkDistributedGpu::C2070); if(properties.contains("nvidia")) gpu->setArchitecture(dtkDistributedGpu::Nvidia); if(properties.contains("amd")) gpu->setArchitecture(dtkDistributedGpu::AMD); *node << gpu; } for(int i = 0; i < ncpus; i++) { dtkDistributedCpu *cpu = new dtkDistributedCpu(node); int cores = ncores / ncpus; cpu->setCardinality(cores); if(properties.contains("x86")) cpu->setArchitecture(dtkDistributedCpu::x86); else cpu->setArchitecture(dtkDistributedCpu::x86_64); if(properties.contains("opteron")) cpu->setModel(dtkDistributedCpu::Opteron); if(properties.contains("xeon")) cpu->setModel(dtkDistributedCpu::Xeon); for(int j = 0; j < cores; j++) *cpu << new dtkDistributedCore(cpu); *node << cpu; } d->nodes[d->sockets.key(socket)] << node; qDebug() << "Found node" << node->name() << "with" << node->cpus().count() << "cpus"; } status_contents.clear(); } } void dtkDistributedController::error(QAbstractSocket::SocketError error) { switch(error) { case QAbstractSocket::ConnectionRefusedError: qDebug() << DTK_PRETTY_FUNCTION << "The connection was refused by the peer (or timed out)."; break; case QAbstractSocket::RemoteHostClosedError: qDebug() << DTK_PRETTY_FUNCTION << "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."; break; case QAbstractSocket::HostNotFoundError: qDebug() << DTK_PRETTY_FUNCTION << "The host address was not found."; break; case QAbstractSocket::SocketAccessError: qDebug() << DTK_PRETTY_FUNCTION << "The socket operation failed because the application lacked the required privileges."; break; case QAbstractSocket::SocketResourceError: qDebug() << DTK_PRETTY_FUNCTION << "The local system ran out of resources (e.g., too many sockets)."; break; case QAbstractSocket::SocketTimeoutError: qDebug() << DTK_PRETTY_FUNCTION << "The socket operation timed out."; break; case QAbstractSocket::DatagramTooLargeError: qDebug() << DTK_PRETTY_FUNCTION << "The datagram was larger than the operating system's limit (which can be as low as 8192 bytes)."; break; case QAbstractSocket::NetworkError: qDebug() << DTK_PRETTY_FUNCTION << "An error occurred with the network (e.g., the network cable was accidentally plugged out)."; break; case QAbstractSocket::AddressInUseError: qDebug() << DTK_PRETTY_FUNCTION << "The address specified to QUdpSocket::bind() is already in use and was set to be exclusive."; break; case QAbstractSocket::SocketAddressNotAvailableError: qDebug() << DTK_PRETTY_FUNCTION << "The address specified to QUdpSocket::bind() does not belong to the host."; break; case QAbstractSocket::UnsupportedSocketOperationError: qDebug() << DTK_PRETTY_FUNCTION << "The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support)."; break; case QAbstractSocket::ProxyAuthenticationRequiredError: qDebug() << DTK_PRETTY_FUNCTION << "The socket is using a proxy, and the proxy requires authentication."; break; case QAbstractSocket::SslHandshakeFailedError: qDebug() << DTK_PRETTY_FUNCTION << "The SSL/TLS handshake failed, so the connection was closed (only used in QSslSocket)"; break; case QAbstractSocket::UnfinishedSocketOperationError: qDebug() << DTK_PRETTY_FUNCTION << "Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background)."; break; case QAbstractSocket::ProxyConnectionRefusedError: qDebug() << DTK_PRETTY_FUNCTION << "Could not contact the proxy server because the connection to that server was denied"; break; case QAbstractSocket::ProxyConnectionClosedError: qDebug() << DTK_PRETTY_FUNCTION << "The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)"; break; case QAbstractSocket::ProxyConnectionTimeoutError: qDebug() << DTK_PRETTY_FUNCTION << "The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase."; break; case QAbstractSocket::ProxyNotFoundError: qDebug() << DTK_PRETTY_FUNCTION << "The proxy address set with setProxy() (or the application proxy) was not found."; break; case QAbstractSocket::ProxyProtocolError: qDebug() << DTK_PRETTY_FUNCTION << "The connection negotiation with the proxy server because the response from the proxy server could not be understood."; break; case QAbstractSocket::UnknownSocketError: qDebug() << DTK_PRETTY_FUNCTION << "An unidentified error occurred."; break; default: break; } } <|endoftext|>
<commit_before>/* * Copyright 2017-2019 Leonid Yuriev <leo@yuriev.ru> * and other libmdbx authors: please see AUTHORS file. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ #include "test.h" #include <cmath> #include <queue> static unsigned edge2count(uint64_t edge, unsigned count_max) { const double rnd = u64_to_double1(prng64_map1_white(edge)); const unsigned count = std::lrint(std::pow(count_max, rnd)); return count; } static unsigned edge2window(uint64_t edge, unsigned window_max) { const double rnd = u64_to_double1(prng64_map2_white(edge)); const unsigned window = window_max - std::lrint(std::pow(window_max, rnd)); return window - (window > 0); } bool testcase_ttl::run() { db_open(); txn_begin(false); MDBX_dbi dbi = db_table_open(true); int rc = mdbx_drop(txn_guard.get(), dbi, false); if (unlikely(rc != MDBX_SUCCESS)) failure_perror("mdbx_drop(delete=false)", rc); txn_end(false); /* LY: тест "эмуляцией time-to-live": * - организуется "скользящее окно", которое двигается вперед вдоль * числовой оси каждую транзакцию. * - по переднему краю "скользящего окна" записи добавляются в таблицу, * а по заднему удаляются. * - количество добавляемых/удаляемых записей псевдослучайно зависит * от номера транзакции, но с экспоненциальным распределением. * - размер "скользящего окна" также псевдослучайно зависит от номера * транзакции с "отрицательным" экспоненциальным распределением * MAX_WIDTH - exp(rnd(N)), при уменьшении окна сдвигается задний * край и удаляются записи позади него. * * Таким образом имитируется поведение таблицы с TTL: записи стохастически * добавляются и удаляются, но изредка происходят массивные удаления. */ /* LY: для параметризации используем подходящие параметры, которые не имеют * здесь смысла в первоначальном значении */ const unsigned window_max = (config.params.batch_read > 999) ? config.params.batch_read : 1000; const unsigned count_max = (config.params.batch_write > 999) ? config.params.batch_write : 1000; log_info("ttl: using `batch_read` value %u for window_max", window_max); log_info("ttl: using `batch_write` value %u for count_max", count_max); keyvalue_maker.setup(config.params, config.actor_id, 0 /* thread_number */); key = keygen::alloc(config.params.keylen_max); data = keygen::alloc(config.params.datalen_max); const unsigned insert_flags = (config.params.table_flags & MDBX_DUPSORT) ? MDBX_NODUPDATA : MDBX_NODUPDATA | MDBX_NOOVERWRITE; std::queue<std::pair<uint64_t, unsigned>> fifo; uint64_t serial = 0; while (should_continue()) { if (!txn_guard) txn_begin(false); const uint64_t salt = mdbx_txn_id(txn_guard.get()); const unsigned window = edge2window(salt, window_max); log_trace("ttl: window %u at %" PRIu64, window, salt); while (fifo.size() > window) { uint64_t tail_serial = fifo.front().first; const unsigned tail_count = fifo.front().second; log_trace("ttl: pop-tail (serial %" PRIu64 ", count %u)", tail_serial, tail_count); fifo.pop(); for (unsigned n = 0; n < tail_count; ++n) { log_trace("ttl: remove-tail %" PRIu64, serial); generate_pair(tail_serial); int err = mdbx_del(txn_guard.get(), dbi, &key->value, &data->value); if (unlikely(err != MDBX_SUCCESS)) failure_perror("mdbx_del(tail)", err); if (unlikely(!keyvalue_maker.increment(tail_serial, 1))) failure("ttl: unexpected key-space overflow on the tail"); } } txn_restart(false, false); const unsigned head_count = edge2count(salt, count_max); fifo.push(std::make_pair(serial, head_count)); log_trace("ttl: push-head (serial %" PRIu64 ", count %u)", serial, head_count); for (unsigned n = 0; n < head_count; ++n) { log_trace("ttl: insert-head %" PRIu64, serial); generate_pair(serial); int err = mdbx_put(txn_guard.get(), dbi, &key->value, &data->value, insert_flags); if (unlikely(err != MDBX_SUCCESS)) failure_perror("mdbx_put(head)", err); if (unlikely(!keyvalue_maker.increment(serial, 1))) failure("uphill: unexpected key-space overflow"); } txn_end(false); report(1); } if (dbi) { if (config.params.drop_table && !mode_readonly()) { txn_begin(false); db_table_drop(dbi); txn_end(false); } else db_table_close(dbi); } return true; } <commit_msg>mdbx-test: use common keygen-seed for `ttl` testcase.<commit_after>/* * Copyright 2017-2019 Leonid Yuriev <leo@yuriev.ru> * and other libmdbx authors: please see AUTHORS file. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ #include "test.h" #include <cmath> #include <queue> static unsigned edge2window(uint64_t edge, unsigned window_max) { const double rnd = u64_to_double1(bleach64(edge)); const unsigned window = window_max - std::lrint(std::pow(window_max, rnd)); return window - (window > 0); } static unsigned edge2count(uint64_t edge, unsigned count_max) { const double rnd = u64_to_double1(prng64_map1_white(edge)); const unsigned count = std::lrint(std::pow(count_max, rnd)); return count; } bool testcase_ttl::run() { db_open(); txn_begin(false); MDBX_dbi dbi = db_table_open(true); int rc = mdbx_drop(txn_guard.get(), dbi, false); if (unlikely(rc != MDBX_SUCCESS)) failure_perror("mdbx_drop(delete=false)", rc); txn_end(false); /* LY: тест "эмуляцией time-to-live": * - организуется "скользящее окно", которое двигается вперед вдоль * числовой оси каждую транзакцию. * - по переднему краю "скользящего окна" записи добавляются в таблицу, * а по заднему удаляются. * - количество добавляемых/удаляемых записей псевдослучайно зависит * от номера транзакции, но с экспоненциальным распределением. * - размер "скользящего окна" также псевдослучайно зависит от номера * транзакции с "отрицательным" экспоненциальным распределением * MAX_WIDTH - exp(rnd(N)), при уменьшении окна сдвигается задний * край и удаляются записи позади него. * * Таким образом имитируется поведение таблицы с TTL: записи стохастически * добавляются и удаляются, но изредка происходят массивные удаления. */ /* LY: для параметризации используем подходящие параметры, которые не имеют * здесь смысла в первоначальном значении */ const unsigned window_max = (config.params.batch_read > 999) ? config.params.batch_read : 1000; const unsigned count_max = (config.params.batch_write > 999) ? config.params.batch_write : 1000; log_info("ttl: using `batch_read` value %u for window_max", window_max); log_info("ttl: using `batch_write` value %u for count_max", count_max); uint64_t seed = prng64_map2_white(config.params.keygen.seed) + config.actor_id; keyvalue_maker.setup(config.params, config.actor_id, 0 /* thread_number */); key = keygen::alloc(config.params.keylen_max); data = keygen::alloc(config.params.datalen_max); const unsigned insert_flags = (config.params.table_flags & MDBX_DUPSORT) ? MDBX_NODUPDATA : MDBX_NODUPDATA | MDBX_NOOVERWRITE; std::queue<std::pair<uint64_t, unsigned>> fifo; uint64_t serial = 0; while (should_continue()) { if (!txn_guard) txn_begin(false); const uint64_t salt = prng64_white(seed)/* mdbx_txn_id(txn_guard.get()) */; const unsigned window = edge2window(salt, window_max); log_trace("ttl: window %u at %" PRIu64, window, salt); while (fifo.size() > window) { uint64_t tail_serial = fifo.front().first; const unsigned tail_count = fifo.front().second; log_trace("ttl: pop-tail (serial %" PRIu64 ", count %u)", tail_serial, tail_count); fifo.pop(); for (unsigned n = 0; n < tail_count; ++n) { log_trace("ttl: remove-tail %" PRIu64, serial); generate_pair(tail_serial); int err = mdbx_del(txn_guard.get(), dbi, &key->value, &data->value); if (unlikely(err != MDBX_SUCCESS)) failure_perror("mdbx_del(tail)", err); if (unlikely(!keyvalue_maker.increment(tail_serial, 1))) failure("ttl: unexpected key-space overflow on the tail"); } } txn_restart(false, false); const unsigned head_count = edge2count(salt, count_max); fifo.push(std::make_pair(serial, head_count)); log_trace("ttl: push-head (serial %" PRIu64 ", count %u)", serial, head_count); for (unsigned n = 0; n < head_count; ++n) { log_trace("ttl: insert-head %" PRIu64, serial); generate_pair(serial); int err = mdbx_put(txn_guard.get(), dbi, &key->value, &data->value, insert_flags); if (unlikely(err != MDBX_SUCCESS)) failure_perror("mdbx_put(head)", err); if (unlikely(!keyvalue_maker.increment(serial, 1))) failure("uphill: unexpected key-space overflow"); } txn_end(false); report(1); } if (dbi) { if (config.params.drop_table && !mode_readonly()) { txn_begin(false); db_table_drop(dbi); txn_end(false); } else db_table_close(dbi); } return true; } <|endoftext|>
<commit_before>// SciTE - Scintilla based Text Editor // LexBullant.cxx - lexer for Bullant #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static int classifyWordBullant(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { char s[100]; for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) { s[i] = static_cast<char>(tolower(styler[start + i])); s[i + 1] = '\0'; } int lev= 0; char chAttr = SCE_C_IDENTIFIER; if (isdigit(s[0]) || (s[0] == '.')){ chAttr = SCE_C_NUMBER; } else { if (keywords.InList(s)) { chAttr = SCE_C_WORD; /* if (strcmp(s, "end method") == 0 || strcmp(s, "end case") == 0 || strcmp(s, "end class") == 0 || strcmp(s, "end debug") == 0 || strcmp(s, "end test") == 0 || strcmp(s, "end if") == 0 || strcmp(s, "end lock") == 0 || strcmp(s, "end transaction") == 0 || strcmp(s, "end trap") == 0 || strcmp(s, "end until") == 0 || strcmp(s, "end while") == 0) lev = -1;*/ if (strcmp(s, "end") == 0) lev = -1; else if (strcmp(s, "method") == 0 || strcmp(s, "case") == 0 || strcmp(s, "class") == 0 || strcmp(s, "debug") == 0 || strcmp(s, "test") == 0 || strcmp(s, "if") == 0 || strcmp(s, "lock") == 0 || strcmp(s, "transaction") == 0 || strcmp(s, "trap") == 0 || strcmp(s, "until") == 0 || strcmp(s, "while") == 0) lev = 1; } } styler.ColourTo(end, chAttr); return lev; } static void ColouriseBullantDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); bool fold = styler.GetPropertyInt("fold") != 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; int state = initStyle; if (state == SCE_C_STRINGEOL) // Does not leak onto next line state = SCE_C_DEFAULT; char chPrev = ' '; char chNext = styler[startPos]; unsigned int lengthDoc = startPos + length; int visibleChars = 0; // int blockChange = 0; styler.StartSegment(startPos); int endFoundThisLine = 0; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if ((ch == '\r' && chNext != '\n') || (ch == '\n')) { // Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix) // Avoid triggering two times on Dos/Win // End of line endFoundThisLine = 0; if (state == SCE_C_STRINGEOL) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } if (fold) { int lev = levelPrev; if (visibleChars == 0) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; styler.SetLevel(lineCurrent, lev); lineCurrent++; levelPrev = levelCurrent; } visibleChars = 0; /* int indentBlock = GetLineIndentation(lineCurrent); if (blockChange==1){ lineCurrent++; int pos=SetLineIndentation(lineCurrent, indentBlock + indentSize); } else if (blockChange==-1) { indentBlock -= indentSize; if (indentBlock < 0) indentBlock = 0; SetLineIndentation(lineCurrent, indentBlock); lineCurrent++; } blockChange=0; */ } if (!isspace(ch)) visibleChars++; if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); chPrev = ' '; i += 1; continue; } if (state == SCE_C_DEFAULT) { if (iswordstart(ch)) { styler.ColourTo(i-1, state); state = SCE_C_IDENTIFIER; } else if (ch == '@' && chNext == 'o') { if ((styler.SafeGetCharAt(i+2) =='f') && (styler.SafeGetCharAt(i+3) == 'f')) { styler.ColourTo(i-1, state); state = SCE_C_COMMENT; } } else if (ch == '#') { styler.ColourTo(i-1, state); state = SCE_C_COMMENTLINE; } else if (ch == '\"') { styler.ColourTo(i-1, state); state = SCE_C_STRING; } else if (ch == '\'') { styler.ColourTo(i-1, state); state = SCE_C_CHARACTER; } else if (isoperator(ch)) { styler.ColourTo(i-1, state); styler.ColourTo(i, SCE_C_OPERATOR); } } else if (state == SCE_C_IDENTIFIER) { if (!iswordchar(ch)) { int levelChange = classifyWordBullant(styler.GetStartSegment(), i - 1, keywords, styler); state = SCE_C_DEFAULT; chNext = styler.SafeGetCharAt(i + 1); if (ch == '#') { state = SCE_C_COMMENTLINE; } else if (ch == '\"') { state = SCE_C_STRING; } else if (ch == '\'') { state = SCE_C_CHARACTER; } else if (isoperator(ch)) { styler.ColourTo(i, SCE_C_OPERATOR); } if (endFoundThisLine == 0) levelCurrent+=levelChange; if (levelChange == -1) endFoundThisLine=1; } } else if (state == SCE_C_COMMENT) { if (ch == '@' && chNext == 'o') { if (styler.SafeGetCharAt(i+2) == 'n') { styler.ColourTo(i+2, state); state = SCE_C_DEFAULT; i+=2; } } } else if (state == SCE_C_COMMENTLINE) { if (ch == '\r' || ch == '\n') { endFoundThisLine = 0; styler.ColourTo(i-1, state); state = SCE_C_DEFAULT; } } else if (state == SCE_C_STRING) { if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\"') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } else if (chNext == '\r' || chNext == '\n') { endFoundThisLine = 0; styler.ColourTo(i-1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } } else if (state == SCE_C_CHARACTER) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { endFoundThisLine = 0; styler.ColourTo(i-1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } else if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\'') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } chPrev = ch; } styler.ColourTo(lengthDoc - 1, state); // Fill in the real level of the next line, keeping the current flags as they will be filled in later if (fold) { int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; //styler.SetLevel(lineCurrent, levelCurrent | flagsNext); styler.SetLevel(lineCurrent, levelPrev | flagsNext); } } LexerModule lmBullant(SCLEX_BULLANT, ColouriseBullantDoc, "bullant"); <commit_msg>Upgraded keyword list descriptions from Brian Quinlan.<commit_after>// SciTE - Scintilla based Text Editor // LexBullant.cxx - lexer for Bullant #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static int classifyWordBullant(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { char s[100]; for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) { s[i] = static_cast<char>(tolower(styler[start + i])); s[i + 1] = '\0'; } int lev= 0; char chAttr = SCE_C_IDENTIFIER; if (isdigit(s[0]) || (s[0] == '.')){ chAttr = SCE_C_NUMBER; } else { if (keywords.InList(s)) { chAttr = SCE_C_WORD; if (strcmp(s, "end") == 0) lev = -1; else if (strcmp(s, "method") == 0 || strcmp(s, "case") == 0 || strcmp(s, "class") == 0 || strcmp(s, "debug") == 0 || strcmp(s, "test") == 0 || strcmp(s, "if") == 0 || strcmp(s, "lock") == 0 || strcmp(s, "transaction") == 0 || strcmp(s, "trap") == 0 || strcmp(s, "until") == 0 || strcmp(s, "while") == 0) lev = 1; } } styler.ColourTo(end, chAttr); return lev; } static void ColouriseBullantDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); bool fold = styler.GetPropertyInt("fold") != 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; int state = initStyle; if (state == SCE_C_STRINGEOL) // Does not leak onto next line state = SCE_C_DEFAULT; char chPrev = ' '; char chNext = styler[startPos]; unsigned int lengthDoc = startPos + length; int visibleChars = 0; styler.StartSegment(startPos); int endFoundThisLine = 0; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if ((ch == '\r' && chNext != '\n') || (ch == '\n')) { // Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix) // Avoid triggering two times on Dos/Win // End of line endFoundThisLine = 0; if (state == SCE_C_STRINGEOL) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } if (fold) { int lev = levelPrev; if (visibleChars == 0) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; styler.SetLevel(lineCurrent, lev); lineCurrent++; levelPrev = levelCurrent; } visibleChars = 0; /* int indentBlock = GetLineIndentation(lineCurrent); if (blockChange==1){ lineCurrent++; int pos=SetLineIndentation(lineCurrent, indentBlock + indentSize); } else if (blockChange==-1) { indentBlock -= indentSize; if (indentBlock < 0) indentBlock = 0; SetLineIndentation(lineCurrent, indentBlock); lineCurrent++; } blockChange=0; */ } if (!isspace(ch)) visibleChars++; if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); chPrev = ' '; i += 1; continue; } if (state == SCE_C_DEFAULT) { if (iswordstart(ch)) { styler.ColourTo(i-1, state); state = SCE_C_IDENTIFIER; } else if (ch == '@' && chNext == 'o') { if ((styler.SafeGetCharAt(i+2) =='f') && (styler.SafeGetCharAt(i+3) == 'f')) { styler.ColourTo(i-1, state); state = SCE_C_COMMENT; } } else if (ch == '#') { styler.ColourTo(i-1, state); state = SCE_C_COMMENTLINE; } else if (ch == '\"') { styler.ColourTo(i-1, state); state = SCE_C_STRING; } else if (ch == '\'') { styler.ColourTo(i-1, state); state = SCE_C_CHARACTER; } else if (isoperator(ch)) { styler.ColourTo(i-1, state); styler.ColourTo(i, SCE_C_OPERATOR); } } else if (state == SCE_C_IDENTIFIER) { if (!iswordchar(ch)) { int levelChange = classifyWordBullant(styler.GetStartSegment(), i - 1, keywords, styler); state = SCE_C_DEFAULT; chNext = styler.SafeGetCharAt(i + 1); if (ch == '#') { state = SCE_C_COMMENTLINE; } else if (ch == '\"') { state = SCE_C_STRING; } else if (ch == '\'') { state = SCE_C_CHARACTER; } else if (isoperator(ch)) { styler.ColourTo(i, SCE_C_OPERATOR); } if (endFoundThisLine == 0) levelCurrent+=levelChange; if (levelChange == -1) endFoundThisLine=1; } } else if (state == SCE_C_COMMENT) { if (ch == '@' && chNext == 'o') { if (styler.SafeGetCharAt(i+2) == 'n') { styler.ColourTo(i+2, state); state = SCE_C_DEFAULT; i+=2; } } } else if (state == SCE_C_COMMENTLINE) { if (ch == '\r' || ch == '\n') { endFoundThisLine = 0; styler.ColourTo(i-1, state); state = SCE_C_DEFAULT; } } else if (state == SCE_C_STRING) { if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\"') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } else if (chNext == '\r' || chNext == '\n') { endFoundThisLine = 0; styler.ColourTo(i-1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } } else if (state == SCE_C_CHARACTER) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { endFoundThisLine = 0; styler.ColourTo(i-1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } else if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\'') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } chPrev = ch; } styler.ColourTo(lengthDoc - 1, state); // Fill in the real level of the next line, keeping the current flags as they will be filled in later if (fold) { int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; //styler.SetLevel(lineCurrent, levelCurrent | flagsNext); styler.SetLevel(lineCurrent, levelPrev | flagsNext); } } static const char * const bullantWordListDesc[] = { "Keywords", 0 }; LexerModule lmBullant(SCLEX_BULLANT, ColouriseBullantDoc, "bullant", 0, bullantWordListDesc); <|endoftext|>
<commit_before>#include <cstdlib> #include <ctime> #include <clocale> #include <iostream> #include <vector> #include <glibmm.h> #include <libiqxmlrpc/libiqxmlrpc.h> #include <libiqxmlrpc/client.h> #include <libiqxmlrpc/http_client.h> #include "LiveJournal.h" #include "Config.h" #include "Event.h" using namespace iqxmlrpc; LiveJournal::LiveJournal() { setlocale(LC_ALL, ""); this->config = new Config(); //std::string(getenv("HOME")) + "/.ecru/default.conf"); this->client = new Client<Http_client_connection>(iqnet::Inet_addr("livejournal.com", 80), "/interface/xmlrpc"); username = this->config->queryConfigProperty("config.account.login"); passwd = this->config->queryConfigProperty("config.account.password"); } std::string LiveJournal::decodeTextValue(const iqxmlrpc::Value *value) { std::cout << "decodeTextValue, type = " << value->is_string() << endl; } string LiveJournal::postEvent(string event, string subject) { login(); string login = this->config->queryConfigProperty("config.account.login"); string passwd = this->config->queryConfigProperty("config.account.password"); Client<Http_client_connection> client(iqnet::Inet_addr("livejournal.com", 80), "/interface/xmlrpc"); Param_list param_list; param_list.push_back(Struct()); unsigned int allowmask = 0; allowmask |= 1<<0; param_list[0].insert("username", login); param_list[0].insert("hpassword", passwd); param_list[0].insert("ver", "1"); param_list[0].insert("event", event); param_list[0].insert("subject", subject); param_list[0].insert("security", "usemask"); param_list[0].insert("allowmask", (int)allowmask); param_list[0].insert("lineendings", "unix"); /* time stuff */ time_t rawtime; struct tm * timeinfo; char buffer [80]; time ( &rawtime ); timeinfo = localtime ( &rawtime ); //strftime (buffer,80,"Now is %I:%M%p.",timeinfo); // puts (buffer); param_list[0].insert("year", timeinfo->tm_year + 1900); param_list[0].insert("mon", timeinfo->tm_mon + 1); param_list[0].insert("day", timeinfo->tm_mday); param_list[0].insert("hour", timeinfo->tm_hour); param_list[0].insert("min", timeinfo->tm_min); Response response = client.execute("LJ.XMLRPC.postevent", param_list); Struct st = response.value().the_struct(); //std::cout << st["itemid"].type_name() << std::endl; //std::cout << st["url"].type_name() << std::endl; return st["url"].get_string(); } void LiveJournal::login() { string login = this->config->queryConfigProperty("config.account.login"); string passwd = this->config->queryConfigProperty("config.account.password"); Client<Http_client_connection> client(iqnet::Inet_addr("livejournal.com", 80), "/interface/xmlrpc"); Param_list param_list; param_list.push_back(Struct()); param_list[0].insert("username", login); param_list[0].insert("hpassword", passwd); Response response = client.execute("LJ.XMLRPC.login", param_list); } vector<Event*> LiveJournal::list(int count) { login(); Param_list param_list; param_list.push_back(Struct()); param_list[0].insert("username", username); param_list[0].insert("hpassword", passwd); param_list[0].insert("ver", "1"); param_list[0].insert("truncate", "40"); param_list[0].insert("noprops", "1"); param_list[0].insert("selecttype", "lastn"); param_list[0].insert("howmany", count); param_list[0].insert("lineendings", "unix"); Response response = client->execute("LJ.XMLRPC.getevents", param_list); Struct st = response.value().the_struct(); Array events = st["events"].the_array(); vector<Event*> events_vector; for (Array::const_iterator i = events.begin(); i != events.end(); ++i) { Struct event = i->the_struct(); Event *ljevent = new Event(); ljevent->setItemId(event["itemid"].get_int()); ljevent->setURL(event["url"].get_string()); ljevent->setEventTime(event["eventtime"].get_string()); /* cout << "------------" << endl; cout << "itemid = " << event["itemid"].get_int() << endl; cout << "url = " << event["url"].get_string() << endl; cout << "event = " << event["event"].type_name() << endl; cout << "------------" << endl;*/ //cout << "eventtime = " << event["eventtime"].get_string() << endl; if (event["event"].is_string()) { ljevent->setEvent(event["event"].get_string()); } else if (event["event"].is_binary()) { string strEvent = event["event"].get_binary().get_data(); Glib::ustring uevent(strEvent); try { ljevent->setEvent(Glib::locale_from_utf8(uevent)); } catch (Glib::ConvertError ex) { //cout << Glib::convert_with_fallback(strEvent, "koi8-r", "utf-8") << endl; //ljevent->setEvent(ljevent->getURL()); ljevent->setEvent("cannot convert text to your locale"); } } events_vector.push_back(ljevent); } return events_vector; } Event* LiveJournal::getEvent(int itemId) { login(); Param_list param_list; param_list.push_back(Struct()); param_list[0].insert("username", username); param_list[0].insert("hpassword", passwd); param_list[0].insert("ver", "1"); param_list[0].insert("itemid", itemId); param_list[0].insert("selecttype", "one"); param_list[0].insert("lineendings", "unix"); Response response = client->execute("LJ.XMLRPC.getevents", param_list); Struct st = response.value().the_struct(); Array events = st["events"].the_array(); vector<Event*> events_vector; for (Array::const_iterator i = events.begin(); i != events.end(); ++i) { Struct eventStruct = i->the_struct(); std::cout << eventStruct["url"].get_string() << std::endl; if (eventStruct.has_field("props") == true) { // process properties Struct propsStruct = eventStruct["props"].the_struct(); for (Struct::const_iterator j = propsStruct.begin(); j != propsStruct.end(); j++) { //std::cout << "here we go" << std::endl; //decodeTextValue(new Value(j->second)); iqxmlrpc::Value *myvalue = new iqxmlrpc::Value(j->second); decodeTextValue(myvalue); //std::cout << j->first << ": " << j->second->type_name() << std::endl; std::string propvalue; if (j->second->is_binary()) { propvalue = j->second->get_binary().get_data(); } else if (j->second->is_string()) { propvalue = j->second->get_string(); } else { propvalue = ""; } std::string key = j->first; //.get_string(); std::cout << key << " : " << propvalue << std::endl; } } } // std::cout << events.size() << std::endl; Event *event = new Event(); return event; } <commit_msg>Fix LiveJournal::decodeTextValue().<commit_after>#include <cstdlib> #include <ctime> #include <clocale> #include <iostream> #include <vector> #include <glibmm.h> #include <libiqxmlrpc/libiqxmlrpc.h> #include <libiqxmlrpc/client.h> #include <libiqxmlrpc/http_client.h> #include "LiveJournal.h" #include "Config.h" #include "Event.h" using namespace iqxmlrpc; LiveJournal::LiveJournal() { setlocale(LC_ALL, ""); this->config = new Config(); //std::string(getenv("HOME")) + "/.ecru/default.conf"); this->client = new Client<Http_client_connection>(iqnet::Inet_addr("livejournal.com", 80), "/interface/xmlrpc"); username = this->config->queryConfigProperty("config.account.login"); passwd = this->config->queryConfigProperty("config.account.password"); } std::string LiveJournal::decodeTextValue(const iqxmlrpc::Value *value) { //std::cout << "decodeTextValue, type = " << value->is_string() << endl; std::string result; if (value->is_string()) { result = value->get_string(); } else if (value->is_binary()) { string raw = value->get_binary().get_data(); Glib::ustring unicodeString(raw); try { result = (std::string)(Glib::locale_from_utf8(unicodeString)); } catch (Glib::ConvertError ex) { result = "error encoding string"; } } return result; } string LiveJournal::postEvent(string event, string subject) { login(); string login = this->config->queryConfigProperty("config.account.login"); string passwd = this->config->queryConfigProperty("config.account.password"); Client<Http_client_connection> client(iqnet::Inet_addr("livejournal.com", 80), "/interface/xmlrpc"); Param_list param_list; param_list.push_back(Struct()); unsigned int allowmask = 0; allowmask |= 1<<0; param_list[0].insert("username", login); param_list[0].insert("hpassword", passwd); param_list[0].insert("ver", "1"); param_list[0].insert("event", event); param_list[0].insert("subject", subject); param_list[0].insert("security", "usemask"); param_list[0].insert("allowmask", (int)allowmask); param_list[0].insert("lineendings", "unix"); /* time stuff */ time_t rawtime; struct tm * timeinfo; char buffer [80]; time ( &rawtime ); timeinfo = localtime ( &rawtime ); //strftime (buffer,80,"Now is %I:%M%p.",timeinfo); // puts (buffer); param_list[0].insert("year", timeinfo->tm_year + 1900); param_list[0].insert("mon", timeinfo->tm_mon + 1); param_list[0].insert("day", timeinfo->tm_mday); param_list[0].insert("hour", timeinfo->tm_hour); param_list[0].insert("min", timeinfo->tm_min); Response response = client.execute("LJ.XMLRPC.postevent", param_list); Struct st = response.value().the_struct(); //std::cout << st["itemid"].type_name() << std::endl; //std::cout << st["url"].type_name() << std::endl; return st["url"].get_string(); } void LiveJournal::login() { string login = this->config->queryConfigProperty("config.account.login"); string passwd = this->config->queryConfigProperty("config.account.password"); Client<Http_client_connection> client(iqnet::Inet_addr("livejournal.com", 80), "/interface/xmlrpc"); Param_list param_list; param_list.push_back(Struct()); param_list[0].insert("username", login); param_list[0].insert("hpassword", passwd); Response response = client.execute("LJ.XMLRPC.login", param_list); } vector<Event*> LiveJournal::list(int count) { login(); Param_list param_list; param_list.push_back(Struct()); param_list[0].insert("username", username); param_list[0].insert("hpassword", passwd); param_list[0].insert("ver", "1"); param_list[0].insert("truncate", "40"); param_list[0].insert("noprops", "1"); param_list[0].insert("selecttype", "lastn"); param_list[0].insert("howmany", count); param_list[0].insert("lineendings", "unix"); Response response = client->execute("LJ.XMLRPC.getevents", param_list); Struct st = response.value().the_struct(); Array events = st["events"].the_array(); vector<Event*> events_vector; for (Array::const_iterator i = events.begin(); i != events.end(); ++i) { Struct event = i->the_struct(); Event *ljevent = new Event(); ljevent->setItemId(event["itemid"].get_int()); ljevent->setURL(event["url"].get_string()); ljevent->setEventTime(event["eventtime"].get_string()); /* cout << "------------" << endl; cout << "itemid = " << event["itemid"].get_int() << endl; cout << "url = " << event["url"].get_string() << endl; cout << "event = " << event["event"].type_name() << endl; cout << "------------" << endl;*/ //cout << "eventtime = " << event["eventtime"].get_string() << endl; ljevent->setEvent(decodeTextValue(&event["event"])); #if 0 if (event["event"].is_string()) { ljevent->setEvent(event["event"].get_string()); } else if (event["event"].is_binary()) { string strEvent = event["event"].get_binary().get_data(); Glib::ustring uevent(strEvent); try { ljevent->setEvent(Glib::locale_from_utf8(uevent)); } catch (Glib::ConvertError ex) { //cout << Glib::convert_with_fallback(strEvent, "koi8-r", "utf-8") << endl; //ljevent->setEvent(ljevent->getURL()); ljevent->setEvent("cannot convert text to your locale"); } } #endif events_vector.push_back(ljevent); } return events_vector; } Event* LiveJournal::getEvent(int itemId) { login(); Param_list param_list; param_list.push_back(Struct()); param_list[0].insert("username", username); param_list[0].insert("hpassword", passwd); param_list[0].insert("ver", "1"); param_list[0].insert("itemid", itemId); param_list[0].insert("selecttype", "one"); param_list[0].insert("lineendings", "unix"); Response response = client->execute("LJ.XMLRPC.getevents", param_list); Struct st = response.value().the_struct(); Array events = st["events"].the_array(); vector<Event*> events_vector; Event *ljevent = new Event(); //for (Array::const_iterator i = events.begin(); i != events.end(); ++i) { Value i = events[0]; Struct eventStruct = i.the_struct(); std::cout << eventStruct["url"].get_string() << std::endl; //std::cout << decodeTextValue((Value)eventStruct["url"]) << std::endl; if (eventStruct.has_field("props") == true) { // process properties Struct propsStruct = eventStruct["props"].the_struct(); for (Struct::const_iterator j = propsStruct.begin(); j != propsStruct.end(); j++) { std::string key = j->first; std::cout << key << " : " << decodeTextValue(j->second) << std::endl; } } ljevent->setEvent(decodeTextValue(&eventStruct["event"])); std::cout << ljevent->getEvent() << endl; // } // std::cout << events.size() << std::endl; // Event *event = new Event(); return ljevent; } <|endoftext|>
<commit_before>#include "MainWindow.hpp" #include "ui_MainWindow.h" #include <algorithm> #include <QSettings> #include <QProgressBar> #include <QLabel> #include <QSystemTrayIcon> #include "matrix/Room.hpp" #include "matrix/Session.hpp" #include "sort.hpp" #include "RoomView.hpp" #include "ChatWindow.hpp" MainWindow::MainWindow(QSettings &settings, std::unique_ptr<matrix::Session> session) : ui(new Ui::MainWindow), settings_(settings), session_(std::move(session)), progress_(new QProgressBar(this)), sync_label_(new QLabel(this)) { ui->setupUi(this); ui->status_bar->addPermanentWidget(sync_label_); ui->status_bar->addPermanentWidget(progress_); auto tray = new QSystemTrayIcon(QIcon::fromTheme("user-available"), this); tray->setContextMenu(ui->menu_matrix); connect(tray, &QSystemTrayIcon::activated, [this](QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::Trigger) { setVisible(!isVisible()); } }); tray->show(); connect(ui->action_log_out, &QAction::triggered, session_.get(), &matrix::Session::log_out); connect(session_.get(), &matrix::Session::logged_out, [this]() { settings_.remove("session/access_token"); settings_.remove("session/user_id"); ui->action_quit->trigger(); }); connect(session_.get(), &matrix::Session::error, [this](QString msg) { qDebug() << "Session error: " << msg; }); connect(session_.get(), &matrix::Session::synced_changed, [this]() { if(session_->synced()) { sync_label_->hide(); } else { sync_label_->setText(tr("Disconnected")); sync_label_->show(); } }); connect(session_.get(), &matrix::Session::sync_progress, this, &MainWindow::sync_progress); connect(session_.get(), &matrix::Session::sync_complete, [this]() { progress_->hide(); sync_label_->hide(); }); connect(session_.get(), &matrix::Session::joined, this, &MainWindow::joined); ui->action_quit->setShortcuts(QKeySequence::Quit); connect(ui->action_quit, &QAction::triggered, this, &MainWindow::quit); connect(ui->room_list, &QListWidget::itemActivated, [this](QListWidgetItem *){ for(auto item : ui->room_list->selectedItems()) { auto &room = *reinterpret_cast<matrix::Room *>(item->data(Qt::UserRole).value<void*>()); ChatWindow *window; auto it = chat_windows_.find(room.id()); if(it != chat_windows_.end()) { window = it->second; // Focus in existing window } else if(last_focused_) { window = last_focused_; // Add to most recently used window } else { if(chat_windows_.empty()) { // Create first window window = spawn_chat_window(); } else { // Select arbitrary window window = chat_windows_.begin()->second; } } window->add_or_focus(room); window->show(); window->raise(); window->activateWindow(); } }); sync_progress(0, -1); for(auto room : session_->rooms()) { joined(*room); } } MainWindow::~MainWindow() { delete ui; } void MainWindow::joined(matrix::Room &room) { connect(&room, &matrix::Room::highlight_count_changed, [this, &room](uint64_t old) { highlighted(room, old); }); connect(&room, &matrix::Room::notification_count_changed, this, &MainWindow::update_rooms); connect(&room, &matrix::Room::name_changed, this, &MainWindow::update_rooms); connect(&room, &matrix::Room::canonical_alias_changed, this, &MainWindow::update_rooms); connect(&room, &matrix::Room::aliases_changed, this, &MainWindow::update_rooms); connect(&room, &matrix::Room::membership_changed, this, &MainWindow::update_rooms); update_rooms(); } void MainWindow::highlighted(matrix::Room &room, uint64_t old) { update_rooms(); if(old > room.highlight_count()) return; auto it = chat_windows_.find(room.id()); QWidget *window; if(it == chat_windows_.end()) { window = this; } else { window = it->second; } window->show(); QApplication::alert(window); } void MainWindow::update_rooms() { auto rooms = session_->rooms(); std::sort(rooms.begin(), rooms.end(), [&](const matrix::Room *a, const matrix::Room *b) { return room_sort_key(a->pretty_name()) < room_sort_key(b->pretty_name()); }); ui->room_list->clear(); for(auto room : rooms) { auto item = new QListWidgetItem; item->setText(room->pretty_name_highlights()); { auto f = font(); f.setBold(room->highlight_count() != 0 || room->notification_count() != 0); item->setFont(f); } item->setData(Qt::UserRole, QVariant::fromValue(reinterpret_cast<void*>(room))); ui->room_list->addItem(item); } ui->room_list->viewport()->update(); } void MainWindow::sync_progress(qint64 received, qint64 total) { sync_label_->setText(tr("Synchronizing...")); sync_label_->show(); progress_->show(); if(total == -1 || total == 0) { progress_->setMaximum(0); } else { progress_->setMaximum(1000); progress_->setValue(1000 * static_cast<float>(received)/static_cast<float>(total)); } } RoomWindowBridge::RoomWindowBridge(matrix::Room &room, ChatWindow &parent) : QObject(&parent), room_(room), window_(parent) { connect(&room, &matrix::Room::highlight_count_changed, this, &RoomWindowBridge::display_changed); connect(&room, &matrix::Room::notification_count_changed, this, &RoomWindowBridge::display_changed); connect(&room, &matrix::Room::name_changed, this, &RoomWindowBridge::display_changed); connect(&room, &matrix::Room::canonical_alias_changed, this, &RoomWindowBridge::display_changed); connect(&room, &matrix::Room::aliases_changed, this, &RoomWindowBridge::display_changed); connect(&room, &matrix::Room::membership_changed, this, &RoomWindowBridge::display_changed); connect(&parent, &ChatWindow::released, this, &RoomWindowBridge::check_release); } void RoomWindowBridge::display_changed() { window_.room_display_changed(room_); } void RoomWindowBridge::check_release(const matrix::RoomID &room) { if(room_.id() == room) deleteLater(); } ChatWindow *MainWindow::spawn_chat_window() { auto window = new ChatWindow; connect(window, &ChatWindow::focused, [this, window](){ last_focused_ = window; }); connect(window, &ChatWindow::claimed, [this, window](const matrix::RoomID &r) { auto x = chat_windows_.emplace( std::piecewise_construct, std::forward_as_tuple(r), std::forward_as_tuple(window)); assert(x.second); new RoomWindowBridge(*session_->room_from_id(r), *window); }); connect(window, &ChatWindow::released, [this](const matrix::RoomID &rid) { chat_windows_.erase(rid); }); connect(window, &ChatWindow::pop_out, [this](const matrix::RoomID &r, RoomView *v) { auto w = spawn_chat_window(); w->add(*session_->room_from_id(r), v); w->show(); w->raise(); w->activateWindow(); }); return window; } <commit_msg>Faster many-room opening<commit_after>#include "MainWindow.hpp" #include "ui_MainWindow.h" #include <algorithm> #include <unordered_set> #include <QSettings> #include <QProgressBar> #include <QLabel> #include <QSystemTrayIcon> #include "matrix/Room.hpp" #include "matrix/Session.hpp" #include "sort.hpp" #include "RoomView.hpp" #include "ChatWindow.hpp" MainWindow::MainWindow(QSettings &settings, std::unique_ptr<matrix::Session> session) : ui(new Ui::MainWindow), settings_(settings), session_(std::move(session)), progress_(new QProgressBar(this)), sync_label_(new QLabel(this)) { ui->setupUi(this); ui->status_bar->addPermanentWidget(sync_label_); ui->status_bar->addPermanentWidget(progress_); auto tray = new QSystemTrayIcon(QIcon::fromTheme("user-available"), this); tray->setContextMenu(ui->menu_matrix); connect(tray, &QSystemTrayIcon::activated, [this](QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::Trigger) { setVisible(!isVisible()); } }); tray->show(); connect(ui->action_log_out, &QAction::triggered, session_.get(), &matrix::Session::log_out); connect(session_.get(), &matrix::Session::logged_out, [this]() { settings_.remove("session/access_token"); settings_.remove("session/user_id"); ui->action_quit->trigger(); }); connect(session_.get(), &matrix::Session::error, [this](QString msg) { qDebug() << "Session error: " << msg; }); connect(session_.get(), &matrix::Session::synced_changed, [this]() { if(session_->synced()) { sync_label_->hide(); } else { sync_label_->setText(tr("Disconnected")); sync_label_->show(); } }); connect(session_.get(), &matrix::Session::sync_progress, this, &MainWindow::sync_progress); connect(session_.get(), &matrix::Session::sync_complete, [this]() { progress_->hide(); sync_label_->hide(); }); connect(session_.get(), &matrix::Session::joined, this, &MainWindow::joined); ui->action_quit->setShortcuts(QKeySequence::Quit); connect(ui->action_quit, &QAction::triggered, this, &MainWindow::quit); connect(ui->room_list, &QListWidget::itemActivated, [this](QListWidgetItem *){ std::unordered_set<ChatWindow *> windows; for(auto item : ui->room_list->selectedItems()) { auto &room = *reinterpret_cast<matrix::Room *>(item->data(Qt::UserRole).value<void*>()); ChatWindow *window; auto it = chat_windows_.find(room.id()); if(it != chat_windows_.end()) { window = it->second; // Focus in existing window } else if(last_focused_) { window = last_focused_; // Add to most recently used window } else { if(chat_windows_.empty()) { // Create first window window = spawn_chat_window(); } else { // Select arbitrary window window = chat_windows_.begin()->second; } } window->add_or_focus(room); windows.insert(window); } for(auto window : windows) { window->show(); window->activateWindow(); } }); sync_progress(0, -1); for(auto room : session_->rooms()) { joined(*room); } } MainWindow::~MainWindow() { delete ui; } void MainWindow::joined(matrix::Room &room) { connect(&room, &matrix::Room::highlight_count_changed, [this, &room](uint64_t old) { highlighted(room, old); }); connect(&room, &matrix::Room::notification_count_changed, this, &MainWindow::update_rooms); connect(&room, &matrix::Room::name_changed, this, &MainWindow::update_rooms); connect(&room, &matrix::Room::canonical_alias_changed, this, &MainWindow::update_rooms); connect(&room, &matrix::Room::aliases_changed, this, &MainWindow::update_rooms); connect(&room, &matrix::Room::membership_changed, this, &MainWindow::update_rooms); update_rooms(); } void MainWindow::highlighted(matrix::Room &room, uint64_t old) { update_rooms(); if(old > room.highlight_count()) return; auto it = chat_windows_.find(room.id()); QWidget *window; if(it == chat_windows_.end()) { window = this; } else { window = it->second; } window->show(); QApplication::alert(window); } void MainWindow::update_rooms() { auto rooms = session_->rooms(); std::sort(rooms.begin(), rooms.end(), [&](const matrix::Room *a, const matrix::Room *b) { return room_sort_key(a->pretty_name()) < room_sort_key(b->pretty_name()); }); ui->room_list->clear(); for(auto room : rooms) { auto item = new QListWidgetItem; item->setText(room->pretty_name_highlights()); { auto f = font(); f.setBold(room->highlight_count() != 0 || room->notification_count() != 0); item->setFont(f); } item->setData(Qt::UserRole, QVariant::fromValue(reinterpret_cast<void*>(room))); ui->room_list->addItem(item); } ui->room_list->viewport()->update(); } void MainWindow::sync_progress(qint64 received, qint64 total) { sync_label_->setText(tr("Synchronizing...")); sync_label_->show(); progress_->show(); if(total == -1 || total == 0) { progress_->setMaximum(0); } else { progress_->setMaximum(1000); progress_->setValue(1000 * static_cast<float>(received)/static_cast<float>(total)); } } RoomWindowBridge::RoomWindowBridge(matrix::Room &room, ChatWindow &parent) : QObject(&parent), room_(room), window_(parent) { connect(&room, &matrix::Room::highlight_count_changed, this, &RoomWindowBridge::display_changed); connect(&room, &matrix::Room::notification_count_changed, this, &RoomWindowBridge::display_changed); connect(&room, &matrix::Room::name_changed, this, &RoomWindowBridge::display_changed); connect(&room, &matrix::Room::canonical_alias_changed, this, &RoomWindowBridge::display_changed); connect(&room, &matrix::Room::aliases_changed, this, &RoomWindowBridge::display_changed); connect(&room, &matrix::Room::membership_changed, this, &RoomWindowBridge::display_changed); connect(&parent, &ChatWindow::released, this, &RoomWindowBridge::check_release); } void RoomWindowBridge::display_changed() { window_.room_display_changed(room_); } void RoomWindowBridge::check_release(const matrix::RoomID &room) { if(room_.id() == room) deleteLater(); } ChatWindow *MainWindow::spawn_chat_window() { auto window = new ChatWindow; connect(window, &ChatWindow::focused, [this, window](){ last_focused_ = window; }); connect(window, &ChatWindow::claimed, [this, window](const matrix::RoomID &r) { auto x = chat_windows_.emplace( std::piecewise_construct, std::forward_as_tuple(r), std::forward_as_tuple(window)); assert(x.second); new RoomWindowBridge(*session_->room_from_id(r), *window); }); connect(window, &ChatWindow::released, [this](const matrix::RoomID &rid) { chat_windows_.erase(rid); }); connect(window, &ChatWindow::pop_out, [this](const matrix::RoomID &r, RoomView *v) { auto w = spawn_chat_window(); w->add(*session_->room_from_id(r), v); w->show(); w->raise(); w->activateWindow(); }); return window; } <|endoftext|>
<commit_before>#include <iostream> #include "convexHull.h" #include "testUtil.h" using namespace Eigen; int testConvexHull() { Matrix<double, 2, Dynamic> pts(2, 4); pts << 1, 2, 3, 2, 2, 1, 2, 3; if (!inConvexHull(pts, Vector2d(2, 2))) { fprintf(stderr, "2,2 should be in hull\n"); return 1; } if (!inConvexHull(pts, Vector2d(1.0001, 2))) { fprintf(stderr, "1.0001, 2 should be in hull\n"); return 1; } if (inConvexHull(pts, Vector2d(0.9999, 2))) { fprintf(stderr, "0.9999, 2 should not be in hull\n"); return 1; } if (!inConvexHull(pts, Vector2d(2.49, 2.49))) { fprintf(stderr, "2.49,2.49 should be in hull\n"); return 1; } if (inConvexHull(pts, Vector2d(2.51, 2.51))) { fprintf(stderr, "2.51,2.51 should not be in hull\n"); return 1; } return 0; } void testDistanceFromHull() { Matrix<double, 2, Dynamic> pts(2, 5); pts << 0, 1, 1, 0, 0.5, 0, 1, 0, 1, 0.5; double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); pts << 0, 2, 2, 0, 0.5, 0, 2, 0, 2, 0.5; d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); } void testRealData() { Matrix<double, 2, Dynamic> pts(2, 16); pts << 0.237506, 0.330077, 0.297687, 0.390258, 0.177325, 0.269896, 0.357868, 0.450439, 0.00257912, 0.116144, 0.0466612, 0.160226, -0.03475, 0.0788149, 0.0873669, 0.200932, -0.00459488, -0.093748, 0.0579462, -0.0312069, -0.067136, -0.156289, 0.120487, 0.0313342, 0.102483, 0.0421703, 0.185504, 0.125191, 0.0321808, -0.0281323, 0.262166, 0.201853; Vector2d q(0.196956, 0.0487772); double d = signedDistanceInsideConvexHull(pts, q); valuecheck(d, 0.136017, 1e-6); } int main() { bool failed = false; int error; error = testConvexHull(); if (error) { std::cout << "testConvexHull FAILED" << std::endl; failed = true; } else { std::cout << "testConvexHull passed" << std::endl; } testDistanceFromHull(); std::cout << "testDistanceFromHull passed" << std::endl; testRealData(); std::cout << "testRealData passed" << std::endl; if (!failed) { std::cout << "convexHull tests passed" << std::endl; } else { std::cout << "convexHull tests FAILED" << std::endl; exit(1); } } <commit_msg>more tests<commit_after>#include <iostream> #include "convexHull.h" #include "testUtil.h" using namespace Eigen; int testConvexHull() { Matrix<double, 2, Dynamic> pts(2, 4); pts << 1.0, 2.0, 3.0, 2.0, 2.0, 1.0, 2.0, 3.0; if (!inConvexHull(pts, Vector2d(2.0, 2.0))) { fprintf(stderr, "2.0,2.0 should be in hull\n"); return 1; } if (!inConvexHull(pts, Vector2d(1.0001, 2.0))) { fprintf(stderr, "1.0001, 2.0 should be in hull\n"); return 1; } if (inConvexHull(pts, Vector2d(0.9999, 2.0))) { fprintf(stderr, "0.9999, 2.0 should not be in hull\n"); return 1; } if (!inConvexHull(pts, Vector2d(2.49, 2.49))) { fprintf(stderr, "2.49,2.49 should be in hull\n"); return 1; } if (inConvexHull(pts, Vector2d(2.51, 2.51))) { fprintf(stderr, "2.51,2.51 should not be in hull\n"); return 1; } return 0; } void testDistanceFromHull() { Matrix<double, 2, Dynamic> pts(2, 5); pts << 0, 1, 1, 0, 0.5, 0, 1, 0, 1, 0.5; double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); pts << 0, 2, 2, 0, 0.5, 0, 2, 0, 2, 0.5; d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); } void testRealData() { Matrix<double, 2, Dynamic> pts(2, 16); pts << 0.237506, 0.330077, 0.297687, 0.390258, 0.177325, 0.269896, 0.357868, 0.450439, 0.00257912, 0.116144, 0.0466612, 0.160226, -0.03475, 0.0788149, 0.0873669, 0.200932, -0.00459488, -0.093748, 0.0579462, -0.0312069, -0.067136, -0.156289, 0.120487, 0.0313342, 0.102483, 0.0421703, 0.185504, 0.125191, 0.0321808, -0.0281323, 0.262166, 0.201853; Vector2d q(0.196956, 0.0487772); double d = signedDistanceInsideConvexHull(pts, q); valuecheck(d, 0.136017, 1e-6); } void testDuplicates() { Matrix<double, 2, Dynamic> pts(2, 8); pts << 0.0, 1.0, 1.0, 0.0, 0.5, 0.0, 0.0, 1.0 - 1e-16, 0.0, 1.0, 0.0, 1.0, 0.5, 0.0, 0.0, 1.0 - 1e-16; double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); } int main() { bool failed = false; int error; error = testConvexHull(); if (error) { std::cout << "testConvexHull FAILED" << std::endl; failed = true; } else { std::cout << "testConvexHull passed" << std::endl; } testDistanceFromHull(); std::cout << "testDistanceFromHull passed" << std::endl; testRealData(); std::cout << "testRealData passed" << std::endl; testDuplicates(); std::cout << "testDuplicates passed" << std::endl; if (!failed) { std::cout << "convexHull tests passed" << std::endl; } else { std::cout << "convexHull tests FAILED" << std::endl; exit(1); } } <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> //#include "clotho/powerset/powerset.hpp" // #include "clotho/powerset/block_map.hpp" #include "clotho/powerset/variable_subset.hpp" struct test_element { double k, v; test_element( double _k = 0., double _v = 0.) : k (_k), v(_v) {} test_element( const test_element & t ) : k(t.k), v(t.v) {} friend bool operator==( const test_element & lhs, const test_element & rhs ); friend bool operator!=( const test_element & lhs, const test_element & rhs ); }; inline bool operator==( const test_element & lhs, const test_element & rhs ) { return ( lhs.k == rhs.k && lhs.v == rhs.v); } inline bool operator!=( const test_element & lhs, const test_element & rhs ) { return ( lhs.k != rhs.k && lhs.v != rhs.v); } namespace clotho { namespace powersets { template <> struct element_key_of< test_element > { typedef double key_type; inline key_type operator()( const test_element & t ) { return t.k; } }; template< class Block > struct block_map< test_element, Block > { typedef test_element element_type; typedef Block size_type; static const unsigned int bits_per_block = sizeof(size_type) * 8; inline size_type operator()( const element_type & elem ) { assert( 0. <= elem.k && elem.k < 1. ); return elem.k * bits_per_block; } }; } // namespace powersets } // namespace clotho typedef clotho::powersets::variable_subset< test_element > subset_type; typedef typename subset_type::powerset_type powerset_type; typedef powerset_type::block_map_type bmap; BOOST_AUTO_TEST_SUITE( test_powerset ) /** * Create an empty powerset * * Manually append element to powerset * Verify that new element is assigned to expected index * * Verify allocated size */ BOOST_AUTO_TEST_CASE( create_powerset_append) { powerset_type ps; typename powerset_type::element_index_type idx = ps.appendElement( test_element( 0., 1.0) ); BOOST_REQUIRE_MESSAGE( idx == 0, "Unexpected index " << idx << " returned for " << 0 << "(" << 0 << ")" ); BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bmap::bits_per_block, "Unexpected variable space: " << ps.variable_allocated_size() ); } /** * Create an empty powerset * * Manually add element to powerset (results in append) * Verify that new element is assigned to expected index * * Verify allocated size */ BOOST_AUTO_TEST_CASE( create_powerset_add) { powerset_type ps; typename powerset_type::element_index_type idx = ps.addElement( test_element( 0., 1.0) ); BOOST_REQUIRE_MESSAGE( idx == 0, "Unexpected index " << idx << " returned for " << 0 << "(" << 0 << ")" ); BOOST_REQUIRE_MESSAGE( ps.size() == 1, "Unexpected size" ); BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bmap::bits_per_block, "Unexpected variable space: " << ps.variable_allocated_size() ); } /** * Create an empty powerset * * Manually append first element to powerset * Verify that new element is assigned to expected index * * add the remaining elements of a block * Verify that each new element is assigned to expected index * * Verify allocated size */ BOOST_AUTO_TEST_CASE( create_powerset_width ) { powerset_type ps; BOOST_REQUIRE_MESSAGE( ps.empty(), "Unexpected size" ); typename powerset_type::element_index_type idx = ps.appendElement( test_element( 0., 1.0) ); BOOST_REQUIRE_MESSAGE( idx == 0, "Unexpected index " << idx << " returned for " << 0 << "(" << 0 << ")" ); BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bmap::bits_per_block, "Unexpected variable space: " << ps.variable_allocated_size() ); for( unsigned int i = 1; i < bmap::bits_per_block; ++i ) { double v = (double) i; double k = v / (double) bmap::bits_per_block; test_element te(k, 1.0); typename powerset_type::element_index_type e_idx = ps.findFreeIndex(te); BOOST_REQUIRE_MESSAGE( e_idx == i, e_idx << " != " << i ); typename powerset_type::element_index_type idx = ps.addElement(te); BOOST_REQUIRE_MESSAGE( idx == i, "Unexpected index " << idx << " returned for " << i << "(" << k << "; " << e_idx << ")" ); } const unsigned int bpb = bmap::bits_per_block; BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bpb, "Unexpected size: " << ps.variable_allocated_size() << "(" << bpb << ")" ); } /** * Create an empty powerset * * find_or_create elements in a round robin order. * Verify that each new element is assigned to expected index */ BOOST_AUTO_TEST_CASE( create_powerset_find_or_create_unique ) { powerset_type ps; const unsigned int sub_div = 3; const double div_offset = (1.0/ ((double)sub_div*bmap::bits_per_block)); for( unsigned int i = 0; i < sub_div * bmap::bits_per_block; ++i ) { double v = (double) (i % bmap::bits_per_block); unsigned int s = (i / bmap::bits_per_block ); double k = v / (double) bmap::bits_per_block + (double)s*div_offset; test_element te(k, 1.0); typename powerset_type::element_index_type idx = ps.find_or_create(te); BOOST_REQUIRE_MESSAGE( idx == i, "Unexpected index " << idx << " returned for " << i << "(" << k << ")" ); } const unsigned int bpb = sub_div * bmap::bits_per_block; BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bpb, "Unexpected size: " << ps.variable_allocated_size() << "(" << bpb << ")" ); } /** * Create an empty powerset * * find_or_create an element to the powerset (results in create) * * Verify that it is in expected position * * find_or_create different element with same key (results in find) * * Verify that element index returned is same as earlier element. */ BOOST_AUTO_TEST_CASE( create_powerset_find_or_create_collision ) { powerset_type ps; double k = 0.5; test_element te(k, 1.0); typename powerset_type::element_index_type idx = ps.find_or_create(te); BOOST_REQUIRE_MESSAGE( idx == bmap()(te), "Unexpected index " << idx << " returned for " << 0 << "(" << k << ")" ); test_element te2(k, 2.0); typename powerset_type::element_index_type cidx = ps.find_or_create(te2); BOOST_REQUIRE_MESSAGE( cidx == idx, "Unexpected index " << idx << " returned for " << cidx << "(" << k << ")" ); } /** * Creates a subset of the powerset * * Verify that subset was added to family * * Adds a element * * Checks that element has been added to the set and subset * Checks subset count * Verifies expected sizes * Verifies expected bit state * * Removes earlier element * Checks subset count * Checks element bit state */ BOOST_AUTO_TEST_CASE( create_powerset_subset ) { powerset_type ps; typename powerset_type::subset_ptr c = ps.create_subset(); BOOST_REQUIRE_MESSAGE( ps.family_size() == 1, "Subset was not added to family"); double k = 0.5; test_element te(k, 1.0); c->addElement( te ); size_t cnt = c->count(); BOOST_REQUIRE_MESSAGE( cnt == 1, "Element has not been added to the subset: " << cnt << "(1)" ); const unsigned int bpb = bmap::bits_per_block; BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bpb, "Unexpected size: " << ps.variable_allocated_size() << "(" << bpb << ")" ); typename powerset_type::element_index_type idx = ps.find_or_create(te); BOOST_REQUIRE_MESSAGE( idx == bmap()(te), "Unexpected index " << idx << " returned for " << 0 << "(" << k << ")" ); BOOST_REQUIRE_MESSAGE( c->check_state( idx ), "Unexpected state for element after add" ); c->removeElement( te ); cnt = c->count(); BOOST_REQUIRE_MESSAGE( cnt == 0, "Element has not been removed to the subset: " << cnt << "(0)" ); BOOST_REQUIRE_MESSAGE( !c->check_state( idx ), "Unexpected state for element after remove" ); } /** * Create a powerset * * Create a subset with one element in it, in a sub-scope; * Assuming subset_ptr is a shared_ptr, the change in scope should dereference * a single instance to the subset, leaving a single instance of the subset * in the family. If the family contains only a single instance of a subset, * prune the powerset should remove the subset, and free up lost|fixed * elements. * */ BOOST_AUTO_TEST_CASE( create_powerset_prunespace ) { powerset_type ps; // change in scope should release one instance of subset_ptr { typename powerset_type::subset_ptr c = ps.create_subset(); double k = 0.5; test_element te(k, 1.0); c->addElement( te ); } BOOST_REQUIRE_MESSAGE( ps.family_size() == 1, "Subset was not added to family"); const unsigned int bpb = bmap::bits_per_block; size_t fs = ps.free_size(); BOOST_REQUIRE_MESSAGE( fs == (bpb - 1), "Unexpected free size " << fs << "(" << (bpb - 1) << ")" ); BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bpb, "Unexpected size: " << ps.variable_allocated_size() << "(" << bpb << ")" ); ps.pruneSpace(); BOOST_REQUIRE_MESSAGE( ps.family_size() == 0, "Subset was not removed from family"); fs = ps.free_size(); BOOST_REQUIRE_MESSAGE( fs == bpb, "Unexpected free size " << fs << "(" << bpb << ")" ); } /** * Create a powerset * * Create a subset with one element in it, in a sub-scope; * Create a second subset with the same element (a duplicate of the first subset) * * As before the first subset should be dereferenced, and will be removed from * the family. The second subset, however, will not because two references to the * subset should exist (one in this scope, and one in the family). * * Therefore, pruning the powerset space should result in the subsets being * reduced to 1. Furthermore, since there is a single subset, with a single * element, that element becomes fixed within the powerset. The fixed element * should be copied to the fixed subset, and its positions should be freed * */ BOOST_AUTO_TEST_CASE( create_powerset_prunespace2 ) { powerset_type ps; double k = 0.5; test_element te(k, 1.0); // change in scope should release one instance of subset_ptr { typename powerset_type::subset_ptr c = ps.create_subset(); c->addElement( te ); } typename powerset_type::subset_ptr c2 = ps.create_subset(); c2->addElement(te); BOOST_REQUIRE_MESSAGE( ps.family_size() == 2, "Subset was not added to family"); typename powerset_type::element_index_type idx = ps.find_or_create(te); const unsigned int bpb = bmap::bits_per_block; size_t fs = ps.free_size(); BOOST_REQUIRE_MESSAGE( fs == (bpb - 1), "Unexpected free size " << fs << "(" << (bpb - 1) << ")" ); BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bpb, "Unexpected size: " << ps.variable_allocated_size() << " (" << bpb << ")" ); ps.pruneSpace(); fs = ps.free_size(); BOOST_REQUIRE_MESSAGE( ps.family_size() == 1, "Expected subset was not removed from family " << ps.family_size() << " (1)" ); BOOST_REQUIRE_MESSAGE( fs == bpb, "Unexpected free size " << fs << " (" << bpb << ")" ); BOOST_REQUIRE_MESSAGE( ps.fixed_size() == 1, "Unexpected fixed size " << ps.fixed_size() << " (1)"); typename powerset_type::element_index_type idx2 = ps.find_or_create(te); BOOST_REQUIRE_MESSAGE( idx != idx2, "After pruning, fixed element has same index. Should be different"); BOOST_REQUIRE_MESSAGE( idx2 == ps.encode_index(0, true), "Unxpected fixed index " << idx2 << " (" << ps.encode_index(0, true) << ")"); bool is_fixed = ps.decode_index(idx2); BOOST_REQUIRE_MESSAGE( is_fixed, "Unexpected state decoding false (true)" ); BOOST_REQUIRE_MESSAGE( idx2 == 0, "Unexpected index decoded " << idx2 << " (0)"); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Cleaned up header section<commit_after>#include <boost/test/unit_test.hpp> #include "test_element.h" #include "clotho/powerset/variable_subset.hpp" typedef clotho::powersets::variable_subset< test_element > subset_type; typedef typename subset_type::powerset_type powerset_type; typedef powerset_type::block_map_type bmap; BOOST_AUTO_TEST_SUITE( test_powerset ) /** * Create an empty powerset * * Manually append element to powerset * Verify that new element is assigned to expected index * * Verify allocated size */ BOOST_AUTO_TEST_CASE( create_powerset_append) { powerset_type ps; typename powerset_type::element_index_type idx = ps.appendElement( test_element( 0., 1.0) ); BOOST_REQUIRE_MESSAGE( idx == 0, "Unexpected index " << idx << " returned for " << 0 << "(" << 0 << ")" ); BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bmap::bits_per_block, "Unexpected variable space: " << ps.variable_allocated_size() ); } /** * Create an empty powerset * * Manually add element to powerset (results in append) * Verify that new element is assigned to expected index * * Verify allocated size */ BOOST_AUTO_TEST_CASE( create_powerset_add) { powerset_type ps; typename powerset_type::element_index_type idx = ps.addElement( test_element( 0., 1.0) ); BOOST_REQUIRE_MESSAGE( idx == 0, "Unexpected index " << idx << " returned for " << 0 << "(" << 0 << ")" ); BOOST_REQUIRE_MESSAGE( ps.size() == 1, "Unexpected size" ); BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bmap::bits_per_block, "Unexpected variable space: " << ps.variable_allocated_size() ); } /** * Create an empty powerset * * Manually append first element to powerset * Verify that new element is assigned to expected index * * add the remaining elements of a block * Verify that each new element is assigned to expected index * * Verify allocated size */ BOOST_AUTO_TEST_CASE( create_powerset_width ) { powerset_type ps; BOOST_REQUIRE_MESSAGE( ps.empty(), "Unexpected size" ); typename powerset_type::element_index_type idx = ps.appendElement( test_element( 0., 1.0) ); BOOST_REQUIRE_MESSAGE( idx == 0, "Unexpected index " << idx << " returned for " << 0 << "(" << 0 << ")" ); BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bmap::bits_per_block, "Unexpected variable space: " << ps.variable_allocated_size() ); for( unsigned int i = 1; i < bmap::bits_per_block; ++i ) { double v = (double) i; double k = v / (double) bmap::bits_per_block; test_element te(k, 1.0); typename powerset_type::element_index_type e_idx = ps.findFreeIndex(te); BOOST_REQUIRE_MESSAGE( e_idx == i, e_idx << " != " << i ); typename powerset_type::element_index_type idx = ps.addElement(te); BOOST_REQUIRE_MESSAGE( idx == i, "Unexpected index " << idx << " returned for " << i << "(" << k << "; " << e_idx << ")" ); } const unsigned int bpb = bmap::bits_per_block; BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bpb, "Unexpected size: " << ps.variable_allocated_size() << "(" << bpb << ")" ); } /** * Create an empty powerset * * find_or_create elements in a round robin order. * Verify that each new element is assigned to expected index */ BOOST_AUTO_TEST_CASE( create_powerset_find_or_create_unique ) { powerset_type ps; const unsigned int sub_div = 3; const double div_offset = (1.0/ ((double)sub_div*bmap::bits_per_block)); for( unsigned int i = 0; i < sub_div * bmap::bits_per_block; ++i ) { double v = (double) (i % bmap::bits_per_block); unsigned int s = (i / bmap::bits_per_block ); double k = v / (double) bmap::bits_per_block + (double)s*div_offset; test_element te(k, 1.0); typename powerset_type::element_index_type idx = ps.find_or_create(te); BOOST_REQUIRE_MESSAGE( idx == i, "Unexpected index " << idx << " returned for " << i << "(" << k << ")" ); } const unsigned int bpb = sub_div * bmap::bits_per_block; BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bpb, "Unexpected size: " << ps.variable_allocated_size() << "(" << bpb << ")" ); } /** * Create an empty powerset * * find_or_create an element to the powerset (results in create) * * Verify that it is in expected position * * find_or_create different element with same key (results in find) * * Verify that element index returned is same as earlier element. */ BOOST_AUTO_TEST_CASE( create_powerset_find_or_create_collision ) { powerset_type ps; double k = 0.5; test_element te(k, 1.0); typename powerset_type::element_index_type idx = ps.find_or_create(te); BOOST_REQUIRE_MESSAGE( idx == bmap()(te), "Unexpected index " << idx << " returned for " << 0 << "(" << k << ")" ); test_element te2(k, 2.0); typename powerset_type::element_index_type cidx = ps.find_or_create(te2); BOOST_REQUIRE_MESSAGE( cidx == idx, "Unexpected index " << idx << " returned for " << cidx << "(" << k << ")" ); } /** * Create an empty powerset * * find_or_create elements in a bit position order. * Every element after the first in each sub-division should result in a collision. * * Verify that each new element is assigned to expected index */ BOOST_AUTO_TEST_CASE( create_powerset_find_or_create_order_collision ) { powerset_type ps; const unsigned int sub_div = 3; const double div_offset = (1.0/ ((double)sub_div*bmap::bits_per_block)); for( unsigned int i = 0; i < bmap::bits_per_block; ++i ) { for( unsigned int j = 0; j < sub_div; ++j ) { double v = (double)i; double k = v / (double) bmap::bits_per_block + (double)j*div_offset; test_element te(k, 1.0); unsigned int e_idx = i + j * bmap::bits_per_block; typename powerset_type::element_index_type idx = ps.find_or_create(te); BOOST_REQUIRE_MESSAGE( idx == e_idx, "Unexpected index " << idx << " returned for " << e_idx << "(" << k << ")" ); } } const unsigned int e_size = sub_div * bmap::bits_per_block; BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == e_size, "Unexpected size: " << ps.variable_allocated_size() << "(" << e_size << ")" ); } /** * Creates a subset of the powerset * * Verify that subset was added to family * * Adds a element * * Checks that element has been added to the set and subset * Checks subset count * Verifies expected sizes * Verifies expected bit state * * Removes earlier element * Checks subset count * Checks element bit state */ BOOST_AUTO_TEST_CASE( create_powerset_subset ) { powerset_type ps; typename powerset_type::subset_ptr c = ps.create_subset(); BOOST_REQUIRE_MESSAGE( ps.family_size() == 1, "Subset was not added to family"); double k = 0.5; test_element te(k, 1.0); c->addElement( te ); size_t cnt = c->count(); BOOST_REQUIRE_MESSAGE( cnt == 1, "Element has not been added to the subset: " << cnt << "(1)" ); const unsigned int bpb = bmap::bits_per_block; BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bpb, "Unexpected size: " << ps.variable_allocated_size() << "(" << bpb << ")" ); typename powerset_type::element_index_type idx = ps.find_or_create(te); BOOST_REQUIRE_MESSAGE( idx == bmap()(te), "Unexpected index " << idx << " returned for " << 0 << "(" << k << ")" ); BOOST_REQUIRE_MESSAGE( c->check_state( idx ), "Unexpected state for element after add" ); c->removeElement( te ); cnt = c->count(); BOOST_REQUIRE_MESSAGE( cnt == 0, "Element has not been removed to the subset: " << cnt << "(0)" ); BOOST_REQUIRE_MESSAGE( !c->check_state( idx ), "Unexpected state for element after remove" ); } /** * Create a powerset * * Create a subset with one element in it, in a sub-scope; * Assuming subset_ptr is a shared_ptr, the change in scope should dereference * a single instance to the subset, leaving a single instance of the subset * in the family. If the family contains only a single instance of a subset, * prune the powerset should remove the subset, and free up lost|fixed * elements. * */ BOOST_AUTO_TEST_CASE( create_powerset_prunespace ) { powerset_type ps; // change in scope should release one instance of subset_ptr { typename powerset_type::subset_ptr c = ps.create_subset(); double k = 0.5; test_element te(k, 1.0); c->addElement( te ); } BOOST_REQUIRE_MESSAGE( ps.family_size() == 1, "Subset was not added to family"); const unsigned int bpb = bmap::bits_per_block; size_t fs = ps.free_size(); BOOST_REQUIRE_MESSAGE( fs == (bpb - 1), "Unexpected free size " << fs << "(" << (bpb - 1) << ")" ); BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bpb, "Unexpected size: " << ps.variable_allocated_size() << "(" << bpb << ")" ); ps.pruneSpace(); BOOST_REQUIRE_MESSAGE( ps.family_size() == 0, "Subset was not removed from family"); fs = ps.free_size(); BOOST_REQUIRE_MESSAGE( fs == bpb, "Unexpected free size " << fs << "(" << bpb << ")" ); } /** * Create a powerset * * Create a subset with one element in it, in a sub-scope; * Create a second subset with the same element (a duplicate of the first subset) * * As before the first subset should be dereferenced, and will be removed from * the family. The second subset, however, will not because two references to the * subset should exist (one in this scope, and one in the family). * * Therefore, pruning the powerset space should result in the subsets being * reduced to 1. Furthermore, since there is a single subset, with a single * element, that element becomes fixed within the powerset. The fixed element * should be copied to the fixed subset, and its positions should be freed * */ BOOST_AUTO_TEST_CASE( create_powerset_prunespace2 ) { powerset_type ps; double k = 0.5; test_element te(k, 1.0); // change in scope should release one instance of subset_ptr { typename powerset_type::subset_ptr c = ps.create_subset(); c->addElement( te ); } typename powerset_type::subset_ptr c2 = ps.create_subset(); c2->addElement(te); BOOST_REQUIRE_MESSAGE( ps.family_size() == 2, "Subset was not added to family"); typename powerset_type::element_index_type idx = ps.find_or_create(te); const unsigned int bpb = bmap::bits_per_block; size_t fs = ps.free_size(); BOOST_REQUIRE_MESSAGE( fs == (bpb - 1), "Unexpected free size " << fs << "(" << (bpb - 1) << ")" ); BOOST_REQUIRE_MESSAGE( ps.variable_allocated_size() == bpb, "Unexpected size: " << ps.variable_allocated_size() << " (" << bpb << ")" ); ps.pruneSpace(); fs = ps.free_size(); BOOST_REQUIRE_MESSAGE( ps.family_size() == 1, "Expected subset was not removed from family " << ps.family_size() << " (1)" ); BOOST_REQUIRE_MESSAGE( fs == bpb, "Unexpected free size " << fs << " (" << bpb << ")" ); BOOST_REQUIRE_MESSAGE( ps.fixed_size() == 1, "Unexpected fixed size " << ps.fixed_size() << " (1)"); typename powerset_type::element_index_type idx2 = ps.find_or_create(te); BOOST_REQUIRE_MESSAGE( idx != idx2, "After pruning, fixed element has same index. Should be different"); BOOST_REQUIRE_MESSAGE( idx2 == ps.encode_index(0, true), "Unxpected fixed index " << idx2 << " (" << ps.encode_index(0, true) << ")"); bool is_fixed = ps.decode_index(idx2); BOOST_REQUIRE_MESSAGE( is_fixed, "Unexpected state decoding false (true)" ); BOOST_REQUIRE_MESSAGE( idx2 == 0, "Unexpected index decoded " << idx2 << " (0)"); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#ifndef OCLUTIL_OCLUTIL_HPP #define OCLUTIL_OCLUTIL_HPP /** * \file oclutil.hpp * \author Denis Demidov <ddemidov@ksu.ru> * \brief OpenCL convenience utilities. */ /** \mainpage oclutil oclutil is header-only template library created for ease of C++ based OpenCL development. Vector arithmetic and multidevice computation is supported. \section devlist Selection of compute devices You can select any number of available compute devices, which satisfy provided filters. Filter is a functor returning bool and acting on a cl::Device parameter. Several standard filters are provided, such as device type or name filter, double precision support etc. Filters can be combined with logical operators. In the example below all devices with names matching "Radeon" and supporting double precision are selected: \code #include <iostream> #include <oclutil/oclutil.hpp> using namespace clu; int main() { auto device = device_list( Filter::Name("Radeon") && Filter::DoublePrecision() ); std::cout << device.size() << " GPUs found:" << std::endl; for(auto &d : device) std::cout << "\t" << d.getInfo<CL_DEVICE_NAME>() << std::endl; } \endcode Often you want not just device list, but initialized OpenCL context with command queue on each available device. This may be achieved with queue_list() function: \code cl::Context context; std::vector<cl::CommandQueue> queue; // Select no more than 2 NVIDIA GPUs: std::tie(context, queue) = queue_list( [](const cl::Device &d) { return d.getInfo<CL_DEVICE_VENDOR>() == "NVIDIA Corporation"; } && Filter::Count(2) ); \endcode \section vector Memory allocation and vector arithmetic Once you got queue list, you can allocate OpenCL buffers on the associated devices. clu::vector constructor accepts std::vector of cl::CommandQueue. The contents of the created vector will be equally partitioned between each queue (presumably, each of the provided queues is linked with separate device). \code const uint n = 1 << 20; std::vector<double> x(n); std::generate(x.begin(), x.end(), [](){ return (double)rand() / RAND_MAX; }); cl::Context context; std::vector<cl::CommandQueue> queue; std::tie(context, queue) = queue_list(Filter::Type(CL_DEVICE_TYPE_GPU)); clu::vector<double> X(queue, CL_MEM_READ_ONLY, x); clu::vector<double> Y(queue, CL_MEM_READ_WRITE, n); clu::vector<double> Z(queue, CL_MEM_READ_WRITE, n); \endcode You can now use simple vector arithmetic with device vector. For every expression you use, appropriate kernel is compiled (first time it is encountered in your program) and called automagically. Vectors are processed in parallel across all devices they were allocated on: \code Y = Const(42); Z = sqrt(Const(2) * X) + cos(Y); \endcode You can copy the result back to host or you can use vector::operator[] to read (or write) vector elements diectly. Though latter technique is very ineffective and should be used for debugging purposes only. \code copy(Z, x); assert(x[42] == Z[42]); \endcode Another frequently performed operation is reduction of a vector expresion to single value, such as summation. This can be done with clu::Reductor class: \code Reductor<double> sum(queue); std::cout << sum(Z) << std::endl; std::cout << sum(sqrt(Const(2) * X) + cos(Y)) << std::endl; \endcode \section spmv Sparse matrix-vector multiplication One of the most common operations in linear algebra is matrix-vector multiplication. Class clu::SpMat holds representation of a sparse matrix, spanning several GPUs. In the example below it is used for solution of a system of linear equations with conjugate gradients method: \code typedef double real; // Solve system of linear equations A u = f with conjugate gradients method. // Input matrix is represented in CSR format (parameters row, col, and val). void cg_gpu( const std::vector<uint> &row, // Indices to col and val vectors. const std::vector<uint> &col, // Column numbers of non-zero elements. const std::vector<real> &val, // Values of non-zero elements. const std::vector<real> &rhs, // Right-hand side. std::vector<real> &x // In: initial approximation; out: result. ) { // Init OpenCL cl::Context context; std::vector<cl::CommandQueue> queue; std::tie(context, queue) = queue_list(Filter::Type(CL_DEVICE_TYPE_GPU)); // Move data to GPU(s) uint n = x.size(); clu::SpMat<real> A(queue, queue, n, row.data(), col.data(), val.data()); clu::vector<real> f(queue, CL_MEM_READ_ONLY, rhs); clu::vector<real> u(queue, CL_MEM_READ_WRITE, x); clu::vector<real> r(queue, CL_MEM_READ_WRITE, n); clu::vector<real> p(queue, CL_MEM_READ_WRITE, n); clu::vector<real> q(queue, CL_MEM_READ_WRITE, n); Reductor<real,MAX> max(queue); // Solve equation Au = f with conjugate gradients method. real rho1, rho2; q = A * u; r = f - q; for(uint iter = 0; max(Abs(r)) > 1e-8 && iter < n; iter++) { rho1 = inner_product(r, r); if (iter == 0) { p = r; } else { real beta = rho1 / rho2; p = r + Const(beta) * p; } q = A * p; real alpha = rho1 / inner_product(p, q); u = u + Const(alpha) * p; r = r - Const(alpha) * q; rho2 = rho1; } // Get result to host. copy(u, x); } \endcode \section custkern Using custom kernels Custom kernels are of course possible as well. vector::operator(uint) returns cl::Buffer object for a specified device: \code cl::Context context; std::vector<cl::CommandQueue> queue; std::tie(context, queue) = queue_list(Filter::Type(CL_DEVICE_TYPE_GPU)); const uint n = 1 << 20; clu::vector<float> x(queue, CL_MEM_WRITE_ONLY, n); auto program = build_sources(context, std::string( "kernel void dummy(uint size, global float *x)\n" "{\n" " uint i = get_global_id(0);\n" " if (i < size) x[i] = 4.2;\n" "}\n" )); for(uint d = 0; d < queue.size(); d++) { auto dummy = cl::Kernel(program, "dummy").bind(queue[d], alignup(n, 256), 256); dummy((uint)x.part_size(d), x(d)); } std::cout << sum(x) << std::endl; \endcode */ #ifdef WIN32 # pragma warning(disable : 4290) # define NOMINMAX #endif #include <CL/cl.hpp> #include <iostream> #include <oclutil/util.hpp> #include <oclutil/devlist.hpp> #include <oclutil/vector.hpp> #include <oclutil/spmat.hpp> #include <oclutil/reduce.hpp> #endif <commit_msg>Referenced github repo in documentation<commit_after>#ifndef OCLUTIL_OCLUTIL_HPP #define OCLUTIL_OCLUTIL_HPP /** * \file oclutil.hpp * \author Denis Demidov <ddemidov@ksu.ru> * \brief OpenCL convenience utilities. */ /** \mainpage oclutil oclutil is header-only template library created for ease of C++ based OpenCL development. Vector arithmetic and multidevice computation is supported. The source code is available at https://github.com/ddemidov/oclutil. \section devlist Selection of compute devices You can select any number of available compute devices, which satisfy provided filters. Filter is a functor returning bool and acting on a cl::Device parameter. Several standard filters are provided, such as device type or name filter, double precision support etc. Filters can be combined with logical operators. In the example below all devices with names matching "Radeon" and supporting double precision are selected: \code #include <iostream> #include <oclutil/oclutil.hpp> using namespace clu; int main() { auto device = device_list( Filter::Name("Radeon") && Filter::DoublePrecision() ); std::cout << device.size() << " GPUs found:" << std::endl; for(auto &d : device) std::cout << "\t" << d.getInfo<CL_DEVICE_NAME>() << std::endl; } \endcode Often you want not just device list, but initialized OpenCL context with command queue on each available device. This may be achieved with queue_list() function: \code cl::Context context; std::vector<cl::CommandQueue> queue; // Select no more than 2 NVIDIA GPUs: std::tie(context, queue) = queue_list( [](const cl::Device &d) { return d.getInfo<CL_DEVICE_VENDOR>() == "NVIDIA Corporation"; } && Filter::Count(2) ); \endcode \section vector Memory allocation and vector arithmetic Once you got queue list, you can allocate OpenCL buffers on the associated devices. clu::vector constructor accepts std::vector of cl::CommandQueue. The contents of the created vector will be equally partitioned between each queue (presumably, each of the provided queues is linked with separate device). \code const uint n = 1 << 20; std::vector<double> x(n); std::generate(x.begin(), x.end(), [](){ return (double)rand() / RAND_MAX; }); cl::Context context; std::vector<cl::CommandQueue> queue; std::tie(context, queue) = queue_list(Filter::Type(CL_DEVICE_TYPE_GPU)); clu::vector<double> X(queue, CL_MEM_READ_ONLY, x); clu::vector<double> Y(queue, CL_MEM_READ_WRITE, n); clu::vector<double> Z(queue, CL_MEM_READ_WRITE, n); \endcode You can now use simple vector arithmetic with device vector. For every expression you use, appropriate kernel is compiled (first time it is encountered in your program) and called automagically. Vectors are processed in parallel across all devices they were allocated on: \code Y = Const(42); Z = sqrt(Const(2) * X) + cos(Y); \endcode You can copy the result back to host or you can use vector::operator[] to read (or write) vector elements diectly. Though latter technique is very ineffective and should be used for debugging purposes only. \code copy(Z, x); assert(x[42] == Z[42]); \endcode Another frequently performed operation is reduction of a vector expresion to single value, such as summation. This can be done with clu::Reductor class: \code Reductor<double> sum(queue); std::cout << sum(Z) << std::endl; std::cout << sum(sqrt(Const(2) * X) + cos(Y)) << std::endl; \endcode \section spmv Sparse matrix-vector multiplication One of the most common operations in linear algebra is matrix-vector multiplication. Class clu::SpMat holds representation of a sparse matrix, spanning several GPUs. In the example below it is used for solution of a system of linear equations with conjugate gradients method: \code typedef double real; // Solve system of linear equations A u = f with conjugate gradients method. // Input matrix is represented in CSR format (parameters row, col, and val). void cg_gpu( const std::vector<uint> &row, // Indices to col and val vectors. const std::vector<uint> &col, // Column numbers of non-zero elements. const std::vector<real> &val, // Values of non-zero elements. const std::vector<real> &rhs, // Right-hand side. std::vector<real> &x // In: initial approximation; out: result. ) { // Init OpenCL cl::Context context; std::vector<cl::CommandQueue> queue; std::tie(context, queue) = queue_list(Filter::Type(CL_DEVICE_TYPE_GPU)); // Move data to GPU(s) uint n = x.size(); clu::SpMat<real> A(queue, queue, n, row.data(), col.data(), val.data()); clu::vector<real> f(queue, CL_MEM_READ_ONLY, rhs); clu::vector<real> u(queue, CL_MEM_READ_WRITE, x); clu::vector<real> r(queue, CL_MEM_READ_WRITE, n); clu::vector<real> p(queue, CL_MEM_READ_WRITE, n); clu::vector<real> q(queue, CL_MEM_READ_WRITE, n); Reductor<real,MAX> max(queue); // Solve equation Au = f with conjugate gradients method. real rho1, rho2; q = A * u; r = f - q; for(uint iter = 0; max(Abs(r)) > 1e-8 && iter < n; iter++) { rho1 = inner_product(r, r); if (iter == 0) { p = r; } else { real beta = rho1 / rho2; p = r + Const(beta) * p; } q = A * p; real alpha = rho1 / inner_product(p, q); u = u + Const(alpha) * p; r = r - Const(alpha) * q; rho2 = rho1; } // Get result to host. copy(u, x); } \endcode \section custkern Using custom kernels Custom kernels are of course possible as well. vector::operator(uint) returns cl::Buffer object for a specified device: \code cl::Context context; std::vector<cl::CommandQueue> queue; std::tie(context, queue) = queue_list(Filter::Type(CL_DEVICE_TYPE_GPU)); const uint n = 1 << 20; clu::vector<float> x(queue, CL_MEM_WRITE_ONLY, n); auto program = build_sources(context, std::string( "kernel void dummy(uint size, global float *x)\n" "{\n" " uint i = get_global_id(0);\n" " if (i < size) x[i] = 4.2;\n" "}\n" )); for(uint d = 0; d < queue.size(); d++) { auto dummy = cl::Kernel(program, "dummy").bind(queue[d], alignup(n, 256), 256); dummy((uint)x.part_size(d), x(d)); } std::cout << sum(x) << std::endl; \endcode */ #ifdef WIN32 # pragma warning(disable : 4290) # define NOMINMAX #endif #include <CL/cl.hpp> #include <iostream> #include <oclutil/util.hpp> #include <oclutil/devlist.hpp> #include <oclutil/vector.hpp> #include <oclutil/spmat.hpp> #include <oclutil/reduce.hpp> #endif <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr> // // 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/. #include "main.h" #include <unsupported/Eigen/AlignedVector3> template<typename Scalar> void alignedvector3() { Scalar s1 = internal::random<Scalar>(); Scalar s2 = internal::random<Scalar>(); typedef Matrix<Scalar,3,1> RefType; typedef Matrix<Scalar,3,3> Mat33; typedef AlignedVector3<Scalar> FastType; RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()), r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random()); FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6); Mat33 m1(Mat33::Random()); VERIFY_IS_APPROX(f1,r1); VERIFY_IS_APPROX(f4,r4); VERIFY_IS_APPROX(f4+f1,r4+r1); VERIFY_IS_APPROX(f4-f1,r4-r1); VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2); VERIFY_IS_APPROX(f4+=f3,r4+=r3); VERIFY_IS_APPROX(f4-=f5,r4-=r5); VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1); VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2); VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2); VERIFY_IS_APPROX(m1*f4,m1*r4); VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1); VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3)); VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3)); VERIFY_IS_APPROX(f2.norm(),r2.norm()); VERIFY_IS_APPROX(f2.normalized(),r2.normalized()); VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized()); f2.normalize(); r2.normalize(); VERIFY_IS_APPROX(f2,r2); } void test_alignedvector3() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST( alignedvector3<float>() ); } } <commit_msg>Fix compilation of alignedvector3 unit test<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr> // // 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/. #include "main.h" #include <unsupported/Eigen/AlignedVector3> namespace Eigen { template<typename T,typename Derived> T test_relative_error(const AlignedVector3<T> &a, const MatrixBase<Derived> &b) { return test_relative_error(a.coeffs().template head<3>(), b); } } template<typename Scalar> void alignedvector3() { Scalar s1 = internal::random<Scalar>(); Scalar s2 = internal::random<Scalar>(); typedef Matrix<Scalar,3,1> RefType; typedef Matrix<Scalar,3,3> Mat33; typedef AlignedVector3<Scalar> FastType; RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()), r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random()); FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6); Mat33 m1(Mat33::Random()); VERIFY_IS_APPROX(f1,r1); VERIFY_IS_APPROX(f4,r4); VERIFY_IS_APPROX(f4+f1,r4+r1); VERIFY_IS_APPROX(f4-f1,r4-r1); VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2); VERIFY_IS_APPROX(f4+=f3,r4+=r3); VERIFY_IS_APPROX(f4-=f5,r4-=r5); VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1); VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2); VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2); VERIFY_IS_APPROX(m1*f4,m1*r4); VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1); VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3)); VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3)); VERIFY_IS_APPROX(f2.norm(),r2.norm()); VERIFY_IS_APPROX(f2.normalized(),r2.normalized()); VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized()); f2.normalize(); r2.normalize(); VERIFY_IS_APPROX(f2,r2); } void test_alignedvector3() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST( alignedvector3<float>() ); } } <|endoftext|>
<commit_before>/* pvsops.c: pvs and other spectral-based opcodes Copyright (C) 2017 Victor Lazzarini This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <algorithm> #include <plugin.h> struct PVTrace : csnd::FPlugin<1, 2> { csnd::AuxMem<float> amps; static constexpr char const *otypes = "f"; static constexpr char const *itypes = "fk"; int init() { if (inargs.fsig_data(0).isSliding()) return csound->init_error(Str("sliding not supported")); if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs && inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar) return csound->init_error(Str("fsig format not supported")); amps.allocate(csound, inargs.fsig_data(0).nbins()); csnd::Fsig &fout = outargs.fsig_data(0); fout.init(csound, inargs.fsig_data(0)); framecount = 0; return OK; } int kperf() { csnd::pv_frame &fin = inargs.fsig_data(0); csnd::pv_frame &fout = outargs.fsig_data(0); if (framecount < fin.count()) { int n = fin.len() - (int)inargs[1]; float thrsh; std::transform(fin.begin(), fin.end(), amps.begin(), [](csnd::pv_bin f) { return f.amp(); }); std::nth_element(amps.begin(), amps.begin() + n, amps.end()); thrsh = amps[n]; std::transform(fin.begin(), fin.end(), fout.begin(), [thrsh](csnd::pv_bin f) { return f.amp() >= thrsh ? f : csnd::pv_bin(); }); framecount = fout.count(fin.count()); } return OK; } }; struct TVConv : csnd::Plugin<1, 6> { csnd::AuxMem<MYFLT> ir; csnd::AuxMem<MYFLT> in; csnd::AuxMem<MYFLT> insp; csnd::AuxMem<MYFLT> irsp; csnd::AuxMem<MYFLT> out; csnd::AuxMem<MYFLT> saved; csnd::AuxMem<MYFLT>::iterator itn; csnd::AuxMem<MYFLT>::iterator itr; csnd::AuxMem<MYFLT>::iterator itnsp; csnd::AuxMem<MYFLT>::iterator itrsp; uint32_t n; uint32_t fils; uint32_t pars; uint32_t ffts; csnd::fftp fwd, inv; typedef std::complex<MYFLT> cmplx; uint32_t rpow2(uint32_t n) { uint32_t v = 2; while (v <= n) v <<= 1; if ((n - (v >> 1)) < (v - n)) return v >> 1; else return v; } cmplx *to_cmplx(MYFLT *f) { return reinterpret_cast<cmplx *>(f); } cmplx real_prod(cmplx &a, cmplx &b) { return cmplx(a.real() * b.real(), a.imag() * b.imag()); } int init() { pars = inargs[4]; fils = inargs[5]; if (pars > fils) std::swap(pars, fils); if (pars > 1) { pars = rpow2(pars); fils = rpow2(fils) * 2; ffts = pars * 2; fwd = csound->fft_setup(ffts, FFT_FWD); inv = csound->fft_setup(ffts, FFT_INV); out.allocate(csound, 2 * pars); insp.allocate(csound, 2 * fils); irsp.allocate(csound, 2 * fils); saved.allocate(csound, pars); ir.allocate(csound, 2 * fils); in.allocate(csound, 2 * fils); itnsp = insp.begin(); itrsp = insp.begin(); n = 0; } else { ir.allocate(csound, fils); in.allocate(csound, fils); } itn = in.begin(); itr = ir.begin(); return OK; } int pconv() { csnd::AudioSig insig(this, inargs(0)); csnd::AudioSig irsig(this, inargs(1)); csnd::AudioSig outsig(this, outargs(0)); auto irp = irsig.begin(); auto inp = insig.begin(); auto *frz1 = inargs(2); auto *frz2 = inargs(3); auto inc1 = csound->is_asig(frz1); auto inc2 = csound->is_asig(frz2); for (auto &s : outsig) { if(*frz1 > 0) itn[n] = *inp; if(*frz2 > 0) itr[n] = *irp; s = out[n] + saved[n]; saved[n] = out[n + pars]; if (++n == pars) { cmplx *ins, *irs, *ous = to_cmplx(out.data()); std::copy(itn, itn + ffts, itnsp); std::copy(itr, itr + ffts, itrsp); std::fill(out.begin(), out.end(), 0.); // FFT csound->rfft(fwd, itnsp); csound->rfft(fwd, itrsp); // increment iterators itnsp += ffts; itrsp += ffts; itn += ffts; itr += ffts; if (itnsp == insp.end()) { itnsp = insp.begin(); itrsp = irsp.begin(); itn = in.begin(); itr = ir.begin(); } // spectral delay line for (csnd::AuxMem<MYFLT>::iterator it1 = itnsp, it2 = irsp.end() - ffts; it2 >= irsp.begin(); it1 += ffts, it2 -= ffts) { if (it1 == insp.end()) it1 = insp.begin(); ins = to_cmplx(it1); irs = to_cmplx(it2); // spectral product for (uint32_t i = 1; i < pars; i++) ous[i] += ins[i] * irs[i]; ous[0] += real_prod(ins[0], irs[0]); } // IFFT csound->rfft(inv, out.data()); n = 0; } frz1 += inc1; frz2 += inc2; irp++; inp++; } return OK; } int dconv() { csnd::AudioSig insig(this, inargs(0)); csnd::AudioSig irsig(this, inargs(1)); csnd::AudioSig outsig(this, outargs(0)); auto irp = irsig.begin(); auto inp = insig.begin(); auto frz1 = inargs(2); auto frz2 = inargs(3); auto inc1 = csound->is_asig(frz1); auto inc2 = csound->is_asig(frz2); for (auto &s : outsig) { if(*frz1 > 0) *itn++ = *inp; if(*frz2 > 0) *itr++ = *irp; if(itn == in.end()) itn = in.begin(); if(itr == ir.end()) itr = ir.begin(); s = 0.; for (csnd::AuxMem<MYFLT>::iterator it1 = itn, it2 = ir.end() - 1; it2 >= ir.begin(); it1++, it2--) { if(it1 == in.end()) it1 = in.begin(); s += *it1 * *it2; } frz1 += inc1; frz2 += inc2; inp++; irp++; } return OK; } int aperf() { if (pars > 1) return pconv(); else return dconv(); } }; /* class PrintThread : public csnd::Thread { std::atomic_bool splock; std::atomic_bool on; std::string message; void lock() { bool tmp = false; while(!splock.compare_exchange_weak(tmp,true)) tmp = false; } void unlock() { splock = false; } uintptr_t run() { std::string old; while(on) { lock(); if(old.compare(message)) { csound->message(message.c_str()); old = message; } unlock(); } return 0; } public: PrintThread(csnd::Csound *csound) : Thread(csound), splock(false), on(true), message("") {}; ~PrintThread(){ on = false; join(); } void set_message(const char *m) { lock(); message = m; unlock(); } }; struct TPrint : csnd::Plugin<0, 1> { static constexpr char const *otypes = ""; static constexpr char const *itypes = "S"; PrintThread t; int init() { csound->plugin_deinit(this); csnd::constr(&t, csound); return OK; } int deinit() { csnd::destr(&t); return OK; } int kperf() { t.set_message(inargs.str_data(0).data); return OK; } }; */ #include <modload.h> void csnd::on_load(Csound *csound) { csnd::plugin<PVTrace>(csound, "pvstrace", csnd::thread::ik); csnd::plugin<TVConv>(csound, "tvconv", "a", "aaxxii", csnd::thread::ia); } <commit_msg>little tweak<commit_after>/* pvsops.c: pvs and other spectral-based opcodes Copyright (C) 2017 Victor Lazzarini This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <algorithm> #include <plugin.h> struct PVTrace : csnd::FPlugin<1, 2> { csnd::AuxMem<float> amps; static constexpr char const *otypes = "f"; static constexpr char const *itypes = "fk"; int init() { if (inargs.fsig_data(0).isSliding()) return csound->init_error(Str("sliding not supported")); if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs && inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar) return csound->init_error(Str("fsig format not supported")); amps.allocate(csound, inargs.fsig_data(0).nbins()); csnd::Fsig &fout = outargs.fsig_data(0); fout.init(csound, inargs.fsig_data(0)); framecount = 0; return OK; } int kperf() { csnd::pv_frame &fin = inargs.fsig_data(0); csnd::pv_frame &fout = outargs.fsig_data(0); if (framecount < fin.count()) { int n = fin.len() - (int)inargs[1]; float thrsh; std::transform(fin.begin(), fin.end(), amps.begin(), [](csnd::pv_bin f) { return f.amp(); }); std::nth_element(amps.begin(), amps.begin() + n, amps.end()); thrsh = amps[n]; std::transform(fin.begin(), fin.end(), fout.begin(), [thrsh](csnd::pv_bin f) { return f.amp() >= thrsh ? f : csnd::pv_bin(); }); framecount = fout.count(fin.count()); } return OK; } }; struct TVConv : csnd::Plugin<1, 6> { csnd::AuxMem<MYFLT> ir; csnd::AuxMem<MYFLT> in; csnd::AuxMem<MYFLT> insp; csnd::AuxMem<MYFLT> irsp; csnd::AuxMem<MYFLT> out; csnd::AuxMem<MYFLT> saved; csnd::AuxMem<MYFLT>::iterator itn; csnd::AuxMem<MYFLT>::iterator itr; csnd::AuxMem<MYFLT>::iterator itnsp; csnd::AuxMem<MYFLT>::iterator itrsp; uint32_t n; uint32_t fils; uint32_t pars; uint32_t ffts; csnd::fftp fwd, inv; typedef std::complex<MYFLT> cmplx; uint32_t rpow2(uint32_t n) { uint32_t v = 2; while (v <= n) v <<= 1; if ((n - (v >> 1)) < (v - n)) return v >> 1; else return v; } cmplx *to_cmplx(MYFLT *f) { return reinterpret_cast<cmplx *>(f); } cmplx real_prod(cmplx &a, cmplx &b) { return cmplx(a.real() * b.real(), a.imag() * b.imag()); } int init() { pars = inargs[4]; fils = inargs[5]; if (pars > fils) std::swap(pars, fils); if (pars > 1) { pars = rpow2(pars); fils = rpow2(fils) * 2; ffts = pars * 2; fwd = csound->fft_setup(ffts, FFT_FWD); inv = csound->fft_setup(ffts, FFT_INV); out.allocate(csound, ffts); insp.allocate(csound, fils); irsp.allocate(csound, fils); saved.allocate(csound, pars); ir.allocate(csound, fils); in.allocate(csound, fils); itnsp = insp.begin(); itrsp = insp.begin(); n = 0; } else { ir.allocate(csound, fils); in.allocate(csound, fils); } itn = in.begin(); itr = ir.begin(); return OK; } int pconv() { csnd::AudioSig insig(this, inargs(0)); csnd::AudioSig irsig(this, inargs(1)); csnd::AudioSig outsig(this, outargs(0)); auto irp = irsig.begin(); auto inp = insig.begin(); auto *frz1 = inargs(2); auto *frz2 = inargs(3); auto inc1 = csound->is_asig(frz1); auto inc2 = csound->is_asig(frz2); for (auto &s : outsig) { if(*frz1 > 0) itn[n] = *inp; if(*frz2 > 0) itr[n] = *irp; s = out[n] + saved[n]; saved[n] = out[n + pars]; if (++n == pars) { cmplx *ins, *irs, *ous = to_cmplx(out.data()); std::copy(itn, itn + ffts, itnsp); std::copy(itr, itr + ffts, itrsp); std::fill(out.begin(), out.end(), 0.); // FFT csound->rfft(fwd, itnsp); csound->rfft(fwd, itrsp); // increment iterators itnsp += ffts; itrsp += ffts; itn += ffts; itr += ffts; if (itnsp == insp.end()) { itnsp = insp.begin(); itrsp = irsp.begin(); itn = in.begin(); itr = ir.begin(); } // spectral delay line for (csnd::AuxMem<MYFLT>::iterator it1 = itnsp, it2 = irsp.end() - ffts; it2 >= irsp.begin(); it1 += ffts, it2 -= ffts) { if (it1 == insp.end()) it1 = insp.begin(); ins = to_cmplx(it1); irs = to_cmplx(it2); // spectral product for (uint32_t i = 1; i < pars; i++) ous[i] += ins[i] * irs[i]; ous[0] += real_prod(ins[0], irs[0]); } // IFFT csound->rfft(inv, out.data()); n = 0; } frz1 += inc1; frz2 += inc2; irp++; inp++; } return OK; } int dconv() { csnd::AudioSig insig(this, inargs(0)); csnd::AudioSig irsig(this, inargs(1)); csnd::AudioSig outsig(this, outargs(0)); auto irp = irsig.begin(); auto inp = insig.begin(); auto frz1 = inargs(2); auto frz2 = inargs(3); auto inc1 = csound->is_asig(frz1); auto inc2 = csound->is_asig(frz2); for (auto &s : outsig) { if(*frz1 > 0) *itn++ = *inp; if(*frz2 > 0) *itr++ = *irp; if(itn == in.end()) itn = in.begin(); if(itr == ir.end()) itr = ir.begin(); s = 0.; for (csnd::AuxMem<MYFLT>::iterator it1 = itn, it2 = ir.end() - 1; it2 >= ir.begin(); it1++, it2--) { if(it1 == in.end()) it1 = in.begin(); s += *it1 * *it2; } frz1 += inc1; frz2 += inc2; inp++; irp++; } return OK; } int aperf() { if (pars > 1) return pconv(); else return dconv(); } }; /* class PrintThread : public csnd::Thread { std::atomic_bool splock; std::atomic_bool on; std::string message; void lock() { bool tmp = false; while(!splock.compare_exchange_weak(tmp,true)) tmp = false; } void unlock() { splock = false; } uintptr_t run() { std::string old; while(on) { lock(); if(old.compare(message)) { csound->message(message.c_str()); old = message; } unlock(); } return 0; } public: PrintThread(csnd::Csound *csound) : Thread(csound), splock(false), on(true), message("") {}; ~PrintThread(){ on = false; join(); } void set_message(const char *m) { lock(); message = m; unlock(); } }; struct TPrint : csnd::Plugin<0, 1> { static constexpr char const *otypes = ""; static constexpr char const *itypes = "S"; PrintThread t; int init() { csound->plugin_deinit(this); csnd::constr(&t, csound); return OK; } int deinit() { csnd::destr(&t); return OK; } int kperf() { t.set_message(inargs.str_data(0).data); return OK; } }; */ #include <modload.h> void csnd::on_load(Csound *csound) { csnd::plugin<PVTrace>(csound, "pvstrace", csnd::thread::ik); csnd::plugin<TVConv>(csound, "tvconv", "a", "aaxxii", csnd::thread::ia); } <|endoftext|>
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #ifndef __RAPICORN_AIDA_PROPS_HH__ #define __RAPICORN_AIDA_PROPS_HH__ #include <rcore/aida.hh> #include <rcore/strings.hh> namespace Rapicorn { namespace Aida { // == PropertyHostInterface == typedef ImplicitBase PropertyHostInterface; // == Property == class Property { protected: virtual ~Property(); public: const char *ident; char *label; char *blurb; char *hints; Property (const char *cident, const char *clabel, const char *cblurb, const char *chints); virtual void set_value (PropertyHostInterface &obj, const String &svalue) = 0; virtual String get_value (PropertyHostInterface &obj) = 0; virtual bool get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &stepping) = 0; bool readable () const; bool writable () const; }; // == PropertyList == struct PropertyList /// Container structure for property descriptions. { typedef Aida::Property Property; // make Property available as class member private: size_t n_properties_; Property **properties_; void append_properties (size_t n_props, Property **props, const PropertyList &c0, const PropertyList &c1, const PropertyList &c2, const PropertyList &c3, const PropertyList &c4, const PropertyList &c5, const PropertyList &c6, const PropertyList &c7, const PropertyList &c8, const PropertyList &c9); public: Property** list_properties (size_t *n_properties) const; /*dtor*/ ~PropertyList (); explicit PropertyList () : n_properties_ (0), properties_ (NULL) {} template<typename Array> explicit PropertyList (Array &a, const PropertyList &c0 = PropertyList(), const PropertyList &c1 = PropertyList(), const PropertyList &c2 = PropertyList(), const PropertyList &c3 = PropertyList(), const PropertyList &c4 = PropertyList(), const PropertyList &c5 = PropertyList(), const PropertyList &c6 = PropertyList(), const PropertyList &c7 = PropertyList(), const PropertyList &c8 = PropertyList(), const PropertyList &c9 = PropertyList()) : n_properties_ (0), properties_ (NULL) { const size_t n_props = sizeof (a) / sizeof (a[0]); Property *props[n_props]; for (size_t i = 0; i < sizeof (a) / sizeof (a[0]); i++) props[i] = a[i]; append_properties (n_props, props, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9); } }; // == Property Creation == #define RAPICORN_AIDA_PROPERTY(Type, accessor, label, blurb, ...) \ Rapicorn::Aida::create_property (&Type::accessor, &Type::accessor, #accessor, label, blurb, __VA_ARGS__) #define RAPICORN_AIDA_PROPERTY_CHAIN(first,...) (*({ \ static Property *__dummy_[] = {}; \ static const PropertyList property_list (__dummy_, first, __VA_ARGS__); \ &property_list; })) /* --- bool --- */ template<class Class> struct PropertyBool : Property { void (Class::*setter) (bool); bool (Class::*getter) () const; PropertyBool (void (Class::*csetter) (bool), bool (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const char *chints); virtual void set_value (PropertyHostInterface &obj, const String &svalue); virtual String get_value (PropertyHostInterface &obj); virtual bool get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &stepping) { return false; } }; template<class Class> inline Property* create_property (void (Class::*setter) (bool), bool (Class::*getter) () const, const char *ident, const char *label, const char *blurb, const char *hints) { return new PropertyBool<Class> (setter, getter, ident, label, blurb, hints); } /* --- range --- */ template<class Class, typename Type> struct PropertyRange : Property { Type minimum_value; Type maximum_value; Type stepping; void (Class::*setter) (Type); Type (Class::*getter) () const; PropertyRange (void (Class::*csetter) (Type), Type (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, Type cminimum_value, Type cmaximum_value, Type cstepping, const char *chints); virtual void set_value (PropertyHostInterface &obj, const String &svalue); virtual String get_value (PropertyHostInterface &obj); virtual bool get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &stepping); }; /* int */ template<class Class> inline Property* create_property (void (Class::*setter) (int), int (Class::*getter) () const, const char *ident, const char *label, const char *blurb, int min_value, int max_value, int stepping, const char *hints) { return new PropertyRange<Class,int> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } template<class Class> inline Property* create_property (void (Class::*setter) (int), int (Class::*getter) () const, const char *ident, const char *label, const char *blurb, const char *hints) { return new PropertyRange<Class,int> (setter, getter, ident, label, blurb, INT_MIN, INT_MAX, 1, hints); } /* int16 */ template<class Class> inline Property* create_property (void (Class::*setter) (int16), int16 (Class::*getter) () const, const char *ident, const char *label, const char *blurb, int16 min_value, int16 max_value, int16 stepping, const char *hints) { return new PropertyRange<Class,int16> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } /* uint */ template<class Class> inline Property* create_property (void (Class::*setter) (uint), uint (Class::*getter) () const, const char *ident, const char *label, const char *blurb, uint min_value, uint max_value, uint stepping, const char *hints) { return new PropertyRange<Class,uint> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } /* uint16 */ template<class Class> inline Property* create_property (void (Class::*setter) (uint16), uint16 (Class::*getter) () const, const char *ident, const char *label, const char *blurb, uint16 min_value, uint16 max_value, uint16 stepping, const char *hints) { return new PropertyRange<Class,uint16> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } /* float */ template<class Class> inline Property* create_property (void (Class::*setter) (float), float (Class::*getter) () const, const char *ident, const char *label, const char *blurb, float min_value, float max_value, float stepping, const char *hints) { return new PropertyRange<Class,float> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } /* double */ template<class Class> inline Property* create_property (void (Class::*setter) (double), double (Class::*getter) () const, const char *ident, const char *label, const char *blurb, double min_value, double max_value, double stepping, const char *hints) { return new PropertyRange<Class,double> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } template<class Class> inline Property* create_property (void (Class::*setter) (double), double (Class::*getter) () const, const char *ident, const char *label, const char *blurb, const char *hints) { return new PropertyRange<Class,double> (setter, getter, ident, label, blurb, DBL_MIN, DBL_MAX, 1, hints); } /* --- string --- */ template<class Class> struct PropertyString : Property { void (Class::*setter) (const String&); String (Class::*getter) () const; PropertyString (void (Class::*csetter) (const String&), String (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const char *chints); virtual void set_value (PropertyHostInterface &obj, const String &svalue); virtual String get_value (PropertyHostInterface &obj); virtual bool get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &stepping) { return false; } }; template<class Class> inline Property* create_property (void (Class::*setter) (const String&), String (Class::*getter) () const, const char *ident, const char *label, const char *blurb, const char *hints) { return new PropertyString<Class> (setter, getter, ident, label, blurb, hints); } // == Enum Properties == template<class Class, typename Type> struct PropertyEnum : Property { const EnumValue *const enum_values; void (Class::*setter) (Type); Type (Class::*getter) () const; PropertyEnum (void (Class::*csetter) (Type), Type (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const EnumValue *values, const char *chints); virtual void set_value (PropertyHostInterface &obj, const String &svalue); virtual String get_value (PropertyHostInterface &obj); virtual bool get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &stepping) { return false; } }; template<class Class, typename Type> inline Property* create_property (void (Class::*setter) (Type), Type (Class::*getter) () const, const char *ident, const char *label, const char *blurb, const char *hints) { return new PropertyEnum<Class,Type> (setter, getter, ident, label, blurb, enum_value_list<Type>(), hints); } /* --- implementations --- */ /* bool property implementation */ template<class Class> PropertyBool<Class>::PropertyBool (void (Class::*csetter) (bool), bool (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const char *chints) : Property (cident, clabel, cblurb, chints), setter (csetter), getter (cgetter) {} template<class Class> void PropertyBool<Class>::set_value (PropertyHostInterface &obj, const String &svalue) { bool b = string_to_bool (svalue); Class *instance = dynamic_cast<Class*> (&obj); (instance->*setter) (b); } template<class Class> String PropertyBool<Class>::get_value (PropertyHostInterface &obj) { Class *instance = dynamic_cast<Class*> (&obj); bool b = (instance->*getter) (); return string_from_bool (b); } /* range property implementation */ template<class Class, typename Type> PropertyRange<Class,Type>::PropertyRange (void (Class::*csetter) (Type), Type (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, Type cminimum_value, Type cmaximum_value, Type cstepping, const char *chints) : Property (cident, clabel, cblurb, chints), minimum_value (cminimum_value), maximum_value (cmaximum_value), stepping (cstepping), setter (csetter), getter (cgetter) { AIDA_ASSERT (minimum_value <= maximum_value); AIDA_ASSERT (minimum_value + stepping <= maximum_value); } template<class Class, typename Type> void PropertyRange<Class,Type>::set_value (PropertyHostInterface &obj, const String &svalue) { Type v = string_to_type<Type> (svalue); Class *instance = dynamic_cast<Class*> (&obj); (instance->*setter) (v); } template<class Class, typename Type> String PropertyRange<Class,Type>::get_value (PropertyHostInterface &obj) { Class *instance = dynamic_cast<Class*> (&obj); Type v = (instance->*getter) (); return string_from_type<Type> (v); } template<class Class, typename Type> bool PropertyRange<Class,Type>::get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &vstepping) { minimum = minimum_value, maximum = maximum_value, vstepping = stepping; return true; } /* string property implementation */ template<class Class> PropertyString<Class>::PropertyString (void (Class::*csetter) (const String&), String (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const char *chints) : Property (cident, clabel, cblurb, chints), setter (csetter), getter (cgetter) {} template<class Class> void PropertyString<Class>::set_value (PropertyHostInterface &obj, const String &svalue) { Class *instance = dynamic_cast<Class*> (&obj); (instance->*setter) (svalue); } template<class Class> String PropertyString<Class>::get_value (PropertyHostInterface &obj) { Class *instance = dynamic_cast<Class*> (&obj); return (instance->*getter) (); } /* enum property implementation */ template<class Class, typename Type> PropertyEnum<Class,Type>::PropertyEnum (void (Class::*csetter) (Type), Type (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const EnumValue *values, const char *chints) : Property (cident, clabel, cblurb, chints), enum_values (values), setter (csetter), getter (cgetter) {} template<class Class, typename Type> void PropertyEnum<Class,Type>::set_value (PropertyHostInterface &obj, const String &svalue) { String error_string; const EnumValue *ev = enum_value_find (enum_values, svalue.c_str()); if (!ev) print_warning (String (__PRETTY_FUNCTION__) + ": invalid enum value name: " + svalue); Type v = Type (ev ? ev->value : 0); Class *instance = dynamic_cast<Class*> (&obj); (instance->*setter) (v); } template<class Class, typename Type> String PropertyEnum<Class,Type>::get_value (PropertyHostInterface &obj) { Class *instance = dynamic_cast<Class*> (&obj); Type v = (instance->*getter) (); const EnumValue *ev = enum_value_find (enum_values, v); if (!ev) print_warning (String (__PRETTY_FUNCTION__) + ": unrecognized enum value"); return ev ? ev->ident : ""; } } } // Rapicorn::Aida #endif // __RAPICORN_AIDA_PROPS_HH__ <commit_msg>RCORE: aidaprops: ensure create_property<Enum>() only matches Enum types<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #ifndef __RAPICORN_AIDA_PROPS_HH__ #define __RAPICORN_AIDA_PROPS_HH__ #include <rcore/aida.hh> #include <rcore/strings.hh> namespace Rapicorn { namespace Aida { // == PropertyHostInterface == typedef ImplicitBase PropertyHostInterface; // == Property == class Property { protected: virtual ~Property(); public: const char *ident; char *label; char *blurb; char *hints; Property (const char *cident, const char *clabel, const char *cblurb, const char *chints); virtual void set_value (PropertyHostInterface &obj, const String &svalue) = 0; virtual String get_value (PropertyHostInterface &obj) = 0; virtual bool get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &stepping) = 0; bool readable () const; bool writable () const; }; // == PropertyList == struct PropertyList /// Container structure for property descriptions. { typedef Aida::Property Property; // make Property available as class member private: size_t n_properties_; Property **properties_; void append_properties (size_t n_props, Property **props, const PropertyList &c0, const PropertyList &c1, const PropertyList &c2, const PropertyList &c3, const PropertyList &c4, const PropertyList &c5, const PropertyList &c6, const PropertyList &c7, const PropertyList &c8, const PropertyList &c9); public: Property** list_properties (size_t *n_properties) const; /*dtor*/ ~PropertyList (); explicit PropertyList () : n_properties_ (0), properties_ (NULL) {} template<typename Array> explicit PropertyList (Array &a, const PropertyList &c0 = PropertyList(), const PropertyList &c1 = PropertyList(), const PropertyList &c2 = PropertyList(), const PropertyList &c3 = PropertyList(), const PropertyList &c4 = PropertyList(), const PropertyList &c5 = PropertyList(), const PropertyList &c6 = PropertyList(), const PropertyList &c7 = PropertyList(), const PropertyList &c8 = PropertyList(), const PropertyList &c9 = PropertyList()) : n_properties_ (0), properties_ (NULL) { const size_t n_props = sizeof (a) / sizeof (a[0]); Property *props[n_props]; for (size_t i = 0; i < sizeof (a) / sizeof (a[0]); i++) props[i] = a[i]; append_properties (n_props, props, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9); } }; // == Property Creation == #define RAPICORN_AIDA_PROPERTY(Type, accessor, label, blurb, ...) \ Rapicorn::Aida::create_property (&Type::accessor, &Type::accessor, #accessor, label, blurb, __VA_ARGS__) #define RAPICORN_AIDA_PROPERTY_CHAIN(first,...) (*({ \ static Property *__dummy_[] = {}; \ static const PropertyList property_list (__dummy_, first, __VA_ARGS__); \ &property_list; })) /* --- bool --- */ template<class Class> struct PropertyBool : Property { void (Class::*setter) (bool); bool (Class::*getter) () const; PropertyBool (void (Class::*csetter) (bool), bool (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const char *chints); virtual void set_value (PropertyHostInterface &obj, const String &svalue); virtual String get_value (PropertyHostInterface &obj); virtual bool get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &stepping) { return false; } }; template<class Class> inline Property* create_property (void (Class::*setter) (bool), bool (Class::*getter) () const, const char *ident, const char *label, const char *blurb, const char *hints) { return new PropertyBool<Class> (setter, getter, ident, label, blurb, hints); } /* --- range --- */ template<class Class, typename Type> struct PropertyRange : Property { Type minimum_value; Type maximum_value; Type stepping; void (Class::*setter) (Type); Type (Class::*getter) () const; PropertyRange (void (Class::*csetter) (Type), Type (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, Type cminimum_value, Type cmaximum_value, Type cstepping, const char *chints); virtual void set_value (PropertyHostInterface &obj, const String &svalue); virtual String get_value (PropertyHostInterface &obj); virtual bool get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &stepping); }; /* int */ template<class Class> inline Property* create_property (void (Class::*setter) (int), int (Class::*getter) () const, const char *ident, const char *label, const char *blurb, int min_value, int max_value, int stepping, const char *hints) { return new PropertyRange<Class,int> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } template<class Class> inline Property* create_property (void (Class::*setter) (int), int (Class::*getter) () const, const char *ident, const char *label, const char *blurb, const char *hints) { return new PropertyRange<Class,int> (setter, getter, ident, label, blurb, INT_MIN, INT_MAX, 1, hints); } /* int16 */ template<class Class> inline Property* create_property (void (Class::*setter) (int16), int16 (Class::*getter) () const, const char *ident, const char *label, const char *blurb, int16 min_value, int16 max_value, int16 stepping, const char *hints) { return new PropertyRange<Class,int16> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } /* uint */ template<class Class> inline Property* create_property (void (Class::*setter) (uint), uint (Class::*getter) () const, const char *ident, const char *label, const char *blurb, uint min_value, uint max_value, uint stepping, const char *hints) { return new PropertyRange<Class,uint> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } /* uint16 */ template<class Class> inline Property* create_property (void (Class::*setter) (uint16), uint16 (Class::*getter) () const, const char *ident, const char *label, const char *blurb, uint16 min_value, uint16 max_value, uint16 stepping, const char *hints) { return new PropertyRange<Class,uint16> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } /* float */ template<class Class> inline Property* create_property (void (Class::*setter) (float), float (Class::*getter) () const, const char *ident, const char *label, const char *blurb, float min_value, float max_value, float stepping, const char *hints) { return new PropertyRange<Class,float> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } /* double */ template<class Class> inline Property* create_property (void (Class::*setter) (double), double (Class::*getter) () const, const char *ident, const char *label, const char *blurb, double min_value, double max_value, double stepping, const char *hints) { return new PropertyRange<Class,double> (setter, getter, ident, label, blurb, min_value, max_value, stepping, hints); } template<class Class> inline Property* create_property (void (Class::*setter) (double), double (Class::*getter) () const, const char *ident, const char *label, const char *blurb, const char *hints) { return new PropertyRange<Class,double> (setter, getter, ident, label, blurb, DBL_MIN, DBL_MAX, 1, hints); } /* --- string --- */ template<class Class> struct PropertyString : Property { void (Class::*setter) (const String&); String (Class::*getter) () const; PropertyString (void (Class::*csetter) (const String&), String (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const char *chints); virtual void set_value (PropertyHostInterface &obj, const String &svalue); virtual String get_value (PropertyHostInterface &obj); virtual bool get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &stepping) { return false; } }; template<class Class> inline Property* create_property (void (Class::*setter) (const String&), String (Class::*getter) () const, const char *ident, const char *label, const char *blurb, const char *hints) { return new PropertyString<Class> (setter, getter, ident, label, blurb, hints); } // == Enum Properties == template<class Class, typename Type> struct PropertyEnum : Property { const EnumValue *const enum_values; void (Class::*setter) (Type); Type (Class::*getter) () const; PropertyEnum (void (Class::*csetter) (Type), Type (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const EnumValue *values, const char *chints); virtual void set_value (PropertyHostInterface &obj, const String &svalue); virtual String get_value (PropertyHostInterface &obj); virtual bool get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &stepping) { return false; } }; template<class Class, typename Type, typename std::enable_if<std::is_enum<Type>::value>::type* = nullptr> inline Property* create_property (void (Class::*setter) (Type), Type (Class::*getter) () const, const char *ident, const char *label, const char *blurb, const char *hints) { return new PropertyEnum<Class,Type> (setter, getter, ident, label, blurb, enum_value_list<Type>(), hints); } /* --- implementations --- */ /* bool property implementation */ template<class Class> PropertyBool<Class>::PropertyBool (void (Class::*csetter) (bool), bool (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const char *chints) : Property (cident, clabel, cblurb, chints), setter (csetter), getter (cgetter) {} template<class Class> void PropertyBool<Class>::set_value (PropertyHostInterface &obj, const String &svalue) { bool b = string_to_bool (svalue); Class *instance = dynamic_cast<Class*> (&obj); (instance->*setter) (b); } template<class Class> String PropertyBool<Class>::get_value (PropertyHostInterface &obj) { Class *instance = dynamic_cast<Class*> (&obj); bool b = (instance->*getter) (); return string_from_bool (b); } /* range property implementation */ template<class Class, typename Type> PropertyRange<Class,Type>::PropertyRange (void (Class::*csetter) (Type), Type (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, Type cminimum_value, Type cmaximum_value, Type cstepping, const char *chints) : Property (cident, clabel, cblurb, chints), minimum_value (cminimum_value), maximum_value (cmaximum_value), stepping (cstepping), setter (csetter), getter (cgetter) { AIDA_ASSERT (minimum_value <= maximum_value); AIDA_ASSERT (minimum_value + stepping <= maximum_value); } template<class Class, typename Type> void PropertyRange<Class,Type>::set_value (PropertyHostInterface &obj, const String &svalue) { Type v = string_to_type<Type> (svalue); Class *instance = dynamic_cast<Class*> (&obj); (instance->*setter) (v); } template<class Class, typename Type> String PropertyRange<Class,Type>::get_value (PropertyHostInterface &obj) { Class *instance = dynamic_cast<Class*> (&obj); Type v = (instance->*getter) (); return string_from_type<Type> (v); } template<class Class, typename Type> bool PropertyRange<Class,Type>::get_range (PropertyHostInterface &obj, double &minimum, double &maximum, double &vstepping) { minimum = minimum_value, maximum = maximum_value, vstepping = stepping; return true; } /* string property implementation */ template<class Class> PropertyString<Class>::PropertyString (void (Class::*csetter) (const String&), String (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const char *chints) : Property (cident, clabel, cblurb, chints), setter (csetter), getter (cgetter) {} template<class Class> void PropertyString<Class>::set_value (PropertyHostInterface &obj, const String &svalue) { Class *instance = dynamic_cast<Class*> (&obj); (instance->*setter) (svalue); } template<class Class> String PropertyString<Class>::get_value (PropertyHostInterface &obj) { Class *instance = dynamic_cast<Class*> (&obj); return (instance->*getter) (); } /* enum property implementation */ template<class Class, typename Type> PropertyEnum<Class,Type>::PropertyEnum (void (Class::*csetter) (Type), Type (Class::*cgetter) () const, const char *cident, const char *clabel, const char *cblurb, const EnumValue *values, const char *chints) : Property (cident, clabel, cblurb, chints), enum_values (values), setter (csetter), getter (cgetter) {} template<class Class, typename Type> void PropertyEnum<Class,Type>::set_value (PropertyHostInterface &obj, const String &svalue) { String error_string; const EnumValue *ev = enum_value_find (enum_values, svalue.c_str()); if (!ev) print_warning (String (__PRETTY_FUNCTION__) + ": invalid enum value name: " + svalue); Type v = Type (ev ? ev->value : 0); Class *instance = dynamic_cast<Class*> (&obj); (instance->*setter) (v); } template<class Class, typename Type> String PropertyEnum<Class,Type>::get_value (PropertyHostInterface &obj) { Class *instance = dynamic_cast<Class*> (&obj); Type v = (instance->*getter) (); const EnumValue *ev = enum_value_find (enum_values, v); if (!ev) print_warning (String (__PRETTY_FUNCTION__) + ": unrecognized enum value"); return ev ? ev->ident : ""; } } } // Rapicorn::Aida #endif // __RAPICORN_AIDA_PROPS_HH__ <|endoftext|>
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #ifndef __RAPICORN_THREADLIB_HH__ #define __RAPICORN_THREADLIB_HH__ #include <condition_variable> namespace Rapicorn { namespace Lib { #define RAPICORN_CACHE_LINE_ALIGNMENT 128 #define RAPICORN_MFENCE __sync_synchronize() ///< Memory Fence - prevent processor (and compiler) from reordering loads/stores (read/write barrier). #define RAPICORN_SFENCE RAPICORN_X86SFENCE ///< Store Fence - prevent processor (and compiler) from reordering stores (read barrier). #define RAPICORN_LFENCE RAPICORN_X86LFENCE ///< Load Fence - prevent processor (and compiler) from reordering loads (read barrier). #define RAPICORN_CFENCE __asm__ __volatile__ ("" ::: "memory") ///< Compiler Fence, prevent compiler from reordering non-volatiles loads/stores. #define RAPICORN_X86LFENCE __asm__ __volatile__ ("lfence" ::: "memory") ///< X86 lfence - prevent processor from reordering loads (read barrier). #define RAPICORN_X86SFENCE __asm__ __volatile__ ("sfence" ::: "memory") ///< X86 sfence - prevent processor from reordering stores (write barrier). template<typename T> T atomic_load (T volatile *p) { RAPICORN_CFENCE; T t = *p; RAPICORN_LFENCE; return t; } template<typename T> void atomic_store (T volatile *p, T i) { RAPICORN_SFENCE; *p = i; RAPICORN_CFENCE; } template<typename T> class Atomic { T volatile v; /*ctor*/ Atomic () = delete; protected: constexpr Atomic (T i) : v (i) {} Atomic<T>& operator=(Atomic<T> &o) { store (o.load()); return *this; } Atomic<T> volatile& operator=(Atomic<T> &o) volatile { store (o.load()); return *this; } public: T load () const volatile { return atomic_load (&v); } void store (T i) volatile { atomic_store (&v, i); } bool cas (T o, T n) volatile { return __sync_bool_compare_and_swap (&v, o, n); } T operator+=(T i) volatile { return __sync_add_and_fetch (&v, i); } T operator-=(T i) volatile { return __sync_sub_and_fetch (&v, i); } T operator&=(T i) volatile { return __sync_and_and_fetch (&v, i); } T operator^=(T i) volatile { return __sync_xor_and_fetch (&v, i); } T operator|=(T i) volatile { return __sync_or_and_fetch (&v, i); } T operator++() volatile { return __sync_add_and_fetch (&v, 1); } T operator++(int) volatile { return __sync_fetch_and_add (&v, 1); } T operator--() volatile { return __sync_sub_and_fetch (&v, 1); } T operator--(int) volatile { return __sync_fetch_and_sub (&v, 1); } void operator= (T i) volatile { store (i); } operator T () const volatile { return load(); } }; // == Once Scope == void once_list_enter (); bool once_list_bounce (volatile void *ptr); bool once_list_leave (volatile void *ptr); class OnceScope { /*ctor*/ OnceScope (const OnceScope&) = delete; OnceScope& operator= (const OnceScope&) = delete; volatile char *volatile flagp; bool entered_once; public: OnceScope (volatile char *volatile p) : flagp (p), entered_once (false) {} inline bool operator() () { if (RAPICORN_LIKELY (*flagp != 0)) return false; if (entered_once > 0) // second or later invocation from for() { const bool is_first_initialization = __sync_bool_compare_and_swap (flagp, 0, 1); const bool found_and_removed = once_list_leave (flagp); if (!is_first_initialization || !found_and_removed) printerr ("__once: %s: assertion failed during leave: %d %d", __func__, is_first_initialization, found_and_removed); } entered_once = 1; // mark first invocation once_list_enter(); const bool initialized = atomic_load (flagp) != 0; const bool needs_init = once_list_bounce (initialized ? NULL : flagp); return needs_init; } }; #define RAPICORN_ASECTION(bytes) __attribute__ ((section (".data.aligned" #bytes), aligned (bytes))) #define RAPICORN_DO_ONCE_COUNTER ({ static volatile char RAPICORN_ASECTION (1) __rapicorn_oncebyte_ = 0; &__rapicorn_oncebyte_; }) #define RAPICORN_DO_ONCE for (Rapicorn::Lib::OnceScope __rapicorn_oncescope_ (RAPICORN_DO_ONCE_COUNTER); __rapicorn_oncescope_(); ) } // Lib } // Rapicorn #endif // __RAPICORN_THREADLIB_HH__ <commit_msg>RCORE: typo fix<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #ifndef __RAPICORN_THREADLIB_HH__ #define __RAPICORN_THREADLIB_HH__ #include <condition_variable> namespace Rapicorn { namespace Lib { #define RAPICORN_CACHE_LINE_ALIGNMENT 128 #define RAPICORN_MFENCE __sync_synchronize() ///< Memory Fence - prevent processor (and compiler) from reordering loads/stores (read/write barrier). #define RAPICORN_SFENCE RAPICORN_X86SFENCE ///< Store Fence - prevent processor (and compiler) from reordering stores (write barrier). #define RAPICORN_LFENCE RAPICORN_X86LFENCE ///< Load Fence - prevent processor (and compiler) from reordering loads (read barrier). #define RAPICORN_CFENCE __asm__ __volatile__ ("" ::: "memory") ///< Compiler Fence, prevent compiler from reordering non-volatiles loads/stores. #define RAPICORN_X86LFENCE __asm__ __volatile__ ("lfence" ::: "memory") ///< X86 lfence - prevent processor from reordering loads (read barrier). #define RAPICORN_X86SFENCE __asm__ __volatile__ ("sfence" ::: "memory") ///< X86 sfence - prevent processor from reordering stores (write barrier). template<typename T> T atomic_load (T volatile *p) { RAPICORN_CFENCE; T t = *p; RAPICORN_LFENCE; return t; } template<typename T> void atomic_store (T volatile *p, T i) { RAPICORN_SFENCE; *p = i; RAPICORN_CFENCE; } template<typename T> class Atomic { T volatile v; /*ctor*/ Atomic () = delete; protected: constexpr Atomic (T i) : v (i) {} Atomic<T>& operator=(Atomic<T> &o) { store (o.load()); return *this; } Atomic<T> volatile& operator=(Atomic<T> &o) volatile { store (o.load()); return *this; } public: T load () const volatile { return atomic_load (&v); } void store (T i) volatile { atomic_store (&v, i); } bool cas (T o, T n) volatile { return __sync_bool_compare_and_swap (&v, o, n); } T operator+=(T i) volatile { return __sync_add_and_fetch (&v, i); } T operator-=(T i) volatile { return __sync_sub_and_fetch (&v, i); } T operator&=(T i) volatile { return __sync_and_and_fetch (&v, i); } T operator^=(T i) volatile { return __sync_xor_and_fetch (&v, i); } T operator|=(T i) volatile { return __sync_or_and_fetch (&v, i); } T operator++() volatile { return __sync_add_and_fetch (&v, 1); } T operator++(int) volatile { return __sync_fetch_and_add (&v, 1); } T operator--() volatile { return __sync_sub_and_fetch (&v, 1); } T operator--(int) volatile { return __sync_fetch_and_sub (&v, 1); } void operator= (T i) volatile { store (i); } operator T () const volatile { return load(); } }; // == Once Scope == void once_list_enter (); bool once_list_bounce (volatile void *ptr); bool once_list_leave (volatile void *ptr); class OnceScope { /*ctor*/ OnceScope (const OnceScope&) = delete; OnceScope& operator= (const OnceScope&) = delete; volatile char *volatile flagp; bool entered_once; public: OnceScope (volatile char *volatile p) : flagp (p), entered_once (false) {} inline bool operator() () { if (RAPICORN_LIKELY (*flagp != 0)) return false; if (entered_once > 0) // second or later invocation from for() { const bool is_first_initialization = __sync_bool_compare_and_swap (flagp, 0, 1); const bool found_and_removed = once_list_leave (flagp); if (!is_first_initialization || !found_and_removed) printerr ("__once: %s: assertion failed during leave: %d %d", __func__, is_first_initialization, found_and_removed); } entered_once = 1; // mark first invocation once_list_enter(); const bool initialized = atomic_load (flagp) != 0; const bool needs_init = once_list_bounce (initialized ? NULL : flagp); return needs_init; } }; #define RAPICORN_ASECTION(bytes) __attribute__ ((section (".data.aligned" #bytes), aligned (bytes))) #define RAPICORN_DO_ONCE_COUNTER ({ static volatile char RAPICORN_ASECTION (1) __rapicorn_oncebyte_ = 0; &__rapicorn_oncebyte_; }) #define RAPICORN_DO_ONCE for (Rapicorn::Lib::OnceScope __rapicorn_oncescope_ (RAPICORN_DO_ONCE_COUNTER); __rapicorn_oncescope_(); ) } // Lib } // Rapicorn #endif // __RAPICORN_THREADLIB_HH__ <|endoftext|>
<commit_before>// Time: O(klog(min(m, n, k)) // Space: O(min(m, n, k)) // BST solution. class Solution { public: /** * @param matrix: a matrix of integers * @param k: an integer * @return: the kth smallest number in the matrix */ int kthSmallest(vector<vector<int>> &matrix, int k) { if (matrix.size() < matrix[0].size()) { // Height is smaller. return horizontal_search(matrix, k); } else { // Width is smaller. return vertical_search(matrix, k); } } int horizontal_search(const vector<vector<int>> &matrix, int k) { multimap<int, pair<int, int>> min_bst; // Init BST by the first element of the first kth row. for (int i = 0; i < min(static_cast<int>(matrix.size()), k); ++i) { min_bst.emplace(move(pair<int, pair<int, int>>{matrix[i][0], {i, 0}})); } int kth_smallest = INT_MAX; while (!min_bst.empty() && k--) { // Pop the min of BST. if (k == 0) { kth_smallest = min_bst.cbegin()->first; } // Pop the min of BST. int i = min_bst.cbegin()->second.first; int j = min_bst.cbegin()->second.second; min_bst.erase(min_bst.cbegin()); // Insert the next possible element. if (j + 1 < matrix[i].size()) { min_bst.emplace(move(pair<int, pair<int, int>>{matrix[i][j + 1], {i, j + 1}})); } } return kth_smallest; } int vertical_search(const vector<vector<int>> &matrix, int k) { multimap<int, pair<int, int>> min_bst; // Init BST by the first element of the first kth column. for (int j = 0; j < min(static_cast<int>(matrix[0].size()), k); ++j) { min_bst.emplace(move(pair<int, pair<int, int>>{matrix[0][j], {0, j}})); } int kth_smallest = INT_MAX; while (!min_bst.empty() && k--) { // Pop the min of Heap. if (k == 0) { kth_smallest = min_bst.cbegin()->first; } // Pop the min of BST. int i = min_bst.cbegin()->second.first; int j = min_bst.cbegin()->second.second; min_bst.erase(min_bst.cbegin()); // Insert the next possible element. if (i + 1 < matrix.size()) { min_bst.emplace(move(pair<int, pair<int, int>>{matrix[i + 1][j], {i + 1, j}})); } } return kth_smallest; } }; // Time: O(klog(min(m, n, k)) // Space: O(min(m, n, k)) // Heap solution. class Solution2 { public: struct Compare { bool operator()(const pair<int, pair<int, int>>& a, const pair<int, pair<int, int>>& b) { return a.first > b.first; } }; /** * @param matrix: a matrix of integers * @param k: an integer * @return: the kth smallest number in the matrix */ int kthSmallest(vector<vector<int>> &matrix, int k) { if (matrix.size() < matrix[0].size()) { // Height is smaller. return horizontal_search(matrix, k); } else { // Width is smaller. return vertical_search(matrix, k); } } int horizontal_search(const vector<vector<int>> &matrix, int k) { priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, Compare> min_heap; // Init Heap by the first element of the first kth row. for (int i = 0; i < min(static_cast<int>(matrix.size()), k); ++i) { min_heap.emplace(move(pair<int, pair<int, int>>{matrix[i][0], {i, 0}})); } int kth_smallest = INT_MAX; while (!min_heap.empty() && k--) { // Pop the min of Heap. if (k == 0) { kth_smallest = min_heap.top().first; } kth_smallest = min_heap.top().first; int i = min_heap.top().second.first; int j = min_heap.top().second.second; min_heap.pop(); // Insert the next possible element. if (j + 1 < matrix[i].size()) { min_heap.emplace(move(pair<int, pair<int, int>>{matrix[i][j + 1], {i, j + 1}})); } } return kth_smallest; } int vertical_search(const vector<vector<int>> &matrix, int k) { priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, Compare> min_heap; // Init Heap by the first element of the first kth column. for (int j = 0; j < min(static_cast<int>(matrix[0].size()), k); ++j) { min_heap.emplace(move(pair<int, pair<int, int>>{matrix[0][j], {0, j}})); } int kth_smallest = INT_MAX; while (!min_heap.empty() && k--) { // Pop the min of Heap. if (k == 0) { kth_smallest = min_heap.top().first; } int i = min_heap.top().second.first; int j = min_heap.top().second.second; min_heap.pop(); // Insert the next possible element. if (i + 1 < matrix.size()) { min_heap.emplace(move(pair<int, pair<int, int>>{matrix[i + 1][j], {i + 1, j}})); } } return kth_smallest; } }; <commit_msg>Update kth-smallest-number-in-sorted-matrix.cpp<commit_after>// Time: O(klog(min(m, n, k)) // Space: O(min(m, n, k)) // BST solution. class Solution { public: /** * @param matrix: a matrix of integers * @param k: an integer * @return: the kth smallest number in the matrix */ int kthSmallest(vector<vector<int>> &matrix, int k) { if (matrix.size() < matrix[0].size()) { // Height is smaller. return horizontal_search(matrix, k); } else { // Width is smaller. return vertical_search(matrix, k); } } int horizontal_search(const vector<vector<int>> &matrix, int k) { multimap<int, pair<int, int>> min_bst; // Init BST by the first element of the first kth row. for (int i = 0; i < min(static_cast<int>(matrix.size()), k); ++i) { min_bst.emplace(pair<int, pair<int, int>>{matrix[i][0], {i, 0}}); } int kth_smallest = INT_MAX; while (!min_bst.empty() && k--) { // Pop the min of BST. if (k == 0) { kth_smallest = min_bst.cbegin()->first; } // Pop the min of BST. int i = min_bst.cbegin()->second.first; int j = min_bst.cbegin()->second.second; min_bst.erase(min_bst.cbegin()); // Insert the next possible element. if (j + 1 < matrix[i].size()) { min_bst.emplace(pair<int, pair<int, int>>{matrix[i][j + 1], {i, j + 1}}); } } return kth_smallest; } int vertical_search(const vector<vector<int>> &matrix, int k) { multimap<int, pair<int, int>> min_bst; // Init BST by the first element of the first kth column. for (int j = 0; j < min(static_cast<int>(matrix[0].size()), k); ++j) { min_bst.emplace(pair<int, pair<int, int>>{matrix[0][j], {0, j}}); } int kth_smallest = INT_MAX; while (!min_bst.empty() && k--) { // Pop the min of Heap. if (k == 0) { kth_smallest = min_bst.cbegin()->first; } // Pop the min of BST. int i = min_bst.cbegin()->second.first; int j = min_bst.cbegin()->second.second; min_bst.erase(min_bst.cbegin()); // Insert the next possible element. if (i + 1 < matrix.size()) { min_bst.emplace(pair<int, pair<int, int>>{matrix[i + 1][j], {i + 1, j}}); } } return kth_smallest; } }; // Time: O(klog(min(m, n, k)) // Space: O(min(m, n, k)) // Heap solution. class Solution2 { public: struct Compare { bool operator()(const pair<int, pair<int, int>>& a, const pair<int, pair<int, int>>& b) { return a.first > b.first; } }; /** * @param matrix: a matrix of integers * @param k: an integer * @return: the kth smallest number in the matrix */ int kthSmallest(vector<vector<int>> &matrix, int k) { if (matrix.size() < matrix[0].size()) { // Height is smaller. return horizontal_search(matrix, k); } else { // Width is smaller. return vertical_search(matrix, k); } } int horizontal_search(const vector<vector<int>> &matrix, int k) { priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, Compare> min_heap; // Init Heap by the first element of the first kth row. for (int i = 0; i < min(static_cast<int>(matrix.size()), k); ++i) { min_heap.emplace(pair<int, pair<int, int>>{matrix[i][0], {i, 0}}); } int kth_smallest = INT_MAX; while (!min_heap.empty() && k--) { // Pop the min of Heap. if (k == 0) { kth_smallest = min_heap.top().first; } kth_smallest = min_heap.top().first; int i = min_heap.top().second.first; int j = min_heap.top().second.second; min_heap.pop(); // Insert the next possible element. if (j + 1 < matrix[i].size()) { min_heap.emplace(pair<int, pair<int, int>>{matrix[i][j + 1], {i, j + 1}}); } } return kth_smallest; } int vertical_search(const vector<vector<int>> &matrix, int k) { priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, Compare> min_heap; // Init Heap by the first element of the first kth column. for (int j = 0; j < min(static_cast<int>(matrix[0].size()), k); ++j) { min_heap.emplace(pair<int, pair<int, int>>{matrix[0][j], {0, j}}); } int kth_smallest = INT_MAX; while (!min_heap.empty() && k--) { // Pop the min of Heap. if (k == 0) { kth_smallest = min_heap.top().first; } int i = min_heap.top().second.first; int j = min_heap.top().second.second; min_heap.pop(); // Insert the next possible element. if (i + 1 < matrix.size()) { min_heap.emplace(pair<int, pair<int, int>>{matrix[i + 1][j], {i + 1, j}}); } } return kth_smallest; } }; <|endoftext|>
<commit_before>// Source : https://leetcode.com/problems/lexicographical-numbers/ // Author : Hao Chen // Date : 2016-08-23 /*************************************************************************************** * * Given an integer n, return 1 - n in lexicographical order. * * For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. * * Please optimize your algorithm to use less time and space. The input size may be as * large as 5,000,000. ***************************************************************************************/ class Solution { //Solution 1: convert the int to string for sort, Time complexity is high (Time Limited Error) public: vector<int> lexicalOrder01(int n) { vector<int> result; for (int i=1; i<=n; i++) { result.push_back(i); } sort(result.begin(), result.end(), this->myComp); return result; } private: static bool myComp(int i,int j) { static char si[32]={0}, sj[32]={0}; sprintf(si, "%d\0", i); sprintf(sj, "%d\0", j); return (strcmp(si, sj)<0); } //Solution 2 : using recursive way to solution the problem, 540ms public: vector<int> lexicalOrder02(int n) { vector<int> result; for (int i=1; i<=n && i<=9; i++) { result.push_back(i); lexicalOrder_helper(i, n, result); } return result; } private: void lexicalOrder_helper(int num, int& n, vector<int>& result) { for (int i=0; i<=9; i++) { int tmp = num * 10 + i; if (tmp > n) { break; } result.push_back(tmp); lexicalOrder_helper(tmp, n, result); } } //Solution 3: no recursive way, but the code is not easy to read public : vector<int> lexicalOrder03(int n) { vector<int> result; int curr = 1; while (result.size()<n) { // Step One // --------- //Adding all of the possible number which multiply 10 as much as possible // such as: curr = 1, then 1, 10, 100, 1000 ... // curr = 12, then 12, 120, 1200, ... for (; curr <= n; curr*=10 ) { result.push_back(curr); } // Step Two // --------- // After find the number which multiply 10 greater than `n`, then go back the previous one, // and keep adding 1 until it carry on to next number // for example: // curr = 100, then we need evalute: 11,12,13,14,15,16,17,18,19, but stop at 20 // curr = 230, then we need evaluate: 24,25,26,27,28,29, but stop at 30. curr = curr/10 + 1; for (; curr <= n && curr % 10 != 0; curr++) { result.push_back(curr); } // Step Three // ---------- // Now, we finished all of the number, we need go back for next number // Here is a bit tricky. // // Assuming the n is 234, and Step One evaluted 190, and Step Two, evaluted 191,192,...,199 // Now, the `curr` is 200, and we need start from 2 instead of 20, that's why need keep dividing 10 for (; curr%10 == 0; curr/=10); } return result; } //start point public: vector<int> lexicalOrder(int n) { //srand(time(NULL)); //if (rand()%2) // return lexicalOrder02(n); // recursive way 560ms //else return lexicalOrder03(n); // non-recursive way, 460ms } }; <commit_msg>uncomment the code<commit_after>// Source : https://leetcode.com/problems/lexicographical-numbers/ // Author : Hao Chen // Date : 2016-08-23 /*************************************************************************************** * * Given an integer n, return 1 - n in lexicographical order. * * For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. * * Please optimize your algorithm to use less time and space. The input size may be as * large as 5,000,000. ***************************************************************************************/ class Solution { //Solution 1: convert the int to string for sort, Time complexity is high (Time Limited Error) public: vector<int> lexicalOrder01(int n) { vector<int> result; for (int i=1; i<=n; i++) { result.push_back(i); } sort(result.begin(), result.end(), this->myComp); return result; } private: static bool myComp(int i,int j) { static char si[32]={0}, sj[32]={0}; sprintf(si, "%d\0", i); sprintf(sj, "%d\0", j); return (strcmp(si, sj)<0); } //Solution 2 : using recursive way to solution the problem, 540ms public: vector<int> lexicalOrder02(int n) { vector<int> result; for (int i=1; i<=n && i<=9; i++) { result.push_back(i); lexicalOrder_helper(i, n, result); } return result; } private: void lexicalOrder_helper(int num, int& n, vector<int>& result) { for (int i=0; i<=9; i++) { int tmp = num * 10 + i; if (tmp > n) { break; } result.push_back(tmp); lexicalOrder_helper(tmp, n, result); } } //Solution 3: no recursive way, but the code is not easy to read public : vector<int> lexicalOrder03(int n) { vector<int> result; int curr = 1; while (result.size()<n) { // Step One // --------- //Adding all of the possible number which multiply 10 as much as possible // such as: curr = 1, then 1, 10, 100, 1000 ... // curr = 12, then 12, 120, 1200, ... for (; curr <= n; curr*=10 ) { result.push_back(curr); } // Step Two // --------- // After find the number which multiply 10 greater than `n`, then go back the previous one, // and keep adding 1 until it carry on to next number // for example: // curr = 100, then we need evalute: 11,12,13,14,15,16,17,18,19, but stop at 20 // curr = 230, then we need evaluate: 24,25,26,27,28,29, but stop at 30. curr = curr/10 + 1; for (; curr <= n && curr % 10 != 0; curr++) { result.push_back(curr); } // Step Three // ---------- // Now, we finished all of the number, we need go back for next number // Here is a bit tricky. // // Assuming the n is 234, and Step One evaluted 190, and Step Two, evaluted 191,192,...,199 // Now, the `curr` is 200, and we need start from 2 instead of 20, that's why need keep dividing 10 for (; curr%10 == 0; curr/=10); } return result; } //start point public: vector<int> lexicalOrder(int n) { srand(time(NULL)); if (rand()%2) return lexicalOrder02(n); // recursive way 560ms else return lexicalOrder03(n); // non-recursive way, 460ms } }; <|endoftext|>
<commit_before>#include <wpi_jaco_wrapper/jaco_manipulation.h> using namespace std; JacoManipulation::JacoManipulation() { loadParameters(n); acGripper = new GripperClient(n, arm_name_ + "_arm/fingers_controller/gripper", true); asGripper = new GripperServer(n, arm_name_ + "_arm/manipulation/gripper", boost::bind(&JacoManipulation::execute_gripper, this, _1), false); asLift = new LiftServer(n, arm_name_ + "_arm/manipulation/lift", boost::bind(&JacoManipulation::execute_lift, this, _1), false); // Messages cartesianCmdPublisher = n.advertise<wpi_jaco_msgs::CartesianCommand>(arm_name_ + "_arm/cartesian_cmd", 1); angularCmdPublisher = n.advertise<wpi_jaco_msgs::AngularCommand>(arm_name_ + "_arm/angular_cmd", 1); jointStateSubscriber = n.subscribe(arm_name_ + "_arm/joint_states", 1, &JacoManipulation::jointStateCallback, this); // Services cartesianPositionClient = n.serviceClient<wpi_jaco_msgs::GetCartesianPosition>(arm_name_ + "_arm/get_cartesian_position"); eraseTrajectoriesClient = n.serviceClient<std_srvs::Empty>(arm_name_ + "_arm/erase_trajectories"); ROS_INFO("Waiting for gripper action server..."); acGripper->waitForServer(); ROS_INFO("Finished waiting for action server."); // Action servers asGripper->start(); asLift->start(); } bool JacoManipulation::loadParameters(const ros::NodeHandle n) { ROS_DEBUG("Loading parameters"); n.param("wpi_jaco/arm_name", arm_name_, std::string("jaco")); n.param("wpi_jaco/gripper_closed", gripper_closed_, 0.0); n.param("wpi_jaco/gripper_open", gripper_open_, 65.0); n.param("wpi_jaco/num_fingers", num_fingers_, 3); num_joints_ = num_fingers_ + NUM_JACO_JOINTS; joint_pos_.resize(num_joints_); ROS_INFO("arm_name: %s", arm_name_.c_str()); ROS_INFO("Parameters loaded."); //! @todo MdL [IMPR]: Return is values are all correctly loaded. return true; } void JacoManipulation::jointStateCallback(const sensor_msgs::JointState msg) { for (unsigned int i = 0; i < num_joints_; i++) { joint_pos_[i] = msg.position[i]; } } void JacoManipulation::execute_gripper(const rail_manipulation_msgs::GripperGoalConstPtr &goal) { rail_manipulation_msgs::GripperResult result; if (asLift->isActive()) { asGripper->setPreempted(); ROS_INFO("Lift server already running, grasp action preempted"); return; } float startingFingerPos[3]; startingFingerPos[0] = joint_pos_[6]; startingFingerPos[1] = joint_pos_[7]; startingFingerPos[2] = joint_pos_[8]; //check if grasp is already finished (for opening case only) if (!goal->close) { if (startingFingerPos[0] <= GRIPPER_OPEN_THRESHOLD && startingFingerPos[1] <= GRIPPER_OPEN_THRESHOLD && startingFingerPos[2] <= GRIPPER_OPEN_THRESHOLD) { ROS_INFO("Gripper is open."); result.success = true; asGripper->setSucceeded(result, "Open gripper action succeeded, as the gripper is already open."); return; } } control_msgs::GripperCommandGoal gripperGoal; if (goal->close) gripperGoal.command.position = gripper_closed_; else gripperGoal.command.position = gripper_open_; acGripper->sendGoal(gripperGoal); ros::Rate loopRate(30); while (!acGripper->getState().isDone()) { //check for preempt requests from clients if (asGripper->isPreemptRequested() || !ros::ok()) { acGripper->cancelAllGoals(); //preempt action server asGripper->setPreempted(); ROS_INFO("Gripper action server preempted by client"); return; } loopRate.sleep(); } rail_manipulation_msgs::GripperResult serverResult; //success occurs if the gripper has moved, as it is unlikely to reach the final "closed" position when grasping an object //serverResult.success = acGripper->getResult()->reached_goal; if (goal->close) { if (joint_pos_[6] > startingFingerPos[0] || joint_pos_[7] > startingFingerPos[1] || joint_pos_[8] > startingFingerPos[2]) serverResult.success = true; else serverResult.success = false; } else { if (joint_pos_[6] < startingFingerPos[0] || joint_pos_[7] < startingFingerPos[1] || joint_pos_[8] < startingFingerPos[2]) serverResult.success = true; else serverResult.success = false; } asGripper->setSucceeded(serverResult); ROS_INFO("Gripper action finished."); } void JacoManipulation::execute_lift(rail_manipulation_msgs::LiftGoalConstPtr const &goal) { if (asGripper->isActive()) { asLift->setPreempted(); ROS_INFO("Gripper server already running, lift action preempted"); return; } //get initial end effector height wpi_jaco_msgs::GetCartesianPosition srv; rail_manipulation_msgs::LiftResult result; if (cartesianPositionClient.call(srv)) { float initialZ = srv.response.pos.linear.z; //populate the velocity command wpi_jaco_msgs::CartesianCommand cmd; cmd.position = false; cmd.armCommand = true; cmd.fingerCommand = true; cmd.repeat = true; cmd.fingers.resize(3); cmd.arm.linear.x = 0.0; cmd.arm.linear.y = 0.0; cmd.arm.linear.z = DEFAULT_LIFT_VEL; cmd.arm.angular.x = 0.0; cmd.arm.angular.y = 0.0; cmd.arm.angular.z = 0.0; cmd.fingers[0] = MAX_FINGER_VEL; cmd.fingers[1] = MAX_FINGER_VEL; cmd.fingers[2] = MAX_FINGER_VEL; bool finished = false; float currentZ; double startTime = ros::Time::now().toSec(); //send the lift and close command until a certain height has been reached, or the //action times out while (!finished) { //check for preempt requests from clients if (asLift->isPreemptRequested() || !ros::ok()) { //stop pickup action std_srvs::Empty emptySrv; if(!eraseTrajectoriesClient.call(emptySrv)) { ROS_INFO("Could not call erase trajectories service"); } //preempt action server asLift->setPreempted(); ROS_INFO("Lift action server preempted by client"); return; } cartesianCmdPublisher.publish(cmd); if (cartesianPositionClient.call(srv)) { currentZ = srv.response.pos.linear.z; } else { ROS_INFO("Couldn't call Cartesian position server"); result.success = false; break; } if (currentZ - initialZ >= LIFT_HEIGHT) { finished = true; result.success = true; } else if (ros::Time::now().toSec() - startTime >= LIFT_TIMEOUT) { finished = true; result.success = false; } } //stop arm std_srvs::Empty emptySrv; if(!eraseTrajectoriesClient.call(emptySrv)) { ROS_INFO("Could not call erase trajectories service"); } } else { ROS_INFO("Couldn't call Cartesian position server"); result.success = false; } asLift->setSucceeded(result); ROS_INFO("Pickup execution complete"); } int main(int argc, char** argv) { ros::init(argc, argv, "jaco_manipulation"); JacoManipulation jm; ros::spin(); } <commit_msg>Deal with different number of fingers<commit_after>#include <wpi_jaco_wrapper/jaco_manipulation.h> using namespace std; JacoManipulation::JacoManipulation() { loadParameters(n); acGripper = new GripperClient(n, arm_name_ + "_arm/fingers_controller/gripper", true); asGripper = new GripperServer(n, arm_name_ + "_arm/manipulation/gripper", boost::bind(&JacoManipulation::execute_gripper, this, _1), false); asLift = new LiftServer(n, arm_name_ + "_arm/manipulation/lift", boost::bind(&JacoManipulation::execute_lift, this, _1), false); // Messages cartesianCmdPublisher = n.advertise<wpi_jaco_msgs::CartesianCommand>(arm_name_ + "_arm/cartesian_cmd", 1); angularCmdPublisher = n.advertise<wpi_jaco_msgs::AngularCommand>(arm_name_ + "_arm/angular_cmd", 1); jointStateSubscriber = n.subscribe(arm_name_ + "_arm/joint_states", 1, &JacoManipulation::jointStateCallback, this); // Services cartesianPositionClient = n.serviceClient<wpi_jaco_msgs::GetCartesianPosition>(arm_name_ + "_arm/get_cartesian_position"); eraseTrajectoriesClient = n.serviceClient<std_srvs::Empty>(arm_name_ + "_arm/erase_trajectories"); ROS_INFO("Waiting for gripper action server..."); acGripper->waitForServer(); ROS_INFO("Finished waiting for action server."); // Action servers asGripper->start(); asLift->start(); } bool JacoManipulation::loadParameters(const ros::NodeHandle n) { ROS_DEBUG("Loading parameters"); n.param("wpi_jaco/arm_name", arm_name_, std::string("jaco")); n.param("wpi_jaco/gripper_closed", gripper_closed_, 0.0); n.param("wpi_jaco/gripper_open", gripper_open_, 65.0); n.param("wpi_jaco/num_fingers", num_fingers_, 3); num_joints_ = num_fingers_ + NUM_JACO_JOINTS; joint_pos_.resize(num_joints_); ROS_INFO("arm_name: %s", arm_name_.c_str()); ROS_INFO("Parameters loaded."); //! @todo MdL [IMPR]: Return is values are all correctly loaded. return true; } void JacoManipulation::jointStateCallback(const sensor_msgs::JointState msg) { for (unsigned int i = 0; i < num_joints_; i++) joint_pos_[i] = msg.position[i]; } void JacoManipulation::execute_gripper(const rail_manipulation_msgs::GripperGoalConstPtr &goal) { rail_manipulation_msgs::GripperResult result; if (asLift->isActive()) { asGripper->setPreempted(); ROS_INFO("Lift server already running, grasp action preempted"); return; } float startingFingerPos[3]; for (int i = 0 ; i < num_fingers_ ; i++) startingFingerPos[i] = joint_pos_[NUM_JACO_JOINTS+i]; //check if grasp is already finished (for opening case only) if (!goal->close) { bool gripper_open = true; for (int i = 0 ; i < num_fingers_ ; i++) gripper_open = gripper_open && startingFingerPos[i] <= GRIPPER_OPEN_THRESHOLD; if (gripper_open) { ROS_INFO("Gripper is open."); result.success = true; asGripper->setSucceeded(result, "Open gripper action succeeded, as the gripper is already open."); return; } } control_msgs::GripperCommandGoal gripperGoal; if (goal->close) gripperGoal.command.position = gripper_closed_; else gripperGoal.command.position = gripper_open_; acGripper->sendGoal(gripperGoal); ros::Rate loopRate(30); while (!acGripper->getState().isDone()) { //check for preempt requests from clients if (asGripper->isPreemptRequested() || !ros::ok()) { acGripper->cancelAllGoals(); //preempt action server asGripper->setPreempted(); ROS_INFO("Gripper action server preempted by client"); return; } loopRate.sleep(); } rail_manipulation_msgs::GripperResult serverResult; //success occurs if the gripper has moved, as it is unlikely to reach the final "closed" position when grasping an object //serverResult.success = acGripper->getResult()->reached_goal; if (goal->close) { bool gripper_closing = true; for (int i = 0 ; i < num_fingers_ ; i++) gripper_closing = gripper_closing && joint_pos_[NUM_JACO_JOINTS+i] > startingFingerPos[i]; serverResult.success = gripper_closing; } else { bool gripper_opening = true; for (int i = 0 ; i < num_fingers_ ; i++) gripper_opening = gripper_opening && joint_pos_[NUM_JACO_JOINTS+i] > startingFingerPos[i]; serverResult.success = gripper_opening; } asGripper->setSucceeded(serverResult); ROS_INFO("Gripper action finished."); } void JacoManipulation::execute_lift(rail_manipulation_msgs::LiftGoalConstPtr const &goal) { if (asGripper->isActive()) { asLift->setPreempted(); ROS_INFO("Gripper server already running, lift action preempted"); return; } //get initial end effector height wpi_jaco_msgs::GetCartesianPosition srv; rail_manipulation_msgs::LiftResult result; if (cartesianPositionClient.call(srv)) { float initialZ = srv.response.pos.linear.z; //populate the velocity command wpi_jaco_msgs::CartesianCommand cmd; cmd.position = false; cmd.armCommand = true; cmd.fingerCommand = true; cmd.repeat = true; cmd.fingers.resize(3); cmd.arm.linear.x = 0.0; cmd.arm.linear.y = 0.0; cmd.arm.linear.z = DEFAULT_LIFT_VEL; cmd.arm.angular.x = 0.0; cmd.arm.angular.y = 0.0; cmd.arm.angular.z = 0.0; cmd.fingers[0] = MAX_FINGER_VEL; cmd.fingers[1] = MAX_FINGER_VEL; cmd.fingers[2] = MAX_FINGER_VEL; bool finished = false; float currentZ; double startTime = ros::Time::now().toSec(); //send the lift and close command until a certain height has been reached, or the //action times out while (!finished) { //check for preempt requests from clients if (asLift->isPreemptRequested() || !ros::ok()) { //stop pickup action std_srvs::Empty emptySrv; if(!eraseTrajectoriesClient.call(emptySrv)) { ROS_INFO("Could not call erase trajectories service"); } //preempt action server asLift->setPreempted(); ROS_INFO("Lift action server preempted by client"); return; } cartesianCmdPublisher.publish(cmd); if (cartesianPositionClient.call(srv)) { currentZ = srv.response.pos.linear.z; } else { ROS_INFO("Couldn't call Cartesian position server"); result.success = false; break; } if (currentZ - initialZ >= LIFT_HEIGHT) { finished = true; result.success = true; } else if (ros::Time::now().toSec() - startTime >= LIFT_TIMEOUT) { finished = true; result.success = false; } } //stop arm std_srvs::Empty emptySrv; if(!eraseTrajectoriesClient.call(emptySrv)) { ROS_INFO("Could not call erase trajectories service"); } } else { ROS_INFO("Couldn't call Cartesian position server"); result.success = false; } asLift->setSucceeded(result); ROS_INFO("Pickup execution complete"); } int main(int argc, char** argv) { ros::init(argc, argv, "jaco_manipulation"); JacoManipulation jm; ros::spin(); } <|endoftext|>
<commit_before>#include <wpi_jaco_wrapper/jaco_manipulation.h> using namespace std; JacoManipulation::JacoManipulation() : executeGraspServer(n, "jaco_arm/manipulation/grasp", boost::bind(&JacoManipulation::execute_grasp, this, _1), false), executePickupServer(n, "jaco_arm/manipulation/pickup", boost::bind(&JacoManipulation::execute_pickup, this, _1), false) { // Messages cartesianCmdPublisher = n.advertise<wpi_jaco_msgs::CartesianCommand>("jaco_arm/cartesian_cmd", 1); angularCmdPublisher = n.advertise<wpi_jaco_msgs::AngularCommand>("jaco_arm/angular_cmd", 1); jointStateSubscriber = n.subscribe("jaco_arm/joint_states", 1, &JacoManipulation::jointStateCallback, this); // Services cartesianPositionClient = n.serviceClient<wpi_jaco_msgs::GetCartesianPosition>("jaco_arm/get_cartesian_position"); // Action servers executeGraspServer.start(); executePickupServer.start(); } void JacoManipulation::jointStateCallback(const sensor_msgs::JointState msg) { for (unsigned int i = 0; i < NUM_JOINTS; i++) { jointPos[i] = msg.position[i]; } } void JacoManipulation::execute_grasp(const wpi_jaco_msgs::ExecuteGraspGoalConstPtr &goal) { if (executePickupServer.isActive()) { executeGraspServer.setPreempted(); ROS_INFO("Pickup server already running, grasp action preempted"); return; } wpi_jaco_msgs::AngularCommand cmd; cmd.position = false; cmd.armCommand = false; cmd.fingerCommand = true; cmd.repeat = true; cmd.fingers.resize(3); //set direction for opening and closing int direction = 1; if (!goal->closeGripper) direction = -1; //set finger velocities if they were specified if (goal->limitFingerVelocity) { cmd.fingers[0] = direction * fabs(goal->fingerVelocities.finger1Vel); cmd.fingers[1] = direction * fabs(goal->fingerVelocities.finger2Vel); cmd.fingers[2] = direction * fabs(goal->fingerVelocities.finger3Vel); } else { cmd.fingers[0] = direction * MAX_FINGER_VEL; cmd.fingers[1] = direction * MAX_FINGER_VEL; cmd.fingers[2] = direction * MAX_FINGER_VEL; } //get initial finger position float prevFingerPos[3]; prevFingerPos[0] = jointPos[6]; prevFingerPos[1] = jointPos[7]; prevFingerPos[2] = jointPos[8]; float currentFingerPos[3]; currentFingerPos[0] = prevFingerPos[0]; currentFingerPos[1] = prevFingerPos[1]; currentFingerPos[2] = prevFingerPos[2]; double prevCheckTime = ros::Time::now().toSec(); bool finishedGrasp = false; //check if grasp is already finished (for opening case only) if (!goal->closeGripper) { if (currentFingerPos[0] <= GRIPPER_OPEN_THRESHOLD && currentFingerPos[1] <= GRIPPER_OPEN_THRESHOLD && currentFingerPos[2] <= GRIPPER_OPEN_THRESHOLD) { finishedGrasp = true; } } while (!finishedGrasp) { //check for preempt requests from clients if (executeGraspServer.isPreemptRequested() || !ros::ok()) { //stop gripper control cmd.fingers[0] = 0.0; cmd.fingers[1] = 0.0; cmd.fingers[2] = 0.0; angularCmdPublisher.publish(cmd); //preempt action server executeGraspServer.setPreempted(); ROS_INFO("Grasp action server preempted by client"); return; } angularCmdPublisher.publish(cmd); if (ros::Time::now().toSec() - prevCheckTime > .25) //occaisionally check to see if the fingers have stopped moving { prevCheckTime = ros::Time::now().toSec(); currentFingerPos[0] = jointPos[6]; currentFingerPos[1] = jointPos[7]; currentFingerPos[2] = jointPos[8]; if (!goal->closeGripper) { if (currentFingerPos[0] <= GRIPPER_OPEN_THRESHOLD && currentFingerPos[1] <= GRIPPER_OPEN_THRESHOLD && currentFingerPos[2] <= GRIPPER_OPEN_THRESHOLD) { finishedGrasp = true; } } //grasp is finished if fingers haven't moved since the last check if ((fabs(prevFingerPos[0] - currentFingerPos[0]) + fabs(prevFingerPos[1] - currentFingerPos[1]) + fabs(prevFingerPos[2] - currentFingerPos[2])) == 0.0) { finishedGrasp = true; } else { prevFingerPos[0] = currentFingerPos[0]; prevFingerPos[1] = currentFingerPos[1]; prevFingerPos[2] = currentFingerPos[2]; } } } //stop arm cmd.fingers[0] = 0.0; cmd.fingers[1] = 0.0; cmd.fingers[2] = 0.0; angularCmdPublisher.publish(cmd); wpi_jaco_msgs::ExecuteGraspResult result; result.fingerJoints.resize(3); result.fingerJoints.at(0) = jointPos[6]; result.fingerJoints.at(1) = jointPos[7]; result.fingerJoints.at(2) = jointPos[8]; executeGraspServer.setSucceeded(result); ROS_INFO("Grasp execution complete"); } void JacoManipulation::execute_pickup(const wpi_jaco_msgs::ExecutePickupGoalConstPtr &goal) { if (executeGraspServer.isActive()) { executePickupServer.setPreempted(); ROS_INFO("Grasp server already running, pickup action preempted"); return; } //get initial end effector height wpi_jaco_msgs::GetCartesianPosition srv; wpi_jaco_msgs::ExecutePickupResult result; if (cartesianPositionClient.call(srv)) { float initialZ = srv.response.pos.linear.z; //populate the velocity command wpi_jaco_msgs::CartesianCommand cmd; cmd.position = false; cmd.armCommand = true; cmd.fingerCommand = true; cmd.repeat = true; cmd.fingers.resize(3); cmd.arm.linear.x = 0.0; cmd.arm.linear.y = 0.0; if (goal->setLiftVelocity) cmd.arm.linear.z = goal->liftVelocity; else cmd.arm.linear.z = DEFAULT_LIFT_VEL; cmd.arm.angular.x = 0.0; cmd.arm.angular.y = 0.0; cmd.arm.angular.z = 0.0; if (goal->limitFingerVelocity) { cmd.fingers[0] = fabs(goal->fingerVelocities.finger1Vel); cmd.fingers[1] = fabs(goal->fingerVelocities.finger2Vel); cmd.fingers[2] = fabs(goal->fingerVelocities.finger3Vel); } else { cmd.fingers[0] = MAX_FINGER_VEL; cmd.fingers[1] = MAX_FINGER_VEL; cmd.fingers[2] = MAX_FINGER_VEL; } bool finished = false; float currentZ; double startTime = ros::Time::now().toSec(); //send the lift and close command until a certain height has been reached, or the //action times out while (!finished) { //check for preempt requests from clients if (executePickupServer.isPreemptRequested() || !ros::ok()) { //stop pickup action cmd.fingers.resize(3); cmd.arm.linear.x = 0.0; cmd.arm.linear.y = 0.0; cmd.arm.linear.z = 0.0; cmd.arm.angular.x = 0.0; cmd.arm.angular.y = 0.0; cmd.arm.angular.z = 0.0; cmd.fingers[0] = 0.0; cmd.fingers[1] = 0.0; cmd.fingers[2] = 0.0; cartesianCmdPublisher.publish(cmd); //preempt action server executePickupServer.setPreempted(); ROS_INFO("Pickup action server preempted by client"); return; } cartesianCmdPublisher.publish(cmd); if (cartesianPositionClient.call(srv)) { currentZ = srv.response.pos.linear.z; } else { ROS_INFO("Couldn't call cartesian position server"); result.success = false; break; } if (currentZ - initialZ >= LIFT_HEIGHT) { finished = true; result.success = true; } else if (ros::Time::now().toSec() - startTime >= LIFT_TIMEOUT) { finished = true; result.success = false; } } //stop arm cmd.fingers.resize(3); cmd.arm.linear.x = 0.0; cmd.arm.linear.y = 0.0; cmd.arm.linear.z = 0.0; cmd.arm.angular.x = 0.0; cmd.arm.angular.y = 0.0; cmd.arm.angular.z = 0.0; cmd.fingers[0] = 0.0; cmd.fingers[1] = 0.0; cmd.fingers[2] = 0.0; cartesianCmdPublisher.publish(cmd); } else { ROS_INFO("Couldn't call cartesian position server"); result.success = false; } executePickupServer.setSucceeded(result); ROS_INFO("Pickup execution complete"); } int main(int argc, char** argv) { ros::init(argc, argv, "jaco_manipulation"); JacoManipulation jm; ros::spin(); } <commit_msg>tuning<commit_after>#include <wpi_jaco_wrapper/jaco_manipulation.h> using namespace std; JacoManipulation::JacoManipulation() : executeGraspServer(n, "jaco_arm/manipulation/grasp", boost::bind(&JacoManipulation::execute_grasp, this, _1), false), executePickupServer(n, "jaco_arm/manipulation/pickup", boost::bind(&JacoManipulation::execute_pickup, this, _1), false) { // Messages cartesianCmdPublisher = n.advertise<wpi_jaco_msgs::CartesianCommand>("jaco_arm/cartesian_cmd", 1); angularCmdPublisher = n.advertise<wpi_jaco_msgs::AngularCommand>("jaco_arm/angular_cmd", 1); jointStateSubscriber = n.subscribe("jaco_arm/joint_states", 1, &JacoManipulation::jointStateCallback, this); // Services cartesianPositionClient = n.serviceClient<wpi_jaco_msgs::GetCartesianPosition>("jaco_arm/get_cartesian_position"); // Action servers executeGraspServer.start(); executePickupServer.start(); } void JacoManipulation::jointStateCallback(const sensor_msgs::JointState msg) { for (unsigned int i = 0; i < NUM_JOINTS; i++) { jointPos[i] = msg.position[i]; } } void JacoManipulation::execute_grasp(const wpi_jaco_msgs::ExecuteGraspGoalConstPtr &goal) { if (executePickupServer.isActive()) { executeGraspServer.setPreempted(); ROS_INFO("Pickup server already running, grasp action preempted"); return; } wpi_jaco_msgs::AngularCommand cmd; cmd.position = false; cmd.armCommand = false; cmd.fingerCommand = true; cmd.repeat = true; cmd.fingers.resize(3); //set direction for opening and closing int direction = 1; if (!goal->closeGripper) direction = -1; //set finger velocities if they were specified if (goal->limitFingerVelocity) { cmd.fingers[0] = direction * fabs(goal->fingerVelocities.finger1Vel); cmd.fingers[1] = direction * fabs(goal->fingerVelocities.finger2Vel); cmd.fingers[2] = direction * fabs(goal->fingerVelocities.finger3Vel); } else { cmd.fingers[0] = direction * MAX_FINGER_VEL; cmd.fingers[1] = direction * MAX_FINGER_VEL; cmd.fingers[2] = direction * MAX_FINGER_VEL; } //get initial finger position float prevFingerPos[3]; prevFingerPos[0] = jointPos[6]; prevFingerPos[1] = jointPos[7]; prevFingerPos[2] = jointPos[8]; float currentFingerPos[3]; currentFingerPos[0] = prevFingerPos[0]; currentFingerPos[1] = prevFingerPos[1]; currentFingerPos[2] = prevFingerPos[2]; double prevCheckTime = ros::Time::now().toSec(); bool finishedGrasp = false; //check if grasp is already finished (for opening case only) if (!goal->closeGripper) { if (currentFingerPos[0] <= GRIPPER_OPEN_THRESHOLD && currentFingerPos[1] <= GRIPPER_OPEN_THRESHOLD && currentFingerPos[2] <= GRIPPER_OPEN_THRESHOLD) { ROS_INFO("Gripper already open."); finishedGrasp = true; } } while (!finishedGrasp) { //check for preempt requests from clients if (executeGraspServer.isPreemptRequested() || !ros::ok()) { //stop gripper control cmd.fingers[0] = 0.0; cmd.fingers[1] = 0.0; cmd.fingers[2] = 0.0; angularCmdPublisher.publish(cmd); //preempt action server executeGraspServer.setPreempted(); ROS_INFO("Grasp action server preempted by client"); return; } angularCmdPublisher.publish(cmd); if (ros::Time::now().toSec() - prevCheckTime > .25) //occaisionally check to see if the fingers have stopped moving { prevCheckTime = ros::Time::now().toSec(); currentFingerPos[0] = jointPos[6]; currentFingerPos[1] = jointPos[7]; currentFingerPos[2] = jointPos[8]; if (!goal->closeGripper) { if (currentFingerPos[0] <= GRIPPER_OPEN_THRESHOLD && currentFingerPos[1] <= GRIPPER_OPEN_THRESHOLD && currentFingerPos[2] <= GRIPPER_OPEN_THRESHOLD) { finishedGrasp = true; } } //grasp is finished if fingers haven't moved since the last check if ((fabs(prevFingerPos[0] - currentFingerPos[0]) + fabs(prevFingerPos[1] - currentFingerPos[1]) + fabs(prevFingerPos[2] - currentFingerPos[2])) == 0.0) { finishedGrasp = true; } else { prevFingerPos[0] = currentFingerPos[0]; prevFingerPos[1] = currentFingerPos[1]; prevFingerPos[2] = currentFingerPos[2]; } } } //stop arm cmd.fingers[0] = 0.0; cmd.fingers[1] = 0.0; cmd.fingers[2] = 0.0; angularCmdPublisher.publish(cmd); wpi_jaco_msgs::ExecuteGraspResult result; result.fingerJoints.resize(3); result.fingerJoints.at(0) = jointPos[6]; result.fingerJoints.at(1) = jointPos[7]; result.fingerJoints.at(2) = jointPos[8]; executeGraspServer.setSucceeded(result); ROS_INFO("Grasp execution complete"); } void JacoManipulation::execute_pickup(const wpi_jaco_msgs::ExecutePickupGoalConstPtr &goal) { if (executeGraspServer.isActive()) { executePickupServer.setPreempted(); ROS_INFO("Grasp server already running, pickup action preempted"); return; } //get initial end effector height wpi_jaco_msgs::GetCartesianPosition srv; wpi_jaco_msgs::ExecutePickupResult result; if (cartesianPositionClient.call(srv)) { float initialZ = srv.response.pos.linear.z; //populate the velocity command wpi_jaco_msgs::CartesianCommand cmd; cmd.position = false; cmd.armCommand = true; cmd.fingerCommand = true; cmd.repeat = true; cmd.fingers.resize(3); cmd.arm.linear.x = 0.0; cmd.arm.linear.y = 0.0; if (goal->setLiftVelocity) cmd.arm.linear.z = goal->liftVelocity; else cmd.arm.linear.z = DEFAULT_LIFT_VEL; cmd.arm.angular.x = 0.0; cmd.arm.angular.y = 0.0; cmd.arm.angular.z = 0.0; if (goal->limitFingerVelocity) { cmd.fingers[0] = fabs(goal->fingerVelocities.finger1Vel); cmd.fingers[1] = fabs(goal->fingerVelocities.finger2Vel); cmd.fingers[2] = fabs(goal->fingerVelocities.finger3Vel); } else { cmd.fingers[0] = MAX_FINGER_VEL; cmd.fingers[1] = MAX_FINGER_VEL; cmd.fingers[2] = MAX_FINGER_VEL; } bool finished = false; float currentZ; double startTime = ros::Time::now().toSec(); //send the lift and close command until a certain height has been reached, or the //action times out while (!finished) { //check for preempt requests from clients if (executePickupServer.isPreemptRequested() || !ros::ok()) { //stop pickup action cmd.fingers.resize(3); cmd.arm.linear.x = 0.0; cmd.arm.linear.y = 0.0; cmd.arm.linear.z = 0.0; cmd.arm.angular.x = 0.0; cmd.arm.angular.y = 0.0; cmd.arm.angular.z = 0.0; cmd.fingers[0] = 0.0; cmd.fingers[1] = 0.0; cmd.fingers[2] = 0.0; cartesianCmdPublisher.publish(cmd); //preempt action server executePickupServer.setPreempted(); ROS_INFO("Pickup action server preempted by client"); return; } cartesianCmdPublisher.publish(cmd); if (cartesianPositionClient.call(srv)) { currentZ = srv.response.pos.linear.z; } else { ROS_INFO("Couldn't call cartesian position server"); result.success = false; break; } if (currentZ - initialZ >= LIFT_HEIGHT) { finished = true; result.success = true; } else if (ros::Time::now().toSec() - startTime >= LIFT_TIMEOUT) { finished = true; result.success = false; } } //stop arm cmd.fingers.resize(3); cmd.arm.linear.x = 0.0; cmd.arm.linear.y = 0.0; cmd.arm.linear.z = 0.0; cmd.arm.angular.x = 0.0; cmd.arm.angular.y = 0.0; cmd.arm.angular.z = 0.0; cmd.fingers[0] = 0.0; cmd.fingers[1] = 0.0; cmd.fingers[2] = 0.0; cartesianCmdPublisher.publish(cmd); } else { ROS_INFO("Couldn't call cartesian position server"); result.success = false; } executePickupServer.setSucceeded(result); ROS_INFO("Pickup execution complete"); } int main(int argc, char** argv) { ros::init(argc, argv, "jaco_manipulation"); JacoManipulation jm; ros::spin(); } <|endoftext|>
<commit_before>/* * CampSiteActiveAreaImplementation.cpp * * Created on: Jan 1, 2012 * Author: Kyle */ #include "CampSiteActiveArea.h" #include "CampSiteObserver.h" #include "server/zone/objects/structure/StructureObject.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/objects/tangible/terminal/Terminal.h" #include "server/zone/Zone.h" #include "server/zone/objects/area/events/CampAbandonTask.h" #include "server/zone/objects/area/events/CampDespawnTask.h" void CampSiteActiveAreaImplementation::initializeTransientMembers() { startTasks(); } void CampSiteActiveAreaImplementation::init(CampStructureTemplate* campData) { campStructureData = campData; setRadius(campStructureData->getRadius()); startTasks(); } void CampSiteActiveAreaImplementation::startTasks() { if(despawnTask == NULL) { despawnTask = new CampDespawnTask(_this); } else { if(despawnTask->isScheduled()) despawnTask->cancel(); } if(abandonTask == NULL) { abandonTask = new CampAbandonTask(_this); } else { if(abandonTask->isScheduled()) abandonTask->cancel(); } despawnTask->schedule(CampSiteActiveArea::DESPAWNTIME); abandonTask->schedule(CampSiteActiveArea::ABANDONTIME); } void CampSiteActiveAreaImplementation::notifyEnter(SceneObject* object) { if (!object->isPlayerCreature()) return; CreatureObject* player = cast<CreatureObject*> (object); if (player == NULL) return; camp->addTemplateSkillMods(player); if (campObserver == NULL) { campObserver = new CampSiteObserver(_this); campObserver->deploy(); } if(object == campOwner && !abandoned) { if(abandonTask->isScheduled()) abandonTask->cancel(); object->registerObserver(ObserverEventType::STARTCOMBAT, campObserver); } else { StringIdChatParameter stringID("camp", "prose_camp_enter"); stringID.setTO(terminal->getDisplayedName()); player->sendSystemMessage(stringID); player->sendSystemMessage("@camp:sys_camp_heal"); } if (object->isPlayerCreature() && !visitors.contains(object->getObjectID())) visitors.add(object->getObjectID()); if (object->isPlayerCreature()) object->registerObserver(ObserverEventType::HEALINGPERFORMED, campObserver); } void CampSiteActiveAreaImplementation::notifyExit(SceneObject* object) { object->dropObserver(ObserverEventType::HEALINGPERFORMED, campObserver); if (!object->isPlayerCreature()) return; CreatureObject* player = cast<CreatureObject*> (object); if (player == NULL) return; camp->removeTemplateSkillMods(player); if(abandoned || object != campOwner) { StringIdChatParameter stringID("camp", "prose_camp_exit"); stringID.setTO(terminal->getDisplayedName()); player->sendSystemMessage(stringID); return; } if(!abandoned && abandonTask != NULL) { abandonTask->schedule(CampSiteActiveArea::ABANDONTIME); } } int CampSiteActiveAreaImplementation::notifyHealEvent(int64 quantity) { // Increase XP Pool for heals currentXp += 5; return 1; } int CampSiteActiveAreaImplementation::notifyCombatEvent() { abandonCamp(); if(abandonTask != NULL) if(abandonTask->isScheduled()) abandonTask->cancel(); if(campOwner != NULL) campOwner->sendSystemMessage("@camp:sys_abandoned_camp"); return 1; } void CampSiteActiveAreaImplementation::abandonCamp() { abandoned = true; currentXp = 0; if(despawnTask != NULL && despawnTask->isScheduled()) { despawnTask->cancel(); int newTime = (CampSiteActiveArea::DESPAWNTIME / 6); int maxTime = CampSiteActiveArea::DESPAWNTIME - ((System::getTime() - timeCreated) * 1000); despawnTask->schedule(newTime < maxTime ? newTime : maxTime); } if(terminal != NULL) terminal->setCustomObjectName("Abandoned Camp", true); if(campOwner != NULL) { campOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver); campOwner->sendSystemMessage("@camp:sys_abandoned_camp"); } } bool CampSiteActiveAreaImplementation::despawnCamp() { if(!abandoned && campOwner != NULL && campOwner->getZoneServer() != NULL) { /// Get Player Manager PlayerManager* playerManager = campOwner->getZoneServer()->getPlayerManager(); if (playerManager == NULL) { error("playerManager is null"); return false; } float durationUsed = ((float)(System::getTime() - timeCreated)) / (campStructureData->getDuration()); int amount = 0; amount += (int)(campStructureData->getExperience() * durationUsed); amount += ((visitors.size() -1) * 15); amount += currentXp; int awarded = (amount > campStructureData->getExperience() ? campStructureData->getExperience() : amount); playerManager->awardExperience(campOwner, "camp", awarded, true); } if(despawnTask != NULL ) { if(despawnTask->isScheduled()) despawnTask->cancel(); despawnTask = NULL; } if(abandonTask != NULL) { if(abandonTask->isScheduled()) abandonTask->cancel(); abandonTask = NULL; } if(campOwner != NULL) campOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver); if(camp->getZone() == NULL) return false; ManagedReference<StructureManager*> structureManager = camp->getZone()->getStructureManager(); if (structureManager == NULL) { error("Unable to get StructureManager when placing camp"); return false; } destroyObjectFromWorld(true); destroyObjectFromDatabase(true); structureManager->destroyStructure(camp); return true; } void CampSiteActiveAreaImplementation::assumeOwnership(CreatureObject* player) { /// Get Ghost PlayerObject* ghost = campOwner->getPlayerObject(); if (ghost != NULL) { ghost->removeOwnedStructure(camp); } setOwner(player); abandoned = false; currentXp = 0; /// Get Ghost ghost = campOwner->getPlayerObject(); if (ghost != NULL) { ghost->addOwnedStructure(camp); } player->registerObserver(ObserverEventType::STARTCOMBAT, campObserver); if(abandonTask != NULL && abandonTask->isScheduled()) abandonTask->cancel(); if(terminal != NULL) { String campName = player->getFirstName(); if(!player->getLastName().isEmpty()) campName += " " + player->getLastName(); campName += "'s Camp"; terminal->setCustomObjectName(campName, true); } } <commit_msg>[fixed] stability issues<commit_after>/* * CampSiteActiveAreaImplementation.cpp * * Created on: Jan 1, 2012 * Author: Kyle */ #include "CampSiteActiveArea.h" #include "CampSiteObserver.h" #include "server/zone/objects/structure/StructureObject.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/objects/tangible/terminal/Terminal.h" #include "server/zone/Zone.h" #include "server/zone/objects/area/events/CampAbandonTask.h" #include "server/zone/objects/area/events/CampDespawnTask.h" void CampSiteActiveAreaImplementation::initializeTransientMembers() { startTasks(); } void CampSiteActiveAreaImplementation::init(CampStructureTemplate* campData) { campStructureData = campData; setRadius(campStructureData->getRadius()); startTasks(); } void CampSiteActiveAreaImplementation::startTasks() { if(despawnTask == NULL) { despawnTask = new CampDespawnTask(_this); } else { if(despawnTask->isScheduled()) despawnTask->cancel(); } if(abandonTask == NULL) { abandonTask = new CampAbandonTask(_this); } else { if(abandonTask->isScheduled()) abandonTask->cancel(); } despawnTask->schedule(CampSiteActiveArea::DESPAWNTIME); abandonTask->schedule(CampSiteActiveArea::ABANDONTIME); } void CampSiteActiveAreaImplementation::notifyEnter(SceneObject* object) { if (!object->isPlayerCreature()) return; CreatureObject* player = cast<CreatureObject*> (object); if (player == NULL) return; camp->addTemplateSkillMods(player); if (campObserver == NULL) { campObserver = new CampSiteObserver(_this); campObserver->deploy(); } if(object == campOwner && !abandoned) { if(abandonTask->isScheduled()) abandonTask->cancel(); object->registerObserver(ObserverEventType::STARTCOMBAT, campObserver); } else { StringIdChatParameter stringID("camp", "prose_camp_enter"); stringID.setTO(terminal->getDisplayedName()); player->sendSystemMessage(stringID); player->sendSystemMessage("@camp:sys_camp_heal"); } if (object->isPlayerCreature() && !visitors.contains(object->getObjectID())) visitors.add(object->getObjectID()); if (object->isPlayerCreature()) object->registerObserver(ObserverEventType::HEALINGPERFORMED, campObserver); } void CampSiteActiveAreaImplementation::notifyExit(SceneObject* object) { object->dropObserver(ObserverEventType::HEALINGPERFORMED, campObserver); if (!object->isPlayerCreature()) return; CreatureObject* player = cast<CreatureObject*> (object); if (player == NULL) return; camp->removeTemplateSkillMods(player); if(abandoned || object != campOwner) { StringIdChatParameter stringID("camp", "prose_camp_exit"); stringID.setTO(terminal->getDisplayedName()); player->sendSystemMessage(stringID); return; } if(!abandoned && abandonTask != NULL && !abandonTask->isScheduled()) { try { abandonTask->schedule(CampSiteActiveArea::ABANDONTIME); } catch (Exception& e) { } } } int CampSiteActiveAreaImplementation::notifyHealEvent(int64 quantity) { // Increase XP Pool for heals currentXp += 5; return 1; } int CampSiteActiveAreaImplementation::notifyCombatEvent() { abandonCamp(); if(abandonTask != NULL) if(abandonTask->isScheduled()) abandonTask->cancel(); if(campOwner != NULL) campOwner->sendSystemMessage("@camp:sys_abandoned_camp"); return 1; } void CampSiteActiveAreaImplementation::abandonCamp() { abandoned = true; currentXp = 0; if(despawnTask != NULL && despawnTask->isScheduled()) { despawnTask->cancel(); int newTime = (CampSiteActiveArea::DESPAWNTIME / 6); int maxTime = CampSiteActiveArea::DESPAWNTIME - ((System::getTime() - timeCreated) * 1000); despawnTask->schedule(newTime < maxTime ? newTime : maxTime); } if(terminal != NULL) terminal->setCustomObjectName("Abandoned Camp", true); if(campOwner != NULL) { campOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver); campOwner->sendSystemMessage("@camp:sys_abandoned_camp"); } } bool CampSiteActiveAreaImplementation::despawnCamp() { if(!abandoned && campOwner != NULL && campOwner->getZoneServer() != NULL) { /// Get Player Manager PlayerManager* playerManager = campOwner->getZoneServer()->getPlayerManager(); if (playerManager == NULL) { error("playerManager is null"); return false; } float durationUsed = ((float)(System::getTime() - timeCreated)) / (campStructureData->getDuration()); int amount = 0; amount += (int)(campStructureData->getExperience() * durationUsed); amount += ((visitors.size() -1) * 15); amount += currentXp; int awarded = (amount > campStructureData->getExperience() ? campStructureData->getExperience() : amount); playerManager->awardExperience(campOwner, "camp", awarded, true); } if(despawnTask != NULL ) { if(despawnTask->isScheduled()) despawnTask->cancel(); despawnTask = NULL; } if(abandonTask != NULL) { if(abandonTask->isScheduled()) abandonTask->cancel(); abandonTask = NULL; } if(campOwner != NULL) campOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver); if(camp->getZone() == NULL) return false; ManagedReference<StructureManager*> structureManager = camp->getZone()->getStructureManager(); if (structureManager == NULL) { error("Unable to get StructureManager when placing camp"); return false; } destroyObjectFromWorld(true); destroyObjectFromDatabase(true); structureManager->destroyStructure(camp); return true; } void CampSiteActiveAreaImplementation::assumeOwnership(CreatureObject* player) { /// Get Ghost PlayerObject* ghost = campOwner->getPlayerObject(); if (ghost != NULL) { ghost->removeOwnedStructure(camp); } setOwner(player); abandoned = false; currentXp = 0; /// Get Ghost ghost = campOwner->getPlayerObject(); if (ghost != NULL) { ghost->addOwnedStructure(camp); } player->registerObserver(ObserverEventType::STARTCOMBAT, campObserver); if(abandonTask != NULL && abandonTask->isScheduled()) abandonTask->cancel(); if(terminal != NULL) { String campName = player->getFirstName(); if(!player->getLastName().isEmpty()) campName += " " + player->getLastName(); campName += "'s Camp"; terminal->setCustomObjectName(campName, true); } } <|endoftext|>